title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Degree of a Cycle Graph - GeeksforGeeks
16 Jun, 2021 Given the number of vertices in a Cycle Graph. The task is to find the Degree and the number of Edges of the cycle graph. Degree: Degree of any vertex is defined as the number of edge Incident on it. Cycle Graph: In graph theory, a graph that consists of single cycle is called a cycle graph or circular graph. The cycle graph with n vertices is called Cn. Properties of Cycle Graph:- It is a Connected Graph. A Cycle Graph or Circular Graph is a graph that consists of a single cycle. In a Cycle Graph number of vertices is equal to number of edges. A Cycle Graph is 2-edge colorable or 2-vertex colorable, if and only if it has an even number of vertices. A Cycle Graph is 3-edge colorable or 3-edge colorable, if and only if it has an odd number of vertices. In a Cycle Graph, Degree of each vertex in a graph is two. The degree of a Cycle graph is 2 times the number of vertices. As each edge is counted twice. Examples: Input: Number of vertices = 4 Output: Degree is 8 Edges are 4 Explanation: The total edges are 4 and the Degree of the Graph is 8 as 2 edge incident on each of the vertices i.e on a, b, c, and d. Input: number of vertices = 5 Output: Degree is 10 Edges are 5 Below is the implementation of the above problem: Program 1: For 4 vertices cycle graph C++ Java Python3 C# PHP Javascript // C++ implementation of above program. #include <bits/stdc++.h>using namespace std; // function that calculates the// number of Edge in a cycle graph.int getnumberOfEdges(int numberOfVertices){ int numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges;} // function that calculates the degreeint getDegree(int numberOfVertices){ int degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree;} // Driver codeint main(){ // Get the number of vertices int numberOfVertices = 4; // Find the numberOfEdges and degree // from the numberOfVertices // and print the result cout << "For numberOfVertices = " << numberOfVertices << "\nDegree = " << getDegree(numberOfVertices) << "\nNumber of Edges = " << getnumberOfEdges(numberOfVertices); return 0;} // Java implementation of above program.import java.io.*; class GFG { // function that calculates the // number of Edge in a cycle graph. static int getnumberOfEdges(int numberOfVertices) { int numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges; } // function that calculates the degree static int getDegree(int numberOfVertices) { int degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree; } // Driver code public static void main(String[] args) { // Get the number of vertices int numberOfVertices = 4; // Find the numberOfEdges and degree // from the numberOfVertices // and print the result System.out.print("For numberOfVertices = " + numberOfVertices + "\nDegree = " + getDegree(numberOfVertices) + "\nNumber of Edges = " + getnumberOfEdges(numberOfVertices)); }} // This code is contributed by anuj_67.. # Python3 implementation of above program. # function that calculates the# number of Edge in a cycle graph.def getnumberOfEdges(numberOfVertices) : # The numberOfEdges of the cycle graph # will be same as the numberOfVertices numberOfEdges = numberOfVertices # return the numberOfEdges return numberOfEdges # function that calculates the degreedef getDegree(numberOfVertices) : # The degree of the cycle graph # will be twice the numberOfVertices degree = 2 * numberOfVertices # return the degree return degree # Driver code if __name__ == "__main__" : # Get the number of vertices numberOfVertices = 4 # Find the numberOfEdges and degree # from the numberOfVertices # and print the result print("For numberOfVertices =", numberOfVertices, "\nDegree =", getDegree(numberOfVertices), "\nNumber of Edges =", getnumberOfEdges(numberOfVertices)) # This code is contributed by ANKITRAI1 // C# implementation of above program.using System; class GFG { // function that calculates the // number of Edge in a cycle graph. static int getnumberOfEdges(int numberOfVertices) { int numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges; } // function that calculates the degree static int getDegree(int numberOfVertices) { int degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree; } // Driver code public static void Main() { // Get the number of vertices int numberOfVertices = 4; // Find the numberOfEdges and degree // from the numberOfVertices // and print the result Console.WriteLine("For numberOfVertices = " + numberOfVertices + "\nDegree = " + getDegree(numberOfVertices) + "\nNumber of Edges = " + getnumberOfEdges(numberOfVertices)); }} // This code is contributed by anuj_67.. <?php// PHP implementation of above program // function that calculates the// number of Edge in a cycle graph.function getnumberOfEdges($numberOfVertices){ $numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices $numberOfEdges = $numberOfVertices; // return the numberOfEdges return $numberOfEdges;} // function that calculates the degreefunction getDegree($numberOfVertices){ // The degree of the cycle graph // will be twice the numberOfVertices $degree = 2 * $numberOfVertices; // return the degree return $degree;} // Driver code // Get the number of vertices$numberOfVertices = 4; // Find the numberOfEdges and degree// from the numberOfVertices// and print the resultecho ("For numberOfVertices = ");echo ($numberOfVertices);echo ("\nDegree = ");echo getDegree($numberOfVertices);echo("\nNumber of Edges = ");echo getnumberOfEdges($numberOfVertices); // This code is contributed by Shivi_Aggarwal?> <script> // Javascript implementation of above program. // function that calculates the// number of Edge in a cycle graph.function getnumberOfEdges(numberOfVertices){ var numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges;} // function that calculates the degreefunction getDegree(numberOfVertices){ var degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree;} // Driver code // Get the number of verticesvar numberOfVertices = 4; // Find the numberOfEdges and degree// from the numberOfVertices// and print the resultdocument.write("For numberOfVertices = " + numberOfVertices + "<br>Degree = " + getDegree(numberOfVertices) + "<br>Number of Edges = " + getnumberOfEdges(numberOfVertices)); // This code is contributed by itsok </script> For numberOfVertices = 4 Degree = 8 Number of Edges = 4 Program 2: For 6 vertices cycle graph C++ Java Python3 C# PHP Javascript // C++ implementation of above program. #include <bits/stdc++.h>using namespace std; // function that calculates the// number of Edge in a cycle graph.int getnumberOfEdges(int numberOfVertices){ int numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges;} // function that calculates the degreeint getDegree(int numberOfVertices){ int degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree;} // Driver codeint main(){ // Get the number of vertices int numberOfVertices = 6; // Find the numberOfEdges and degree // from the numberOfVertices // and print the result cout << "For numberOfVertices = " << numberOfVertices << "\nDegree = " << getDegree(numberOfVertices) << "\nNumber of Edges = " << getnumberOfEdges(numberOfVertices); return 0;} // Java implementation of above program.class GfG { // function that calculates the // number of Edge in a cycle graph. static int getnumberOfEdges(int numberOfVertices) { int numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges; } // function that calculates the degree static int getDegree(int numberOfVertices) { int degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree; } // Driver code public static void main(String[] args) { // Get the number of vertices int numberOfVertices = 6; // Find the numberOfEdges and degree // from the numberOfVertices // and print the result System.out.println("For numberOfVertices = " + numberOfVertices + "\nDegree = " + getDegree(numberOfVertices) + "\nNumber of Edges = " + getnumberOfEdges(numberOfVertices)); }} // This code contributed by Rajput-Ji # Python 3 implementation of above program # function that calculates the# number of Edge in a cycle graph.def getnumberOfEdges(numberOfVertices): numberOfEdges = 0 # The numberOfEdges of the cycle graph # will be same as the numberOfVertices numberOfEdges = numberOfVertices # return the numberOfEdges return numberOfEdges # function that calculates the degreedef getDegree(numberOfVertices): # The degree of the cycle graph # will be twice the numberOfVertices degree = 2 * numberOfVertices # return the degree return degree # Driver codeif __name__ == "__main__": # Get the number of vertices numberOfVertices = 6 # Find the numberOfEdges and degree # from the numberOfVertices # and print the result print("For numberOfVertices = ", numberOfVertices, "\nDegree = ", getDegree(numberOfVertices), "\nNumber of Edges = ", getnumberOfEdges(numberOfVertices)) # This code is contributed by ChitraNayal // C# implementation of above program.class GfG { // function that calculates the // number of Edge in a cycle graph. static int getnumberOfEdges(int numberOfVertices) { int numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges; } // function that calculates the degree static int getDegree(int numberOfVertices) { int degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree; } // Driver code static void Main() { // Get the number of vertices int numberOfVertices = 6; // Find the numberOfEdges and degree // from the numberOfVertices // and print the result System.Console.WriteLine("For numberOfVertices = " + numberOfVertices + "\nDegree = " + getDegree(numberOfVertices) + "\nNumber of Edges = " + getnumberOfEdges(numberOfVertices)); }} // This code contributed by mits <?php// PHP implementation of above program. // function that calculates the// number of Edge in a cycle graph.function getnumberOfEdges($numberOfVertices){ $numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices $numberOfEdges = $numberOfVertices; // return the numberOfEdges return $numberOfEdges;} // function that calculates the degreefunction getDegree($numberOfVertices){ $degree = 0; // The degree of the cycle graph // will be twice the numberOfVertices $degree = 2 * $numberOfVertices; // return the degree return $degree;} // Driver code // Get the number of vertices$numberOfVertices = 6; // Find the numberOfEdges and degree// from the numberOfVertices// and print the resultecho "For numberOfVertices = " . $numberOfVertices . "\nDegree = " . getDegree($numberOfVertices) . "\nNumber of Edges = " . getnumberOfEdges($numberOfVertices); // This code is contributed by mits?> <script>// Javascript implementation of above program // function that calculates the // number of Edge in a cycle graph. function getnumberOfEdges(numberOfVertices) { let numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges; } // function that calculates the degree function getDegree(numberOfVertices) { let degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree; } // Driver code // Get the number of vertices let numberOfVertices = 6; // Find the numberOfEdges and degree // from the numberOfVertices // and print the result document.write("For numberOfVertices = " + numberOfVertices + "<br>Degree = " + getDegree(numberOfVertices) + "<br>Number of Edges = " + getnumberOfEdges(numberOfVertices)); // This code is contributed by avanitrachhadiya2155</script> For numberOfVertices = 6 Degree = 12 Number of Edges = 6 Shivi_Aggarwal ankthon ukasp vt_m Rajput-Ji Mithun Kumar itsok avanitrachhadiya2155 arorakashish0911 Data Structures-Graph graph-cycle C++ Programs Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Passing a function as a parameter in C++ Const keyword in C++ Program to implement Singly Linked List in C++ using class cout in C++ Dynamic _Cast in C++ Breadth First Search or BFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Depth First Search or DFS for a Graph Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
[ { "code": null, "e": 24631, "s": 24603, "text": "\n16 Jun, 2021" }, { "code": null, "e": 24753, "s": 24631, "text": "Given the number of vertices in a Cycle Graph. The task is to find the Degree and the number of Edges of the cycle graph." }, { "code": null, "e": 24831, "s": 24753, "text": "Degree: Degree of any vertex is defined as the number of edge Incident on it." }, { "code": null, "e": 24989, "s": 24831, "text": "Cycle Graph: In graph theory, a graph that consists of single cycle is called a cycle graph or circular graph. The cycle graph with n vertices is called Cn. " }, { "code": null, "e": 25019, "s": 24989, "text": "Properties of Cycle Graph:- " }, { "code": null, "e": 25044, "s": 25019, "text": "It is a Connected Graph." }, { "code": null, "e": 25120, "s": 25044, "text": "A Cycle Graph or Circular Graph is a graph that consists of a single cycle." }, { "code": null, "e": 25185, "s": 25120, "text": "In a Cycle Graph number of vertices is equal to number of edges." }, { "code": null, "e": 25292, "s": 25185, "text": "A Cycle Graph is 2-edge colorable or 2-vertex colorable, if and only if it has an even number of vertices." }, { "code": null, "e": 25396, "s": 25292, "text": "A Cycle Graph is 3-edge colorable or 3-edge colorable, if and only if it has an odd number of vertices." }, { "code": null, "e": 25455, "s": 25396, "text": "In a Cycle Graph, Degree of each vertex in a graph is two." }, { "code": null, "e": 25549, "s": 25455, "text": "The degree of a Cycle graph is 2 times the number of vertices. As each edge is counted twice." }, { "code": null, "e": 25561, "s": 25549, "text": "Examples: " }, { "code": null, "e": 25769, "s": 25561, "text": "Input: Number of vertices = 4\nOutput: Degree is 8\n Edges are 4\nExplanation: \nThe total edges are 4 \nand the Degree of the Graph is 8\nas 2 edge incident on each of \nthe vertices i.e on a, b, c, and d. " }, { "code": null, "e": 25840, "s": 25769, "text": "Input: number of vertices = 5\nOutput: Degree is 10\n Edges are 5" }, { "code": null, "e": 25890, "s": 25840, "text": "Below is the implementation of the above problem:" }, { "code": null, "e": 25930, "s": 25890, "text": "Program 1: For 4 vertices cycle graph " }, { "code": null, "e": 25934, "s": 25930, "text": "C++" }, { "code": null, "e": 25939, "s": 25934, "text": "Java" }, { "code": null, "e": 25947, "s": 25939, "text": "Python3" }, { "code": null, "e": 25950, "s": 25947, "text": "C#" }, { "code": null, "e": 25954, "s": 25950, "text": "PHP" }, { "code": null, "e": 25965, "s": 25954, "text": "Javascript" }, { "code": "// C++ implementation of above program. #include <bits/stdc++.h>using namespace std; // function that calculates the// number of Edge in a cycle graph.int getnumberOfEdges(int numberOfVertices){ int numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges;} // function that calculates the degreeint getDegree(int numberOfVertices){ int degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree;} // Driver codeint main(){ // Get the number of vertices int numberOfVertices = 4; // Find the numberOfEdges and degree // from the numberOfVertices // and print the result cout << \"For numberOfVertices = \" << numberOfVertices << \"\\nDegree = \" << getDegree(numberOfVertices) << \"\\nNumber of Edges = \" << getnumberOfEdges(numberOfVertices); return 0;}", "e": 27028, "s": 25965, "text": null }, { "code": "// Java implementation of above program.import java.io.*; class GFG { // function that calculates the // number of Edge in a cycle graph. static int getnumberOfEdges(int numberOfVertices) { int numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges; } // function that calculates the degree static int getDegree(int numberOfVertices) { int degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree; } // Driver code public static void main(String[] args) { // Get the number of vertices int numberOfVertices = 4; // Find the numberOfEdges and degree // from the numberOfVertices // and print the result System.out.print(\"For numberOfVertices = \" + numberOfVertices + \"\\nDegree = \" + getDegree(numberOfVertices) + \"\\nNumber of Edges = \" + getnumberOfEdges(numberOfVertices)); }} // This code is contributed by anuj_67..", "e": 28354, "s": 27028, "text": null }, { "code": "# Python3 implementation of above program. # function that calculates the# number of Edge in a cycle graph.def getnumberOfEdges(numberOfVertices) : # The numberOfEdges of the cycle graph # will be same as the numberOfVertices numberOfEdges = numberOfVertices # return the numberOfEdges return numberOfEdges # function that calculates the degreedef getDegree(numberOfVertices) : # The degree of the cycle graph # will be twice the numberOfVertices degree = 2 * numberOfVertices # return the degree return degree # Driver code if __name__ == \"__main__\" : # Get the number of vertices numberOfVertices = 4 # Find the numberOfEdges and degree # from the numberOfVertices # and print the result print(\"For numberOfVertices =\", numberOfVertices, \"\\nDegree =\", getDegree(numberOfVertices), \"\\nNumber of Edges =\", getnumberOfEdges(numberOfVertices)) # This code is contributed by ANKITRAI1", "e": 29313, "s": 28354, "text": null }, { "code": "// C# implementation of above program.using System; class GFG { // function that calculates the // number of Edge in a cycle graph. static int getnumberOfEdges(int numberOfVertices) { int numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges; } // function that calculates the degree static int getDegree(int numberOfVertices) { int degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree; } // Driver code public static void Main() { // Get the number of vertices int numberOfVertices = 4; // Find the numberOfEdges and degree // from the numberOfVertices // and print the result Console.WriteLine(\"For numberOfVertices = \" + numberOfVertices + \"\\nDegree = \" + getDegree(numberOfVertices) + \"\\nNumber of Edges = \" + getnumberOfEdges(numberOfVertices)); }} // This code is contributed by anuj_67..", "e": 30626, "s": 29313, "text": null }, { "code": "<?php// PHP implementation of above program // function that calculates the// number of Edge in a cycle graph.function getnumberOfEdges($numberOfVertices){ $numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices $numberOfEdges = $numberOfVertices; // return the numberOfEdges return $numberOfEdges;} // function that calculates the degreefunction getDegree($numberOfVertices){ // The degree of the cycle graph // will be twice the numberOfVertices $degree = 2 * $numberOfVertices; // return the degree return $degree;} // Driver code // Get the number of vertices$numberOfVertices = 4; // Find the numberOfEdges and degree// from the numberOfVertices// and print the resultecho (\"For numberOfVertices = \");echo ($numberOfVertices);echo (\"\\nDegree = \");echo getDegree($numberOfVertices);echo(\"\\nNumber of Edges = \");echo getnumberOfEdges($numberOfVertices); // This code is contributed by Shivi_Aggarwal?>", "e": 31617, "s": 30626, "text": null }, { "code": "<script> // Javascript implementation of above program. // function that calculates the// number of Edge in a cycle graph.function getnumberOfEdges(numberOfVertices){ var numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges;} // function that calculates the degreefunction getDegree(numberOfVertices){ var degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree;} // Driver code // Get the number of verticesvar numberOfVertices = 4; // Find the numberOfEdges and degree// from the numberOfVertices// and print the resultdocument.write(\"For numberOfVertices = \" + numberOfVertices + \"<br>Degree = \" + getDegree(numberOfVertices) + \"<br>Number of Edges = \" + getnumberOfEdges(numberOfVertices)); // This code is contributed by itsok </script>", "e": 32673, "s": 31617, "text": null }, { "code": null, "e": 32729, "s": 32673, "text": "For numberOfVertices = 4\nDegree = 8\nNumber of Edges = 4" }, { "code": null, "e": 32771, "s": 32731, "text": "Program 2: For 6 vertices cycle graph " }, { "code": null, "e": 32775, "s": 32771, "text": "C++" }, { "code": null, "e": 32780, "s": 32775, "text": "Java" }, { "code": null, "e": 32788, "s": 32780, "text": "Python3" }, { "code": null, "e": 32791, "s": 32788, "text": "C#" }, { "code": null, "e": 32795, "s": 32791, "text": "PHP" }, { "code": null, "e": 32806, "s": 32795, "text": "Javascript" }, { "code": "// C++ implementation of above program. #include <bits/stdc++.h>using namespace std; // function that calculates the// number of Edge in a cycle graph.int getnumberOfEdges(int numberOfVertices){ int numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges;} // function that calculates the degreeint getDegree(int numberOfVertices){ int degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree;} // Driver codeint main(){ // Get the number of vertices int numberOfVertices = 6; // Find the numberOfEdges and degree // from the numberOfVertices // and print the result cout << \"For numberOfVertices = \" << numberOfVertices << \"\\nDegree = \" << getDegree(numberOfVertices) << \"\\nNumber of Edges = \" << getnumberOfEdges(numberOfVertices); return 0;}", "e": 33869, "s": 32806, "text": null }, { "code": "// Java implementation of above program.class GfG { // function that calculates the // number of Edge in a cycle graph. static int getnumberOfEdges(int numberOfVertices) { int numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges; } // function that calculates the degree static int getDegree(int numberOfVertices) { int degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree; } // Driver code public static void main(String[] args) { // Get the number of vertices int numberOfVertices = 6; // Find the numberOfEdges and degree // from the numberOfVertices // and print the result System.out.println(\"For numberOfVertices = \" + numberOfVertices + \"\\nDegree = \" + getDegree(numberOfVertices) + \"\\nNumber of Edges = \" + getnumberOfEdges(numberOfVertices)); }} // This code contributed by Rajput-Ji", "e": 35161, "s": 33869, "text": null }, { "code": "# Python 3 implementation of above program # function that calculates the# number of Edge in a cycle graph.def getnumberOfEdges(numberOfVertices): numberOfEdges = 0 # The numberOfEdges of the cycle graph # will be same as the numberOfVertices numberOfEdges = numberOfVertices # return the numberOfEdges return numberOfEdges # function that calculates the degreedef getDegree(numberOfVertices): # The degree of the cycle graph # will be twice the numberOfVertices degree = 2 * numberOfVertices # return the degree return degree # Driver codeif __name__ == \"__main__\": # Get the number of vertices numberOfVertices = 6 # Find the numberOfEdges and degree # from the numberOfVertices # and print the result print(\"For numberOfVertices = \", numberOfVertices, \"\\nDegree = \", getDegree(numberOfVertices), \"\\nNumber of Edges = \", getnumberOfEdges(numberOfVertices)) # This code is contributed by ChitraNayal", "e": 36164, "s": 35161, "text": null }, { "code": "// C# implementation of above program.class GfG { // function that calculates the // number of Edge in a cycle graph. static int getnumberOfEdges(int numberOfVertices) { int numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges; } // function that calculates the degree static int getDegree(int numberOfVertices) { int degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree; } // Driver code static void Main() { // Get the number of vertices int numberOfVertices = 6; // Find the numberOfEdges and degree // from the numberOfVertices // and print the result System.Console.WriteLine(\"For numberOfVertices = \" + numberOfVertices + \"\\nDegree = \" + getDegree(numberOfVertices) + \"\\nNumber of Edges = \" + getnumberOfEdges(numberOfVertices)); }} // This code contributed by mits", "e": 37459, "s": 36164, "text": null }, { "code": "<?php// PHP implementation of above program. // function that calculates the// number of Edge in a cycle graph.function getnumberOfEdges($numberOfVertices){ $numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices $numberOfEdges = $numberOfVertices; // return the numberOfEdges return $numberOfEdges;} // function that calculates the degreefunction getDegree($numberOfVertices){ $degree = 0; // The degree of the cycle graph // will be twice the numberOfVertices $degree = 2 * $numberOfVertices; // return the degree return $degree;} // Driver code // Get the number of vertices$numberOfVertices = 6; // Find the numberOfEdges and degree// from the numberOfVertices// and print the resultecho \"For numberOfVertices = \" . $numberOfVertices . \"\\nDegree = \" . getDegree($numberOfVertices) . \"\\nNumber of Edges = \" . getnumberOfEdges($numberOfVertices); // This code is contributed by mits?>", "e": 38443, "s": 37459, "text": null }, { "code": "<script>// Javascript implementation of above program // function that calculates the // number of Edge in a cycle graph. function getnumberOfEdges(numberOfVertices) { let numberOfEdges = 0; // The numberOfEdges of the cycle graph // will be same as the numberOfVertices numberOfEdges = numberOfVertices; // return the numberOfEdges return numberOfEdges; } // function that calculates the degree function getDegree(numberOfVertices) { let degree; // The degree of the cycle graph // will be twice the numberOfVertices degree = 2 * numberOfVertices; // return the degree return degree; } // Driver code // Get the number of vertices let numberOfVertices = 6; // Find the numberOfEdges and degree // from the numberOfVertices // and print the result document.write(\"For numberOfVertices = \" + numberOfVertices + \"<br>Degree = \" + getDegree(numberOfVertices) + \"<br>Number of Edges = \" + getnumberOfEdges(numberOfVertices)); // This code is contributed by avanitrachhadiya2155</script>", "e": 39703, "s": 38443, "text": null }, { "code": null, "e": 39760, "s": 39703, "text": "For numberOfVertices = 6\nDegree = 12\nNumber of Edges = 6" }, { "code": null, "e": 39777, "s": 39762, "text": "Shivi_Aggarwal" }, { "code": null, "e": 39785, "s": 39777, "text": "ankthon" }, { "code": null, "e": 39791, "s": 39785, "text": "ukasp" }, { "code": null, "e": 39796, "s": 39791, "text": "vt_m" }, { "code": null, "e": 39806, "s": 39796, "text": "Rajput-Ji" }, { "code": null, "e": 39819, "s": 39806, "text": "Mithun Kumar" }, { "code": null, "e": 39825, "s": 39819, "text": "itsok" }, { "code": null, "e": 39846, "s": 39825, "text": "avanitrachhadiya2155" }, { "code": null, "e": 39863, "s": 39846, "text": "arorakashish0911" }, { "code": null, "e": 39885, "s": 39863, "text": "Data Structures-Graph" }, { "code": null, "e": 39897, "s": 39885, "text": "graph-cycle" }, { "code": null, "e": 39910, "s": 39897, "text": "C++ Programs" }, { "code": null, "e": 39916, "s": 39910, "text": "Graph" }, { "code": null, "e": 39922, "s": 39916, "text": "Graph" }, { "code": null, "e": 40020, "s": 39922, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40029, "s": 40020, "text": "Comments" }, { "code": null, "e": 40042, "s": 40029, "text": "Old Comments" }, { "code": null, "e": 40083, "s": 40042, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 40104, "s": 40083, "text": "Const keyword in C++" }, { "code": null, "e": 40163, "s": 40104, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 40175, "s": 40163, "text": "cout in C++" }, { "code": null, "e": 40196, "s": 40175, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 40236, "s": 40196, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 40287, "s": 40236, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 40325, "s": 40287, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 40383, "s": 40325, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
How to change backends in Matplotlib?
We can override the backend value using atplotlib.rcParams['backend'] variable. Using get_backend() method, return the name of the current backend, i.e., default name. Using get_backend() method, return the name of the current backend, i.e., default name. Now override the backend name. Now override the backend name. Using get_backend() method, return the name of the current backend, i.e., updated name. Using get_backend() method, return the name of the current backend, i.e., updated name. import matplotlib print("Before, Backend used by matplotlib is: ", matplotlib.get_backend()) matplotlib.rcParams['backend'] = 'TkAgg' print("After, Backend used by matplotlib is: ", matplotlib.get_backend()) Before, Backend used by matplotlib is: GTK3Agg After, Backend used by matplotlib is: TkAgg Enter number of bars: 5
[ { "code": null, "e": 1142, "s": 1062, "text": "We can override the backend value using atplotlib.rcParams['backend'] variable." }, { "code": null, "e": 1230, "s": 1142, "text": "Using get_backend() method, return the name of the current backend, i.e., default name." }, { "code": null, "e": 1318, "s": 1230, "text": "Using get_backend() method, return the name of the current backend, i.e., default name." }, { "code": null, "e": 1349, "s": 1318, "text": "Now override the backend name." }, { "code": null, "e": 1380, "s": 1349, "text": "Now override the backend name." }, { "code": null, "e": 1468, "s": 1380, "text": "Using get_backend() method, return the name of the current backend, i.e., updated name." }, { "code": null, "e": 1556, "s": 1468, "text": "Using get_backend() method, return the name of the current backend, i.e., updated name." }, { "code": null, "e": 1764, "s": 1556, "text": "import matplotlib\nprint(\"Before, Backend used by matplotlib is: \", matplotlib.get_backend())\nmatplotlib.rcParams['backend'] = 'TkAgg'\nprint(\"After, Backend used by matplotlib is: \", matplotlib.get_backend())" }, { "code": null, "e": 1879, "s": 1764, "text": "Before, Backend used by matplotlib is: GTK3Agg\nAfter, Backend used by matplotlib is: TkAgg\nEnter number of bars: 5" } ]
Period comparisons in Power BI. Comparison over different time periods... | by Nikola Ilic | Towards Data Science
Just recently, I’ve come across a question on the LinkedIn platform, if it’s possible to create the following visualization in Power BI: Since one of the common business requests is to perform different comparisons between various time periods, I would say that Power BI has a lot to offer in this regard. I’ve already explained some basic calculations related to Time Intelligence, but there are obviously a significant number of users who are not quite familiar with them. First of all, I would like to emphasize a great feature called “Quick Measures”, where you get out-of-the-box solutions for multiple commonly used calculations, such as: Year-to-date total, Quarter-to-date total, Month-to-date total, Year-over-year change, Rolling Average, etc. In order for Quick Measures to work, you need to have a properly defined Date table. However, we will not use Quick Measures here to achieve our original goal, so let’s switch over to a Power BI Desktop and get into the action! As usual, I will use the Contoso database for demo purposes. The first step is to create a base measure to calculate Sales Amount: Sales Amt = SUM(FactOnlineSales[SalesAmount]) I will straight away create another measure, which will calculate same figures, but shifting one month back: Sales Amt PM = CALCULATE([Sales Amt], DATEADD(DimDate[Datekey],-1,MONTH) ) There are multiple different ways to calculate this measure, but I prefer using DATEADD() function since it gives me more flexibility with shifting periods (that’s an official excuse:)...In reality, I’m coming from the SQL world, where DATEADD() is one of the most important functions when working with dates). Now, when I choose dates between November 17th and December 17th, I can see how my numbers correlate between themselves: As you may notice, our formulas work well — as intended, we see that Sales Amt PM for December 17th, matches Sales Amt for November 17th. Also, our Line chart nicely visualizes trends for easier comparison, while Card visuals in the upper left corner show Sales Amount for the selected period and difference between two periods which we are comparing. For those differences, I’ve created two additional measures: Sales Amt Diff PM = [Sales Amt] - [Sales Amt PM]Sales Amt Diff PM % = DIVIDE([Sales Amt],[Sales Amt PM],BLANK()) - 1 Lower Card is conditionally formatted based on the values, so it goes red when we are performing worse than in the previous period, while it shows green when the outcome is the opposite: Now, that’s fine and you saw how we could easily answer the original question. However, I wanted to add some more ingredients here and enable our users to choose between MoM (Month-over-month) and YoY (Year-over-year) comparison. In our example, if we choose again dates between November 17th and December 17th, instead of showing me values from the previous month (comparing December 17th and November 17th), with YoY comparison I want to compare December 17th 2009 with December 17th 2008! So, let’s create a measure for this. Again, you can use different functions to achieve this, like SAMEPERIODLASTYEAR() function, but I want to keep consistency and therefore I will again use DATEADD(): Sales Amt PY = CALCULATE([Sales Amt], DATEADD(DimDate[Datekey],-1,YEAR) ) Same as for MoM calculations, two additional measures are needed to calculate differences for YoY figures: Sales Amt Diff PY = [Sales Amt] - [Sales Amt PY]Sales Amt Diff PY % = DIVIDE([Sales Amt],[Sales Amt PY],BLANK()) - 1 I will then create two bookmarks, so that users can navigate to MoM or YoY, by clicking on respective buttons: By default, they should see MoM comparison, but as soon as they click on YoY button, the report will look slightly different: You can notice that numbers in the card visuals changed to reflect YoY difference calculation, while Line chart also shows different trends! Before we conclude, here is the final behavior of our report: As we saw, Power BI is quite a powerful tool when it comes to time intelligence calculations. Basically, all kinds of comparisons between different periods can be created — most common ones even without needing to write a single line of DAX! If you need to expand on built-in Quick Measures, there is a whole range of useful Time Intelligence functions. You can check all of them in more depth here. Thanks for reading! Become a member and read every story on Medium! Subscribe here to get more insightful data articles!
[ { "code": null, "e": 309, "s": 172, "text": "Just recently, I’ve come across a question on the LinkedIn platform, if it’s possible to create the following visualization in Power BI:" }, { "code": null, "e": 647, "s": 309, "text": "Since one of the common business requests is to perform different comparisons between various time periods, I would say that Power BI has a lot to offer in this regard. I’ve already explained some basic calculations related to Time Intelligence, but there are obviously a significant number of users who are not quite familiar with them." }, { "code": null, "e": 926, "s": 647, "text": "First of all, I would like to emphasize a great feature called “Quick Measures”, where you get out-of-the-box solutions for multiple commonly used calculations, such as: Year-to-date total, Quarter-to-date total, Month-to-date total, Year-over-year change, Rolling Average, etc." }, { "code": null, "e": 1011, "s": 926, "text": "In order for Quick Measures to work, you need to have a properly defined Date table." }, { "code": null, "e": 1215, "s": 1011, "text": "However, we will not use Quick Measures here to achieve our original goal, so let’s switch over to a Power BI Desktop and get into the action! As usual, I will use the Contoso database for demo purposes." }, { "code": null, "e": 1285, "s": 1215, "text": "The first step is to create a base measure to calculate Sales Amount:" }, { "code": null, "e": 1331, "s": 1285, "text": "Sales Amt = SUM(FactOnlineSales[SalesAmount])" }, { "code": null, "e": 1440, "s": 1331, "text": "I will straight away create another measure, which will calculate same figures, but shifting one month back:" }, { "code": null, "e": 1561, "s": 1440, "text": "Sales Amt PM = CALCULATE([Sales Amt], DATEADD(DimDate[Datekey],-1,MONTH) )" }, { "code": null, "e": 1872, "s": 1561, "text": "There are multiple different ways to calculate this measure, but I prefer using DATEADD() function since it gives me more flexibility with shifting periods (that’s an official excuse:)...In reality, I’m coming from the SQL world, where DATEADD() is one of the most important functions when working with dates)." }, { "code": null, "e": 1993, "s": 1872, "text": "Now, when I choose dates between November 17th and December 17th, I can see how my numbers correlate between themselves:" }, { "code": null, "e": 2345, "s": 1993, "text": "As you may notice, our formulas work well — as intended, we see that Sales Amt PM for December 17th, matches Sales Amt for November 17th. Also, our Line chart nicely visualizes trends for easier comparison, while Card visuals in the upper left corner show Sales Amount for the selected period and difference between two periods which we are comparing." }, { "code": null, "e": 2406, "s": 2345, "text": "For those differences, I’ve created two additional measures:" }, { "code": null, "e": 2524, "s": 2406, "text": "Sales Amt Diff PM = [Sales Amt] - [Sales Amt PM]Sales Amt Diff PM % = DIVIDE([Sales Amt],[Sales Amt PM],BLANK()) - 1" }, { "code": null, "e": 2711, "s": 2524, "text": "Lower Card is conditionally formatted based on the values, so it goes red when we are performing worse than in the previous period, while it shows green when the outcome is the opposite:" }, { "code": null, "e": 2941, "s": 2711, "text": "Now, that’s fine and you saw how we could easily answer the original question. However, I wanted to add some more ingredients here and enable our users to choose between MoM (Month-over-month) and YoY (Year-over-year) comparison." }, { "code": null, "e": 3203, "s": 2941, "text": "In our example, if we choose again dates between November 17th and December 17th, instead of showing me values from the previous month (comparing December 17th and November 17th), with YoY comparison I want to compare December 17th 2009 with December 17th 2008!" }, { "code": null, "e": 3405, "s": 3203, "text": "So, let’s create a measure for this. Again, you can use different functions to achieve this, like SAMEPERIODLASTYEAR() function, but I want to keep consistency and therefore I will again use DATEADD():" }, { "code": null, "e": 3525, "s": 3405, "text": "Sales Amt PY = CALCULATE([Sales Amt], DATEADD(DimDate[Datekey],-1,YEAR) )" }, { "code": null, "e": 3632, "s": 3525, "text": "Same as for MoM calculations, two additional measures are needed to calculate differences for YoY figures:" }, { "code": null, "e": 3749, "s": 3632, "text": "Sales Amt Diff PY = [Sales Amt] - [Sales Amt PY]Sales Amt Diff PY % = DIVIDE([Sales Amt],[Sales Amt PY],BLANK()) - 1" }, { "code": null, "e": 3860, "s": 3749, "text": "I will then create two bookmarks, so that users can navigate to MoM or YoY, by clicking on respective buttons:" }, { "code": null, "e": 3986, "s": 3860, "text": "By default, they should see MoM comparison, but as soon as they click on YoY button, the report will look slightly different:" }, { "code": null, "e": 4127, "s": 3986, "text": "You can notice that numbers in the card visuals changed to reflect YoY difference calculation, while Line chart also shows different trends!" }, { "code": null, "e": 4189, "s": 4127, "text": "Before we conclude, here is the final behavior of our report:" }, { "code": null, "e": 4431, "s": 4189, "text": "As we saw, Power BI is quite a powerful tool when it comes to time intelligence calculations. Basically, all kinds of comparisons between different periods can be created — most common ones even without needing to write a single line of DAX!" }, { "code": null, "e": 4589, "s": 4431, "text": "If you need to expand on built-in Quick Measures, there is a whole range of useful Time Intelligence functions. You can check all of them in more depth here." }, { "code": null, "e": 4609, "s": 4589, "text": "Thanks for reading!" }, { "code": null, "e": 4657, "s": 4609, "text": "Become a member and read every story on Medium!" } ]
Tryit Editor v3.7
RWD Media Queries Tryit: Typical media query breakpoints
[ { "code": null, "e": 27, "s": 9, "text": "RWD Media Queries" } ]
Plotting and Data Representation using Python. A guided walk through using a Coursera question | by Emmanuel Sibanda | Towards Data Science
This post is based off an assignment from a Coursera course, 'Applied Plotting, Charting & Data Representation in Python'. This is part 2 of the University of Michigan's Applied Data Science with Python Specialization. This is meant to run you through one of my solutions to one of the assignments explained in a way that makes it easier to understand for someone with limited Python experience. Please note that if you are taking this course, you can learn from my solution but it is in your best interest not to copy it as it will only hurt you in the long run. Additionally, there is a better solution which gives you a better visualization for the purposes of the assignment. The Scenario Imagine you are measuring temperature in weather stations in a particular city or region. From my research, albeit limited, this weather is often measured to tenths of a degree (for whatever reason). You start collecting data over a ten year period, measuring daily and monthly maximum and minimum temperatures and this data is compiled on an excel spreadsheet. A new year passes, let's assume its 2015 and you continue measuring the temperature as you always do. You have been observing record highs and lows and heatwaves around the country during 2015. You start wondering how temperatures of this year are measuring against temperatures over the previous 10 years. You want to answer the question; how do the record highs and lows for each month that has passed this year measure against record highs for each month set over the last 10 years. You decide that the best way to present these findings is through a visualization of a line chart that will show the record highs and lows of each month over the last 10 years. To answer your current question you also want to superimpose a scatterplot of the record highs and lows from 2015 that either exceed the record lows or highs set over the last 10 years. The Code So now you have a question and you know what you need to develop to answer your question. You decide to write out the code in Python. In order to help with your visualization you will need to import certain libraries that will help you perform many complex actions without writing lengthy and complex code. Importing Libraries and reading data import datetimeimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt#read data from a csvdf = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv') For this visualization we would want to use the datetime library to stipulate a cut-off date so that we can divide the data into 2 tables; i.) temperature measurements between 2005 and the 31st of December 2014 and ii.) measurements occurring after the cutoff date. Numpy which is short for numerical python will allow us to carry out mathematical functions on multi-dimensional matrices and arrays. The pandas and library will allow us to carry out manipulations and calculations on the dataframes we will be interacting with. While matplotlib will be used for plotting our graphs. We use the aliases pd and plt (and np for numpy) to interact with these libraries for ease of reference. The next line of code then uses the read_csv module included in the pandas library to read the data we want from our csv. This is automatically saved as a pandas dataframe — we named this dataframe 'df'. At this point I like to use the head method to read the top 5 rows of our dataframe. This helps me understand what columns the dataframe has and just get a better feel of what the data looks like df.head() Now we know that the dataframe has 4 columns; ID, Date, Element, and Data_Value. There is also an index column listing the row number starting from zero. The dataframe contains a total of 165 085 rows You notice from this that the measurements are categorised as either TMAX (the maximum temperature) and TMIN (the minimum temperature). The ID shows the station identification code which presumably shows which station took the measurements. Removing leap year data Since 2015 is not a leap year, we want to remove all leap year data. In the event that a leap year had record high/low temperatures over the 10 year period as this could have an impact on record high/low temperature measurements. Since 2015 would have 1 less day than years with leap years (2008 and 2012) this wouldn’t be an accurate comparison. #converting date to date timestampdf['Date'] = pd.DatetimeIndex(df['Date']).datelis = ['2922008','2922012'] #list of 29 Febs appearing in each leap yeardates = [datetime.datetime.strptime(i, '%d%m%Y').date() for i in lis] #converting into list of datetime.date objectsdf = df[~df['Date'].isin(dates)] #remove all 29 February dates In this code we convert the entire Date column using the DatetimeIndex module. This converts the Date column into a timestamp object. We then specify with .date that we want to return a datetime.date object (‘the date time of the timestamp without the timezone information’). Using the datetime.date library, we convert our list of leap year dates into a datetime.date object. We then only select the dates that are not listed as leap year dates (under the list ‘lis’) and filter out all leap year dates from our dataframe. Dates, cutoff dates and dividing dataframe into 2 tables Next, since we have ensured that all the Dates in the date column are the same data type (that they are all dates and not string for example), we want to divide the data into two tables based on whether the measurements occurred before or after the cutoff date. #creating a separate column for the monthdf['Month'] = pd.DatetimeIndex(df['Date']).month#we are colleting dates between 2005 - 2014, so want to remove any data from dates after 31 Dec 2014#creating datetime.date format of cutoff datea= '31122014'#converting a string into datetime.date objectcutoff_date = datetime.datetime.strptime(a,'%d%m%Y').date()#dataframe for values after 31 Dec 2014df2 = df[df['Date'] <= cutoff_date]#returning dates before cutoff datedf3 = df[df['Date'] > cutoff_date] Since we want our table to show us monthly highs over a ten year period we also want to create a month column. Listing only the month of the Date column as an integer. For the cutoff date we added the date as an integer and used the datetime.date module to convert the string into a datetime.date object (similar to our Date column), in 'date/month/year' format. We then proceed to create 2 new dataframes; df2- which contains all the measurements before or on the cutoff date and df3- which contains all the measurements after the cutoff date. Finding record highs and lows Now we need to answer the question, how do we find the record high and low temperatures over the ten years between 2005 and 2014 by month. From looking at our dataframe with the head method we already know that there is a column that specifies whether a measurement is recorded as a minimum of maximum temperature. Additionally, since we have created a month column, we know that this contains the month in which the measurement was recorded. In order to help us carry out this computation we will use groupby. This is a pandas module that allows us to split data into groups based on one or more criterions. This can be combined with the aggregation method, 'aggregate' which lets us carry out aggregations on our data such as returning the maximum or minimum values. Combined with groupby we can identify the maximum and minimum values between the groups we have created grouped by month. df_min = df2[df2['Element'] =='TMIN'].groupby('Month').aggregate({'Data_Value':np.min})df_max = df2[df2['Element'] == 'TMAX'].groupby('Month').aggregate({'Data_Value':np.max}) In this code, we created 2 dataframes; df_min- here we filtered measurements classified as minimum temperatures, grouped them by month and found the lowest temperature for each month over the ten year period and df_max- we filtered measurements classified as maximum temperatures, grouped them by month and found the highest temperature for each month. The Visualization process Now we want to start making use of the matplotlib library to visualize our data. plt.plot(df_max, '-o',df_min,'-o') We start off by plotting the record highs and lows over the ten year period as a line chart. These two will automatically be plotted in different colours. We used '-o' to identify each data value plotted on this chart, this is represented as a circle on our line chart. For visualization purposes we want to shade the area between the highest and lowest point grey. I believe this will make the data easier on the eye, helping you focus on the highest and lowest temperatures and the variability of record temperatures over the ten year period. x = df_max.index.valuesplt.fill_between(x,df_min.values.flatten(),df_max.values.flatten(), color='grey',alpha='0.5') We use the fill_between module to fill the area between the two lines. For fill_between to function you need to have the length of the x coordinates that you want to fill and the coordinates/values from both df_min and df_max. To find the length of the x coordinates we have created an x variable that contains the values of the index of df_max. This will return an numpy array containing the numbers 1–12 corresponding with the months of the year. Since df_min and df_max are dataframes and we only want the values in the dataframes (the temperatures) of both df_min and df_max. However, this will return an array of arrays whereas we need a one dimensional array to use the fill_between module. We then opt to flatten the array into a one dimensional array. Color and alpha simply allow us to specify the colour and hue of the fill_between. Super imposing scatterplot To answer our central question we need to start looking at the recordings after the cutoff date. In order to do this we need to group the data by month and look for measurements that exceed the lowest and highest recorded temperatures on our line chart. #superimpose scatterplotdf3_max = df3[df3['Data_Value'] > df3['Month'].map(df_max['Data_Value'])]df4_min = df3[df3['Data_Value'] < df3['Month'].map(df_min['Data_Value'])]plt.scatter(df3_max.Month.tolist(),df3_max['Data_Value'],s=10,c='red') #values over maxplt.scatter(df4_min.Month.tolist(),df4_min['Data_Value'],s=10,c='black') #values under min In order to compare each temperature grouped my month to the lowest and highest temperatures of each month, we use the map function to iterate through the df3 database, identify the month of each column and compare the temperature listed under the Data_Value column to the value listed for that particular month in the df_min and df_max dataframes (depending on whether we are looking at the minimum or maximum temperatures). If the value is higher or lower than the highest and lowest temperatures recorded over the ten year period, we add that row to our new dataframes; df3_max and df4_min. Now we want to superimpose our scatterplot over our line chart. For the scatter plot we need to specify the x (months) and y axis (data values). We also want to specify the size of the circle representing each value and the colour to differentiate it from the line chart circles. Making the chart easier to interpret If you are planning on showing this chart to anyone else, it is important to make sure that the chart is easy to interpret and shows what you want it to show without misleading your audience. The first problem with the chart as it stands is that the x-axis incrementing in 2s skipping odd number months. plt.xticks(list(df_max.index),['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec']) #we want to show all the x values and rename according to the month In order to rectify this I specify the xticks and rename them as abbreviations of the months they represent. The next issue pertains to how the temperature is recorded. We would want to show the temperature in degrees celsius and no as tenths of a degree. df_max['Data_Value'] = df_max['Data_Value']/10df_min['Data_Value'] = df_min['Data_Value']/10df4_min['Data_Value'] = df4_min['Data_Value']/10df3_max['Data_Value'] = df3_max['Data_Value']/10 I then divide all the temperature values by ten to convert tenths of a degree to degrees celsius. The final issue is that the graph is not labelled, and the size makes it difficult for us to know how many days in were recorded as exceeded the monthly high or low temperature. plt.title('Min and Max temperatures in Ann Arbor Michigan United States between 2005-2015', fontsize=20)plt.xlabel('Years', fontsize=20)plt.ylabel('Temperatures', fontsize=20)fig = plt.gcf()fig.set_size_inches(20,10)plt.tick_params(labelsize=20)plt.show() I then proceed to enlarge the chart by first getting the current figure (gcf), saving it as fig and setting the size of fig in inches. Since this will only enlarge the figure I need to also enlarge the x and y tick parameters and the font size of both the y and x label. From this chart we get identify that we had about 6 days in February were the minimum temperatures dropped below the lowest minimum temperature recorded between 2005 and 2014 for the month of February and 2 other days that occurred in November and December were the temperatures exceeded any high that had been previously recorded over a ten year period. The meaning of this interpretation will be largely dependant on the question you are trying to answer with this visualization. This is not the only way to represent this data as you may opt to show the highest recorded temperature for each individual day over the course of ten years and use that to identify individual days after 2015 that have exceeded those previously set record highs and lows. If anything doing this would probably give you a clearer picture of how the year 2015 is measuring up in terms of records temperatures (the solution shouldn't be too different).
[ { "code": null, "e": 852, "s": 172, "text": "This post is based off an assignment from a Coursera course, 'Applied Plotting, Charting & Data Representation in Python'. This is part 2 of the University of Michigan's Applied Data Science with Python Specialization. This is meant to run you through one of my solutions to one of the assignments explained in a way that makes it easier to understand for someone with limited Python experience. Please note that if you are taking this course, you can learn from my solution but it is in your best interest not to copy it as it will only hurt you in the long run. Additionally, there is a better solution which gives you a better visualization for the purposes of the assignment." }, { "code": null, "e": 865, "s": 852, "text": "The Scenario" }, { "code": null, "e": 1227, "s": 865, "text": "Imagine you are measuring temperature in weather stations in a particular city or region. From my research, albeit limited, this weather is often measured to tenths of a degree (for whatever reason). You start collecting data over a ten year period, measuring daily and monthly maximum and minimum temperatures and this data is compiled on an excel spreadsheet." }, { "code": null, "e": 1713, "s": 1227, "text": "A new year passes, let's assume its 2015 and you continue measuring the temperature as you always do. You have been observing record highs and lows and heatwaves around the country during 2015. You start wondering how temperatures of this year are measuring against temperatures over the previous 10 years. You want to answer the question; how do the record highs and lows for each month that has passed this year measure against record highs for each month set over the last 10 years." }, { "code": null, "e": 2076, "s": 1713, "text": "You decide that the best way to present these findings is through a visualization of a line chart that will show the record highs and lows of each month over the last 10 years. To answer your current question you also want to superimpose a scatterplot of the record highs and lows from 2015 that either exceed the record lows or highs set over the last 10 years." }, { "code": null, "e": 2085, "s": 2076, "text": "The Code" }, { "code": null, "e": 2392, "s": 2085, "text": "So now you have a question and you know what you need to develop to answer your question. You decide to write out the code in Python. In order to help with your visualization you will need to import certain libraries that will help you perform many complex actions without writing lengthy and complex code." }, { "code": null, "e": 2429, "s": 2392, "text": "Importing Libraries and reading data" }, { "code": null, "e": 2645, "s": 2429, "text": "import datetimeimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt#read data from a csvdf = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')" }, { "code": null, "e": 2911, "s": 2645, "text": "For this visualization we would want to use the datetime library to stipulate a cut-off date so that we can divide the data into 2 tables; i.) temperature measurements between 2005 and the 31st of December 2014 and ii.) measurements occurring after the cutoff date." }, { "code": null, "e": 3045, "s": 2911, "text": "Numpy which is short for numerical python will allow us to carry out mathematical functions on multi-dimensional matrices and arrays." }, { "code": null, "e": 3333, "s": 3045, "text": "The pandas and library will allow us to carry out manipulations and calculations on the dataframes we will be interacting with. While matplotlib will be used for plotting our graphs. We use the aliases pd and plt (and np for numpy) to interact with these libraries for ease of reference." }, { "code": null, "e": 3537, "s": 3333, "text": "The next line of code then uses the read_csv module included in the pandas library to read the data we want from our csv. This is automatically saved as a pandas dataframe — we named this dataframe 'df'." }, { "code": null, "e": 3733, "s": 3537, "text": "At this point I like to use the head method to read the top 5 rows of our dataframe. This helps me understand what columns the dataframe has and just get a better feel of what the data looks like" }, { "code": null, "e": 3743, "s": 3733, "text": "df.head()" }, { "code": null, "e": 3944, "s": 3743, "text": "Now we know that the dataframe has 4 columns; ID, Date, Element, and Data_Value. There is also an index column listing the row number starting from zero. The dataframe contains a total of 165 085 rows" }, { "code": null, "e": 4185, "s": 3944, "text": "You notice from this that the measurements are categorised as either TMAX (the maximum temperature) and TMIN (the minimum temperature). The ID shows the station identification code which presumably shows which station took the measurements." }, { "code": null, "e": 4209, "s": 4185, "text": "Removing leap year data" }, { "code": null, "e": 4556, "s": 4209, "text": "Since 2015 is not a leap year, we want to remove all leap year data. In the event that a leap year had record high/low temperatures over the 10 year period as this could have an impact on record high/low temperature measurements. Since 2015 would have 1 less day than years with leap years (2008 and 2012) this wouldn’t be an accurate comparison." }, { "code": null, "e": 4887, "s": 4556, "text": "#converting date to date timestampdf['Date'] = pd.DatetimeIndex(df['Date']).datelis = ['2922008','2922012'] #list of 29 Febs appearing in each leap yeardates = [datetime.datetime.strptime(i, '%d%m%Y').date() for i in lis] #converting into list of datetime.date objectsdf = df[~df['Date'].isin(dates)] #remove all 29 February dates" }, { "code": null, "e": 5163, "s": 4887, "text": "In this code we convert the entire Date column using the DatetimeIndex module. This converts the Date column into a timestamp object. We then specify with .date that we want to return a datetime.date object (‘the date time of the timestamp without the timezone information’)." }, { "code": null, "e": 5411, "s": 5163, "text": "Using the datetime.date library, we convert our list of leap year dates into a datetime.date object. We then only select the dates that are not listed as leap year dates (under the list ‘lis’) and filter out all leap year dates from our dataframe." }, { "code": null, "e": 5468, "s": 5411, "text": "Dates, cutoff dates and dividing dataframe into 2 tables" }, { "code": null, "e": 5730, "s": 5468, "text": "Next, since we have ensured that all the Dates in the date column are the same data type (that they are all dates and not string for example), we want to divide the data into two tables based on whether the measurements occurred before or after the cutoff date." }, { "code": null, "e": 6226, "s": 5730, "text": "#creating a separate column for the monthdf['Month'] = pd.DatetimeIndex(df['Date']).month#we are colleting dates between 2005 - 2014, so want to remove any data from dates after 31 Dec 2014#creating datetime.date format of cutoff datea= '31122014'#converting a string into datetime.date objectcutoff_date = datetime.datetime.strptime(a,'%d%m%Y').date()#dataframe for values after 31 Dec 2014df2 = df[df['Date'] <= cutoff_date]#returning dates before cutoff datedf3 = df[df['Date'] > cutoff_date]" }, { "code": null, "e": 6394, "s": 6226, "text": "Since we want our table to show us monthly highs over a ten year period we also want to create a month column. Listing only the month of the Date column as an integer." }, { "code": null, "e": 6589, "s": 6394, "text": "For the cutoff date we added the date as an integer and used the datetime.date module to convert the string into a datetime.date object (similar to our Date column), in 'date/month/year' format." }, { "code": null, "e": 6771, "s": 6589, "text": "We then proceed to create 2 new dataframes; df2- which contains all the measurements before or on the cutoff date and df3- which contains all the measurements after the cutoff date." }, { "code": null, "e": 6801, "s": 6771, "text": "Finding record highs and lows" }, { "code": null, "e": 6940, "s": 6801, "text": "Now we need to answer the question, how do we find the record high and low temperatures over the ten years between 2005 and 2014 by month." }, { "code": null, "e": 7692, "s": 6940, "text": "From looking at our dataframe with the head method we already know that there is a column that specifies whether a measurement is recorded as a minimum of maximum temperature. Additionally, since we have created a month column, we know that this contains the month in which the measurement was recorded. In order to help us carry out this computation we will use groupby. This is a pandas module that allows us to split data into groups based on one or more criterions. This can be combined with the aggregation method, 'aggregate' which lets us carry out aggregations on our data such as returning the maximum or minimum values. Combined with groupby we can identify the maximum and minimum values between the groups we have created grouped by month." }, { "code": null, "e": 7868, "s": 7692, "text": "df_min = df2[df2['Element'] =='TMIN'].groupby('Month').aggregate({'Data_Value':np.min})df_max = df2[df2['Element'] == 'TMAX'].groupby('Month').aggregate({'Data_Value':np.max})" }, { "code": null, "e": 8221, "s": 7868, "text": "In this code, we created 2 dataframes; df_min- here we filtered measurements classified as minimum temperatures, grouped them by month and found the lowest temperature for each month over the ten year period and df_max- we filtered measurements classified as maximum temperatures, grouped them by month and found the highest temperature for each month." }, { "code": null, "e": 8247, "s": 8221, "text": "The Visualization process" }, { "code": null, "e": 8328, "s": 8247, "text": "Now we want to start making use of the matplotlib library to visualize our data." }, { "code": null, "e": 8363, "s": 8328, "text": "plt.plot(df_max, '-o',df_min,'-o')" }, { "code": null, "e": 8633, "s": 8363, "text": "We start off by plotting the record highs and lows over the ten year period as a line chart. These two will automatically be plotted in different colours. We used '-o' to identify each data value plotted on this chart, this is represented as a circle on our line chart." }, { "code": null, "e": 8908, "s": 8633, "text": "For visualization purposes we want to shade the area between the highest and lowest point grey. I believe this will make the data easier on the eye, helping you focus on the highest and lowest temperatures and the variability of record temperatures over the ten year period." }, { "code": null, "e": 9025, "s": 8908, "text": "x = df_max.index.valuesplt.fill_between(x,df_min.values.flatten(),df_max.values.flatten(), color='grey',alpha='0.5')" }, { "code": null, "e": 9252, "s": 9025, "text": "We use the fill_between module to fill the area between the two lines. For fill_between to function you need to have the length of the x coordinates that you want to fill and the coordinates/values from both df_min and df_max." }, { "code": null, "e": 9474, "s": 9252, "text": "To find the length of the x coordinates we have created an x variable that contains the values of the index of df_max. This will return an numpy array containing the numbers 1–12 corresponding with the months of the year." }, { "code": null, "e": 9868, "s": 9474, "text": "Since df_min and df_max are dataframes and we only want the values in the dataframes (the temperatures) of both df_min and df_max. However, this will return an array of arrays whereas we need a one dimensional array to use the fill_between module. We then opt to flatten the array into a one dimensional array. Color and alpha simply allow us to specify the colour and hue of the fill_between." }, { "code": null, "e": 9895, "s": 9868, "text": "Super imposing scatterplot" }, { "code": null, "e": 10149, "s": 9895, "text": "To answer our central question we need to start looking at the recordings after the cutoff date. In order to do this we need to group the data by month and look for measurements that exceed the lowest and highest recorded temperatures on our line chart." }, { "code": null, "e": 10497, "s": 10149, "text": "#superimpose scatterplotdf3_max = df3[df3['Data_Value'] > df3['Month'].map(df_max['Data_Value'])]df4_min = df3[df3['Data_Value'] < df3['Month'].map(df_min['Data_Value'])]plt.scatter(df3_max.Month.tolist(),df3_max['Data_Value'],s=10,c='red') #values over maxplt.scatter(df4_min.Month.tolist(),df4_min['Data_Value'],s=10,c='black') #values under min" }, { "code": null, "e": 11091, "s": 10497, "text": "In order to compare each temperature grouped my month to the lowest and highest temperatures of each month, we use the map function to iterate through the df3 database, identify the month of each column and compare the temperature listed under the Data_Value column to the value listed for that particular month in the df_min and df_max dataframes (depending on whether we are looking at the minimum or maximum temperatures). If the value is higher or lower than the highest and lowest temperatures recorded over the ten year period, we add that row to our new dataframes; df3_max and df4_min." }, { "code": null, "e": 11371, "s": 11091, "text": "Now we want to superimpose our scatterplot over our line chart. For the scatter plot we need to specify the x (months) and y axis (data values). We also want to specify the size of the circle representing each value and the colour to differentiate it from the line chart circles." }, { "code": null, "e": 11408, "s": 11371, "text": "Making the chart easier to interpret" }, { "code": null, "e": 11600, "s": 11408, "text": "If you are planning on showing this chart to anyone else, it is important to make sure that the chart is easy to interpret and shows what you want it to show without misleading your audience." }, { "code": null, "e": 11712, "s": 11600, "text": "The first problem with the chart as it stands is that the x-axis incrementing in 2s skipping odd number months." }, { "code": null, "e": 11886, "s": 11712, "text": "plt.xticks(list(df_max.index),['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec']) #we want to show all the x values and rename according to the month" }, { "code": null, "e": 11995, "s": 11886, "text": "In order to rectify this I specify the xticks and rename them as abbreviations of the months they represent." }, { "code": null, "e": 12142, "s": 11995, "text": "The next issue pertains to how the temperature is recorded. We would want to show the temperature in degrees celsius and no as tenths of a degree." }, { "code": null, "e": 12331, "s": 12142, "text": "df_max['Data_Value'] = df_max['Data_Value']/10df_min['Data_Value'] = df_min['Data_Value']/10df4_min['Data_Value'] = df4_min['Data_Value']/10df3_max['Data_Value'] = df3_max['Data_Value']/10" }, { "code": null, "e": 12429, "s": 12331, "text": "I then divide all the temperature values by ten to convert tenths of a degree to degrees celsius." }, { "code": null, "e": 12607, "s": 12429, "text": "The final issue is that the graph is not labelled, and the size makes it difficult for us to know how many days in were recorded as exceeded the monthly high or low temperature." }, { "code": null, "e": 12863, "s": 12607, "text": "plt.title('Min and Max temperatures in Ann Arbor Michigan United States between 2005-2015', fontsize=20)plt.xlabel('Years', fontsize=20)plt.ylabel('Temperatures', fontsize=20)fig = plt.gcf()fig.set_size_inches(20,10)plt.tick_params(labelsize=20)plt.show()" }, { "code": null, "e": 13134, "s": 12863, "text": "I then proceed to enlarge the chart by first getting the current figure (gcf), saving it as fig and setting the size of fig in inches. Since this will only enlarge the figure I need to also enlarge the x and y tick parameters and the font size of both the y and x label." }, { "code": null, "e": 13616, "s": 13134, "text": "From this chart we get identify that we had about 6 days in February were the minimum temperatures dropped below the lowest minimum temperature recorded between 2005 and 2014 for the month of February and 2 other days that occurred in November and December were the temperatures exceeded any high that had been previously recorded over a ten year period. The meaning of this interpretation will be largely dependant on the question you are trying to answer with this visualization." } ]
Groovy - Logical Operators
Logical operators are used to evaluate Boolean expressions. Following are the logical operators available in Groovy − The following code snippet shows how the various operators can be used. class Example { static void main(String[] args) { boolean x = true; boolean y = false; boolean z = true; println(x&&y); println(x&&z); println(x||z); println(x||y); println(!x); } } When we run the above program, we will get the following result. It can be seen that the results are as expected from the description of the operators as shown above. false true true true false 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2356, "s": 2238, "text": "Logical operators are used to evaluate Boolean expressions. Following are the logical operators available in Groovy −" }, { "code": null, "e": 2428, "s": 2356, "text": "The following code snippet shows how the various operators can be used." }, { "code": null, "e": 2681, "s": 2428, "text": "class Example { \n static void main(String[] args) { \n boolean x = true; \n boolean y = false; \n boolean z = true; \n\t\t\n println(x&&y); \n println(x&&z); \n\t\t\n println(x||z); \n println(x||y); \n println(!x); \n } \n}" }, { "code": null, "e": 2848, "s": 2681, "text": "When we run the above program, we will get the following result. It can be seen that the results are as expected from the description of the operators as shown above." }, { "code": null, "e": 2880, "s": 2848, "text": "false \ntrue \ntrue \ntrue \nfalse\n" }, { "code": null, "e": 2913, "s": 2880, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 2931, "s": 2913, "text": " Krishna Sakinala" }, { "code": null, "e": 2966, "s": 2931, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2984, "s": 2966, "text": " Packt Publishing" }, { "code": null, "e": 2991, "s": 2984, "text": " Print" }, { "code": null, "e": 3002, "s": 2991, "text": " Add Notes" } ]
Spam or Ham: Introduction to Natural Language Processing Part 2 | by Mandy Gu | Towards Data Science
This is the second part of my series covering the basics of natural language processing. If you haven’t read the first part yet, you can find it here. In this part, we will go through an end to end walk through of building a very simple text classifier in Python 3. We will be using the SMS Spam Collection Dataset which tags 5,574 text messages based on whether they are “spam” or “ham” (not spam). Our goal is to build a predictive model which will determine whether a text message is spam or ham. For the code, see here. After importing the data, I changed the column names to be more descriptive. import pandas as pddata = pd.read_csv("spam.csv", encoding = "latin-1")data = data[['v1', 'v2']]data = data.rename(columns = {'v1': 'label', 'v2': 'text'}) The first few entries of our data set looks like this: From briefly exploring our data, we gain some insight into the text that we are working with: colloquial English. This particular data set also has 87% messages labelled as “ham” and 13% messages labelled as “spam”. The class imbalance will become important later when assessing the strength of our classifier. Cleaning textual data is a little different than regular data cleaning. There is a much heavier emphasis on text normalisation than removing outliers or leverage points. As per Wikipedia: Text normalisation is the process of transforming text into a single canonical form that it might not have had before. When used correctly, it reduces noise, groups terms with similar semantic meanings and reduces computational costs by giving us a smaller matrix to work with. I will go through several common methods of normalisation, but keep in mind that it is not always a good idea to use them. Reserving the judgement for when to use what is the human component in data science. No Free Lunch Theorem: there is never one solution that works well with everything. Try it with your data set to determine if it works for your special use case. Case normalisation Does casing provide any relevant information as to whether a text message is spam or ham? Is HELLO semantically the same as hello or Hello? You could argue based on prior knowledge that spam messages tend to use more upper casing to capture the readers’ attention. Or, you could argue that it makes no difference and that all words should be reduced to the same case. Removing stop words Stop words are common words which do not add predictive value because they are found everywhere. They are analogous to the villain’s remark from the Incredibles movie that: when everyone is a super, no one will be [a super]. Some commonly agreed upon stop words from the English language: I a because to There is a lot of debate over when removing stop words is a good idea. This practice is used in many information retrieval tasks (such as search engine querying), but can be detrimental when syntactical understanding of language is required. Removing punctuations, special symbols Once again, we must consider the importance of punctuation and special symbols to our classifier’s predictive capabilities. We must also consider the importance of each symbol’s functionality. For example, the apostrophe allows us to define contractions and differentiate between words like it’s and its. Lemmatising/Stemming Both of these techniques reduce inflection forms to normalise words with the same lemma. The difference between lemmatising and stemming is that lemmatising performs this reduction by considering the context of the word while stemming does not. The drawback is that there is currently no lemmatiser or stemmer with a very high accuracy rate. Less common normalisation techniques include error correction, converting words to their parts of speech or mapping synonyms using a synonym dictionary. With the exception of error correction and synonym mapping, there are many pre-built tools for the other normalisation techniques, all of which can be found in the nltk library. For this particular classification problem, we will only use case normalisation. The rationale is that it will be hard to apply a stemmer or lemmatiser onto colloquial English and that since the text messages are so short, removing stop words might not leave us with much to work with. def review_messages(msg): # converting messages to lowercase msg = msg.lower() return msg For reference, this function does case normalisation, removing stop words and stemming. from nltk import stemfrom nltk.corpus import stopwordsstemmer = stem.SnowballStemmer('english')stopwords = set(stopwords.words('english'))def alternative_review_messages(msg): # converting messages to lowercase msg = msg.lower() # removing stopwords msg = [word for word in msg.split() if word not in stopwords] # using a stemmer msg = " ".join([stemmer.stem(word) for word in msg]) return msg We apply the first function to normalise the text messages. data['text'] = data['text'].apply(review_messages) In the first part of this series, we explored the most basic type of word vectorizer, the Bag of Words Model, which will not work very well for our Spam or Ham classifier due to its simplicity. Instead, we will use the TF-IDF vectorizer (Term Frequency — Inverse Document Frequency), a similar embedding technique which takes into account the importance of each term to document. While most vectorizers have their unique advantages, it is not always clear which one to use. In our case, the TF-IDF vectorizer was chosen for its simplicity and efficiency in vectorizing documents such as text messages. TF-IDF vectorizes documents by calculating a TF-IDF statistic between the document and each term in the vocabulary. The document vector is constructed by using each statistic as an element in the vector. The TF-IDF statistic for term i in document j is calculated as follows: After settling with TF-IDF, we must decide the granularity of our vectorizer. A popular alternative to assigning each word as its own term is to use a tokenizer. A tokenizer splits documents into tokens (thus assigning each token to its own term) based on white space and special characters. For example, the phrase what’s going on might be split into what, ‘s, going, on. The tokenizer is able to extract more information than word level analysers. However, tokenizers do not work well with colloquial English and may encounter issues splitting URLs or emails. As such, we will use a word level analyser, which assigns each word to its own term. Before training the vectorizer, we split our data into a training set and a testing set. 10% of our data is allocated for testing. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(data['text'], data['label'], test_size = 0.1, random_state = 1)# training the vectorizer from sklearn.feature_extraction.text import TfidfVectorizervectorizer = TfidfVectorizer()X_train = vectorizer.fit_transform(X_train) The next step is to select the type of classifier to use. Typically in this step, we will choose several candidate classifiers and evaluate them against the testing set to see which one works the best. To keep things, we can assume that a Support Vector Machine works well enough. The objective of the SVM is to find The C term is used as a regularization to influence the objective function. A larger value of C typically results in a hyperplane with a smaller margin as it gives more emphasis to the accuracy rather than the margin width. Parameters such as this can be precisely tuned via grid search. from sklearn import svmsvm = svm.SVC(C=1000)svm.fit(X_train, y_train) Now, let’s test it. from sklearn.metrics import confusion_matrixX_test = vectorizer.transform(X_test)y_pred = svm.predict(X_test)print(confusion_matrix(y_test, y_pred)) The results aren’t bad at all! We have no false positives and around 15% false negatives. Let’s test it against a few new examples. def pred(msg): msg = vectorizer.transform([msg]) prediction = svm.predict(msg) return prediction[0] Looks right to me :) I hope you enjoyed Part 2 of this tutorial. Once again, the entire code peice can be found here. Check out Part 3! If you enjoyed this article, check out my other articles on Data Science, Math and Programming. Follow me on Medium for the latest updates. 😃 I am also building a comprehensive set of free Data Science lessons and practice problems at www.dscrashcourse.com as a hobby project. If you want to support my writing, consider using my affiliate link the next time you sign up for a Coursera course. Full disclosure — I receive commission for every enrollment, but it comes at no extra cost for you. Thank you again for reading! 📕
[ { "code": null, "e": 323, "s": 172, "text": "This is the second part of my series covering the basics of natural language processing. If you haven’t read the first part yet, you can find it here." }, { "code": null, "e": 572, "s": 323, "text": "In this part, we will go through an end to end walk through of building a very simple text classifier in Python 3. We will be using the SMS Spam Collection Dataset which tags 5,574 text messages based on whether they are “spam” or “ham” (not spam)." }, { "code": null, "e": 696, "s": 572, "text": "Our goal is to build a predictive model which will determine whether a text message is spam or ham. For the code, see here." }, { "code": null, "e": 773, "s": 696, "text": "After importing the data, I changed the column names to be more descriptive." }, { "code": null, "e": 929, "s": 773, "text": "import pandas as pddata = pd.read_csv(\"spam.csv\", encoding = \"latin-1\")data = data[['v1', 'v2']]data = data.rename(columns = {'v1': 'label', 'v2': 'text'})" }, { "code": null, "e": 984, "s": 929, "text": "The first few entries of our data set looks like this:" }, { "code": null, "e": 1295, "s": 984, "text": "From briefly exploring our data, we gain some insight into the text that we are working with: colloquial English. This particular data set also has 87% messages labelled as “ham” and 13% messages labelled as “spam”. The class imbalance will become important later when assessing the strength of our classifier." }, { "code": null, "e": 1465, "s": 1295, "text": "Cleaning textual data is a little different than regular data cleaning. There is a much heavier emphasis on text normalisation than removing outliers or leverage points." }, { "code": null, "e": 1483, "s": 1465, "text": "As per Wikipedia:" }, { "code": null, "e": 1602, "s": 1483, "text": "Text normalisation is the process of transforming text into a single canonical form that it might not have had before." }, { "code": null, "e": 1761, "s": 1602, "text": "When used correctly, it reduces noise, groups terms with similar semantic meanings and reduces computational costs by giving us a smaller matrix to work with." }, { "code": null, "e": 1969, "s": 1761, "text": "I will go through several common methods of normalisation, but keep in mind that it is not always a good idea to use them. Reserving the judgement for when to use what is the human component in data science." }, { "code": null, "e": 2131, "s": 1969, "text": "No Free Lunch Theorem: there is never one solution that works well with everything. Try it with your data set to determine if it works for your special use case." }, { "code": null, "e": 2150, "s": 2131, "text": "Case normalisation" }, { "code": null, "e": 2518, "s": 2150, "text": "Does casing provide any relevant information as to whether a text message is spam or ham? Is HELLO semantically the same as hello or Hello? You could argue based on prior knowledge that spam messages tend to use more upper casing to capture the readers’ attention. Or, you could argue that it makes no difference and that all words should be reduced to the same case." }, { "code": null, "e": 2538, "s": 2518, "text": "Removing stop words" }, { "code": null, "e": 2711, "s": 2538, "text": "Stop words are common words which do not add predictive value because they are found everywhere. They are analogous to the villain’s remark from the Incredibles movie that:" }, { "code": null, "e": 2763, "s": 2711, "text": "when everyone is a super, no one will be [a super]." }, { "code": null, "e": 2827, "s": 2763, "text": "Some commonly agreed upon stop words from the English language:" }, { "code": null, "e": 2829, "s": 2827, "text": "I" }, { "code": null, "e": 2831, "s": 2829, "text": "a" }, { "code": null, "e": 2839, "s": 2831, "text": "because" }, { "code": null, "e": 2842, "s": 2839, "text": "to" }, { "code": null, "e": 3084, "s": 2842, "text": "There is a lot of debate over when removing stop words is a good idea. This practice is used in many information retrieval tasks (such as search engine querying), but can be detrimental when syntactical understanding of language is required." }, { "code": null, "e": 3123, "s": 3084, "text": "Removing punctuations, special symbols" }, { "code": null, "e": 3428, "s": 3123, "text": "Once again, we must consider the importance of punctuation and special symbols to our classifier’s predictive capabilities. We must also consider the importance of each symbol’s functionality. For example, the apostrophe allows us to define contractions and differentiate between words like it’s and its." }, { "code": null, "e": 3449, "s": 3428, "text": "Lemmatising/Stemming" }, { "code": null, "e": 3791, "s": 3449, "text": "Both of these techniques reduce inflection forms to normalise words with the same lemma. The difference between lemmatising and stemming is that lemmatising performs this reduction by considering the context of the word while stemming does not. The drawback is that there is currently no lemmatiser or stemmer with a very high accuracy rate." }, { "code": null, "e": 4122, "s": 3791, "text": "Less common normalisation techniques include error correction, converting words to their parts of speech or mapping synonyms using a synonym dictionary. With the exception of error correction and synonym mapping, there are many pre-built tools for the other normalisation techniques, all of which can be found in the nltk library." }, { "code": null, "e": 4408, "s": 4122, "text": "For this particular classification problem, we will only use case normalisation. The rationale is that it will be hard to apply a stemmer or lemmatiser onto colloquial English and that since the text messages are so short, removing stop words might not leave us with much to work with." }, { "code": null, "e": 4507, "s": 4408, "text": "def review_messages(msg): # converting messages to lowercase msg = msg.lower() return msg" }, { "code": null, "e": 4595, "s": 4507, "text": "For reference, this function does case normalisation, removing stop words and stemming." }, { "code": null, "e": 5010, "s": 4595, "text": "from nltk import stemfrom nltk.corpus import stopwordsstemmer = stem.SnowballStemmer('english')stopwords = set(stopwords.words('english'))def alternative_review_messages(msg): # converting messages to lowercase msg = msg.lower() # removing stopwords msg = [word for word in msg.split() if word not in stopwords] # using a stemmer msg = \" \".join([stemmer.stem(word) for word in msg]) return msg" }, { "code": null, "e": 5070, "s": 5010, "text": "We apply the first function to normalise the text messages." }, { "code": null, "e": 5121, "s": 5070, "text": "data['text'] = data['text'].apply(review_messages)" }, { "code": null, "e": 5315, "s": 5121, "text": "In the first part of this series, we explored the most basic type of word vectorizer, the Bag of Words Model, which will not work very well for our Spam or Ham classifier due to its simplicity." }, { "code": null, "e": 5501, "s": 5315, "text": "Instead, we will use the TF-IDF vectorizer (Term Frequency — Inverse Document Frequency), a similar embedding technique which takes into account the importance of each term to document." }, { "code": null, "e": 5723, "s": 5501, "text": "While most vectorizers have their unique advantages, it is not always clear which one to use. In our case, the TF-IDF vectorizer was chosen for its simplicity and efficiency in vectorizing documents such as text messages." }, { "code": null, "e": 5927, "s": 5723, "text": "TF-IDF vectorizes documents by calculating a TF-IDF statistic between the document and each term in the vocabulary. The document vector is constructed by using each statistic as an element in the vector." }, { "code": null, "e": 5999, "s": 5927, "text": "The TF-IDF statistic for term i in document j is calculated as follows:" }, { "code": null, "e": 6291, "s": 5999, "text": "After settling with TF-IDF, we must decide the granularity of our vectorizer. A popular alternative to assigning each word as its own term is to use a tokenizer. A tokenizer splits documents into tokens (thus assigning each token to its own term) based on white space and special characters." }, { "code": null, "e": 6372, "s": 6291, "text": "For example, the phrase what’s going on might be split into what, ‘s, going, on." }, { "code": null, "e": 6646, "s": 6372, "text": "The tokenizer is able to extract more information than word level analysers. However, tokenizers do not work well with colloquial English and may encounter issues splitting URLs or emails. As such, we will use a word level analyser, which assigns each word to its own term." }, { "code": null, "e": 6777, "s": 6646, "text": "Before training the vectorizer, we split our data into a training set and a testing set. 10% of our data is allocated for testing." }, { "code": null, "e": 7103, "s": 6777, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(data['text'], data['label'], test_size = 0.1, random_state = 1)# training the vectorizer from sklearn.feature_extraction.text import TfidfVectorizervectorizer = TfidfVectorizer()X_train = vectorizer.fit_transform(X_train)" }, { "code": null, "e": 7384, "s": 7103, "text": "The next step is to select the type of classifier to use. Typically in this step, we will choose several candidate classifiers and evaluate them against the testing set to see which one works the best. To keep things, we can assume that a Support Vector Machine works well enough." }, { "code": null, "e": 7420, "s": 7384, "text": "The objective of the SVM is to find" }, { "code": null, "e": 7496, "s": 7420, "text": "The C term is used as a regularization to influence the objective function." }, { "code": null, "e": 7708, "s": 7496, "text": "A larger value of C typically results in a hyperplane with a smaller margin as it gives more emphasis to the accuracy rather than the margin width. Parameters such as this can be precisely tuned via grid search." }, { "code": null, "e": 7778, "s": 7708, "text": "from sklearn import svmsvm = svm.SVC(C=1000)svm.fit(X_train, y_train)" }, { "code": null, "e": 7798, "s": 7778, "text": "Now, let’s test it." }, { "code": null, "e": 7947, "s": 7798, "text": "from sklearn.metrics import confusion_matrixX_test = vectorizer.transform(X_test)y_pred = svm.predict(X_test)print(confusion_matrix(y_test, y_pred))" }, { "code": null, "e": 8037, "s": 7947, "text": "The results aren’t bad at all! We have no false positives and around 15% false negatives." }, { "code": null, "e": 8079, "s": 8037, "text": "Let’s test it against a few new examples." }, { "code": null, "e": 8188, "s": 8079, "text": "def pred(msg): msg = vectorizer.transform([msg]) prediction = svm.predict(msg) return prediction[0]" }, { "code": null, "e": 8209, "s": 8188, "text": "Looks right to me :)" }, { "code": null, "e": 8306, "s": 8209, "text": "I hope you enjoyed Part 2 of this tutorial. Once again, the entire code peice can be found here." }, { "code": null, "e": 8324, "s": 8306, "text": "Check out Part 3!" }, { "code": null, "e": 8466, "s": 8324, "text": "If you enjoyed this article, check out my other articles on Data Science, Math and Programming. Follow me on Medium for the latest updates. 😃" }, { "code": null, "e": 8601, "s": 8466, "text": "I am also building a comprehensive set of free Data Science lessons and practice problems at www.dscrashcourse.com as a hobby project." }, { "code": null, "e": 8818, "s": 8601, "text": "If you want to support my writing, consider using my affiliate link the next time you sign up for a Coursera course. Full disclosure — I receive commission for every enrollment, but it comes at no extra cost for you." } ]
Check if a HashSet contains the specified element in C#
To check if a HashSet contains the specified element, the code is as follows − Live Demo using System; using System.Collections.Generic; public class Demo { public static void Main(){ HashSet<int> set1 = new HashSet<int>(); set1.Add(25); set1.Add(50); set1.Add(75); set1.Add(100); set1.Add(125); set1.Add(150); Console.WriteLine("Elements in HashSet1"); foreach(int val in set1){ Console.WriteLine(val); } HashSet<int> set2 = new HashSet<int>(); set2.Add(30); set2.Add(60); set2.Add(100); set2.Add(150); set2.Add(200); set2.Add(250); Console.WriteLine("Elements in HashSet2"); foreach(int val in set2){ Console.WriteLine(val); } Console.WriteLine("Do they share common elements? "+set1.Overlaps(set2)); Console.WriteLine("Does HashSet1 has element 60? "+set1.Contains(60)); Console.WriteLine("Does HashSet2 has element 60? "+set2.Contains(60)); } } This will produce the following output − Elements in HashSet1 25 50 75 100 125 150 Elements in HashSet2 30 60 100 150 200 250 Do they share common elements? True Does HashSet1 has element 60? False Does HashSet2 has element 60? True Live Demo Let us now see another example; using System; using System.Collections.Generic; public class Demo { public static void Main(){ HashSet<string> hashSet = new HashSet<string>(); hashSet.Add("Tim"); hashSet.Add("Jack"); hashSet.Add("Matt"); hashSet.Add("Steve"); hashSet.Add("David"); hashSet.Add("Kane"); hashSet.Add("Gary"); Console.WriteLine("Elements in HashSet"); foreach(string val in hashSet){ Console.WriteLine(val); } if (hashSet.Contains("Matt")) Console.WriteLine("The element Matt is in the HashSet"); else Console.WriteLine("The element Matt is not in the HashSet"); } } This will produce the following output − Elements in HashSet Tim Jack Matt Steve David Kane Gary The element Matt is in the HashSet
[ { "code": null, "e": 1141, "s": 1062, "text": "To check if a HashSet contains the specified element, the code is as follows −" }, { "code": null, "e": 1152, "s": 1141, "text": " Live Demo" }, { "code": null, "e": 2074, "s": 1152, "text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(){\n HashSet<int> set1 = new HashSet<int>();\n set1.Add(25);\n set1.Add(50);\n set1.Add(75);\n set1.Add(100);\n set1.Add(125);\n set1.Add(150);\n Console.WriteLine(\"Elements in HashSet1\");\n foreach(int val in set1){\n Console.WriteLine(val);\n }\n HashSet<int> set2 = new HashSet<int>();\n set2.Add(30);\n set2.Add(60);\n set2.Add(100);\n set2.Add(150);\n set2.Add(200);\n set2.Add(250);\n Console.WriteLine(\"Elements in HashSet2\");\n foreach(int val in set2){\n Console.WriteLine(val);\n }\n Console.WriteLine(\"Do they share common elements? \"+set1.Overlaps(set2));\n Console.WriteLine(\"Does HashSet1 has element 60? \"+set1.Contains(60));\n Console.WriteLine(\"Does HashSet2 has element 60? \"+set2.Contains(60));\n }\n}" }, { "code": null, "e": 2115, "s": 2074, "text": "This will produce the following output −" }, { "code": null, "e": 2307, "s": 2115, "text": "Elements in HashSet1\n25\n50\n75\n100\n125\n150\nElements in HashSet2\n30\n60\n100\n150\n200\n250\nDo they share common elements? True\nDoes HashSet1 has element 60? False\nDoes HashSet2 has element 60? True" }, { "code": null, "e": 2318, "s": 2307, "text": " Live Demo" }, { "code": null, "e": 3010, "s": 2318, "text": "Let us now see another example;\nusing System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(){\n HashSet<string> hashSet = new HashSet<string>();\n hashSet.Add(\"Tim\");\n hashSet.Add(\"Jack\");\n hashSet.Add(\"Matt\");\n hashSet.Add(\"Steve\");\n hashSet.Add(\"David\");\n hashSet.Add(\"Kane\");\n hashSet.Add(\"Gary\");\n Console.WriteLine(\"Elements in HashSet\");\n foreach(string val in hashSet){\n Console.WriteLine(val);\n }\n if (hashSet.Contains(\"Matt\"))\n Console.WriteLine(\"The element Matt is in the HashSet\");\n else\n Console.WriteLine(\"The element Matt is not in the HashSet\");\n }\n}" }, { "code": null, "e": 3051, "s": 3010, "text": "This will produce the following output −" }, { "code": null, "e": 3142, "s": 3051, "text": "Elements in HashSet\nTim\nJack\nMatt\nSteve\nDavid\nKane\nGary\nThe element Matt is in the HashSet" } ]
How to add legend to imshow() in Matplotlib?
To add legend to imshow() in Matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Create random data using numpy. Initialize a color map. Get the unique data points from sample data, step 2. Plot each color with different labels and color, to place on the legend. Place a legend at the upper right corner within a box. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt, cm plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True data = np.random.rand(3, 3) cmap = cm.YlOrBr unique_data = np.unique(data) i = 0 for entry in unique_data: mycolor = cmap(entry * 255 / (max(unique_data) - min(unique_data))) plt.plot(0, 0, "-", color=mycolor, label="%d"%i) i += 1 plt.imshow(data, cmap=cmap) plt.legend(loc="upper right", bbox_to_anchor=(1.25, 1.0)) plt.show()
[ { "code": null, "e": 1137, "s": 1062, "text": "To add legend to imshow() in Matplotlib, we can take the following steps −" }, { "code": null, "e": 1213, "s": 1137, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1245, "s": 1213, "text": "Create random data using numpy." }, { "code": null, "e": 1269, "s": 1245, "text": "Initialize a color map." }, { "code": null, "e": 1322, "s": 1269, "text": "Get the unique data points from sample data, step 2." }, { "code": null, "e": 1395, "s": 1322, "text": "Plot each color with different labels and color, to place on the legend." }, { "code": null, "e": 1450, "s": 1395, "text": "Place a legend at the upper right corner within a box." }, { "code": null, "e": 1492, "s": 1450, "text": "To display the figure, use show() method." }, { "code": null, "e": 1981, "s": 1492, "text": "import numpy as np\nfrom matplotlib import pyplot as plt, cm\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndata = np.random.rand(3, 3)\ncmap = cm.YlOrBr\nunique_data = np.unique(data)\ni = 0\n\nfor entry in unique_data:\n mycolor = cmap(entry * 255 / (max(unique_data) - min(unique_data)))\n plt.plot(0, 0, \"-\", color=mycolor, label=\"%d\"%i)\n i += 1\n\nplt.imshow(data, cmap=cmap)\nplt.legend(loc=\"upper right\", bbox_to_anchor=(1.25, 1.0))\n\nplt.show()" } ]
Interactive Exploratory Data Analysis that Generates Python | by Roman Orac | Towards Data Science
Exploratory Data Analysis (EDA) is one of the first steps in the Data Science process — usually, it follows the data extraction. EDA helps us to get familiar with the data before we proceed with modeling or decide to repeat the extraction step. EDA helps Data Scientists to: get familiar with the data find bugs in the data extraction process decide if the data needs cleaning decide what to do with the missing values if there are any visualize data distributions, etc. With Exploratory Data Analysis we get the “feel” for the data By reading this article you’ll get: A practical example of EDA in JupyterLab on Avocado dataset A code snippet of each interactive operation An efficient way to share your analysis with your colleagues In case you’ve missed my previous articles about this topic, see Mito — A Spreadsheet that Generates Python. In this article, we’ll analyze the avocado dataset - one of the more popular datasets on Kaggle — and show a few basic operations in the Exploratory Data Analysis. The avocado dataset contains historical data on avocado prices and sales volume in multiple US markets. You can download it from Kaggle. The original data stems from the HASS AVOCADO BOARD. The Kaggle dataset is licensed under the Open Database License (ODbL). We’ll analyze this dataset with the Mito extension for JupyterLab, which enables users to complete their EDA interactively inside JupyterLab, and have each edit generate the equivalent Python in the code cell below. First, we need to load the Mitosheet interactive environment in Jupyter Lab with this function: # make sure you have Mito installed before running this functionimport mitosheetmitosheet.sheet() These functions call an empty Mitosheet into the Jupyter Environment To load the data into the sheet, we can either pass in an existing Dataframe as an argument to the Mitosheet call: mitosheet.sheet(df) Or we can click the Import button in the toolbar and select a file from our local file system. When we select “avocado.csv” in the import menu, Mito will automatically turn the CSV file into a Dataframe and generate the equivalent Python in the code cell below: # Imported /Users/Downloads/avocado.csvavocado_csv = pd.read_csv(r’/Users/Downloads/avocado.csv’) The CSV file already has an index column, which appears in the Mitosheet as “Unnamed: 0”, so the first thing we want to do is delete this column, which we can do by clicking the delete column button in the toolbar. This will generate the equivalent Python in the code cell below. The code is also auto-documented: # Deleted column Unnamed: 0 from avocado_csvavocado_csv.drop('Unnamed: 0', axis=1, inplace=True) Let’s say we are interested in the different regions of avocados in the dataset. We can select the column menu for the “Region” column and go to the values tab. In the values tab, we can see: all the unique values in the column, the frequency of each of those values, and what percent of the total entries each value represents. From this distribution, it seems the avocados are equally distributed by region. We have decided that we want to only look at rows where the avocado’s region is “Albany.” We can select the Filter/Sort tab in the column menu and set a filter where the “region” column is exactly “Albany.” The generated code for this filter looks like this: # Filtered region in avocado_csvavocado_csv = avocado_csv[avocado_csv['region'] == 'Albany'] Now that we have filtered the dataset, we want to explore the values we are left within the “Date” column. First, let’s use the add column button in the toolbar. Next, let’s add a formula to this column that parses the month value from each of the date values in the “Date” column. =MONTH(Date) Once we have retrieved the month values in a new column, we can use a pivot table to count how many entries there are for each month and compare the aggregated counts. All we need to do is click the “Pivot” button in the toolbar and configure the table from the side menu that appears. This pivot table operation will generate the following Python code snippet: # Pivoted avocado_csv into df3unused_columns = avocado_csv.columns.difference(set(['Month']).union(set([])).union(set({'Month'})))tmp_df = avocado_csv.drop(unused_columns, axis=1)pivot_table = tmp_df.pivot_table( index=['Month'], values=['Month'], aggfunc={'Month': ['count']}) In the column menu, we can also apply a sort by the “Month count” column to see the list of counts for each month in descending order. Here we can see that for the filtered Albany entries, January has the most entries and June and September have the least entries. Finally, we can visualize the analysis by clicking the “Graph’ button in the toolbar. We can configure it in the side menu. You can download this visualization as PNG so that can share it with your colleagues. We can also copy the equivalent code for any visualization by clicking the “Copy Graph Code” button. The outputted code for this graph is: # Import plotly and create a figureimport plotly.graph_objects as gofig = go.Figure()# Add the bar chart traces to the graphfor column_header in ['Month']: fig.add_trace( go.Bar( x=df3[column_header], y=df3['Month count'], name=column_header ) )# Update the title and stacking mode of the graph# See Plotly documentation for customizations: https://plotly.com/python/reference/bar/fig.update_layout( xaxis_title='Month', yaxis_title='Month count', title='Month, Month count bar chart', barmode='group',)fig.show(renderer="iframe") If we run the above code, the same chart that appears in the Mitosheet will appear below the code cell as an output. We went through a few simple operations in the EDA process. While this is not a comprehensive EDA guide, it shows how we can avoid typing code for the simple data wrangling operations in the initial EDA. Generated code is useful for sharing it with colleagues and for inexperienced Data Scientists to learn “the pandas way” of doing analysis. Mito allows for powerful EDA processes to happen interactively within a JupyterLab Ecosystem. Here are the links to learn more about Mito and the link to the Avocado Dataset. If you enjoy reading these stories, why not become a Medium paying member? It is $5 per month, and you will get unlimited access to 10000s of stories and writers. If you sign up using my link, I will earn a small commission.
[ { "code": null, "e": 417, "s": 172, "text": "Exploratory Data Analysis (EDA) is one of the first steps in the Data Science process — usually, it follows the data extraction. EDA helps us to get familiar with the data before we proceed with modeling or decide to repeat the extraction step." }, { "code": null, "e": 447, "s": 417, "text": "EDA helps Data Scientists to:" }, { "code": null, "e": 474, "s": 447, "text": "get familiar with the data" }, { "code": null, "e": 515, "s": 474, "text": "find bugs in the data extraction process" }, { "code": null, "e": 549, "s": 515, "text": "decide if the data needs cleaning" }, { "code": null, "e": 608, "s": 549, "text": "decide what to do with the missing values if there are any" }, { "code": null, "e": 643, "s": 608, "text": "visualize data distributions, etc." }, { "code": null, "e": 705, "s": 643, "text": "With Exploratory Data Analysis we get the “feel” for the data" }, { "code": null, "e": 741, "s": 705, "text": "By reading this article you’ll get:" }, { "code": null, "e": 801, "s": 741, "text": "A practical example of EDA in JupyterLab on Avocado dataset" }, { "code": null, "e": 846, "s": 801, "text": "A code snippet of each interactive operation" }, { "code": null, "e": 907, "s": 846, "text": "An efficient way to share your analysis with your colleagues" }, { "code": null, "e": 1016, "s": 907, "text": "In case you’ve missed my previous articles about this topic, see Mito — A Spreadsheet that Generates Python." }, { "code": null, "e": 1180, "s": 1016, "text": "In this article, we’ll analyze the avocado dataset - one of the more popular datasets on Kaggle — and show a few basic operations in the Exploratory Data Analysis." }, { "code": null, "e": 1441, "s": 1180, "text": "The avocado dataset contains historical data on avocado prices and sales volume in multiple US markets. You can download it from Kaggle. The original data stems from the HASS AVOCADO BOARD. The Kaggle dataset is licensed under the Open Database License (ODbL)." }, { "code": null, "e": 1657, "s": 1441, "text": "We’ll analyze this dataset with the Mito extension for JupyterLab, which enables users to complete their EDA interactively inside JupyterLab, and have each edit generate the equivalent Python in the code cell below." }, { "code": null, "e": 1753, "s": 1657, "text": "First, we need to load the Mitosheet interactive environment in Jupyter Lab with this function:" }, { "code": null, "e": 1851, "s": 1753, "text": "# make sure you have Mito installed before running this functionimport mitosheetmitosheet.sheet()" }, { "code": null, "e": 1920, "s": 1851, "text": "These functions call an empty Mitosheet into the Jupyter Environment" }, { "code": null, "e": 2035, "s": 1920, "text": "To load the data into the sheet, we can either pass in an existing Dataframe as an argument to the Mitosheet call:" }, { "code": null, "e": 2055, "s": 2035, "text": "mitosheet.sheet(df)" }, { "code": null, "e": 2150, "s": 2055, "text": "Or we can click the Import button in the toolbar and select a file from our local file system." }, { "code": null, "e": 2317, "s": 2150, "text": "When we select “avocado.csv” in the import menu, Mito will automatically turn the CSV file into a Dataframe and generate the equivalent Python in the code cell below:" }, { "code": null, "e": 2415, "s": 2317, "text": "# Imported /Users/Downloads/avocado.csvavocado_csv = pd.read_csv(r’/Users/Downloads/avocado.csv’)" }, { "code": null, "e": 2630, "s": 2415, "text": "The CSV file already has an index column, which appears in the Mitosheet as “Unnamed: 0”, so the first thing we want to do is delete this column, which we can do by clicking the delete column button in the toolbar." }, { "code": null, "e": 2729, "s": 2630, "text": "This will generate the equivalent Python in the code cell below. The code is also auto-documented:" }, { "code": null, "e": 2826, "s": 2729, "text": "# Deleted column Unnamed: 0 from avocado_csvavocado_csv.drop('Unnamed: 0', axis=1, inplace=True)" }, { "code": null, "e": 2907, "s": 2826, "text": "Let’s say we are interested in the different regions of avocados in the dataset." }, { "code": null, "e": 2987, "s": 2907, "text": "We can select the column menu for the “Region” column and go to the values tab." }, { "code": null, "e": 3018, "s": 2987, "text": "In the values tab, we can see:" }, { "code": null, "e": 3055, "s": 3018, "text": "all the unique values in the column," }, { "code": null, "e": 3094, "s": 3055, "text": "the frequency of each of those values," }, { "code": null, "e": 3155, "s": 3094, "text": "and what percent of the total entries each value represents." }, { "code": null, "e": 3236, "s": 3155, "text": "From this distribution, it seems the avocados are equally distributed by region." }, { "code": null, "e": 3326, "s": 3236, "text": "We have decided that we want to only look at rows where the avocado’s region is “Albany.”" }, { "code": null, "e": 3443, "s": 3326, "text": "We can select the Filter/Sort tab in the column menu and set a filter where the “region” column is exactly “Albany.”" }, { "code": null, "e": 3495, "s": 3443, "text": "The generated code for this filter looks like this:" }, { "code": null, "e": 3588, "s": 3495, "text": "# Filtered region in avocado_csvavocado_csv = avocado_csv[avocado_csv['region'] == 'Albany']" }, { "code": null, "e": 3695, "s": 3588, "text": "Now that we have filtered the dataset, we want to explore the values we are left within the “Date” column." }, { "code": null, "e": 3750, "s": 3695, "text": "First, let’s use the add column button in the toolbar." }, { "code": null, "e": 3870, "s": 3750, "text": "Next, let’s add a formula to this column that parses the month value from each of the date values in the “Date” column." }, { "code": null, "e": 3883, "s": 3870, "text": "=MONTH(Date)" }, { "code": null, "e": 4051, "s": 3883, "text": "Once we have retrieved the month values in a new column, we can use a pivot table to count how many entries there are for each month and compare the aggregated counts." }, { "code": null, "e": 4169, "s": 4051, "text": "All we need to do is click the “Pivot” button in the toolbar and configure the table from the side menu that appears." }, { "code": null, "e": 4245, "s": 4169, "text": "This pivot table operation will generate the following Python code snippet:" }, { "code": null, "e": 4532, "s": 4245, "text": "# Pivoted avocado_csv into df3unused_columns = avocado_csv.columns.difference(set(['Month']).union(set([])).union(set({'Month'})))tmp_df = avocado_csv.drop(unused_columns, axis=1)pivot_table = tmp_df.pivot_table( index=['Month'], values=['Month'], aggfunc={'Month': ['count']})" }, { "code": null, "e": 4667, "s": 4532, "text": "In the column menu, we can also apply a sort by the “Month count” column to see the list of counts for each month in descending order." }, { "code": null, "e": 4797, "s": 4667, "text": "Here we can see that for the filtered Albany entries, January has the most entries and June and September have the least entries." }, { "code": null, "e": 4921, "s": 4797, "text": "Finally, we can visualize the analysis by clicking the “Graph’ button in the toolbar. We can configure it in the side menu." }, { "code": null, "e": 5007, "s": 4921, "text": "You can download this visualization as PNG so that can share it with your colleagues." }, { "code": null, "e": 5108, "s": 5007, "text": "We can also copy the equivalent code for any visualization by clicking the “Copy Graph Code” button." }, { "code": null, "e": 5146, "s": 5108, "text": "The outputted code for this graph is:" }, { "code": null, "e": 5743, "s": 5146, "text": "# Import plotly and create a figureimport plotly.graph_objects as gofig = go.Figure()# Add the bar chart traces to the graphfor column_header in ['Month']: fig.add_trace( go.Bar( x=df3[column_header], y=df3['Month count'], name=column_header ) )# Update the title and stacking mode of the graph# See Plotly documentation for customizations: https://plotly.com/python/reference/bar/fig.update_layout( xaxis_title='Month', yaxis_title='Month count', title='Month, Month count bar chart', barmode='group',)fig.show(renderer=\"iframe\")" }, { "code": null, "e": 5860, "s": 5743, "text": "If we run the above code, the same chart that appears in the Mitosheet will appear below the code cell as an output." }, { "code": null, "e": 6064, "s": 5860, "text": "We went through a few simple operations in the EDA process. While this is not a comprehensive EDA guide, it shows how we can avoid typing code for the simple data wrangling operations in the initial EDA." }, { "code": null, "e": 6203, "s": 6064, "text": "Generated code is useful for sharing it with colleagues and for inexperienced Data Scientists to learn “the pandas way” of doing analysis." }, { "code": null, "e": 6297, "s": 6203, "text": "Mito allows for powerful EDA processes to happen interactively within a JupyterLab Ecosystem." }, { "code": null, "e": 6378, "s": 6297, "text": "Here are the links to learn more about Mito and the link to the Avocado Dataset." } ]
Swift - Classes
Classes in Swift 4 are building blocks of flexible constructs. Similar to constants, variables and functions the user can define class properties and methods. Swift 4 provides us the functionality that while declaring classes the users need not create interfaces or implementation files. Swift 4 allows us to create classes as a single file and the external interfaces will be created by default once the classes are initialized. Inheritance acquires the properties of one class to another class Inheritance acquires the properties of one class to another class Type casting enables the user to check class type at run time Type casting enables the user to check class type at run time Deinitializers take care of releasing memory resources Deinitializers take care of releasing memory resources Reference counting allows the class instance to have more than one reference Reference counting allows the class instance to have more than one reference Properties are defined to store values Subscripts are defined for providing access to values Methods are initialized to improve functionality Initial state are defined by initializers Functionality are expanded beyond default values Confirming protocol functionality standards Class classname { Definition 1 Definition 2 --- Definition N } class student { var studname: String var mark: Int var mark2: Int } The syntax for creating instances let studrecord = student() class MarksStruct { var mark: Int init(mark: Int) { self.mark = mark } } class studentMarks { var mark = 300 } let marks = studentMarks() print("Mark is \(marks.mark)") When we run the above program using playground, we get the following result − Mark is 300 Class properties can be accessed by the '.' syntax. Property name is separated by a '.' after the instance name. class MarksStruct { var mark: Int init(mark: Int) { self.mark = mark } } class studentMarks { var mark1 = 300 var mark2 = 400 var mark3 = 900 } let marks = studentMarks() print("Mark1 is \(marks.mark1)") print("Mark2 is \(marks.mark2)") print("Mark3 is \(marks.mark3)") When we run the above program using playground, we get the following result − Mark1 is 300 Mark2 is 400 Mark3 is 900 Classes in Swift 4 refers multiple constants and variables pointing to a single instance. To know about the constants and variables pointing to a particular class instance identity operators are used. Class instances are always passed by reference. In Classes NSString, NSArray, and NSDictionary instances are always assigned and passed around as a reference to an existing instance, rather than as a copy. class SampleClass: Equatable { let myProperty: String init(s: String) { myProperty = s } } func ==(lhs: SampleClass, rhs: SampleClass) -> Bool { return lhs.myProperty == rhs.myProperty } let spClass1 = SampleClass(s: "Hello") let spClass2 = SampleClass(s: "Hello") spClass1 === spClass2 // false print("\(spClass1)") spClass1 !== spClass2 // true print("\(spClass2)") When we run the above program using playground, we get the following result − main.SampleClass main.SampleClass 38 Lectures 1 hours Ashish Sharma 13 Lectures 2 hours Three Millennials 7 Lectures 1 hours Three Millennials 22 Lectures 1 hours Frahaan Hussain 12 Lectures 39 mins Devasena Rajendran 40 Lectures 2.5 hours Grant Klimaytys Print Add Notes Bookmark this page
[ { "code": null, "e": 2683, "s": 2253, "text": "Classes in Swift 4 are building blocks of flexible constructs. Similar to constants, variables and functions the user can define class properties and methods. Swift 4 provides us the functionality that while declaring classes the users need not create interfaces or implementation files. Swift 4 allows us to create classes as a single file and the external interfaces will be created by default once the classes are initialized." }, { "code": null, "e": 2749, "s": 2683, "text": "Inheritance acquires the properties of one class to another class" }, { "code": null, "e": 2815, "s": 2749, "text": "Inheritance acquires the properties of one class to another class" }, { "code": null, "e": 2877, "s": 2815, "text": "Type casting enables the user to check class type at run time" }, { "code": null, "e": 2939, "s": 2877, "text": "Type casting enables the user to check class type at run time" }, { "code": null, "e": 2994, "s": 2939, "text": "Deinitializers take care of releasing memory resources" }, { "code": null, "e": 3049, "s": 2994, "text": "Deinitializers take care of releasing memory resources" }, { "code": null, "e": 3126, "s": 3049, "text": "Reference counting allows the class instance to have more than one reference" }, { "code": null, "e": 3203, "s": 3126, "text": "Reference counting allows the class instance to have more than one reference" }, { "code": null, "e": 3242, "s": 3203, "text": "Properties are defined to store values" }, { "code": null, "e": 3296, "s": 3242, "text": "Subscripts are defined for providing access to values" }, { "code": null, "e": 3345, "s": 3296, "text": "Methods are initialized to improve functionality" }, { "code": null, "e": 3387, "s": 3345, "text": "Initial state are defined by initializers" }, { "code": null, "e": 3436, "s": 3387, "text": "Functionality are expanded beyond default values" }, { "code": null, "e": 3480, "s": 3436, "text": "Confirming protocol functionality standards" }, { "code": null, "e": 3557, "s": 3480, "text": "Class classname {\n Definition 1\n Definition 2\n --- \n Definition N\n}\n" }, { "code": null, "e": 3637, "s": 3557, "text": "class student {\n var studname: String\n var mark: Int \n var mark2: Int \n}\n" }, { "code": null, "e": 3671, "s": 3637, "text": "The syntax for creating instances" }, { "code": null, "e": 3699, "s": 3671, "text": "let studrecord = student()\n" }, { "code": null, "e": 3888, "s": 3699, "text": "class MarksStruct {\n var mark: Int\n init(mark: Int) {\n self.mark = mark\n }\n}\n\nclass studentMarks {\n var mark = 300\n}\n\nlet marks = studentMarks()\nprint(\"Mark is \\(marks.mark)\")" }, { "code": null, "e": 3966, "s": 3888, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 3979, "s": 3966, "text": "Mark is 300\n" }, { "code": null, "e": 4092, "s": 3979, "text": "Class properties can be accessed by the '.' syntax. Property name is separated by a '.' after the instance name." }, { "code": null, "e": 4388, "s": 4092, "text": "class MarksStruct {\n var mark: Int\n init(mark: Int) {\n self.mark = mark\n }\n}\n\nclass studentMarks {\n var mark1 = 300\n var mark2 = 400\n var mark3 = 900\n}\n\nlet marks = studentMarks()\nprint(\"Mark1 is \\(marks.mark1)\")\nprint(\"Mark2 is \\(marks.mark2)\")\nprint(\"Mark3 is \\(marks.mark3)\")" }, { "code": null, "e": 4466, "s": 4388, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 4506, "s": 4466, "text": "Mark1 is 300\nMark2 is 400\nMark3 is 900\n" }, { "code": null, "e": 4913, "s": 4506, "text": "Classes in Swift 4 refers multiple constants and variables pointing to a single instance. To know about the constants and variables pointing to a particular class instance identity operators are used. Class instances are always passed by reference. In Classes NSString, NSArray, and NSDictionary instances are always assigned and passed around as a reference to an existing instance, rather than as a copy." }, { "code": null, "e": 5303, "s": 4913, "text": "class SampleClass: Equatable {\n let myProperty: String\n init(s: String) {\n myProperty = s\n }\n}\n\nfunc ==(lhs: SampleClass, rhs: SampleClass) -> Bool {\n return lhs.myProperty == rhs.myProperty\n}\n\nlet spClass1 = SampleClass(s: \"Hello\")\nlet spClass2 = SampleClass(s: \"Hello\")\n\nspClass1 === spClass2 // false\nprint(\"\\(spClass1)\")\n\nspClass1 !== spClass2 // true\nprint(\"\\(spClass2)\")" }, { "code": null, "e": 5381, "s": 5303, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 5416, "s": 5381, "text": "main.SampleClass\nmain.SampleClass\n" }, { "code": null, "e": 5449, "s": 5416, "text": "\n 38 Lectures \n 1 hours \n" }, { "code": null, "e": 5464, "s": 5449, "text": " Ashish Sharma" }, { "code": null, "e": 5497, "s": 5464, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 5516, "s": 5497, "text": " Three Millennials" }, { "code": null, "e": 5548, "s": 5516, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 5567, "s": 5548, "text": " Three Millennials" }, { "code": null, "e": 5600, "s": 5567, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 5617, "s": 5600, "text": " Frahaan Hussain" }, { "code": null, "e": 5649, "s": 5617, "text": "\n 12 Lectures \n 39 mins\n" }, { "code": null, "e": 5669, "s": 5649, "text": " Devasena Rajendran" }, { "code": null, "e": 5704, "s": 5669, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5721, "s": 5704, "text": " Grant Klimaytys" }, { "code": null, "e": 5728, "s": 5721, "text": " Print" }, { "code": null, "e": 5739, "s": 5728, "text": " Add Notes" } ]
How to implement Android TextInputLayout
Before getting into example, we should know what is TextInputLayout in android. TextInputLayout is extended by Linear Layout. It going to act as a wrapper for edit text and shows flatting hint animation for edit text. This example demonstrate about how to implement Android TextInputLayout. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:background = "#dde4dd" android:orientation = "vertical"> <android.support.design.widget.TextInputLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:id = "@+id/layoutEmail" android:layout_marginTop = "8dp" android:layout_marginStart = "8dp" android:layout_marginEnd = "8dp" style = "@style/Widget.MaterialComponents.TextInputLayout.FilledBox"> <android.support.design.widget.TextInputEditText android:layout_width = "match_parent" android:layout_height = "wrap_content" android:id = "@+id/email" android:hint = "Enter Email id" android:inputType = "textEmailAddress"/> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:id = "@+id/layoutPassword" android:layout_marginTop = "8dp" android:layout_marginStart = "8dp" android:layout_marginEnd = "8dp" style = "@style/Widget.MaterialComponents.TextInputLayout.FilledBox"> <android.support.design.widget.TextInputEditText android:layout_width = "match_parent" android:layout_height = "wrap_content" android:id = "@+id/password" android:hint = "Password" android:inputType = "textPassword"/> </android.support.design.widget.TextInputLayout> <Button android:id = "@+id/click" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_gravity = "center" android:text = "Click"></Button> </LinearLayout> In the above code we have given two TextInputEditText and one button. when you click on button it will take data from edit text and show on Toast. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.graphics.Point; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.TextureView; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText email,password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); email = findViewById(R.id.email); password = findViewById(R.id.password); Button click = findViewById(R.id.click); click.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!email.getText().toString().isEmpty()&&(!password.getText().toString().isEmpty())) { Toast.makeText(MainActivity.this, "you have entered email id " + email.getText().toString() + "Password " + password.getText().toString(), Toast.LENGTH_LONG).show(); } else { email.setError("Please Enter Email id"); password.setError("Please Enter Pass word"); } } }); } } Step 4 − Open build.gradle and add design support library dependency. apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.example.andy.myapplication" minSdkVersion 15 targetSdkVersion 28 compileSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support:design:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result is initial screen. Now enter some data and click on button as shown below - Now remove all edittext data and click on button. it will show result as shown below -
[ { "code": null, "e": 1280, "s": 1062, "text": "Before getting into example, we should know what is TextInputLayout in android. TextInputLayout is extended by Linear Layout. It going to act as a wrapper for edit text and shows flatting hint animation for edit text." }, { "code": null, "e": 1353, "s": 1280, "text": "This example demonstrate\nabout how to implement Android TextInputLayout." }, { "code": null, "e": 1482, "s": 1353, "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": 1547, "s": 1482, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3529, "s": 1547, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:background = \"#dde4dd\"\n android:orientation = \"vertical\">\n <android.support.design.widget.TextInputLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:id = \"@+id/layoutEmail\"\n android:layout_marginTop = \"8dp\"\n android:layout_marginStart = \"8dp\"\n android:layout_marginEnd = \"8dp\"\n style = \"@style/Widget.MaterialComponents.TextInputLayout.FilledBox\">\n <android.support.design.widget.TextInputEditText\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:id = \"@+id/email\"\n android:hint = \"Enter Email id\"\n android:inputType = \"textEmailAddress\"/>\n </android.support.design.widget.TextInputLayout>\n <android.support.design.widget.TextInputLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:id = \"@+id/layoutPassword\"\n android:layout_marginTop = \"8dp\"\n android:layout_marginStart = \"8dp\"\n android:layout_marginEnd = \"8dp\"\n style = \"@style/Widget.MaterialComponents.TextInputLayout.FilledBox\">\n <android.support.design.widget.TextInputEditText\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:id = \"@+id/password\"\n android:hint = \"Password\"\n android:inputType = \"textPassword\"/>\n </android.support.design.widget.TextInputLayout>\n <Button\n android:id = \"@+id/click\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\"\n android:text = \"Click\"></Button>\n</LinearLayout>" }, { "code": null, "e": 3676, "s": 3529, "text": "In the above code we have given two TextInputEditText and one button. when you click on button it will take data from edit text and show on Toast." }, { "code": null, "e": 3733, "s": 3676, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5049, "s": 3733, "text": "package com.example.andy.myapplication;\n\nimport android.graphics.Point;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.TextureView;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class MainActivity extends AppCompatActivity {\n EditText email,password;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n email = findViewById(R.id.email);\n password = findViewById(R.id.password);\n Button click = findViewById(R.id.click);\n click.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if(!email.getText().toString().isEmpty()&&(!password.getText().toString().isEmpty())) {\n Toast.makeText(MainActivity.this, \"you have entered email id \" + email.getText().toString() + \"Password \" + password.getText().toString(), Toast.LENGTH_LONG).show();\n } else {\n email.setError(\"Please Enter Email id\");\n password.setError(\"Please Enter Pass word\");\n }\n }\n });\n }\n}" }, { "code": null, "e": 5119, "s": 5049, "text": "Step 4 − Open build.gradle and add design support library dependency." }, { "code": null, "e": 6100, "s": 5119, "text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.myapplication\"\n minSdkVersion 15\n targetSdkVersion 28\n compileSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support:design:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}" }, { "code": null, "e": 6447, "s": 6100, "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": 6543, "s": 6447, "text": "In the above result is initial screen. Now enter some data and click on button as shown below -" }, { "code": null, "e": 6630, "s": 6543, "text": "Now remove all edittext data and click on button. it will show result as shown below -" } ]
Ethical Issues in Information Technology (IT) - GeeksforGeeks
27 Jan, 2020 Information Technology specifies to the components that are used to store, fetch and manipulate the information at the minimum level with the server having an operating system. Information Technology have a wide area of applications in education, business, health, industries, banking sector and scientific research at a large level. With the leading advancement in information technology, it is necessary to have the knowledge of security issues, privacy issues and main negative impacts of IT. To deal with these issues in IT society it is important to find out the ethical issues. Some of the major ethical issues faced by Information Technology (IT) are: 1. Personal Privacy 2. Access Right 3. Harmful Actions 4. Patents 5. Copyright 6. Trade Secrets 7. Liability 8. Piracy These are explained with their affects as following below: Personal Privacy:It is an important aspect of ethical issues in information technology. IT facilitates the users having their own hardware, operating system and software tools to access the servers that are connected to each other and to the users by a network. Due to the distribution of the network on a large scale, data or information transfer in a big amount takes place which leads to the hidden chances of disclosing information and violating the privacy of any individuals or a group. It is a major challenge for IT society and organizations to maintain the privacy and integrity of data. Accidental disclosure to inappropriate individuals and provisions to protect the accuracy of data also comes in the privacy issue.Access Right:The second aspect of ethical issues in information technology is access right. Access right becomes a high priority issue for the IT and cyberspace with the great advancement in technology. E-commerce and Electronic payment systems evolution on the internet heightened this issue for various corporate organizations and government agencies. Network on the internet cannot be made secure from unauthorized access. Generally, the intrusion detection system are used to determine whether the user is an intruder or an appropriate user.Harmful Actions:Harmful actions in the computer ethics refers to the damage or negative consequences to the IT such as loss of important information, loss of property, loss of ownership, destruction of property and undesirable substantial impacts. This principle of ethical conduct restricts any outsiders from the use of information technology in manner which leads to any loss to any of the users, employees, employers and the general public. Typically, these actions comprises of the intentional destruction or alteration of files and program which drives a serious loss of resources. To recover from the harmful actions extra time and efforts are required to remove the viruses from the computer systems.Patents:It is more difficult to deal with these types of ethical issues. A patent can preserve the unique and secret aspect of an idea. Obtaining a patent is very difficult as compared with obtaining a copyright. A thorough disclosure is required with the software. The patent holder has to reveal the full details of a program to a proficient programmer for building a program.Copyright:The information security specialists are to be familiar with necessary concept of the copyright law. Copyright law works as a very powerful legal tool in protecting computer software, both before a security breach and surely after a security breach. This type of breach could be the mishandling and misuse of data, computer programs, documentation and similar material. In many countries, copyright legislation is amended or revised to provide explicit laws to protect computer programs.Trade Secrets:Trade secrets is also a significant ethical issue in information technology. A trade secret secures something of value and usefulness. This law protects the private aspects of ideas which is known only to the discover or his confidants. Once disclosed, trade secret is lost as such and is only protected by the law for trade secrets. The application of trade secret law is very broad in the computer range, where even a slight head start in the advancement of software or hardware can provide a significant competitive influence.Liability:One should be aware of the liability issue in making ethical decisions. Software developer makes promises and assertions to the user about the nature and quality of the product that can be restricted as an express warranty. Programmers or retailers possess the legitimate to determine the express warranties. Thus they have to be practical when they define any claims and predictions about the capacities, quality and nature of their software or hardware. Every word they say about their product may be as legally valid as stated in written. All agreements should be in writing to protect against liability. A disclaimer of express warranties can free a supplier from being held responsible of informal, speculative statements or forecasting made during the agreement stages.Piracy:Piracy is an activity in which the creation of illegal copy of the software is made. It is entirely up to the owner of the software as to whether or not users can make backup copies of their software. As laws made for copyright protection are evolving, also legislation that would stop unauthorized duplication of software is in consideration. The software industry is prepared to do encounter against software piracy. The courts are dealing with an increasing number of actions concerning the protection of software. Personal Privacy:It is an important aspect of ethical issues in information technology. IT facilitates the users having their own hardware, operating system and software tools to access the servers that are connected to each other and to the users by a network. Due to the distribution of the network on a large scale, data or information transfer in a big amount takes place which leads to the hidden chances of disclosing information and violating the privacy of any individuals or a group. It is a major challenge for IT society and organizations to maintain the privacy and integrity of data. Accidental disclosure to inappropriate individuals and provisions to protect the accuracy of data also comes in the privacy issue. Access Right:The second aspect of ethical issues in information technology is access right. Access right becomes a high priority issue for the IT and cyberspace with the great advancement in technology. E-commerce and Electronic payment systems evolution on the internet heightened this issue for various corporate organizations and government agencies. Network on the internet cannot be made secure from unauthorized access. Generally, the intrusion detection system are used to determine whether the user is an intruder or an appropriate user. Harmful Actions:Harmful actions in the computer ethics refers to the damage or negative consequences to the IT such as loss of important information, loss of property, loss of ownership, destruction of property and undesirable substantial impacts. This principle of ethical conduct restricts any outsiders from the use of information technology in manner which leads to any loss to any of the users, employees, employers and the general public. Typically, these actions comprises of the intentional destruction or alteration of files and program which drives a serious loss of resources. To recover from the harmful actions extra time and efforts are required to remove the viruses from the computer systems. Patents:It is more difficult to deal with these types of ethical issues. A patent can preserve the unique and secret aspect of an idea. Obtaining a patent is very difficult as compared with obtaining a copyright. A thorough disclosure is required with the software. The patent holder has to reveal the full details of a program to a proficient programmer for building a program. Copyright:The information security specialists are to be familiar with necessary concept of the copyright law. Copyright law works as a very powerful legal tool in protecting computer software, both before a security breach and surely after a security breach. This type of breach could be the mishandling and misuse of data, computer programs, documentation and similar material. In many countries, copyright legislation is amended or revised to provide explicit laws to protect computer programs. Trade Secrets:Trade secrets is also a significant ethical issue in information technology. A trade secret secures something of value and usefulness. This law protects the private aspects of ideas which is known only to the discover or his confidants. Once disclosed, trade secret is lost as such and is only protected by the law for trade secrets. The application of trade secret law is very broad in the computer range, where even a slight head start in the advancement of software or hardware can provide a significant competitive influence. Liability:One should be aware of the liability issue in making ethical decisions. Software developer makes promises and assertions to the user about the nature and quality of the product that can be restricted as an express warranty. Programmers or retailers possess the legitimate to determine the express warranties. Thus they have to be practical when they define any claims and predictions about the capacities, quality and nature of their software or hardware. Every word they say about their product may be as legally valid as stated in written. All agreements should be in writing to protect against liability. A disclaimer of express warranties can free a supplier from being held responsible of informal, speculative statements or forecasting made during the agreement stages. Piracy:Piracy is an activity in which the creation of illegal copy of the software is made. It is entirely up to the owner of the software as to whether or not users can make backup copies of their software. As laws made for copyright protection are evolving, also legislation that would stop unauthorized duplication of software is in consideration. The software industry is prepared to do encounter against software piracy. The courts are dealing with an increasing number of actions concerning the protection of software. Information-Security GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar GET and POST requests using Python Top 10 Projects For Beginners To Practice HTML and CSS Skills Types of Software Testing Working with csv files in Python Roadmap to Become a Web Developer in 2022 Differences between Procedural and Object Oriented Programming Supervised and Unsupervised learning ML | Underfitting and Overfitting
[ { "code": null, "e": 24677, "s": 24649, "text": "\n27 Jan, 2020" }, { "code": null, "e": 25261, "s": 24677, "text": "Information Technology specifies to the components that are used to store, fetch and manipulate the information at the minimum level with the server having an operating system. Information Technology have a wide area of applications in education, business, health, industries, banking sector and scientific research at a large level. With the leading advancement in information technology, it is necessary to have the knowledge of security issues, privacy issues and main negative impacts of IT. To deal with these issues in IT society it is important to find out the ethical issues." }, { "code": null, "e": 25336, "s": 25261, "text": "Some of the major ethical issues faced by Information Technology (IT) are:" }, { "code": null, "e": 25455, "s": 25336, "text": "1. Personal Privacy\n2. Access Right\n3. Harmful Actions\n4. Patents\n5. Copyright\n6. Trade Secrets\n7. Liability\n8. Piracy" }, { "code": null, "e": 25514, "s": 25455, "text": "These are explained with their affects as following below:" }, { "code": null, "e": 30222, "s": 25514, "text": "Personal Privacy:It is an important aspect of ethical issues in information technology. IT facilitates the users having their own hardware, operating system and software tools to access the servers that are connected to each other and to the users by a network. Due to the distribution of the network on a large scale, data or information transfer in a big amount takes place which leads to the hidden chances of disclosing information and violating the privacy of any individuals or a group. It is a major challenge for IT society and organizations to maintain the privacy and integrity of data. Accidental disclosure to inappropriate individuals and provisions to protect the accuracy of data also comes in the privacy issue.Access Right:The second aspect of ethical issues in information technology is access right. Access right becomes a high priority issue for the IT and cyberspace with the great advancement in technology. E-commerce and Electronic payment systems evolution on the internet heightened this issue for various corporate organizations and government agencies. Network on the internet cannot be made secure from unauthorized access. Generally, the intrusion detection system are used to determine whether the user is an intruder or an appropriate user.Harmful Actions:Harmful actions in the computer ethics refers to the damage or negative consequences to the IT such as loss of important information, loss of property, loss of ownership, destruction of property and undesirable substantial impacts. This principle of ethical conduct restricts any outsiders from the use of information technology in manner which leads to any loss to any of the users, employees, employers and the general public. Typically, these actions comprises of the intentional destruction or alteration of files and program which drives a serious loss of resources. To recover from the harmful actions extra time and efforts are required to remove the viruses from the computer systems.Patents:It is more difficult to deal with these types of ethical issues. A patent can preserve the unique and secret aspect of an idea. Obtaining a patent is very difficult as compared with obtaining a copyright. A thorough disclosure is required with the software. The patent holder has to reveal the full details of a program to a proficient programmer for building a program.Copyright:The information security specialists are to be familiar with necessary concept of the copyright law. Copyright law works as a very powerful legal tool in protecting computer software, both before a security breach and surely after a security breach. This type of breach could be the mishandling and misuse of data, computer programs, documentation and similar material. In many countries, copyright legislation is amended or revised to provide explicit laws to protect computer programs.Trade Secrets:Trade secrets is also a significant ethical issue in information technology. A trade secret secures something of value and usefulness. This law protects the private aspects of ideas which is known only to the discover or his confidants. Once disclosed, trade secret is lost as such and is only protected by the law for trade secrets. The application of trade secret law is very broad in the computer range, where even a slight head start in the advancement of software or hardware can provide a significant competitive influence.Liability:One should be aware of the liability issue in making ethical decisions. Software developer makes promises and assertions to the user about the nature and quality of the product that can be restricted as an express warranty. Programmers or retailers possess the legitimate to determine the express warranties. Thus they have to be practical when they define any claims and predictions about the capacities, quality and nature of their software or hardware. Every word they say about their product may be as legally valid as stated in written. All agreements should be in writing to protect against liability. A disclaimer of express warranties can free a supplier from being held responsible of informal, speculative statements or forecasting made during the agreement stages.Piracy:Piracy is an activity in which the creation of illegal copy of the software is made. It is entirely up to the owner of the software as to whether or not users can make backup copies of their software. As laws made for copyright protection are evolving, also legislation that would stop unauthorized duplication of software is in consideration. The software industry is prepared to do encounter against software piracy. The courts are dealing with an increasing number of actions concerning the protection of software." }, { "code": null, "e": 30950, "s": 30222, "text": "Personal Privacy:It is an important aspect of ethical issues in information technology. IT facilitates the users having their own hardware, operating system and software tools to access the servers that are connected to each other and to the users by a network. Due to the distribution of the network on a large scale, data or information transfer in a big amount takes place which leads to the hidden chances of disclosing information and violating the privacy of any individuals or a group. It is a major challenge for IT society and organizations to maintain the privacy and integrity of data. Accidental disclosure to inappropriate individuals and provisions to protect the accuracy of data also comes in the privacy issue." }, { "code": null, "e": 31496, "s": 30950, "text": "Access Right:The second aspect of ethical issues in information technology is access right. Access right becomes a high priority issue for the IT and cyberspace with the great advancement in technology. E-commerce and Electronic payment systems evolution on the internet heightened this issue for various corporate organizations and government agencies. Network on the internet cannot be made secure from unauthorized access. Generally, the intrusion detection system are used to determine whether the user is an intruder or an appropriate user." }, { "code": null, "e": 32205, "s": 31496, "text": "Harmful Actions:Harmful actions in the computer ethics refers to the damage or negative consequences to the IT such as loss of important information, loss of property, loss of ownership, destruction of property and undesirable substantial impacts. This principle of ethical conduct restricts any outsiders from the use of information technology in manner which leads to any loss to any of the users, employees, employers and the general public. Typically, these actions comprises of the intentional destruction or alteration of files and program which drives a serious loss of resources. To recover from the harmful actions extra time and efforts are required to remove the viruses from the computer systems." }, { "code": null, "e": 32584, "s": 32205, "text": "Patents:It is more difficult to deal with these types of ethical issues. A patent can preserve the unique and secret aspect of an idea. Obtaining a patent is very difficult as compared with obtaining a copyright. A thorough disclosure is required with the software. The patent holder has to reveal the full details of a program to a proficient programmer for building a program." }, { "code": null, "e": 33082, "s": 32584, "text": "Copyright:The information security specialists are to be familiar with necessary concept of the copyright law. Copyright law works as a very powerful legal tool in protecting computer software, both before a security breach and surely after a security breach. This type of breach could be the mishandling and misuse of data, computer programs, documentation and similar material. In many countries, copyright legislation is amended or revised to provide explicit laws to protect computer programs." }, { "code": null, "e": 33626, "s": 33082, "text": "Trade Secrets:Trade secrets is also a significant ethical issue in information technology. A trade secret secures something of value and usefulness. This law protects the private aspects of ideas which is known only to the discover or his confidants. Once disclosed, trade secret is lost as such and is only protected by the law for trade secrets. The application of trade secret law is very broad in the computer range, where even a slight head start in the advancement of software or hardware can provide a significant competitive influence." }, { "code": null, "e": 34412, "s": 33626, "text": "Liability:One should be aware of the liability issue in making ethical decisions. Software developer makes promises and assertions to the user about the nature and quality of the product that can be restricted as an express warranty. Programmers or retailers possess the legitimate to determine the express warranties. Thus they have to be practical when they define any claims and predictions about the capacities, quality and nature of their software or hardware. Every word they say about their product may be as legally valid as stated in written. All agreements should be in writing to protect against liability. A disclaimer of express warranties can free a supplier from being held responsible of informal, speculative statements or forecasting made during the agreement stages." }, { "code": null, "e": 34937, "s": 34412, "text": "Piracy:Piracy is an activity in which the creation of illegal copy of the software is made. It is entirely up to the owner of the software as to whether or not users can make backup copies of their software. As laws made for copyright protection are evolving, also legislation that would stop unauthorized duplication of software is in consideration. The software industry is prepared to do encounter against software piracy. The courts are dealing with an increasing number of actions concerning the protection of software." }, { "code": null, "e": 34958, "s": 34937, "text": "Information-Security" }, { "code": null, "e": 34964, "s": 34958, "text": "GBlog" }, { "code": null, "e": 35062, "s": 34964, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35071, "s": 35062, "text": "Comments" }, { "code": null, "e": 35084, "s": 35071, "text": "Old Comments" }, { "code": null, "e": 35109, "s": 35084, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 35144, "s": 35109, "text": "GET and POST requests using Python" }, { "code": null, "e": 35206, "s": 35144, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 35232, "s": 35206, "text": "Types of Software Testing" }, { "code": null, "e": 35265, "s": 35232, "text": "Working with csv files in Python" }, { "code": null, "e": 35307, "s": 35265, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 35370, "s": 35307, "text": "Differences between Procedural and Object Oriented Programming" }, { "code": null, "e": 35407, "s": 35370, "text": "Supervised and Unsupervised learning" } ]
Can we use "this" keyword in a static method in java?
The static methods belong to the class and they will be loaded into the memory along with the class. You can invoke them without creating an object. (using the class name as reference). public class Sample{ static int num = 50; public static void demo(){ System.out.println("Contents of the static method"); } public static void main(String args[]){ Sample.demo(); } } Contents of the static method The "this" keyword is used as a reference to an instance. Since the static methods doesn’t have (belong to) any instance you cannot use the "this" reference within a static method. If you still, try to do so a compile time error is generated. public class Sample{ static int num = 50; public static void demo(){ System.out.println("Contents of the static method"+this.num); } public static void main(String args[]){ Sample.demo(); } } Sample.java:4: error: non-static variable this cannot be referenced from a static context System.out.println("Contents of the static method"+this.num); ^ 1 error
[ { "code": null, "e": 1248, "s": 1062, "text": "The static methods belong to the class and they will be loaded into the memory along with the class. You can invoke them without creating an object. (using the class name as reference)." }, { "code": null, "e": 1458, "s": 1248, "text": "public class Sample{\n static int num = 50;\n public static void demo(){\n System.out.println(\"Contents of the static method\");\n }\n public static void main(String args[]){\n Sample.demo();\n }\n}" }, { "code": null, "e": 1488, "s": 1458, "text": "Contents of the static method" }, { "code": null, "e": 1731, "s": 1488, "text": "The \"this\" keyword is used as a reference to an instance. Since the static methods doesn’t have (belong to) any instance you cannot use the \"this\" reference within a static method. If you still, try to do so a compile time error is generated." }, { "code": null, "e": 1950, "s": 1731, "text": "public class Sample{\n static int num = 50;\n public static void demo(){\n System.out.println(\"Contents of the static method\"+this.num);\n }\n public static void main(String args[]){\n Sample.demo();\n }\n}" }, { "code": null, "e": 2169, "s": 1950, "text": "Sample.java:4: error: non-static variable this cannot be referenced from a static context\n System.out.println(\"Contents of the static method\"+this.num);\n ^\n1 error" } ]
Face Detection in 10 lines for Beginners | by That Data Bloke | Towards Data Science
I was recently exploring the Haar Cascade object detection module of the OpenCV for a personal side project. Although there are a lot of technical materials on the internet in this area, my focus on this article is to explain the concepts in easy layman’s terms. I hope this will help the beginners in understanding Python’s OpenCV library in a simple manner. In this demo, we will take an image and search for human faces in it. We are going to use a pre-trained classifier to perform this search. I plan on sharing some more articles on how we can train our own models in future. But for now, let’s get started using a pre-trained model. For the uninitiated, OpenCV is a Python library which is mainly used in various computer vision problems. Here, we are using the “haarcascade_frontalface_default.xml” as our model from the opencv github repository. You can download this xml file and place it in the same path as your python file. There are also a bunch of other models here that you might want to try out later (Eg:- eye detection, full body detection, cat face detection etc.) Let’s take a look at a high level flow of the program before jumping into the code. The algorithm requires two inputs: Input Image matrix(we will read an image and convert it into a matrix of numbers/numpy array)The face features (available in the haarcascade_frontalface_default.xml file) Input Image matrix(we will read an image and convert it into a matrix of numbers/numpy array) The face features (available in the haarcascade_frontalface_default.xml file) OpenCV’s Haar Cascade classifier works on the sliding window approach. In this method, a window (default size 20 by 20 pixels) is slid over the image (row by row) to look for the facial features. After each iteration the image is scaled down (resized) by a certain factor (determined by the parameter ‘scaleFactor’). The outputs of each iteration is stored and the sliding operation is repeated on the smaller, resized image. There could be false positives during the initial iterations which is discussed in a bit more detail later in this article. This scaling down and windowing process continues until the image is too small for the sliding window. The smaller the value of scaleFactor, greater the accuracy and higher the computation expenses. Our output image will contain a rectangle around each of the detected faces. Code & Explanation : Let’s get started with the python code. We will require the following Python packages for this experiment: pip install numpypip install opencv-python Let’s call our python file ‘face_detector.py’ and place it in the same path as our xml file downloaded from the github link shared above. # File Name: face_detector.py# Import the OpenCV libraryimport cv2 Now let’s looks at the promised 10 lines ! We prepare the 2 inputs [input image & face features xml]shown in the flow diagram above in the below section. I am using this beautiful photograph by Bess Hamiti(link below) as my input image (kids.jpg). 1We begin by loading our xml classifier and the input image file. Since the input file is quite large, I have resized with approx dimensions similar to the original resolution, so that they don’t appear stretched. Then, I have converted the image into a gray scale image. The gray scale image is believed to improve the efficiency of the algorithm. face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")image = cv2.imread("kids.jpg")image = cv2.resize(image, (800,533))gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) The image read is stored as a multidimensional numpy array, as shown below. print(type(gray_image))<class 'numpy.ndarray'> In the next step, we pass the gray_image as an input to the detectMultiScale method. The detectMultiScale method is the one that will perform the detection for us. It takes the following parameters: scaleFactor : This parameter specifies the factor by which the image is scaled down, eg:- if this value is 1.05, then the image is scaled down by 5%. If this value is 1.10, then the image is scaled down by 10%. A scaleFactor of 1.10 will require less computation than a scaleFactor of 1.05. minNeighbors : It is a threshold value that specifies how many neighbors each rectangle should have in order for it to be marked as true positive. In other words, let’s assume that each iteration marks certain rectangles (i.e. classifies a part of the image as a face). Now, if the subsequent iterations also mark the same areas as a positive, it increases the possibility of that rectangle area to be a true positive. If a certain area is identified as a face in one iteration, but not in any other iteration, they are marked as false positives. In other words, minNeighbors is the minimum number of times a region has to be determined as a face. Let’s perform an experiment to understand it better. We will run our code with different values for minNeighbors parameter. For minNeighbors = 0, All the rectangles are being detected as faces. For some rectangles, there are lots of overlapping rectangles, which signifies that those have been detected as positives during multiple iterations. We set the threshold to increase the accuracy of the algorithm. minNeighbors = 2 With minNeighbors = 2, most of the overlapping rectangles are no longer present. However, we still have a few false positives. If we increase this threshold to 4 or 5, we can see that there aren’t any more false positives. Let’s set this value to 5 and proceed further. faces=face_cascade.detectMultiScale(gray_image,scaleFactor=1.10,minNeighbors=5) The detectMultiScale method returns a numpy array with dimensions and positions of the rectangles containing the faces. x,y — position of the top left corner of the rectangle w, h — width and height of the rectangle We now draw a rectangle with these dimensions in green color (0, 255, 0) (BGR color code) with the border thickness = 1. The window waits for 2 seconds (2000 milliseconds) and closes automatically. for x,y,w,h in faces: image=cv2.rectangle(image, (x,y), (x+w, y+h), (0, 255, 0),1) cv2.imshow("Face Detector", image) k=cv2.waitKey(2000)cv2.destroyAllWindows() Alternately, we can also save the image by adding the below line. cv2.imwrite("kids_face_detected.jpeg", image) Our output image now contains a green rectangle around each of the detected faces. I hope this article leaves you with a basic understanding of how to do face detection using OpenCV in python. We can extend this code to track a face in a video as well. I have uploaded the full code discussed above and for tracking faces in a live webcam video in my GitHub repository here, in case you are interested. Have a great day ahead! medium.com towardsdatascience.com medium.com References & Further Reading: [1]Cascade Classifier, https://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html [2] 5KK73 GPU Assignment, https://sites.google.com/site/5kk73gpu2012/assignment/viola-jones-face-detection [3] OpenCV Github page, https://github.com/opencv/opencv/tree/master/data/haarcascades
[ { "code": null, "e": 532, "s": 172, "text": "I was recently exploring the Haar Cascade object detection module of the OpenCV for a personal side project. Although there are a lot of technical materials on the internet in this area, my focus on this article is to explain the concepts in easy layman’s terms. I hope this will help the beginners in understanding Python’s OpenCV library in a simple manner." }, { "code": null, "e": 812, "s": 532, "text": "In this demo, we will take an image and search for human faces in it. We are going to use a pre-trained classifier to perform this search. I plan on sharing some more articles on how we can train our own models in future. But for now, let’s get started using a pre-trained model." }, { "code": null, "e": 918, "s": 812, "text": "For the uninitiated, OpenCV is a Python library which is mainly used in various computer vision problems." }, { "code": null, "e": 1257, "s": 918, "text": "Here, we are using the “haarcascade_frontalface_default.xml” as our model from the opencv github repository. You can download this xml file and place it in the same path as your python file. There are also a bunch of other models here that you might want to try out later (Eg:- eye detection, full body detection, cat face detection etc.)" }, { "code": null, "e": 1341, "s": 1257, "text": "Let’s take a look at a high level flow of the program before jumping into the code." }, { "code": null, "e": 1376, "s": 1341, "text": "The algorithm requires two inputs:" }, { "code": null, "e": 1547, "s": 1376, "text": "Input Image matrix(we will read an image and convert it into a matrix of numbers/numpy array)The face features (available in the haarcascade_frontalface_default.xml file)" }, { "code": null, "e": 1641, "s": 1547, "text": "Input Image matrix(we will read an image and convert it into a matrix of numbers/numpy array)" }, { "code": null, "e": 1719, "s": 1641, "text": "The face features (available in the haarcascade_frontalface_default.xml file)" }, { "code": null, "e": 2468, "s": 1719, "text": "OpenCV’s Haar Cascade classifier works on the sliding window approach. In this method, a window (default size 20 by 20 pixels) is slid over the image (row by row) to look for the facial features. After each iteration the image is scaled down (resized) by a certain factor (determined by the parameter ‘scaleFactor’). The outputs of each iteration is stored and the sliding operation is repeated on the smaller, resized image. There could be false positives during the initial iterations which is discussed in a bit more detail later in this article. This scaling down and windowing process continues until the image is too small for the sliding window. The smaller the value of scaleFactor, greater the accuracy and higher the computation expenses." }, { "code": null, "e": 2545, "s": 2468, "text": "Our output image will contain a rectangle around each of the detected faces." }, { "code": null, "e": 2566, "s": 2545, "text": "Code & Explanation :" }, { "code": null, "e": 2673, "s": 2566, "text": "Let’s get started with the python code. We will require the following Python packages for this experiment:" }, { "code": null, "e": 2716, "s": 2673, "text": "pip install numpypip install opencv-python" }, { "code": null, "e": 2854, "s": 2716, "text": "Let’s call our python file ‘face_detector.py’ and place it in the same path as our xml file downloaded from the github link shared above." }, { "code": null, "e": 2921, "s": 2854, "text": "# File Name: face_detector.py# Import the OpenCV libraryimport cv2" }, { "code": null, "e": 2964, "s": 2921, "text": "Now let’s looks at the promised 10 lines !" }, { "code": null, "e": 3075, "s": 2964, "text": "We prepare the 2 inputs [input image & face features xml]shown in the flow diagram above in the below section." }, { "code": null, "e": 3169, "s": 3075, "text": "I am using this beautiful photograph by Bess Hamiti(link below) as my input image (kids.jpg)." }, { "code": null, "e": 3518, "s": 3169, "text": "1We begin by loading our xml classifier and the input image file. Since the input file is quite large, I have resized with approx dimensions similar to the original resolution, so that they don’t appear stretched. Then, I have converted the image into a gray scale image. The gray scale image is believed to improve the efficiency of the algorithm." }, { "code": null, "e": 3712, "s": 3518, "text": "face_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")image = cv2.imread(\"kids.jpg\")image = cv2.resize(image, (800,533))gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)" }, { "code": null, "e": 3788, "s": 3712, "text": "The image read is stored as a multidimensional numpy array, as shown below." }, { "code": null, "e": 3835, "s": 3788, "text": "print(type(gray_image))<class 'numpy.ndarray'>" }, { "code": null, "e": 3920, "s": 3835, "text": "In the next step, we pass the gray_image as an input to the detectMultiScale method." }, { "code": null, "e": 4034, "s": 3920, "text": "The detectMultiScale method is the one that will perform the detection for us. It takes the following parameters:" }, { "code": null, "e": 4325, "s": 4034, "text": "scaleFactor : This parameter specifies the factor by which the image is scaled down, eg:- if this value is 1.05, then the image is scaled down by 5%. If this value is 1.10, then the image is scaled down by 10%. A scaleFactor of 1.10 will require less computation than a scaleFactor of 1.05." }, { "code": null, "e": 4973, "s": 4325, "text": "minNeighbors : It is a threshold value that specifies how many neighbors each rectangle should have in order for it to be marked as true positive. In other words, let’s assume that each iteration marks certain rectangles (i.e. classifies a part of the image as a face). Now, if the subsequent iterations also mark the same areas as a positive, it increases the possibility of that rectangle area to be a true positive. If a certain area is identified as a face in one iteration, but not in any other iteration, they are marked as false positives. In other words, minNeighbors is the minimum number of times a region has to be determined as a face." }, { "code": null, "e": 5097, "s": 4973, "text": "Let’s perform an experiment to understand it better. We will run our code with different values for minNeighbors parameter." }, { "code": null, "e": 5119, "s": 5097, "text": "For minNeighbors = 0," }, { "code": null, "e": 5381, "s": 5119, "text": "All the rectangles are being detected as faces. For some rectangles, there are lots of overlapping rectangles, which signifies that those have been detected as positives during multiple iterations. We set the threshold to increase the accuracy of the algorithm." }, { "code": null, "e": 5398, "s": 5381, "text": "minNeighbors = 2" }, { "code": null, "e": 5525, "s": 5398, "text": "With minNeighbors = 2, most of the overlapping rectangles are no longer present. However, we still have a few false positives." }, { "code": null, "e": 5668, "s": 5525, "text": "If we increase this threshold to 4 or 5, we can see that there aren’t any more false positives. Let’s set this value to 5 and proceed further." }, { "code": null, "e": 5748, "s": 5668, "text": "faces=face_cascade.detectMultiScale(gray_image,scaleFactor=1.10,minNeighbors=5)" }, { "code": null, "e": 5868, "s": 5748, "text": "The detectMultiScale method returns a numpy array with dimensions and positions of the rectangles containing the faces." }, { "code": null, "e": 5923, "s": 5868, "text": "x,y — position of the top left corner of the rectangle" }, { "code": null, "e": 5964, "s": 5923, "text": "w, h — width and height of the rectangle" }, { "code": null, "e": 6085, "s": 5964, "text": "We now draw a rectangle with these dimensions in green color (0, 255, 0) (BGR color code) with the border thickness = 1." }, { "code": null, "e": 6162, "s": 6085, "text": "The window waits for 2 seconds (2000 milliseconds) and closes automatically." }, { "code": null, "e": 6332, "s": 6162, "text": "for x,y,w,h in faces: image=cv2.rectangle(image, (x,y), (x+w, y+h), (0, 255, 0),1) cv2.imshow(\"Face Detector\", image) k=cv2.waitKey(2000)cv2.destroyAllWindows()" }, { "code": null, "e": 6398, "s": 6332, "text": "Alternately, we can also save the image by adding the below line." }, { "code": null, "e": 6444, "s": 6398, "text": "cv2.imwrite(\"kids_face_detected.jpeg\", image)" }, { "code": null, "e": 6527, "s": 6444, "text": "Our output image now contains a green rectangle around each of the detected faces." }, { "code": null, "e": 6871, "s": 6527, "text": "I hope this article leaves you with a basic understanding of how to do face detection using OpenCV in python. We can extend this code to track a face in a video as well. I have uploaded the full code discussed above and for tracking faces in a live webcam video in my GitHub repository here, in case you are interested. Have a great day ahead!" }, { "code": null, "e": 6882, "s": 6871, "text": "medium.com" }, { "code": null, "e": 6905, "s": 6882, "text": "towardsdatascience.com" }, { "code": null, "e": 6916, "s": 6905, "text": "medium.com" }, { "code": null, "e": 6946, "s": 6916, "text": "References & Further Reading:" }, { "code": null, "e": 7047, "s": 6946, "text": "[1]Cascade Classifier, https://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html" }, { "code": null, "e": 7154, "s": 7047, "text": "[2] 5KK73 GPU Assignment, https://sites.google.com/site/5kk73gpu2012/assignment/viola-jones-face-detection" } ]
C++ Program to Solve Knapsack Problem Using Dynamic Programming
This is a C++ program to solve 0-1 knapsack problem using dynamic programming. In 0-1 knapsack problem, a set of items are given, each with a weight and a value. We need to determine the number of each item to include in a collection so that the total weight is less than or equal to the given limit and the total value is large as possible. Begin Input set of items each with a weight and a value Set knapsack capacity Create a function that returns maximum of two integers. Create a function which returns the maximum value that can be put in a knapsack of capacity W int knapSack(int W, int w[], int v[], int n) int i, wt; int K[n + 1][W + 1] for i = 0 to n for wt = 0 to W if (i == 0 or wt == 0) Do K[i][wt] = 0 else if (w[i - 1] <= wt) Compute: K[i][wt] = max(v[i - 1] + K[i - 1][wt - w[i - 1]], K[i -1][wt]) else K[i][wt] = K[i - 1][wt] return K[n][W] Call the function and print. End #include <iostream> using namespace std; int max(int x, int y) { return (x > y) ? x : y; } int knapSack(int W, int w[], int v[], int n) { int i, wt; int K[n + 1][W + 1]; for (i = 0; i <= n; i++) { for (wt = 0; wt <= W; wt++) { if (i == 0 || wt == 0) K[i][wt] = 0; else if (w[i - 1] <= wt) K[i][wt] = max(v[i - 1] + K[i - 1][wt - w[i - 1]], K[i - 1][wt]); else K[i][wt] = K[i - 1][wt]; } } return K[n][W]; } int main() { cout << "Enter the number of items in a Knapsack:"; int n, W; cin >> n; int v[n], w[n]; for (int i = 0; i < n; i++) { cout << "Enter value and weight for item " << i << ":"; cin >> v[i]; cin >> w[i]; } cout << "Enter the capacity of knapsack"; cin >> W; cout << knapSack(W, w, v, n); return 0; } Enter the number of items in a Knapsack:4 Enter value and weight for item 0:10 50 Enter value and weight for item 1:20 60 Enter value and weight for item 2:30 70 Enter value and weight for item 3:40 90 Enter the capacity of knapsack100 40
[ { "code": null, "e": 1404, "s": 1062, "text": "This is a C++ program to solve 0-1 knapsack problem using dynamic programming. In 0-1 knapsack problem, a set of items are given, each with a weight and a value. We need to determine the number of each item to include in a collection so that the total weight is less than or equal to the given limit and the total value is large as possible." }, { "code": null, "e": 1968, "s": 1404, "text": "Begin\nInput set of items each with a weight and a value\nSet knapsack capacity\nCreate a function that returns maximum of two integers.\nCreate a function which returns the maximum value that can be put in a knapsack of capacity W\nint knapSack(int W, int w[], int v[], int n)\nint i, wt;\nint K[n + 1][W + 1]\nfor i = 0 to n\nfor wt = 0 to W\nif (i == 0 or wt == 0)\n Do K[i][wt] = 0\nelse if (w[i - 1] <= wt)\n Compute: K[i][wt] = max(v[i - 1] + K[i - 1][wt - w[i - 1]], K[i -1][wt])\nelse\n K[i][wt] = K[i - 1][wt]\n return K[n][W]\n Call the function and print.\nEnd" }, { "code": null, "e": 2818, "s": 1968, "text": "#include <iostream>\nusing namespace std;\nint max(int x, int y) {\n return (x > y) ? x : y;\n}\nint knapSack(int W, int w[], int v[], int n) {\n int i, wt;\n int K[n + 1][W + 1];\n for (i = 0; i <= n; i++) {\n for (wt = 0; wt <= W; wt++) {\n if (i == 0 || wt == 0)\n K[i][wt] = 0;\n else if (w[i - 1] <= wt)\n K[i][wt] = max(v[i - 1] + K[i - 1][wt - w[i - 1]], K[i - 1][wt]);\n else\n K[i][wt] = K[i - 1][wt];\n }\n }\n return K[n][W];\n}\nint main() {\n cout << \"Enter the number of items in a Knapsack:\";\n int n, W;\n cin >> n;\n int v[n], w[n];\n for (int i = 0; i < n; i++) {\n cout << \"Enter value and weight for item \" << i << \":\";\n cin >> v[i];\n cin >> w[i];\n }\n cout << \"Enter the capacity of knapsack\";\n cin >> W;\n cout << knapSack(W, w, v, n);\n return 0;\n}" }, { "code": null, "e": 3057, "s": 2818, "text": "Enter the number of items in a Knapsack:4\nEnter value and weight for item 0:10\n50\nEnter value and weight for item 1:20\n60\nEnter value and weight for item 2:30\n70\nEnter value and weight for item 3:40\n90\nEnter the capacity of knapsack100\n40" } ]
Aggregate Functions in DBMS
Aggregate functions in DBMS take multiple rows from the table and return a value according to the query. All the aggregate functions are used in Select statement. Syntax − SELECT <FUNCTION NAME> (<PARAMETER>) FROM <TABLE NAME> This function returns the average value of the numeric column that is supplied as a parameter. Example: Write a query to select average salary from employee table. Select AVG(salary) from Employee The count function returns the number of rows in the result. It does not count the null values. Example: Write a query to return number of rows where salary > 20000. Select COUNT(*) from Employee where Salary > 20000; Types − COUNT(*): Counts all the number of rows of the table including null. COUNT(*): Counts all the number of rows of the table including null. COUNT( COLUMN_NAME): count number of non-null values in column. COUNT( COLUMN_NAME): count number of non-null values in column. COUNT( DISTINCT COLUMN_NAME): count number of distinct values in a column. COUNT( DISTINCT COLUMN_NAME): count number of distinct values in a column. The MAX function is used to find maximum value in the column that is supplied as a parameter. It can be used on any type of data. Example − Write a query to find the maximum salary in employee table. Select MAX(salary) from Employee This function sums up the values in the column supplied as a parameter. Example: Write a query to get the total salary of employees. Select SUM(salary) from Employee The STDDEV function is used to find standard deviation of the column specified as argument. Example − Write a query to find standard deviation of salary in Employee table. Select STDDEV(salary) from Employee The VARIANCE Function is used to find variance of the column specified as argument. Example − Select VARIANCE(salary) from Employee
[ { "code": null, "e": 1167, "s": 1062, "text": "Aggregate functions in DBMS take multiple rows from the table and return a value according to the query." }, { "code": null, "e": 1225, "s": 1167, "text": "All the aggregate functions are used in Select statement." }, { "code": null, "e": 1235, "s": 1225, "text": "Syntax − " }, { "code": null, "e": 1290, "s": 1235, "text": "SELECT <FUNCTION NAME> (<PARAMETER>) FROM <TABLE NAME>" }, { "code": null, "e": 1385, "s": 1290, "text": "This function returns the average value of the numeric column that is supplied as a parameter." }, { "code": null, "e": 1454, "s": 1385, "text": "Example: Write a query to select average salary from employee table." }, { "code": null, "e": 1487, "s": 1454, "text": "Select AVG(salary) from Employee" }, { "code": null, "e": 1583, "s": 1487, "text": "The count function returns the number of rows in the result. It does not count the null values." }, { "code": null, "e": 1653, "s": 1583, "text": "Example: Write a query to return number of rows where salary > 20000." }, { "code": null, "e": 1705, "s": 1653, "text": "Select COUNT(*) from Employee where Salary > 20000;" }, { "code": null, "e": 1713, "s": 1705, "text": "Types −" }, { "code": null, "e": 1782, "s": 1713, "text": "COUNT(*): Counts all the number of rows of the table including null." }, { "code": null, "e": 1851, "s": 1782, "text": "COUNT(*): Counts all the number of rows of the table including null." }, { "code": null, "e": 1915, "s": 1851, "text": "COUNT( COLUMN_NAME): count number of non-null values in column." }, { "code": null, "e": 1979, "s": 1915, "text": "COUNT( COLUMN_NAME): count number of non-null values in column." }, { "code": null, "e": 2054, "s": 1979, "text": "COUNT( DISTINCT COLUMN_NAME): count number of distinct values in a column." }, { "code": null, "e": 2129, "s": 2054, "text": "COUNT( DISTINCT COLUMN_NAME): count number of distinct values in a column." }, { "code": null, "e": 2259, "s": 2129, "text": "The MAX function is used to find maximum value in the column that is supplied as a parameter. It can be used on any type of data." }, { "code": null, "e": 2329, "s": 2259, "text": "Example − Write a query to find the maximum salary in employee table." }, { "code": null, "e": 2362, "s": 2329, "text": "Select MAX(salary) from Employee" }, { "code": null, "e": 2434, "s": 2362, "text": "This function sums up the values in the column supplied as a parameter." }, { "code": null, "e": 2495, "s": 2434, "text": "Example: Write a query to get the total salary of employees." }, { "code": null, "e": 2528, "s": 2495, "text": "Select SUM(salary) from Employee" }, { "code": null, "e": 2620, "s": 2528, "text": "The STDDEV function is used to find standard deviation of the column specified as argument." }, { "code": null, "e": 2700, "s": 2620, "text": "Example − Write a query to find standard deviation of salary in Employee table." }, { "code": null, "e": 2736, "s": 2700, "text": "Select STDDEV(salary) from Employee" }, { "code": null, "e": 2820, "s": 2736, "text": "The VARIANCE Function is used to find variance of the column specified as argument." }, { "code": null, "e": 2830, "s": 2820, "text": "Example −" }, { "code": null, "e": 2868, "s": 2830, "text": "Select VARIANCE(salary) from Employee" } ]
Convert an int to ASCII character in C/C++
In C or C++ the character values are stored as ASCII values. To convert int to ASCII we can add the ASCII of character ‘0’ with the integer. Let us see an example to convert int to ASCII values. #include<stdio.h> int intToAscii(int number) { return '0' + number; } main() { printf("The ASCII of 5 is %d\n", intToAscii(5)); printf("The ASCII of 8 is %d\n", intToAscii(8)); } The ASCII of 5 is 53 The ASCII of 8 is 56
[ { "code": null, "e": 1257, "s": 1062, "text": "In C or C++ the character values are stored as ASCII values. To convert int to ASCII we can add the ASCII of character ‘0’ with the integer. Let us see an example to convert int to ASCII values." }, { "code": null, "e": 1445, "s": 1257, "text": "#include<stdio.h>\nint intToAscii(int number) {\n return '0' + number;\n}\nmain() {\n printf(\"The ASCII of 5 is %d\\n\", intToAscii(5));\n printf(\"The ASCII of 8 is %d\\n\", intToAscii(8));\n}" }, { "code": null, "e": 1487, "s": 1445, "text": "The ASCII of 5 is 53\nThe ASCII of 8 is 56" } ]
Getting Started with SNAP Toolbox in Python | by Aditya Sharma | Towards Data Science
Developed by the European Space Agency (ESA), SNAP is a common software platform that supports the Sentinel missions. It consists of several modules that can be modified and re-used for image processing, modelling and visualization of data from earth observation satellites. SNAP can be utilized not only as a research support tool for Sentinel missions (Sentinel 1, Sentinel 2 and Sentinel 3) but also as a functional outlet for effectively processing large amounts of satellite data, including data from other missions such as Landsat, MODIS and RapidEye in various different formats. The project page of SNAP and the individual toolboxes can be found at http://step.esa.int. In this article, I want to go through the step-by-step process of configuring your python installation to use the SNAP-Python or “snappy” interface. Doing so will allow you to efficiently analyze large volumes of satellite data by automating image processing tasks using python scripts. The article will cover the following topics: Download and install latest SNAP release (v7.0) on Windows,Configure snappy during and after the SNAP installation process,Setup a virtual environment,Configure optimal settings for snappy, andVisualize satellite data using snappy Download and install latest SNAP release (v7.0) on Windows, Configure snappy during and after the SNAP installation process, Setup a virtual environment, Configure optimal settings for snappy, and Visualize satellite data using snappy SNAP consists of several toolboxes. You can install each toolbox separately or you can install the all-in-one version. In this tutorial, we will install the latter. SNAP Toolboxes can be downloaded from the link below: https://step.esa.int/main/download/snap-download/ Before you should install the SNAP software on your system, I would recommend creating a virtual environment either using pip or conda. For this tutorial, we will use conda. To run this command, you need to have Anaconda or Miniconda installed on your system already. Create a new virtual environment called “snap” with python version 2.7 by executing the command below on your system’s python configured command line tool. conda create -n snap python=2.7 The reason we are using python version 2.7 is because SNAP software only supports python versions 2.7, 3.3 and 3.4. NOTE: If you are using pip to create a new environment you will have to install venv package. Find out more on how to create virtual environments using venv here. Next, we can start installing the SNAP software using the downloaded executable file. You can configure your python installation to use snappy during the SNAP installation itself by checking the tickbox and proving the path to your python directory (as shown below). However, in this tutorial, we will NOT check the tickbox and configure snappy after SNAP has finished installing. The rest of the installation process is pretty straight forward. The first time you start up SNAP it will do some updates. Once they’ve finished you are all set to use the SNAP software. Once SNAP has finished installing, we want to get the directory location of where our virtual environment “snap” is located. From there, we want the following two paths: Python executable path for your virtual environmentA folder called “Lib” in your virtual environment directory Python executable path for your virtual environment A folder called “Lib” in your virtual environment directory Open up the SNAP Command-Line Tool, which is installed as part of the SNAP software and run the following command: snappy-conf {path_to_snap_env}\python.exe {path_to_snap_env}\Lib\ Change the amount of RAM available Before we can start using snappy to create a python script, we need to change a few things in order to ensure that the snappy operators will run with highest optimality. The default setup is quite slow if you’re planning to do some image rendering and batch processing operations. This is important if you want to use snappy to automate heavy processing tasks and work with multiple files. Go over to the {virtural_env “snap ”directory } > Lib > snappy. Open the snappy configuration file called “snappy.ini”. Edit the value for the parameter called “java_max_mem” and set it to a value that corresponds to about 70–80% of your system’s RAM. java_max_mem: 26G In the same directory, lies a file called “jpyconfig.py”. Change the parameter “jvm_maxmem” like so: jvm_maxmem = '26G' Change the TileCache Memory Next, navigate to where your SNAP software is installed. By default it is set to C:\Program Files\snap. Inside it, you will find the folder called etc containing the SNAP properties file called “snap.properties”. Edit the file and change the parameter called snap.jai.tileCacheSize. Set this to a value equal to 70–80% of the java_max_mem value. The number you enter should be in megabytes. You may have to enable administrator privileges to save the changes to this file. snap.jai.tileCacheSize = 21504 NOTE: The values shown here are for a system with 32GB RAM. Changes must be made with your system’s RAM in mind. So for this last section, we want to explore how snappy works and visualize some sample data. Before we can start using snappy, we need some data and in this tutorial, we will use the testing data that comes pre-loaded with snappy installation. # Import Librariesimport osimport numpy as npimport matplotlib.pyplot as pltimport snappyfrom snappy import ProductIO# Set Path to Input Satellite Data# miniconda userspath = r'C:\Users\{User}\miniconda3\envs\snap\Lib\snappy\testdata'# anaconda userspath = r'C:\Users\{User}\anaconda3\envs\snap\Lib\snappy\testdata'filename = 'MER_FRS_L1B_SUBSET.dim'# Read Filedf = ProductIO.readProduct(os.path.join(path, filename))# Get the list of Band Nameslist(df.getBandNames())# Using "radiance_3" band as an exampleband = df.getBand('radiance_3') # Assign Band to a variablew = df.getSceneRasterWidth() # Get Band Widthh = df.getSceneRasterHeight() # Get Band Height# Create an empty arrayband_data = np.zeros(w * h, np.float32)# Populate array with pixel valueband.readPixels(0, 0, w, h, band_data) # Reshapeband_data.shape = h, w# Plot the band plt.figure(figsize=(18,10))plt.imshow(band_data, cmap = plt.cm.binary)plt.show() I’ve also made a video showing everything that I’ve laid out in this post. So if there is any confusion concerning how to go about the process of installing and configuring SNAP Toolbox in Python, do check it out. Github Page: https://github.com/senbox-orgConfiguring SNAP for Python: https://senbox.atlassian.net/wiki/spaces/SNAP/pages/50855941/Configure+Python+to+use+the+SNAP-Python+snappy+interfaceForum discussions that were useful while writing this post Github Page: https://github.com/senbox-org Configuring SNAP for Python: https://senbox.atlassian.net/wiki/spaces/SNAP/pages/50855941/Configure+Python+to+use+the+SNAP-Python+snappy+interface Forum discussions that were useful while writing this post
[ { "code": null, "e": 850, "s": 172, "text": "Developed by the European Space Agency (ESA), SNAP is a common software platform that supports the Sentinel missions. It consists of several modules that can be modified and re-used for image processing, modelling and visualization of data from earth observation satellites. SNAP can be utilized not only as a research support tool for Sentinel missions (Sentinel 1, Sentinel 2 and Sentinel 3) but also as a functional outlet for effectively processing large amounts of satellite data, including data from other missions such as Landsat, MODIS and RapidEye in various different formats. The project page of SNAP and the individual toolboxes can be found at http://step.esa.int." }, { "code": null, "e": 1137, "s": 850, "text": "In this article, I want to go through the step-by-step process of configuring your python installation to use the SNAP-Python or “snappy” interface. Doing so will allow you to efficiently analyze large volumes of satellite data by automating image processing tasks using python scripts." }, { "code": null, "e": 1182, "s": 1137, "text": "The article will cover the following topics:" }, { "code": null, "e": 1413, "s": 1182, "text": "Download and install latest SNAP release (v7.0) on Windows,Configure snappy during and after the SNAP installation process,Setup a virtual environment,Configure optimal settings for snappy, andVisualize satellite data using snappy" }, { "code": null, "e": 1473, "s": 1413, "text": "Download and install latest SNAP release (v7.0) on Windows," }, { "code": null, "e": 1538, "s": 1473, "text": "Configure snappy during and after the SNAP installation process," }, { "code": null, "e": 1567, "s": 1538, "text": "Setup a virtual environment," }, { "code": null, "e": 1610, "s": 1567, "text": "Configure optimal settings for snappy, and" }, { "code": null, "e": 1648, "s": 1610, "text": "Visualize satellite data using snappy" }, { "code": null, "e": 1813, "s": 1648, "text": "SNAP consists of several toolboxes. You can install each toolbox separately or you can install the all-in-one version. In this tutorial, we will install the latter." }, { "code": null, "e": 1917, "s": 1813, "text": "SNAP Toolboxes can be downloaded from the link below: https://step.esa.int/main/download/snap-download/" }, { "code": null, "e": 2185, "s": 1917, "text": "Before you should install the SNAP software on your system, I would recommend creating a virtual environment either using pip or conda. For this tutorial, we will use conda. To run this command, you need to have Anaconda or Miniconda installed on your system already." }, { "code": null, "e": 2341, "s": 2185, "text": "Create a new virtual environment called “snap” with python version 2.7 by executing the command below on your system’s python configured command line tool." }, { "code": null, "e": 2373, "s": 2341, "text": "conda create -n snap python=2.7" }, { "code": null, "e": 2489, "s": 2373, "text": "The reason we are using python version 2.7 is because SNAP software only supports python versions 2.7, 3.3 and 3.4." }, { "code": null, "e": 2652, "s": 2489, "text": "NOTE: If you are using pip to create a new environment you will have to install venv package. Find out more on how to create virtual environments using venv here." }, { "code": null, "e": 2738, "s": 2652, "text": "Next, we can start installing the SNAP software using the downloaded executable file." }, { "code": null, "e": 3033, "s": 2738, "text": "You can configure your python installation to use snappy during the SNAP installation itself by checking the tickbox and proving the path to your python directory (as shown below). However, in this tutorial, we will NOT check the tickbox and configure snappy after SNAP has finished installing." }, { "code": null, "e": 3220, "s": 3033, "text": "The rest of the installation process is pretty straight forward. The first time you start up SNAP it will do some updates. Once they’ve finished you are all set to use the SNAP software." }, { "code": null, "e": 3390, "s": 3220, "text": "Once SNAP has finished installing, we want to get the directory location of where our virtual environment “snap” is located. From there, we want the following two paths:" }, { "code": null, "e": 3501, "s": 3390, "text": "Python executable path for your virtual environmentA folder called “Lib” in your virtual environment directory" }, { "code": null, "e": 3553, "s": 3501, "text": "Python executable path for your virtual environment" }, { "code": null, "e": 3613, "s": 3553, "text": "A folder called “Lib” in your virtual environment directory" }, { "code": null, "e": 3728, "s": 3613, "text": "Open up the SNAP Command-Line Tool, which is installed as part of the SNAP software and run the following command:" }, { "code": null, "e": 3794, "s": 3728, "text": "snappy-conf {path_to_snap_env}\\python.exe {path_to_snap_env}\\Lib\\" }, { "code": null, "e": 3829, "s": 3794, "text": "Change the amount of RAM available" }, { "code": null, "e": 4219, "s": 3829, "text": "Before we can start using snappy to create a python script, we need to change a few things in order to ensure that the snappy operators will run with highest optimality. The default setup is quite slow if you’re planning to do some image rendering and batch processing operations. This is important if you want to use snappy to automate heavy processing tasks and work with multiple files." }, { "code": null, "e": 4283, "s": 4219, "text": "Go over to the {virtural_env “snap ”directory } > Lib > snappy." }, { "code": null, "e": 4339, "s": 4283, "text": "Open the snappy configuration file called “snappy.ini”." }, { "code": null, "e": 4471, "s": 4339, "text": "Edit the value for the parameter called “java_max_mem” and set it to a value that corresponds to about 70–80% of your system’s RAM." }, { "code": null, "e": 4489, "s": 4471, "text": "java_max_mem: 26G" }, { "code": null, "e": 4590, "s": 4489, "text": "In the same directory, lies a file called “jpyconfig.py”. Change the parameter “jvm_maxmem” like so:" }, { "code": null, "e": 4609, "s": 4590, "text": "jvm_maxmem = '26G'" }, { "code": null, "e": 4637, "s": 4609, "text": "Change the TileCache Memory" }, { "code": null, "e": 5110, "s": 4637, "text": "Next, navigate to where your SNAP software is installed. By default it is set to C:\\Program Files\\snap. Inside it, you will find the folder called etc containing the SNAP properties file called “snap.properties”. Edit the file and change the parameter called snap.jai.tileCacheSize. Set this to a value equal to 70–80% of the java_max_mem value. The number you enter should be in megabytes. You may have to enable administrator privileges to save the changes to this file." }, { "code": null, "e": 5141, "s": 5110, "text": "snap.jai.tileCacheSize = 21504" }, { "code": null, "e": 5254, "s": 5141, "text": "NOTE: The values shown here are for a system with 32GB RAM. Changes must be made with your system’s RAM in mind." }, { "code": null, "e": 5499, "s": 5254, "text": "So for this last section, we want to explore how snappy works and visualize some sample data. Before we can start using snappy, we need some data and in this tutorial, we will use the testing data that comes pre-loaded with snappy installation." }, { "code": null, "e": 6420, "s": 5499, "text": "# Import Librariesimport osimport numpy as npimport matplotlib.pyplot as pltimport snappyfrom snappy import ProductIO# Set Path to Input Satellite Data# miniconda userspath = r'C:\\Users\\{User}\\miniconda3\\envs\\snap\\Lib\\snappy\\testdata'# anaconda userspath = r'C:\\Users\\{User}\\anaconda3\\envs\\snap\\Lib\\snappy\\testdata'filename = 'MER_FRS_L1B_SUBSET.dim'# Read Filedf = ProductIO.readProduct(os.path.join(path, filename))# Get the list of Band Nameslist(df.getBandNames())# Using \"radiance_3\" band as an exampleband = df.getBand('radiance_3') # Assign Band to a variablew = df.getSceneRasterWidth() # Get Band Widthh = df.getSceneRasterHeight() # Get Band Height# Create an empty arrayband_data = np.zeros(w * h, np.float32)# Populate array with pixel valueband.readPixels(0, 0, w, h, band_data) # Reshapeband_data.shape = h, w# Plot the band plt.figure(figsize=(18,10))plt.imshow(band_data, cmap = plt.cm.binary)plt.show()" }, { "code": null, "e": 6634, "s": 6420, "text": "I’ve also made a video showing everything that I’ve laid out in this post. So if there is any confusion concerning how to go about the process of installing and configuring SNAP Toolbox in Python, do check it out." }, { "code": null, "e": 6881, "s": 6634, "text": "Github Page: https://github.com/senbox-orgConfiguring SNAP for Python: https://senbox.atlassian.net/wiki/spaces/SNAP/pages/50855941/Configure+Python+to+use+the+SNAP-Python+snappy+interfaceForum discussions that were useful while writing this post" }, { "code": null, "e": 6924, "s": 6881, "text": "Github Page: https://github.com/senbox-org" }, { "code": null, "e": 7071, "s": 6924, "text": "Configuring SNAP for Python: https://senbox.atlassian.net/wiki/spaces/SNAP/pages/50855941/Configure+Python+to+use+the+SNAP-Python+snappy+interface" } ]
How to Join Spatial Data with PostgreSQL/PostGIS | by Abdishakur | Towards Data Science
Joining data is a common task in the data science world. While the regular SQL table join is a great feature, I am most impressed by the real power of spatial joins. With Spatial Join, you can correlate information from different tables based on their geometry relations. In this tutorial, we will see examples of spatial join and also summarizing features after the spatial join. If you are new to the world of PostgreSQL/PostGIS, I have a beginner’s tutorial to set you up the environment and gets you started quickly with step by step guide. towardsdatascience.com We are using Barcelona Airbnb dataset for this tutorial with smaller statistical areas. Our task is to join the Airbnb public listings to the respective smaller statistical area they belong to. In other words, we would like to find out which area each Airbnb points falls in. Finally, we will summary the joined data to find out how many Airbnb guest houses each statistical area has. Before we go through the spatial join, let us first familiarize our self with the dataset. We look at the public listings by querying these columns and limiting the result to the first 100 listings. SELECT name, host_name, room_type, price, reviews_per_month, neighbourhood, geomFROM public.listingsLIMIT 100; We display the result below of the first ten rows. We have the name of the listing, the hostname, room type, price, reviews, neighbourhoods and the geometry(Geom). The geometry column has a small eye that allows you to visualize the spatial data. Here is the output of the geometry viewer for the Airbnb listings. Note that this is limited to the first 100 points only. Now, let us look at the statistical area dataset. We simply limit the columns to the geometry and the code of the area. SELECT aeb, geomFROM public.statistical_areas The following map displays the Statistical area polygons visualized with PgAdmin4 Geometry Viewer. Before, we move to carry out the spatial join, make sure to check out if the Coordinate Reference System (CRS) of both datasets match. We can simply query out the Spatial Reference System of each dataset like this. SELECT ST_SRID(geom) FROM public.statistical_areasLIMIT 1; And both datasets have WGS84 CRS, so we can go ahead and perform the spatial join. We have seen the dataset and checked the CRS of the dataset. All is set now. To join both datasets, we can use different spatial relations including ST_Within ,ST_Contains, ST_Covers, orST_Crosses . In this example, we are using ST_Within to find out which point is within which polygon. SELECT houses.name AS guest_name, houses.room_type as room, houses.price as Price, areas.aeb AS statistical_codeFROM listings AS housesJOIN statistical_areas AS areasON ST_Within(houses.geom, areas.geom) The result is this table with Airbnb listings with an additional column indicated which statistical area code each point belongs to as shown in below table. Great! The spatial join could be your final results if you were after to find out only where each point belongs to. However, we might need to summarize the spatial join result to find out insights in the distribution of the dataset. Any SQL aggregate function would work here to gain insights from the spatially joined dataset. Let us say we want to find out the average Airbnb listings prices for each statistical neighbourhoods. We only need to use the Average aggregate function with listing prices and group the data by statistical area. SELECT AVG(houses.price) AS AVG_Price, areas.aeb AS statistical_codeFROM listings AS housesJOIN statistical_areas AS areasON ST_Within(houses.geom, areas.geom)GROUP BY areas.aeb The result is this table where we have the average price of each statistical area. Here is a map showing the average price distribution for the statistical areas in Barcelona. In this tutorial, we have seen how to do spatial join with PostGIS using real-world dataset. We successfully joined Airbnb listings to their respective statistical areas using geometry relations. You might experiment using ST_Contains to come up with the same results. You might also like to experiment with different aggregation functions, like counting the number of listings in each statistical area.
[ { "code": null, "e": 338, "s": 172, "text": "Joining data is a common task in the data science world. While the regular SQL table join is a great feature, I am most impressed by the real power of spatial joins." }, { "code": null, "e": 553, "s": 338, "text": "With Spatial Join, you can correlate information from different tables based on their geometry relations. In this tutorial, we will see examples of spatial join and also summarizing features after the spatial join." }, { "code": null, "e": 717, "s": 553, "text": "If you are new to the world of PostgreSQL/PostGIS, I have a beginner’s tutorial to set you up the environment and gets you started quickly with step by step guide." }, { "code": null, "e": 740, "s": 717, "text": "towardsdatascience.com" }, { "code": null, "e": 1125, "s": 740, "text": "We are using Barcelona Airbnb dataset for this tutorial with smaller statistical areas. Our task is to join the Airbnb public listings to the respective smaller statistical area they belong to. In other words, we would like to find out which area each Airbnb points falls in. Finally, we will summary the joined data to find out how many Airbnb guest houses each statistical area has." }, { "code": null, "e": 1324, "s": 1125, "text": "Before we go through the spatial join, let us first familiarize our self with the dataset. We look at the public listings by querying these columns and limiting the result to the first 100 listings." }, { "code": null, "e": 1435, "s": 1324, "text": "SELECT name, host_name, room_type, price, reviews_per_month, neighbourhood, geomFROM public.listingsLIMIT 100;" }, { "code": null, "e": 1682, "s": 1435, "text": "We display the result below of the first ten rows. We have the name of the listing, the hostname, room type, price, reviews, neighbourhoods and the geometry(Geom). The geometry column has a small eye that allows you to visualize the spatial data." }, { "code": null, "e": 1805, "s": 1682, "text": "Here is the output of the geometry viewer for the Airbnb listings. Note that this is limited to the first 100 points only." }, { "code": null, "e": 1925, "s": 1805, "text": "Now, let us look at the statistical area dataset. We simply limit the columns to the geometry and the code of the area." }, { "code": null, "e": 1971, "s": 1925, "text": "SELECT aeb, geomFROM public.statistical_areas" }, { "code": null, "e": 2070, "s": 1971, "text": "The following map displays the Statistical area polygons visualized with PgAdmin4 Geometry Viewer." }, { "code": null, "e": 2285, "s": 2070, "text": "Before, we move to carry out the spatial join, make sure to check out if the Coordinate Reference System (CRS) of both datasets match. We can simply query out the Spatial Reference System of each dataset like this." }, { "code": null, "e": 2344, "s": 2285, "text": "SELECT ST_SRID(geom) FROM public.statistical_areasLIMIT 1;" }, { "code": null, "e": 2427, "s": 2344, "text": "And both datasets have WGS84 CRS, so we can go ahead and perform the spatial join." }, { "code": null, "e": 2715, "s": 2427, "text": "We have seen the dataset and checked the CRS of the dataset. All is set now. To join both datasets, we can use different spatial relations including ST_Within ,ST_Contains, ST_Covers, orST_Crosses . In this example, we are using ST_Within to find out which point is within which polygon." }, { "code": null, "e": 2920, "s": 2715, "text": "SELECT houses.name AS guest_name, houses.room_type as room, houses.price as Price, areas.aeb AS statistical_codeFROM listings AS housesJOIN statistical_areas AS areasON ST_Within(houses.geom, areas.geom)" }, { "code": null, "e": 3077, "s": 2920, "text": "The result is this table with Airbnb listings with an additional column indicated which statistical area code each point belongs to as shown in below table." }, { "code": null, "e": 3310, "s": 3077, "text": "Great! The spatial join could be your final results if you were after to find out only where each point belongs to. However, we might need to summarize the spatial join result to find out insights in the distribution of the dataset." }, { "code": null, "e": 3508, "s": 3310, "text": "Any SQL aggregate function would work here to gain insights from the spatially joined dataset. Let us say we want to find out the average Airbnb listings prices for each statistical neighbourhoods." }, { "code": null, "e": 3619, "s": 3508, "text": "We only need to use the Average aggregate function with listing prices and group the data by statistical area." }, { "code": null, "e": 3797, "s": 3619, "text": "SELECT AVG(houses.price) AS AVG_Price, areas.aeb AS statistical_codeFROM listings AS housesJOIN statistical_areas AS areasON ST_Within(houses.geom, areas.geom)GROUP BY areas.aeb" }, { "code": null, "e": 3880, "s": 3797, "text": "The result is this table where we have the average price of each statistical area." }, { "code": null, "e": 3973, "s": 3880, "text": "Here is a map showing the average price distribution for the statistical areas in Barcelona." } ]
SAS - DO Index Loop
This DO Index loop uses a index variable for its start and end value. The SAS statements are repeatedly executed until the final value of the index variable is reached. DO indexvariable = initialvalue to finalvalue ; . . . SAS statements . . . ; END; DATA MYDATA1; SUM = 0; DO VAR = 1 to 5; SUM = SUM+VAR; END; PROC PRINT DATA = MYDATA1; RUN; When the above code is executed, it produces the following result 50 Lectures 5.5 hours Code And Create 124 Lectures 30 hours Juan Galvan 162 Lectures 31.5 hours Yossef Ayman Zedan 35 Lectures 2.5 hours Ermin Dedic 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 2752, "s": 2583, "text": "This DO Index loop uses a index variable for its start and end value. The SAS statements are repeatedly executed until the final value of the index variable is reached." }, { "code": null, "e": 2835, "s": 2752, "text": "DO indexvariable = initialvalue to finalvalue ;\n. . . SAS statements . . . ;\nEND;\n" }, { "code": null, "e": 2931, "s": 2835, "text": "DATA MYDATA1;\nSUM = 0;\nDO VAR = 1 to 5;\n SUM = SUM+VAR;\nEND;\n\nPROC PRINT DATA = MYDATA1;\nRUN;" }, { "code": null, "e": 2997, "s": 2931, "text": "When the above code is executed, it produces the following result" }, { "code": null, "e": 3034, "s": 2999, "text": "\n 50 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3051, "s": 3034, "text": " Code And Create" }, { "code": null, "e": 3086, "s": 3051, "text": "\n 124 Lectures \n 30 hours \n" }, { "code": null, "e": 3099, "s": 3086, "text": " Juan Galvan" }, { "code": null, "e": 3136, "s": 3099, "text": "\n 162 Lectures \n 31.5 hours \n" }, { "code": null, "e": 3156, "s": 3136, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 3191, "s": 3156, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3204, "s": 3191, "text": " Ermin Dedic" }, { "code": null, "e": 3241, "s": 3204, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 3257, "s": 3241, "text": " Muslim Helalee" }, { "code": null, "e": 3264, "s": 3257, "text": " Print" }, { "code": null, "e": 3275, "s": 3264, "text": " Add Notes" } ]
News classification: fine-tuning RoBERTa on TPUs with TensorFlow | by Gabriele Sgroi | Towards Data Science
Fine-tuning large pre-trained models on downstream tasks is a common practice in Natural Language Processing. In this tutorial, we will use a pre-trained RoBERTa model for a multiclass classification task. RoBERTa: A Robustly Optimized BERT Pretraining Approach, developed by Facebook AI, improves on the popular BERT model by modifying key hyperparameters and pretraining on a larger corpus. This leads to improved performance compared to vanilla BERT. The transformers library by Hugging Face allows to easily deploy pre-trained models for a variety of NLP tasks with few lines of code. There is a variety of Auto Model classes that wrap up the pre-trained models implementing automatically the necessary architectural changes needed for common downstream tasks. Furthermore, these models can be cast as Keras models allowing easy training through the Keras API. In this tutorial, we will fine-tune RoBERTa on the News Category Dataset, hosted on Kaggle, to predict the category of news from their title and a short description. The dataset contains 200k news headlines obtained from the year 2012 to 2018. Full code is available in the following public Colab notebook. We first have to install the transformers library, this can be easily done through pip install transformers. Next, we import the libraries needed for the rest of the tutorial. The model has been trained using Colab free TPUs. TPUs will allow us to train our model much faster and will also allow us to use a larger batch size. To enable TPU on Colab click on “Edit”->“Notebook Settings” and select “TPU” in the “Hardware Accelerator” field. To instantiate the TPU in order to use it with TensorFlow we need to run the following code To make full use of the TPU potential, we have set a batch size that is a multiple of the number of TPUs in our cluster. We will then just need to instantiate our model under tpu_strategy.scope(). Let’s load the data. We will concatenate the headline and the description into a single input text that we will feed to our network later. The news headlines are classified into 41 categories, let’s visualize how they are distributed. We see that we have a lot of categories with few entries. Furthermore, some categories may refer to closely related or overlapping concepts. Since there is a significant number of categories to predict, let’s aggregate the categories that refer to similar concepts. This will make the classification task a little bit easier. We are thus left with 28 aggregated categories distributed as follows We have now to preprocess our data in a way that can be used by a Tensorflow Keras model. As a first step, we need to turn the classes labels into indices. We don’t need a one-hot encoding since we will work with TensorFlow SparseCategorical loss. Next, we need to tokenize the text i.e. we need to transform our strings into a list of indices that can be fed to the model. The transformers library provides us the AutoTokenizer class that allows loading the pre-trained tokenizer used for RoBERTa. RoBERTa uses a byte-level BPE tokenizer that performs subword tokenization, i.e. unknown rare words are split into common subwords present in the vocabulary. We will see what this means in examples. Here the flag padding=True will pad the sentence to the max length passed in the batch. On the other side, truncation=True will truncate the sentences to the maximum number of tokens the model can accept (512 for RoBERTa, as for BERT). Let’s visualize how the text gets tokenized. Input: Twitter Users Just Say No To Kellyanne Conway's Drug Abuse Cure Subword tokenization: ['Twitter', 'ĠUsers', 'ĠJust', 'ĠSay', 'ĠNo', 'ĠTo', 'ĠKell', 'yan', 'ne', 'ĠConway', "'s", 'ĠDrug', 'ĠAbuse', 'ĠCure'] Indices: [0, 22838, 16034, 1801, 9867, 440, 598, 12702, 7010, 858, 13896, 18, 8006, 23827, 32641, 2, 1, 1, 1] Input: Target's Wedding Dresses Are Nicer Than You Might Think (VIDEO) Subword tokenization: ['Target', "'s", 'ĠWedding', 'ĠD', 'resses', 'ĠAre', 'ĠNic', 'er', 'ĠThan', 'ĠYou', 'ĠMight', 'ĠThink', 'Ġ(', 'VIDEO', ')'] Indices: [0, 41858, 18, 21238, 211, 13937, 3945, 13608, 254, 15446, 370, 30532, 9387, 36, 36662, 43, 2, 1, 1] Input: Televisa Reinstates Fired Hosts, Is Investigating Sexual Harassment Claims Subword tokenization: ['Te', 'lev', 'isa', 'ĠRe', 'inst', 'ates', 'ĠFired', 'ĠHost', 's', ',', 'ĠIs', 'ĠInvestig', 'ating', 'ĠSexual', 'ĠHar', 'assment', 'ĠClaims'] Indices: [0, 16215, 9525, 6619, 1223, 16063, 1626, 41969, 10664, 29, 6, 1534, 34850, 1295, 18600, 2482, 34145, 28128, 2] The character Ġ appearing in subword tokenization indicates the beginning of a new word, tokens missing it are just parts of a bigger word that has been split. RoBERTa tokenizer uses 0 for the beginning of the sentence token, 1 is the pad token, and 2 is the end of the sentence token. As the last step in our data preprocessing, we create a TensorFlow dataset from our data and we use the first 10% of the data for validation. Now that we have preprocessed the data, we need to instantiate the model. We will use the Hugging Face TensorFlow auto class for sequence classification. Using the method from_pretrained, setting num_labels equal to the number of classes in our dataset, this class will take care of all the dirty work for us. It will download the pre-trained RoBERTa weights and instantiate a Keras model with a classification head on top. We can thus use all the usual Keras methods such as compile, fit and save_weights. We fine-tune our model for 6 epochs with a small learning rate 1e-5 and clipnorm=1. to limit potentially big gradients that could destroy the features learned during pretraining. We see that the validation loss saturates pretty quickly while the training loss continues to lower. The model is in fact quite powerful and starts to overfit if trained for longer. The model reach ~77% top-1-accuracy and ~93% top-3-accuracy on the validation set out of a total of 28 classes. Let’s visualize the confusion matrix on the validation set Let’s compute (weighted) precision, recall, and f1 metrics of the model. For a quick overview of these metrics, you can look at the nice posts Multi-Class Metrics Made Simple, Part I: Precision and Recall, and Multi-Class Metrics Made Simple, Part II: the F1-score. Precision:0.769Recall:0.775F1 score:0.769 Let’s visualize the top-3 predictions by probability for some examples in the validation set. The probability for each prediction is indicated in round brackets. HEADLINE: Homemade Gift Ideas: Tart-Cherry and Dark Chocolate Bar Wrappers SHORT DESCRIPTION: This DIY gift only LOOKS professional. TRUE LABEL: HOME & LIVING Prediction 1:HOME & LIVING (77.5%); Prediction 2:FOOD, DRINK & TASTE (19.8%); Prediction 3:STYLE & BEAUTY (0.7%); HEADLINE: Small Parties Claim Their Share In Upcoming Greek Elections SHORT DESCRIPTION: Some of the country's lesser-known political players believe they've spotted their chance. TRUE LABEL: WORLD NEWS Prediction 1:WORLD NEWS (99.2%); Prediction 2:POLITICS (0.4%); Prediction 3:ENVIRONMENT & GREEN (0.1%); HEADLINE: 46 Tons Of Beads Found In New Orleans' Storm Drains SHORT DESCRIPTION: The Big Easy is also the big messy. TRUE LABEL: WEIRD NEWS Prediction 1:WEIRD NEWS (55.0%); Prediction 2:ENVIRONMENT & GREEN (14.4%); Prediction 3:SCIENCE & TECH (10.0%); We have seen how to use the Hugging Face transformers library together with TensorFlow to fine-tune a large pre-trained model using TPUs on a multiclass classification task. Thanks to the plethora of Auto Classes in the transformers library, other common NLP downstream tasks can be performed with minor modifications to the code provided. I hope this tutorial was useful, thanks for reading!
[ { "code": null, "e": 377, "s": 171, "text": "Fine-tuning large pre-trained models on downstream tasks is a common practice in Natural Language Processing. In this tutorial, we will use a pre-trained RoBERTa model for a multiclass classification task." }, { "code": null, "e": 625, "s": 377, "text": "RoBERTa: A Robustly Optimized BERT Pretraining Approach, developed by Facebook AI, improves on the popular BERT model by modifying key hyperparameters and pretraining on a larger corpus. This leads to improved performance compared to vanilla BERT." }, { "code": null, "e": 1036, "s": 625, "text": "The transformers library by Hugging Face allows to easily deploy pre-trained models for a variety of NLP tasks with few lines of code. There is a variety of Auto Model classes that wrap up the pre-trained models implementing automatically the necessary architectural changes needed for common downstream tasks. Furthermore, these models can be cast as Keras models allowing easy training through the Keras API." }, { "code": null, "e": 1280, "s": 1036, "text": "In this tutorial, we will fine-tune RoBERTa on the News Category Dataset, hosted on Kaggle, to predict the category of news from their title and a short description. The dataset contains 200k news headlines obtained from the year 2012 to 2018." }, { "code": null, "e": 1343, "s": 1280, "text": "Full code is available in the following public Colab notebook." }, { "code": null, "e": 1452, "s": 1343, "text": "We first have to install the transformers library, this can be easily done through pip install transformers." }, { "code": null, "e": 1519, "s": 1452, "text": "Next, we import the libraries needed for the rest of the tutorial." }, { "code": null, "e": 1876, "s": 1519, "text": "The model has been trained using Colab free TPUs. TPUs will allow us to train our model much faster and will also allow us to use a larger batch size. To enable TPU on Colab click on “Edit”->“Notebook Settings” and select “TPU” in the “Hardware Accelerator” field. To instantiate the TPU in order to use it with TensorFlow we need to run the following code" }, { "code": null, "e": 2073, "s": 1876, "text": "To make full use of the TPU potential, we have set a batch size that is a multiple of the number of TPUs in our cluster. We will then just need to instantiate our model under tpu_strategy.scope()." }, { "code": null, "e": 2212, "s": 2073, "text": "Let’s load the data. We will concatenate the headline and the description into a single input text that we will feed to our network later." }, { "code": null, "e": 2308, "s": 2212, "text": "The news headlines are classified into 41 categories, let’s visualize how they are distributed." }, { "code": null, "e": 2634, "s": 2308, "text": "We see that we have a lot of categories with few entries. Furthermore, some categories may refer to closely related or overlapping concepts. Since there is a significant number of categories to predict, let’s aggregate the categories that refer to similar concepts. This will make the classification task a little bit easier." }, { "code": null, "e": 2704, "s": 2634, "text": "We are thus left with 28 aggregated categories distributed as follows" }, { "code": null, "e": 2952, "s": 2704, "text": "We have now to preprocess our data in a way that can be used by a Tensorflow Keras model. As a first step, we need to turn the classes labels into indices. We don’t need a one-hot encoding since we will work with TensorFlow SparseCategorical loss." }, { "code": null, "e": 3203, "s": 2952, "text": "Next, we need to tokenize the text i.e. we need to transform our strings into a list of indices that can be fed to the model. The transformers library provides us the AutoTokenizer class that allows loading the pre-trained tokenizer used for RoBERTa." }, { "code": null, "e": 3402, "s": 3203, "text": "RoBERTa uses a byte-level BPE tokenizer that performs subword tokenization, i.e. unknown rare words are split into common subwords present in the vocabulary. We will see what this means in examples." }, { "code": null, "e": 3638, "s": 3402, "text": "Here the flag padding=True will pad the sentence to the max length passed in the batch. On the other side, truncation=True will truncate the sentences to the maximum number of tokens the model can accept (512 for RoBERTa, as for BERT)." }, { "code": null, "e": 3683, "s": 3638, "text": "Let’s visualize how the text gets tokenized." }, { "code": null, "e": 4728, "s": 3683, "text": "Input: Twitter Users Just Say No To Kellyanne Conway's Drug Abuse Cure Subword tokenization: ['Twitter', 'ĠUsers', 'ĠJust', 'ĠSay', 'ĠNo', 'ĠTo', 'ĠKell', 'yan', 'ne', 'ĠConway', \"'s\", 'ĠDrug', 'ĠAbuse', 'ĠCure'] Indices: [0, 22838, 16034, 1801, 9867, 440, 598, 12702, 7010, 858, 13896, 18, 8006, 23827, 32641, 2, 1, 1, 1] Input: Target's Wedding Dresses Are Nicer Than You Might Think (VIDEO) Subword tokenization: ['Target', \"'s\", 'ĠWedding', 'ĠD', 'resses', 'ĠAre', 'ĠNic', 'er', 'ĠThan', 'ĠYou', 'ĠMight', 'ĠThink', 'Ġ(', 'VIDEO', ')'] Indices: [0, 41858, 18, 21238, 211, 13937, 3945, 13608, 254, 15446, 370, 30532, 9387, 36, 36662, 43, 2, 1, 1] Input: Televisa Reinstates Fired Hosts, Is Investigating Sexual Harassment Claims Subword tokenization: ['Te', 'lev', 'isa', 'ĠRe', 'inst', 'ates', 'ĠFired', 'ĠHost', 's', ',', 'ĠIs', 'ĠInvestig', 'ating', 'ĠSexual', 'ĠHar', 'assment', 'ĠClaims'] Indices: [0, 16215, 9525, 6619, 1223, 16063, 1626, 41969, 10664, 29, 6, 1534, 34850, 1295, 18600, 2482, 34145, 28128, 2]" }, { "code": null, "e": 5015, "s": 4728, "text": "The character Ġ appearing in subword tokenization indicates the beginning of a new word, tokens missing it are just parts of a bigger word that has been split. RoBERTa tokenizer uses 0 for the beginning of the sentence token, 1 is the pad token, and 2 is the end of the sentence token." }, { "code": null, "e": 5157, "s": 5015, "text": "As the last step in our data preprocessing, we create a TensorFlow dataset from our data and we use the first 10% of the data for validation." }, { "code": null, "e": 5843, "s": 5157, "text": "Now that we have preprocessed the data, we need to instantiate the model. We will use the Hugging Face TensorFlow auto class for sequence classification. Using the method from_pretrained, setting num_labels equal to the number of classes in our dataset, this class will take care of all the dirty work for us. It will download the pre-trained RoBERTa weights and instantiate a Keras model with a classification head on top. We can thus use all the usual Keras methods such as compile, fit and save_weights. We fine-tune our model for 6 epochs with a small learning rate 1e-5 and clipnorm=1. to limit potentially big gradients that could destroy the features learned during pretraining." }, { "code": null, "e": 6025, "s": 5843, "text": "We see that the validation loss saturates pretty quickly while the training loss continues to lower. The model is in fact quite powerful and starts to overfit if trained for longer." }, { "code": null, "e": 6137, "s": 6025, "text": "The model reach ~77% top-1-accuracy and ~93% top-3-accuracy on the validation set out of a total of 28 classes." }, { "code": null, "e": 6196, "s": 6137, "text": "Let’s visualize the confusion matrix on the validation set" }, { "code": null, "e": 6462, "s": 6196, "text": "Let’s compute (weighted) precision, recall, and f1 metrics of the model. For a quick overview of these metrics, you can look at the nice posts Multi-Class Metrics Made Simple, Part I: Precision and Recall, and Multi-Class Metrics Made Simple, Part II: the F1-score." }, { "code": null, "e": 6504, "s": 6462, "text": "Precision:0.769Recall:0.775F1 score:0.769" }, { "code": null, "e": 6666, "s": 6504, "text": "Let’s visualize the top-3 predictions by probability for some examples in the validation set. The probability for each prediction is indicated in round brackets." }, { "code": null, "e": 7502, "s": 6666, "text": "HEADLINE: Homemade Gift Ideas: Tart-Cherry and Dark Chocolate Bar Wrappers SHORT DESCRIPTION: This DIY gift only LOOKS professional. TRUE LABEL: HOME & LIVING Prediction 1:HOME & LIVING (77.5%); Prediction 2:FOOD, DRINK & TASTE (19.8%); Prediction 3:STYLE & BEAUTY (0.7%); HEADLINE: Small Parties Claim Their Share In Upcoming Greek Elections SHORT DESCRIPTION: Some of the country's lesser-known political players believe they've spotted their chance. TRUE LABEL: WORLD NEWS Prediction 1:WORLD NEWS (99.2%); Prediction 2:POLITICS (0.4%); Prediction 3:ENVIRONMENT & GREEN (0.1%); HEADLINE: 46 Tons Of Beads Found In New Orleans' Storm Drains SHORT DESCRIPTION: The Big Easy is also the big messy. TRUE LABEL: WEIRD NEWS Prediction 1:WEIRD NEWS (55.0%); Prediction 2:ENVIRONMENT & GREEN (14.4%); Prediction 3:SCIENCE & TECH (10.0%);" }, { "code": null, "e": 7676, "s": 7502, "text": "We have seen how to use the Hugging Face transformers library together with TensorFlow to fine-tune a large pre-trained model using TPUs on a multiclass classification task." }, { "code": null, "e": 7842, "s": 7676, "text": "Thanks to the plethora of Auto Classes in the transformers library, other common NLP downstream tasks can be performed with minor modifications to the code provided." } ]
Python | Find yesterday's, today's and tomorrow's date - GeeksforGeeks
17 Dec, 2019 Prerequisites: datetime module We can handle Data objects by importing the module datetime and timedelta to work with dates. datetime module helps to find the present day by using the now() or today() method. timedelta class from datetime module helps to find the previous day date and next day date. Syntax for timedelta: class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) timedelta class is used because manipulating the date directly with increment and decrement will lead to a false Date. For example, if the present date is 31th of December, incrementing the date directly will only lead to the 32nd of December which is false. If we want to manipulate the Date directly first we have check day month and year combined and them increment accordingly. But, all this mess can be controlled by using timedelta class. Syntax to find a present-day date: datetime.now() Returns: A datetime object containing the current local date and time. Syntax to find a previous-day and next-day date: previous-day = datetime.now()-timedelta(1) next-day = datetime.now()+timedelta(1) Example: # Python program to find yesterday,# today and tomorrow # Import datetime and timedelta# class from datetime modulefrom datetime import datetime, timedelta # Get today's datepresentday = datetime.now() # or presentday = datetime.today() # Get Yesterdayyesterday = presentday - timedelta(1) # Get Tomorrowtomorrow = presentday + timedelta(1) # strftime() is to format date according to# the need by converting them to stringprint("Yesterday = ", yesterday.strftime('%d-%m-%Y'))print("Today = ", presentday.strftime('%d-%m-%Y'))print("Tomorrow = ", tomorrow.strftime('%d-%m-%Y')) Yesterday = 10-12-2019 Today = 11-12-2019 Tomorrow = 12-12-2019 Python datetime-program Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Defaultdict in Python Create a directory in Python Python Classes and Objects
[ { "code": null, "e": 24212, "s": 24184, "text": "\n17 Dec, 2019" }, { "code": null, "e": 24243, "s": 24212, "text": "Prerequisites: datetime module" }, { "code": null, "e": 24337, "s": 24243, "text": "We can handle Data objects by importing the module datetime and timedelta to work with dates." }, { "code": null, "e": 24421, "s": 24337, "text": "datetime module helps to find the present day by using the now() or today() method." }, { "code": null, "e": 24513, "s": 24421, "text": "timedelta class from datetime module helps to find the previous day date and next day date." }, { "code": null, "e": 24535, "s": 24513, "text": "Syntax for timedelta:" }, { "code": null, "e": 24640, "s": 24535, "text": "class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)" }, { "code": null, "e": 25085, "s": 24640, "text": "timedelta class is used because manipulating the date directly with increment and decrement will lead to a false Date. For example, if the present date is 31th of December, incrementing the date directly will only lead to the 32nd of December which is false. If we want to manipulate the Date directly first we have check day month and year combined and them increment accordingly. But, all this mess can be controlled by using timedelta class." }, { "code": null, "e": 25120, "s": 25085, "text": "Syntax to find a present-day date:" }, { "code": null, "e": 25135, "s": 25120, "text": "datetime.now()" }, { "code": null, "e": 25206, "s": 25135, "text": "Returns: A datetime object containing the current local date and time." }, { "code": null, "e": 25255, "s": 25206, "text": "Syntax to find a previous-day and next-day date:" }, { "code": null, "e": 25298, "s": 25255, "text": "previous-day = datetime.now()-timedelta(1)" }, { "code": null, "e": 25337, "s": 25298, "text": "next-day = datetime.now()+timedelta(1)" }, { "code": null, "e": 25346, "s": 25337, "text": "Example:" }, { "code": "# Python program to find yesterday,# today and tomorrow # Import datetime and timedelta# class from datetime modulefrom datetime import datetime, timedelta # Get today's datepresentday = datetime.now() # or presentday = datetime.today() # Get Yesterdayyesterday = presentday - timedelta(1) # Get Tomorrowtomorrow = presentday + timedelta(1) # strftime() is to format date according to# the need by converting them to stringprint(\"Yesterday = \", yesterday.strftime('%d-%m-%Y'))print(\"Today = \", presentday.strftime('%d-%m-%Y'))print(\"Tomorrow = \", tomorrow.strftime('%d-%m-%Y'))", "e": 25935, "s": 25346, "text": null }, { "code": null, "e": 26003, "s": 25935, "text": "Yesterday = 10-12-2019\nToday = 11-12-2019\nTomorrow = 12-12-2019\n" }, { "code": null, "e": 26027, "s": 26003, "text": "Python datetime-program" }, { "code": null, "e": 26043, "s": 26027, "text": "Python-datetime" }, { "code": null, "e": 26050, "s": 26043, "text": "Python" }, { "code": null, "e": 26148, "s": 26050, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26157, "s": 26148, "text": "Comments" }, { "code": null, "e": 26170, "s": 26157, "text": "Old Comments" }, { "code": null, "e": 26202, "s": 26170, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26257, "s": 26202, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26313, "s": 26257, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26352, "s": 26313, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26394, "s": 26352, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26436, "s": 26394, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26467, "s": 26436, "text": "Python | os.path.join() method" }, { "code": null, "e": 26489, "s": 26467, "text": "Defaultdict in Python" }, { "code": null, "e": 26518, "s": 26489, "text": "Create a directory in Python" } ]
Array class in C++
Array class in C++ are efficient enough and also it knows its own size. size() = To return the size of array i.e. returns the no of elements of the array. max_size() = To return maximum number of elements of the array. get(), at(), operator[] = To get access of the array elements. front() = To return front element of the array. back() = To return last element of the array. empty() = Returns true if array size is true otherwise false. fill() = To fill the entire array with a particular value. swap() = To swap the elements of one array to another. Here is an example to implements all the operations as mentioned above − #include<iostream> #include<array> using namespace std; int main() { array<int,4>a = {10, 20, 30, 40}; array<int,4>a1 = {50, 60, 70, 90}; cout << "The size of array is : "; //size of the array using size() cout << a.size() << endl; //maximum no of elements of the array cout << "Maximum elements array can hold is : "; cout << a.max_size() << endl; // Printing array elements using at() cout << "The array elements are (using at()) : "; for ( int i=0; i<4; i++) cout << a.at(i) << " "; cout << endl; // Printing array elements using get() cout << "The array elements are (using get()) : "; cout << get<0>(a) << " " << get<1>(a) << " "<<endl; cout << "The array elements are (using operator[]) : "; for ( int i=0; i<4; i++) cout << a[i] << " "; cout << endl; // Printing first element of array cout << "First element of array is : "; cout << a.front() << endl; // Printing last element of array cout << "Last element of array is : "; cout << a.back() << endl; cout << "The second array elements before swapping are : "; for (int i=0; i<4; i++) cout << a1[i] << " "; cout << endl; // Swapping a1 values with a a.swap(a1); // Printing 1st and 2nd array after swapping cout << "The first array elements after swapping are : "; for (int i=0; i<4; i++) cout << a[i] << " "; cout << endl; cout << "The second array elements after swapping are : "; for (int i = 0; i<4; i++) cout << a1[i] << " "; cout << endl; // Checking if it is empty a1.empty()? cout << "Array is empty": cout << "Array is not empty"; cout << endl; // Filling array with 1 a.fill(1); // Displaying array after filling cout << "Array content after filling operation is : "; for ( int i = 0; i<4; i++) cout << a[i] << " "; return 0; } The size of array is : 4 Maximum elements array can hold is : 4 The array elements are (using at()) : 10 20 30 40 The array elements are (using get()) : 10 20 The array elements are (using operator[]) : 10 20 30 40 First element of array is : 10 Last element of array is : 40 The second array elements before swapping are : 50 60 70 90 The first array elements after swapping are : 50 60 70 90 The second array elements after swapping are : 10 20 30 40 Array is not empty Array content after filling operation is : 1 1 1 1
[ { "code": null, "e": 1134, "s": 1062, "text": "Array class in C++ are efficient enough and also it knows its own size." }, { "code": null, "e": 1217, "s": 1134, "text": "size() = To return the size of array i.e. returns the no of elements of the array." }, { "code": null, "e": 1281, "s": 1217, "text": "max_size() = To return maximum number of elements of the array." }, { "code": null, "e": 1344, "s": 1281, "text": "get(), at(), operator[] = To get access of the array elements." }, { "code": null, "e": 1392, "s": 1344, "text": "front() = To return front element of the array." }, { "code": null, "e": 1438, "s": 1392, "text": "back() = To return last element of the array." }, { "code": null, "e": 1500, "s": 1438, "text": "empty() = Returns true if array size is true otherwise false." }, { "code": null, "e": 1559, "s": 1500, "text": "fill() = To fill the entire array with a particular value." }, { "code": null, "e": 1614, "s": 1559, "text": "swap() = To swap the elements of one array to another." }, { "code": null, "e": 1687, "s": 1614, "text": "Here is an example to implements all the operations as mentioned above −" }, { "code": null, "e": 3579, "s": 1687, "text": "#include<iostream>\n#include<array>\nusing namespace std;\n\nint main() {\n array<int,4>a = {10, 20, 30, 40};\n array<int,4>a1 = {50, 60, 70, 90};\n cout << \"The size of array is : \";\n //size of the array using size()\n cout << a.size() << endl;\n //maximum no of elements of the array\n cout << \"Maximum elements array can hold is : \";\n cout << a.max_size() << endl;\n // Printing array elements using at()\n cout << \"The array elements are (using at()) : \";\n for ( int i=0; i<4; i++)\n cout << a.at(i) << \" \";\n cout << endl;\n // Printing array elements using get()\n cout << \"The array elements are (using get()) : \";\n cout << get<0>(a) << \" \" << get<1>(a) << \" \"<<endl;\n cout << \"The array elements are (using operator[]) : \";\n for ( int i=0; i<4; i++)\n cout << a[i] << \" \";\n cout << endl;\n // Printing first element of array\n cout << \"First element of array is : \";\n cout << a.front() << endl;\n // Printing last element of array\n cout << \"Last element of array is : \";\n cout << a.back() << endl;\n cout << \"The second array elements before swapping are : \";\n for (int i=0; i<4; i++)\n cout << a1[i] << \" \";\n cout << endl;\n // Swapping a1 values with a\n a.swap(a1);\n // Printing 1st and 2nd array after swapping\n cout << \"The first array elements after swapping are : \";\n for (int i=0; i<4; i++)\n cout << a[i] << \" \";\n cout << endl;\n cout << \"The second array elements after swapping are : \";\n for (int i = 0; i<4; i++)\n cout << a1[i] << \" \";\n cout << endl;\n // Checking if it is empty\n a1.empty()? cout << \"Array is empty\":\n cout << \"Array is not empty\";\n cout << endl;\n // Filling array with 1\n a.fill(1);\n // Displaying array after filling\n cout << \"Array content after filling operation is : \";\n for ( int i = 0; i<4; i++)\n cout << a[i] << \" \";\n return 0;\n}" }, { "code": null, "e": 4102, "s": 3579, "text": "The size of array is : 4\nMaximum elements array can hold is : 4\nThe array elements are (using at()) : 10 20 30 40\nThe array elements are (using get()) : 10 20\nThe array elements are (using operator[]) : 10 20 30 40\nFirst element of array is : 10\nLast element of array is : 40\nThe second array elements before swapping are : 50 60 70 90\nThe first array elements after swapping are : 50 60 70 90\nThe second array elements after swapping are : 10 20 30 40\nArray is not empty\nArray content after filling operation is : 1 1 1 1" } ]
What is String Title case in C#?
The ToTitleCase method is used to capitalize the first letter in a word. Title case itself means to capitalize the first letter of each major word. Let us see an example to get the title case − Live Demo using System; using System.Globalization; class Demo { static void Main() { string str = "jack sparrow"; string res = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str); Console.WriteLine(res); } } Jack Sparrow Above, we have set the input string to the ToTitleCase() method. The CultureInfo.TextInfo property is used to provide the culture-specific casing information for strings − CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str);
[ { "code": null, "e": 1210, "s": 1062, "text": "The ToTitleCase method is used to capitalize the first letter in a word. Title case itself means to capitalize the first letter of each major word." }, { "code": null, "e": 1256, "s": 1210, "text": "Let us see an example to get the title case −" }, { "code": null, "e": 1267, "s": 1256, "text": " Live Demo" }, { "code": null, "e": 1492, "s": 1267, "text": "using System;\nusing System.Globalization;\n\nclass Demo {\n static void Main() {\n string str = \"jack sparrow\";\n string res = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str);\n Console.WriteLine(res);\n }\n}" }, { "code": null, "e": 1505, "s": 1492, "text": "Jack Sparrow" }, { "code": null, "e": 1677, "s": 1505, "text": "Above, we have set the input string to the ToTitleCase() method. The CultureInfo.TextInfo property is used to provide the culture-specific casing information for strings −" }, { "code": null, "e": 1731, "s": 1677, "text": "CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str);" } ]
A C/C++ Function Call Puzzle - GeeksforGeeks
06 Jul, 2021 Consider the following program. Predict the output of it when compiled with C and C++ compilers. C void func(){ /* definition */} int main(){ func(); func(2);} The above program compiles fine in C, but doesn’t compile in C++. In C++, func() is equivalent to func(void) In C, func() is equivalent to func(...) Refer this for details and this for more programs that compile in C, but not in C++. This article is compiled by Rahul Mittalal. 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. singhbishalkumarsingh CPP-Functions C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Command line arguments in C/C++ rand() and srand() in C/C++ Core Dump (Segmentation fault) in C/C++ fork() in C Exception Handling in C++ Vector in C++ STL Inheritance in C++ Iterators in C++ STL Initialize a vector in C++ (6 different ways) Socket Programming in C/C++
[ { "code": null, "e": 24534, "s": 24506, "text": "\n06 Jul, 2021" }, { "code": null, "e": 24631, "s": 24534, "text": "Consider the following program. Predict the output of it when compiled with C and C++ compilers." }, { "code": null, "e": 24633, "s": 24631, "text": "C" }, { "code": "void func(){ /* definition */} int main(){ func(); func(2);}", "e": 24703, "s": 24633, "text": null }, { "code": null, "e": 24769, "s": 24703, "text": "The above program compiles fine in C, but doesn’t compile in C++." }, { "code": null, "e": 24852, "s": 24769, "text": "In C++, func() is equivalent to func(void) In C, func() is equivalent to func(...)" }, { "code": null, "e": 24937, "s": 24852, "text": "Refer this for details and this for more programs that compile in C, but not in C++." }, { "code": null, "e": 25204, "s": 24937, "text": "This article is compiled by Rahul Mittalal. 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": 25226, "s": 25204, "text": "singhbishalkumarsingh" }, { "code": null, "e": 25240, "s": 25226, "text": "CPP-Functions" }, { "code": null, "e": 25251, "s": 25240, "text": "C Language" }, { "code": null, "e": 25255, "s": 25251, "text": "C++" }, { "code": null, "e": 25259, "s": 25255, "text": "CPP" }, { "code": null, "e": 25357, "s": 25259, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25366, "s": 25357, "text": "Comments" }, { "code": null, "e": 25379, "s": 25366, "text": "Old Comments" }, { "code": null, "e": 25411, "s": 25379, "text": "Command line arguments in C/C++" }, { "code": null, "e": 25439, "s": 25411, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 25479, "s": 25439, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 25491, "s": 25479, "text": "fork() in C" }, { "code": null, "e": 25517, "s": 25491, "text": "Exception Handling in C++" }, { "code": null, "e": 25535, "s": 25517, "text": "Vector in C++ STL" }, { "code": null, "e": 25554, "s": 25535, "text": "Inheritance in C++" }, { "code": null, "e": 25575, "s": 25554, "text": "Iterators in C++ STL" }, { "code": null, "e": 25621, "s": 25575, "text": "Initialize a vector in C++ (6 different ways)" } ]
C# | Check whether an element is contained in the ArrayList
20 Jun, 2022 ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Contains(Object) method determines whether the element exists in ArrayList or not. Properties of ArrayList Class: Elements can be added or removed from the Array List collection at any point in time. The ArrayList is not guaranteed to be sorted. The capacity of an ArrayList is the number of elements the ArrayList can hold. Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based. It also allows duplicate elements. Using multidimensional arrays as elements in an ArrayList collection is not supported. Syntax: public virtual bool Contains (object item); Here, item is an Object to locate in the ArrayList. The value can be null. Return Value: This method will return True if the item found in the ArrayList otherwise it returns False. Note: This method performs a linear search, therefore, this method is an O(n) operation, where n is Count. Below are the programs to illustrate the ArrayList.Contains(Object) method: Example 1: CSHARP // C# code to check if an element is// contained in ArrayList or notusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add("A"); myList.Add("B"); myList.Add("C"); myList.Add("D"); myList.Add("E"); myList.Add("F"); myList.Add("G"); myList.Add("H"); // To check if the ArrayList Contains element "E" // If yes, then display it's index, else // display the message if (myList.Contains("E")) Console.WriteLine("Yes, exists at index " + myList.IndexOf("E")); else Console.WriteLine("No, doesn't exists"); }} Yes, exists at index 4 Example 2 : CSHARP // C# code to check if an element is// contained in ArrayList or notusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add("5"); myList.Add("7"); myList.Add("9"); myList.Add("11"); myList.Add("12"); myList.Add("16"); myList.Add("20"); myList.Add("25"); // To check if the ArrayList Contains element "24" // If yes, then display it's index, else // display the message if (myList.Contains("24")) Console.WriteLine("Yes, exists at index " + myList.IndexOf("24")); else Console.WriteLine("No, doesn't exists"); }} No, doesn't exists Time complexity: O(n) since using Contains method Auxiliary Space: O(n) where n is the size of the ArrayList Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.contains?view=netframework-4.7.2 technophpfij CSharp-Collections-ArrayList CSharp-Collections-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jun, 2022" }, { "code": null, "e": 378, "s": 28, "text": "ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Contains(Object) method determines whether the element exists in ArrayList or not. Properties of ArrayList Class: " }, { "code": null, "e": 464, "s": 378, "text": "Elements can be added or removed from the Array List collection at any point in time." }, { "code": null, "e": 510, "s": 464, "text": "The ArrayList is not guaranteed to be sorted." }, { "code": null, "e": 589, "s": 510, "text": "The capacity of an ArrayList is the number of elements the ArrayList can hold." }, { "code": null, "e": 700, "s": 589, "text": "Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based." }, { "code": null, "e": 735, "s": 700, "text": "It also allows duplicate elements." }, { "code": null, "e": 822, "s": 735, "text": "Using multidimensional arrays as elements in an ArrayList collection is not supported." }, { "code": null, "e": 830, "s": 822, "text": "Syntax:" }, { "code": null, "e": 874, "s": 830, "text": "public virtual bool Contains (object item);" }, { "code": null, "e": 1250, "s": 874, "text": "Here, item is an Object to locate in the ArrayList. The value can be null. Return Value: This method will return True if the item found in the ArrayList otherwise it returns False. Note: This method performs a linear search, therefore, this method is an O(n) operation, where n is Count. Below are the programs to illustrate the ArrayList.Contains(Object) method: Example 1: " }, { "code": null, "e": 1257, "s": 1250, "text": "CSHARP" }, { "code": "// C# code to check if an element is// contained in ArrayList or notusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add(\"A\"); myList.Add(\"B\"); myList.Add(\"C\"); myList.Add(\"D\"); myList.Add(\"E\"); myList.Add(\"F\"); myList.Add(\"G\"); myList.Add(\"H\"); // To check if the ArrayList Contains element \"E\" // If yes, then display it's index, else // display the message if (myList.Contains(\"E\")) Console.WriteLine(\"Yes, exists at index \" + myList.IndexOf(\"E\")); else Console.WriteLine(\"No, doesn't exists\"); }}", "e": 2086, "s": 1257, "text": null }, { "code": null, "e": 2109, "s": 2086, "text": "Yes, exists at index 4" }, { "code": null, "e": 2122, "s": 2109, "text": "Example 2 : " }, { "code": null, "e": 2129, "s": 2122, "text": "CSHARP" }, { "code": "// C# code to check if an element is// contained in ArrayList or notusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add(\"5\"); myList.Add(\"7\"); myList.Add(\"9\"); myList.Add(\"11\"); myList.Add(\"12\"); myList.Add(\"16\"); myList.Add(\"20\"); myList.Add(\"25\"); // To check if the ArrayList Contains element \"24\" // If yes, then display it's index, else // display the message if (myList.Contains(\"24\")) Console.WriteLine(\"Yes, exists at index \" + myList.IndexOf(\"24\")); else Console.WriteLine(\"No, doesn't exists\"); }}", "e": 2966, "s": 2129, "text": null }, { "code": null, "e": 2985, "s": 2966, "text": "No, doesn't exists" }, { "code": null, "e": 3035, "s": 2985, "text": "Time complexity: O(n) since using Contains method" }, { "code": null, "e": 3094, "s": 3035, "text": "Auxiliary Space: O(n) where n is the size of the ArrayList" }, { "code": null, "e": 3106, "s": 3094, "text": "Reference: " }, { "code": null, "e": 3212, "s": 3106, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.contains?view=netframework-4.7.2" }, { "code": null, "e": 3225, "s": 3212, "text": "technophpfij" }, { "code": null, "e": 3254, "s": 3225, "text": "CSharp-Collections-ArrayList" }, { "code": null, "e": 3283, "s": 3254, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 3297, "s": 3283, "text": "CSharp-method" }, { "code": null, "e": 3300, "s": 3297, "text": "C#" } ]
GATE | GATE CS 2013 | Question 65
10 Sep, 2021 What is the maximum number of reduce moves that can be taken by a bottom-up parser for a grammar with no epsilon- and unit-production (i.e., of type A -> є and A -> a) to parse a string with n tokens?(A) n/2(B) n-1(C) 2n-1(D) 2nAnswer: (B)Explanation: Given in the question, a grammar with no epsilon- and unit-production (i.e., of type A -> є and A -> a). To get maximum number of Reduce moves, we should make sure than in each sentential form only one terminal is reduced. Since there is no unit production, so last 2 tokens will take only 1 move. So To Reduce input string of n tokens, first Reduce n-2 tokens using n-2 reduce moves and then Reduce last 2 tokens using production which has . So total of n-2+1 = n-1 Reduce moves. Suppose the string is abcd. ( n = 4 ). We can write the grammar which accepts this string as follows: S->aB B->bC C->cd The Right Most Derivation for the above is: S -> aB ( Reduction 3 ) -> abC ( Reduction 2 ) -> abcd ( Reduction 1 ) We can see here that no production is for unit or epsilon. Hence 3 reductions here. We can get less number of reductions with some other grammar which also does’t produce unit or epsilon productions, S->abA A-> cd The Right Most Derivation for the above as: S -> abA ( Reduction 2 ) -> abcd ( Reduction 1 ) Hence 2 reductions. But we are interested in knowing the maximum number of reductions which comes from the 1st grammar. Hence total 3 reductions as maximum, which is ( n – 1) as n = 4 here. Thus, Option B. YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Sn5eIxvrNBc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question Ankit87 GATE-CS-2013 GATE-GATE CS 2013 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 1996 | Question 63 GATE | GATE CS 2008 | Question 40 GATE | GATE-CS-2014-(Set-1) | Question 51 GATE | GATE-CS-2001 | Question 50 GATE | Gate IT 2005 | Question 52
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Sep, 2021" }, { "code": null, "e": 409, "s": 52, "text": "What is the maximum number of reduce moves that can be taken by a bottom-up parser for a grammar with no epsilon- and unit-production (i.e., of type A -> є and A -> a) to parse a string with n tokens?(A) n/2(B) n-1(C) 2n-1(D) 2nAnswer: (B)Explanation: Given in the question, a grammar with no epsilon- and unit-production (i.e., of type A -> є and A -> a)." }, { "code": null, "e": 602, "s": 409, "text": "To get maximum number of Reduce moves, we should make sure than in each sentential form only one terminal is reduced. Since there is no unit production, so last 2 tokens will take only 1 move." }, { "code": null, "e": 785, "s": 602, "text": "So To Reduce input string of n tokens, first Reduce n-2 tokens using n-2 reduce moves and then Reduce last 2 tokens using production which has . So total of n-2+1 = n-1 Reduce moves." }, { "code": null, "e": 824, "s": 785, "text": "Suppose the string is abcd. ( n = 4 )." }, { "code": null, "e": 887, "s": 824, "text": "We can write the grammar which accepts this string as follows:" }, { "code": null, "e": 906, "s": 887, "text": "S->aB\nB->bC\nC->cd " }, { "code": null, "e": 950, "s": 906, "text": "The Right Most Derivation for the above is:" }, { "code": null, "e": 1021, "s": 950, "text": "S -> aB ( Reduction 3 )\n-> abC ( Reduction 2 )\n-> abcd ( Reduction 1 )" }, { "code": null, "e": 1105, "s": 1021, "text": "We can see here that no production is for unit or epsilon. Hence 3 reductions here." }, { "code": null, "e": 1221, "s": 1105, "text": "We can get less number of reductions with some other grammar which also does’t produce unit or epsilon productions," }, { "code": null, "e": 1235, "s": 1221, "text": "S->abA\nA-> cd" }, { "code": null, "e": 1279, "s": 1235, "text": "The Right Most Derivation for the above as:" }, { "code": null, "e": 1328, "s": 1279, "text": "S -> abA ( Reduction 2 )\n-> abcd ( Reduction 1 )" }, { "code": null, "e": 1348, "s": 1328, "text": "Hence 2 reductions." }, { "code": null, "e": 1518, "s": 1348, "text": "But we are interested in knowing the maximum number of reductions which comes from the 1st grammar. Hence total 3 reductions as maximum, which is ( n – 1) as n = 4 here." }, { "code": null, "e": 1534, "s": 1518, "text": "Thus, Option B." }, { "code": null, "e": 1847, "s": 1534, "text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Sn5eIxvrNBc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 1855, "s": 1847, "text": "Ankit87" }, { "code": null, "e": 1868, "s": 1855, "text": "GATE-CS-2013" }, { "code": null, "e": 1886, "s": 1868, "text": "GATE-GATE CS 2013" }, { "code": null, "e": 1891, "s": 1886, "text": "GATE" }, { "code": null, "e": 1989, "s": 1891, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2031, "s": 1989, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 2093, "s": 2031, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 2135, "s": 2093, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 2169, "s": 2135, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 2211, "s": 2169, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 2245, "s": 2211, "text": "GATE | GATE CS 1996 | Question 63" }, { "code": null, "e": 2279, "s": 2245, "text": "GATE | GATE CS 2008 | Question 40" }, { "code": null, "e": 2321, "s": 2279, "text": "GATE | GATE-CS-2014-(Set-1) | Question 51" }, { "code": null, "e": 2355, "s": 2321, "text": "GATE | GATE-CS-2001 | Question 50" } ]
Check if binary string multiple of 3 using DFA
15 Jun, 2022 Given a string of binary characters, check if it is multiple of 3 or not.Examples : Input : 1 0 1 0 Output : NO Explanation : (1 0 1 0) is 10 and hence not a multiple of 3 Input : 1 1 0 0 Output : YES Explanation : (1 1 0 0) is 12 and hence a multiple of 3 Approach 1 : One simple method is to convert the binary number into its decimal representation and then check if it is a multiple of 3 or not. Now, when it comes to DFA (Deterministic Finite Automata), there is no concept of memory i.e. you cannot store the string when it is provided, so the above method would not be applicable. In simple terms, a DFA takes a string as input and process it. If it reaches final state, it is accepted, else rejected. As you cannot store the string, so input is taken character by character. The DFA for given problem is : As, when a number is divided by 3, there are only 3 possibilities. The remainder can be either 0, 1 or 2. Here, state 0 represents that the remainder when the number is divided by 3 is 0. State 1 represents that the remainder when the number is divided by 3 is 1 and similarly state 2 represents that the remainder when the number is divided by 3 is 2. So if a string reaches state 0 in the end, it is accepted otherwise rejected. Below is the implementation of above approach : C++ Java Python3 C# PHP Javascript // C++ Program to illustrate// DFA for multiple of 3#include <bits/stdc++.h>using namespace std; // checks if binary characters// are multiple of 3bool isMultiple3(char c[], int size){ // initial state is 0th char state = '0'; for (int i = 0; i < size; i++) { // storing binary digit char digit = c[i]; switch (state) { // when state is 0 case '0': if (digit == '1') state = '1'; break; // when state is 1 case '1': if (digit == '0') state = '2'; else state = '0'; break; // when state is 2 case '2': if (digit == '0') state = '1'; break; } } // if final state is 0th state if (state == '0') return true; return false;} // Driver's Codeint main(){ // size of binary array int size = 5; // array of binary numbers // Here it is 21 in decimal char c[] = { '1', '0', '1', '0', '1' }; // if binary numbers are a multiple of 3 if (isMultiple3(c, size)) cout << "YES\n"; else cout << "NO\n"; return 0;} // Java Program to illustrate// DFA for multiple of 3import java.io.*; class GFG{ // checks if binary characters // are multiple of 3 static boolean isMultiple3(char c[], int size) { // initial state is 0th char state = '0'; for (int i = 0; i < size; i++) { // storing binary digit char digit = c[i]; switch (state) { // when state is 0 case '0': if (digit == '1') state = '1'; break; // when state is 1 case '1': if (digit == '0') state = '2'; else state = '0'; break; // when state is 2 case '2': if (digit == '0') state = '1'; break; } } // if final state is 0th state if (state == '0') return true; return false; } // Driver Code public static void main (String[] args) { // size of binary array int size = 5; // array of binary numbers // Here it is 21 in decimal char c[] = { '1', '0', '1', '0', '1' }; // if binary numbers are a multiple of 3 if (isMultiple3(c, size)) System.out.println ("YES"); else System.out.println ("NO"); }}// This code is contributed by vt_m # Python program to check if the binary String is divisible# by 3. # Function to check if the binary String is divisible by 3.def CheckDivisibilty(A): oddbits = 0; evenbits = 0; for counter in range(len(A)): # checking if the bit is nonzero if (A[counter] == '1'): # checking if the nonzero bit is at even # position if (counter % 2 == 0): evenbits+=1; else: oddbits+=1; # Checking if the difference of non-zero oddbits and # evenbits is divisible by 3. if (abs(oddbits - evenbits) % 3 == 0): print("Yes" + ""); else: print("No" + ""); # Driver Programif __name__ == '__main__': A = "10101"; CheckDivisibilty(A); # This code contributed by umadevi9616 Added code in Python // C# Program to illustrate// DFA for multiple of 3using System; class GFG { // checks if binary characters // are multiple of 3 static bool isMultiple3(char []c, int size) { // initial state is 0th char state = '0'; for (int i = 0; i < size; i++) { // storing binary digit char digit = c[i]; switch (state) { // when state is 0 case '0': if (digit == '1') state = '1'; break; // when state is 1 case '1': if (digit == '0') state = '2'; else state = '0'; break; // when state is 2 case '2': if (digit == '0') state = '1'; break; } } // if final state is 0th state if (state == '0') return true; return false; } // Driver Code public static void Main () { // size of binary array int size = 5; // array of binary numbers // Here it is 21 in decimal char []c = { '1', '0', '1', '0', '1' }; // if binary numbers are a multiple of 3 if (isMultiple3(c, size)) Console.WriteLine ("YES"); else Console.WriteLine ("NO"); }} // This code is contributed by vt_m. <?php// PHP Program to illustrate// DFA for multiple of 3 // checks if binary characters// are multiple of 3function isMultiple3($c,$size){ // initial state is 0th $state = '0'; for ($i = 0; $i < $size; $i++) { // storing binary digit $digit = $c[$i]; switch ($state) { // when state is 0 case '0': if ($digit == '1') $state = '1'; break; // when state is 1 case '1': if ($digit == '0') $state = '2'; else $state = '0'; break; // when state is 2 case '2': if ($digit == '0') $state = '1'; break; } } // if final state is 0th state if ($state == '0') return true; return false;} // Driver Code // size of binary array $size = 5; // array of binary numbers // Here it is 21 in decimal $c= array('1', '0', '1', '0', '1'); // if binary numbers are // a multiple of 3 if (isMultiple3($c, $size)) echo "YES\n"; else echo "NO\n"; //This code is contributed by mits?> <script> // JavaScript Program to illustrate// DFA for multiple of 3 // checks if binary characters // are multiple of 3 function isMultiple3(c, size) { // initial state is 0th let state = '0'; for (let i = 0; i < size; i++) { // storing binary digit let digit = c[i]; switch (state) { // when state is 0 case '0': if (digit == '1') state = '1'; break; // when state is 1 case '1': if (digit == '0') state = '2'; else state = '0'; break; // when state is 2 case '2': if (digit == '0') state = '1'; break; } } // if final state is 0th state if (state == '0') return true; return false; } // Driver code // size of binary array let size = 5; // array of binary numbers // Here it is 21 in decimal let c = [ '1', '0', '1', '0', '1' ]; // if binary numbers are a multiple of 3 if (isMultiple3(c, size)) document.write ("YES"); else document.write ("NO"); </script> YES Time Complexity: O(n)Auxiliary Space: O(1) Approach 2:We will check if the difference between the number of non-zero odd bit positions and non-zero even bit positions is divisible by 3 or not. Mathematically -> |odds-evens| divisible by 3. C++ Java Python3 C# Javascript // C++ program to check if the binary string is divisible// by 3.#include <bits/stdc++.h>using namespace std;// Function to check if the binary string is divisible by 3.void CheckDivisibilty(string A){ int oddbits = 0, evenbits = 0; for (int counter = 0; counter < A.length(); counter++) { // checking if the bit is nonzero if (A[counter] == '1') { // checking if the nonzero bit is at even // position if (counter % 2 == 0) { evenbits++; } else { oddbits++; } } } // Checking if the difference of non-zero oddbits and // evenbits is divisible by 3. if (abs(oddbits - evenbits) % 3 == 0) { cout << "Yes" << endl; } else { cout << "No" << endl; }}// Driver Programint main(){ string A = "10101"; CheckDivisibilty(A); return 0;} // Java program to check if the binary String is divisible// by 3.import java.util.*; class GFG{ // Function to check if the binary String is divisible by 3.static void CheckDivisibilty(String A){ int oddbits = 0, evenbits = 0; for (int counter = 0; counter < A.length(); counter++) { // checking if the bit is nonzero if (A.charAt(counter) == '1') { // checking if the nonzero bit is at even // position if (counter % 2 == 0) { evenbits++; } else { oddbits++; } } } // Checking if the difference of non-zero oddbits and // evenbits is divisible by 3. if (Math.abs(oddbits - evenbits) % 3 == 0) { System.out.print("Yes" +"\n"); } else { System.out.print("No" +"\n"); }} // Driver Programpublic static void main(String[] args){ String A = "10101"; CheckDivisibilty(A);}} // This code is contributed by umadevi9616 # Python program to check if the binary String is divisible# by 3. # Function to check if the binary String is divisible by 3.def CheckDivisibilty(A): oddbits = 0; evenbits = 0; for counter in range(len(A)): # checking if the bit is nonzero if (A[counter] == '1'): # checking if the nonzero bit is at even # position if (counter % 2 == 0): evenbits += 1; else: oddbits += 1; # Checking if the difference of non-zero oddbits and # evenbits is divisible by 3. if (abs(oddbits - evenbits) % 3 == 0): print("Yes" + ""); else: print("No" + ""); # Driver Programif __name__ == '__main__': A = "10101"; CheckDivisibilty(A); # This code is contributed by umadevi9616. // C# program to check if the binary String is divisible// by 3.using System; public class GFG{ // Function to check if the binary String is divisible by 3.static void CheckDivisibilty(String A){ int oddbits = 0, evenbits = 0; for (int counter = 0; counter < A.Length; counter++) { // checking if the bit is nonzero if (A[counter] == '1') { // checking if the nonzero bit is at even // position if (counter % 2 == 0) { evenbits++; } else { oddbits++; } } } // Checking if the difference of non-zero oddbits and // evenbits is divisible by 3. if (Math.Abs(oddbits - evenbits) % 3 == 0) { Console.Write("Yes" +"\n"); } else { Console.Write("No" +"\n"); }} // Driver Programpublic static void Main(String[] args){ String A = "10101"; CheckDivisibilty(A);}} // This code is contributed by umadevi9616 <script>// javascript program to check if the binary String is divisible// by 3. // Function to check if the binary String is divisible by 3. function CheckDivisibilty( A) { var oddbits = 0, evenbits = 0; for (var counter = 0; counter < A.length; counter++) { // checking if the bit is nonzero if (A[counter] == '1') { // checking if the nonzero bit is at even // position if (counter % 2 == 0) { evenbits++; } else { oddbits++; } } } // Checking if the difference of non-zero oddbits and // evenbits is divisible by 3. if (Math.abs(oddbits - evenbits) % 3 == 0) { document.write("Yes" + "\n"); } else { document.write("No" + "\n"); } } // Driver Program var A = "10101"; CheckDivisibilty(A); // This code is contributed by umadevi9616</script> Yes Time Complexity: O(n) where n is the number of bits. Auxiliary Space: O(1) Mithun Kumar nidhi_biet rutvik_56 susmitakundugoaldanga prathamjha5683 umadevi9616 ranjanrohit840 divisibility Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Bits manipulation (Important tactics) Binary representation of a given number Josephus problem | Set 1 (A O(n) Solution) Divide two integers without using multiplication, division and mod operator C++ bitset and its application Add two numbers without using arithmetic operators Find the element that appears once Bit Fields in C Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jun, 2022" }, { "code": null, "e": 137, "s": 52, "text": "Given a string of binary characters, check if it is multiple of 3 or not.Examples : " }, { "code": null, "e": 314, "s": 137, "text": "Input : 1 0 1 0\nOutput : NO\nExplanation : (1 0 1 0) is 10 and hence\nnot a multiple of 3\n\nInput : 1 1 0 0\nOutput : YES\nExplanation : (1 1 0 0) is 12 and hence \na multiple of 3" }, { "code": null, "e": 840, "s": 314, "text": "Approach 1 : One simple method is to convert the binary number into its decimal representation and then check if it is a multiple of 3 or not. Now, when it comes to DFA (Deterministic Finite Automata), there is no concept of memory i.e. you cannot store the string when it is provided, so the above method would not be applicable. In simple terms, a DFA takes a string as input and process it. If it reaches final state, it is accepted, else rejected. As you cannot store the string, so input is taken character by character." }, { "code": null, "e": 872, "s": 840, "text": "The DFA for given problem is : " }, { "code": null, "e": 1303, "s": 872, "text": "As, when a number is divided by 3, there are only 3 possibilities. The remainder can be either 0, 1 or 2. Here, state 0 represents that the remainder when the number is divided by 3 is 0. State 1 represents that the remainder when the number is divided by 3 is 1 and similarly state 2 represents that the remainder when the number is divided by 3 is 2. So if a string reaches state 0 in the end, it is accepted otherwise rejected." }, { "code": null, "e": 1352, "s": 1303, "text": "Below is the implementation of above approach : " }, { "code": null, "e": 1356, "s": 1352, "text": "C++" }, { "code": null, "e": 1361, "s": 1356, "text": "Java" }, { "code": null, "e": 1369, "s": 1361, "text": "Python3" }, { "code": null, "e": 1372, "s": 1369, "text": "C#" }, { "code": null, "e": 1376, "s": 1372, "text": "PHP" }, { "code": null, "e": 1387, "s": 1376, "text": "Javascript" }, { "code": "// C++ Program to illustrate// DFA for multiple of 3#include <bits/stdc++.h>using namespace std; // checks if binary characters// are multiple of 3bool isMultiple3(char c[], int size){ // initial state is 0th char state = '0'; for (int i = 0; i < size; i++) { // storing binary digit char digit = c[i]; switch (state) { // when state is 0 case '0': if (digit == '1') state = '1'; break; // when state is 1 case '1': if (digit == '0') state = '2'; else state = '0'; break; // when state is 2 case '2': if (digit == '0') state = '1'; break; } } // if final state is 0th state if (state == '0') return true; return false;} // Driver's Codeint main(){ // size of binary array int size = 5; // array of binary numbers // Here it is 21 in decimal char c[] = { '1', '0', '1', '0', '1' }; // if binary numbers are a multiple of 3 if (isMultiple3(c, size)) cout << \"YES\\n\"; else cout << \"NO\\n\"; return 0;}", "e": 2570, "s": 1387, "text": null }, { "code": "// Java Program to illustrate// DFA for multiple of 3import java.io.*; class GFG{ // checks if binary characters // are multiple of 3 static boolean isMultiple3(char c[], int size) { // initial state is 0th char state = '0'; for (int i = 0; i < size; i++) { // storing binary digit char digit = c[i]; switch (state) { // when state is 0 case '0': if (digit == '1') state = '1'; break; // when state is 1 case '1': if (digit == '0') state = '2'; else state = '0'; break; // when state is 2 case '2': if (digit == '0') state = '1'; break; } } // if final state is 0th state if (state == '0') return true; return false; } // Driver Code public static void main (String[] args) { // size of binary array int size = 5; // array of binary numbers // Here it is 21 in decimal char c[] = { '1', '0', '1', '0', '1' }; // if binary numbers are a multiple of 3 if (isMultiple3(c, size)) System.out.println (\"YES\"); else System.out.println (\"NO\"); }}// This code is contributed by vt_m", "e": 4066, "s": 2570, "text": null }, { "code": "# Python program to check if the binary String is divisible# by 3. # Function to check if the binary String is divisible by 3.def CheckDivisibilty(A): oddbits = 0; evenbits = 0; for counter in range(len(A)): # checking if the bit is nonzero if (A[counter] == '1'): # checking if the nonzero bit is at even # position if (counter % 2 == 0): evenbits+=1; else: oddbits+=1; # Checking if the difference of non-zero oddbits and # evenbits is divisible by 3. if (abs(oddbits - evenbits) % 3 == 0): print(\"Yes\" + \"\"); else: print(\"No\" + \"\"); # Driver Programif __name__ == '__main__': A = \"10101\"; CheckDivisibilty(A); # This code contributed by umadevi9616 Added code in Python", "e": 4913, "s": 4066, "text": null }, { "code": "// C# Program to illustrate// DFA for multiple of 3using System; class GFG { // checks if binary characters // are multiple of 3 static bool isMultiple3(char []c, int size) { // initial state is 0th char state = '0'; for (int i = 0; i < size; i++) { // storing binary digit char digit = c[i]; switch (state) { // when state is 0 case '0': if (digit == '1') state = '1'; break; // when state is 1 case '1': if (digit == '0') state = '2'; else state = '0'; break; // when state is 2 case '2': if (digit == '0') state = '1'; break; } } // if final state is 0th state if (state == '0') return true; return false; } // Driver Code public static void Main () { // size of binary array int size = 5; // array of binary numbers // Here it is 21 in decimal char []c = { '1', '0', '1', '0', '1' }; // if binary numbers are a multiple of 3 if (isMultiple3(c, size)) Console.WriteLine (\"YES\"); else Console.WriteLine (\"NO\"); }} // This code is contributed by vt_m.", "e": 6489, "s": 4913, "text": null }, { "code": "<?php// PHP Program to illustrate// DFA for multiple of 3 // checks if binary characters// are multiple of 3function isMultiple3($c,$size){ // initial state is 0th $state = '0'; for ($i = 0; $i < $size; $i++) { // storing binary digit $digit = $c[$i]; switch ($state) { // when state is 0 case '0': if ($digit == '1') $state = '1'; break; // when state is 1 case '1': if ($digit == '0') $state = '2'; else $state = '0'; break; // when state is 2 case '2': if ($digit == '0') $state = '1'; break; } } // if final state is 0th state if ($state == '0') return true; return false;} // Driver Code // size of binary array $size = 5; // array of binary numbers // Here it is 21 in decimal $c= array('1', '0', '1', '0', '1'); // if binary numbers are // a multiple of 3 if (isMultiple3($c, $size)) echo \"YES\\n\"; else echo \"NO\\n\"; //This code is contributed by mits?>", "e": 7730, "s": 6489, "text": null }, { "code": "<script> // JavaScript Program to illustrate// DFA for multiple of 3 // checks if binary characters // are multiple of 3 function isMultiple3(c, size) { // initial state is 0th let state = '0'; for (let i = 0; i < size; i++) { // storing binary digit let digit = c[i]; switch (state) { // when state is 0 case '0': if (digit == '1') state = '1'; break; // when state is 1 case '1': if (digit == '0') state = '2'; else state = '0'; break; // when state is 2 case '2': if (digit == '0') state = '1'; break; } } // if final state is 0th state if (state == '0') return true; return false; } // Driver code // size of binary array let size = 5; // array of binary numbers // Here it is 21 in decimal let c = [ '1', '0', '1', '0', '1' ]; // if binary numbers are a multiple of 3 if (isMultiple3(c, size)) document.write (\"YES\"); else document.write (\"NO\"); </script>", "e": 9095, "s": 7730, "text": null }, { "code": null, "e": 9099, "s": 9095, "text": "YES" }, { "code": null, "e": 9142, "s": 9099, "text": "Time Complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 9292, "s": 9142, "text": "Approach 2:We will check if the difference between the number of non-zero odd bit positions and non-zero even bit positions is divisible by 3 or not." }, { "code": null, "e": 9339, "s": 9292, "text": "Mathematically -> |odds-evens| divisible by 3." }, { "code": null, "e": 9343, "s": 9339, "text": "C++" }, { "code": null, "e": 9348, "s": 9343, "text": "Java" }, { "code": null, "e": 9356, "s": 9348, "text": "Python3" }, { "code": null, "e": 9359, "s": 9356, "text": "C#" }, { "code": null, "e": 9370, "s": 9359, "text": "Javascript" }, { "code": "// C++ program to check if the binary string is divisible// by 3.#include <bits/stdc++.h>using namespace std;// Function to check if the binary string is divisible by 3.void CheckDivisibilty(string A){ int oddbits = 0, evenbits = 0; for (int counter = 0; counter < A.length(); counter++) { // checking if the bit is nonzero if (A[counter] == '1') { // checking if the nonzero bit is at even // position if (counter % 2 == 0) { evenbits++; } else { oddbits++; } } } // Checking if the difference of non-zero oddbits and // evenbits is divisible by 3. if (abs(oddbits - evenbits) % 3 == 0) { cout << \"Yes\" << endl; } else { cout << \"No\" << endl; }}// Driver Programint main(){ string A = \"10101\"; CheckDivisibilty(A); return 0;}", "e": 10264, "s": 9370, "text": null }, { "code": "// Java program to check if the binary String is divisible// by 3.import java.util.*; class GFG{ // Function to check if the binary String is divisible by 3.static void CheckDivisibilty(String A){ int oddbits = 0, evenbits = 0; for (int counter = 0; counter < A.length(); counter++) { // checking if the bit is nonzero if (A.charAt(counter) == '1') { // checking if the nonzero bit is at even // position if (counter % 2 == 0) { evenbits++; } else { oddbits++; } } } // Checking if the difference of non-zero oddbits and // evenbits is divisible by 3. if (Math.abs(oddbits - evenbits) % 3 == 0) { System.out.print(\"Yes\" +\"\\n\"); } else { System.out.print(\"No\" +\"\\n\"); }} // Driver Programpublic static void main(String[] args){ String A = \"10101\"; CheckDivisibilty(A);}} // This code is contributed by umadevi9616", "e": 11276, "s": 10264, "text": null }, { "code": "# Python program to check if the binary String is divisible# by 3. # Function to check if the binary String is divisible by 3.def CheckDivisibilty(A): oddbits = 0; evenbits = 0; for counter in range(len(A)): # checking if the bit is nonzero if (A[counter] == '1'): # checking if the nonzero bit is at even # position if (counter % 2 == 0): evenbits += 1; else: oddbits += 1; # Checking if the difference of non-zero oddbits and # evenbits is divisible by 3. if (abs(oddbits - evenbits) % 3 == 0): print(\"Yes\" + \"\"); else: print(\"No\" + \"\"); # Driver Programif __name__ == '__main__': A = \"10101\"; CheckDivisibilty(A); # This code is contributed by umadevi9616.", "e": 12084, "s": 11276, "text": null }, { "code": "// C# program to check if the binary String is divisible// by 3.using System; public class GFG{ // Function to check if the binary String is divisible by 3.static void CheckDivisibilty(String A){ int oddbits = 0, evenbits = 0; for (int counter = 0; counter < A.Length; counter++) { // checking if the bit is nonzero if (A[counter] == '1') { // checking if the nonzero bit is at even // position if (counter % 2 == 0) { evenbits++; } else { oddbits++; } } } // Checking if the difference of non-zero oddbits and // evenbits is divisible by 3. if (Math.Abs(oddbits - evenbits) % 3 == 0) { Console.Write(\"Yes\" +\"\\n\"); } else { Console.Write(\"No\" +\"\\n\"); }} // Driver Programpublic static void Main(String[] args){ String A = \"10101\"; CheckDivisibilty(A);}} // This code is contributed by umadevi9616", "e": 13080, "s": 12084, "text": null }, { "code": "<script>// javascript program to check if the binary String is divisible// by 3. // Function to check if the binary String is divisible by 3. function CheckDivisibilty( A) { var oddbits = 0, evenbits = 0; for (var counter = 0; counter < A.length; counter++) { // checking if the bit is nonzero if (A[counter] == '1') { // checking if the nonzero bit is at even // position if (counter % 2 == 0) { evenbits++; } else { oddbits++; } } } // Checking if the difference of non-zero oddbits and // evenbits is divisible by 3. if (Math.abs(oddbits - evenbits) % 3 == 0) { document.write(\"Yes\" + \"\\n\"); } else { document.write(\"No\" + \"\\n\"); } } // Driver Program var A = \"10101\"; CheckDivisibilty(A); // This code is contributed by umadevi9616</script>", "e": 14080, "s": 13080, "text": null }, { "code": null, "e": 14084, "s": 14080, "text": "Yes" }, { "code": null, "e": 14138, "s": 14084, "text": "Time Complexity: O(n) where n is the number of bits." }, { "code": null, "e": 14160, "s": 14138, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 14173, "s": 14160, "text": "Mithun Kumar" }, { "code": null, "e": 14184, "s": 14173, "text": "nidhi_biet" }, { "code": null, "e": 14194, "s": 14184, "text": "rutvik_56" }, { "code": null, "e": 14216, "s": 14194, "text": "susmitakundugoaldanga" }, { "code": null, "e": 14231, "s": 14216, "text": "prathamjha5683" }, { "code": null, "e": 14243, "s": 14231, "text": "umadevi9616" }, { "code": null, "e": 14258, "s": 14243, "text": "ranjanrohit840" }, { "code": null, "e": 14271, "s": 14258, "text": "divisibility" }, { "code": null, "e": 14281, "s": 14271, "text": "Bit Magic" }, { "code": null, "e": 14291, "s": 14281, "text": "Bit Magic" }, { "code": null, "e": 14389, "s": 14291, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14419, "s": 14389, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 14457, "s": 14419, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 14497, "s": 14457, "text": "Binary representation of a given number" }, { "code": null, "e": 14540, "s": 14497, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 14616, "s": 14540, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 14647, "s": 14616, "text": "C++ bitset and its application" }, { "code": null, "e": 14698, "s": 14647, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 14733, "s": 14698, "text": "Find the element that appears once" }, { "code": null, "e": 14749, "s": 14733, "text": "Bit Fields in C" } ]
How to Integrate Emojis in an Android App?
08 Sep, 2020 Emojis certainly make the app more interesting and fun to interact with. In this article, let’s learn how to add Emojis in our own Android App by creating a simple application that looks like a messaging app. Why do we need Emojis? It makes the app look more user-friendly and fun. If the app features used for building communication, emojis certainly help to express a user’s feelings. It may be used to ask feedback of an app from the user. Step 1: Create a new Android Studio project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add the following dependency to build.gradle(:app) In order to use emojis in the app, add its dependency to build.gradle(:app) file. Add any one of the three dependencies: implementation ‘com.vanniktech:emoji-google:0.6.0’ implementation ‘com.vanniktech:emoji-ios:0.6.0’ implementation ‘com.vanniktech:emoji-twitter:0.6.0’ Each dependency signifies the emoji set we are importing. That is, either from ios, or Google, or Twitter. Step 3: Working with activity_main.xml file In this example, make the app look like a chat app. For this, use two Buttons. One to add emojis and one to send the message. Add also an EditText where the user will type the message. This is how the activity_main.xml looks like: activity_main.xml <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rootView" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#43a047" android:padding="8dp" tools:context=".MainActivity"> <LinearLayout android:id="@+id/llTextViews" android:layout_width="match_parent" android:layout_height="0dp" android:orientation="vertical" app:layout_constraintBottom_toTopOf="@id/etEmoji" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"> </LinearLayout> <com.vanniktech.emoji.EmojiEditText android:id="@+id/etEmoji" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="Say something to GeeksForGeeks..." app:emojiSize="30sp" android:textColor="@android:color/white" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toStartOf="@id/btnEmojis" app:layout_constraintStart_toStartOf="parent"/> <Button android:id="@+id/btnEmojis" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Emojis" app:layout_constraintEnd_toStartOf="@id/btnSend" app:layout_constraintTop_toTopOf="@id/etEmoji" app:layout_constraintBottom_toBottomOf="@id/etEmoji"/> <Button android:id="@+id/btnSend" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="@id/etEmoji" app:layout_constraintBottom_toBottomOf="@id/etEmoji"/> </androidx.constraintlayout.widget.ConstraintLayout> Step 4: Create a layout file called text_view_emoji.xml Create a layout to define how the emoji should look like. Its main purpose is to define the size of the emoji. It will also display the messages which we send. Create a new layout by clicking: app ->res -> layout(right-click) -> New -> Layout Resource File. Name this as text_view_emoji. This is how the text_view_emoji.xml looks like: text_view_emoji.xml <?xml version="1.0" encoding="utf-8"?><com.vanniktech.emoji.EmojiTextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_marginBottom="16dp" app:emojiSize="30sp" android:textSize="30sp" android:textColor="@android:color/white"/> Step 5: Create a class called EmojiApplication Depending on which emoji set the user wants to have, set up the corresponding providing here. By setting up the EmojiManager here, make sure that the user can use them anywhere in the app. To create a new class, click on: File -> New -> Java Class. Name this as EmojiApplication. This is how the EmojiApplication.java looks like: EmojiApplication.java import android.app.Application; import com.vanniktech.emoji.EmojiManager;import com.vanniktech.emoji.google.GoogleEmojiProvider; public class EmojiApplication extends Application { @Override public void onCreate() { super.onCreate(); EmojiManager.install(new GoogleEmojiProvider()); }} Note: Do not forget to add this new class in the AndroidManifest.xml file. This is how the AndroidManifest.xml looks like after adding: AndroidManifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.emojigfg"> <application android:name=".EmojiApplication" 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> Step 6: Working with the MainActivity.java file Here, write a function to inflate the EmojiTextView. The LayoutInfalter is used to convert a View or a ViewGroup written in XML to a View in Java which can use in the code. Also, set the onCreate() function here. After all these changes, this is how the MainActivity.java looks like: MainActivity.java import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import com.vanniktech.emoji.EmojiPopup;import com.vanniktech.emoji.EmojiTextView; public class MainActivity extends AppCompatActivity { EditText etEmoji; LinearLayout llTextViews; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etEmoji=findViewById(R.id.etEmoji); llTextViews=findViewById(R.id.llTextViews); final EmojiPopup popup = EmojiPopup.Builder .fromRootView(findViewById(R.id.rootView)).build(etEmoji); Button btnEmojis=findViewById(R.id.btnEmojis); btnEmojis.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { popup.toggle(); } }); Button btnSend=findViewById(R.id.btnSend); btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { llTextViews.addView(getEmojiTextView()); etEmoji.getText().clear(); } }); } private EmojiTextView getEmojiTextView() { EmojiTextView tvEmoji = (EmojiTextView) LayoutInflater .from(getApplicationContext()) .inflate(R.layout.text_view_emoji, llTextViews,false); tvEmoji.setText(etEmoji.getText().toString()); return tvEmoji; }} android Android How To Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Sep, 2020" }, { "code": null, "e": 237, "s": 28, "text": "Emojis certainly make the app more interesting and fun to interact with. In this article, let’s learn how to add Emojis in our own Android App by creating a simple application that looks like a messaging app." }, { "code": null, "e": 260, "s": 237, "text": "Why do we need Emojis?" }, { "code": null, "e": 310, "s": 260, "text": "It makes the app look more user-friendly and fun." }, { "code": null, "e": 415, "s": 310, "text": "If the app features used for building communication, emojis certainly help to express a user’s feelings." }, { "code": null, "e": 471, "s": 415, "text": "It may be used to ask feedback of an app from the user." }, { "code": null, "e": 515, "s": 471, "text": "Step 1: Create a new Android Studio project" }, { "code": null, "e": 677, "s": 515, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 736, "s": 677, "text": "Step 2: Add the following dependency to build.gradle(:app)" }, { "code": null, "e": 858, "s": 736, "text": "In order to use emojis in the app, add its dependency to build.gradle(:app) file. Add any one of the three dependencies: " }, { "code": null, "e": 909, "s": 858, "text": "implementation ‘com.vanniktech:emoji-google:0.6.0’" }, { "code": null, "e": 957, "s": 909, "text": "implementation ‘com.vanniktech:emoji-ios:0.6.0’" }, { "code": null, "e": 1009, "s": 957, "text": "implementation ‘com.vanniktech:emoji-twitter:0.6.0’" }, { "code": null, "e": 1117, "s": 1009, "text": "Each dependency signifies the emoji set we are importing. That is, either from ios, or Google, or Twitter. " }, { "code": null, "e": 1162, "s": 1117, "text": "Step 3: Working with activity_main.xml file " }, { "code": null, "e": 1393, "s": 1162, "text": "In this example, make the app look like a chat app. For this, use two Buttons. One to add emojis and one to send the message. Add also an EditText where the user will type the message. This is how the activity_main.xml looks like:" }, { "code": null, "e": 1411, "s": 1393, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/rootView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#43a047\" android:padding=\"8dp\" tools:context=\".MainActivity\"> <LinearLayout android:id=\"@+id/llTextViews\" android:layout_width=\"match_parent\" android:layout_height=\"0dp\" android:orientation=\"vertical\" app:layout_constraintBottom_toTopOf=\"@id/etEmoji\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\"> </LinearLayout> <com.vanniktech.emoji.EmojiEditText android:id=\"@+id/etEmoji\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:hint=\"Say something to GeeksForGeeks...\" app:emojiSize=\"30sp\" android:textColor=\"@android:color/white\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toStartOf=\"@id/btnEmojis\" app:layout_constraintStart_toStartOf=\"parent\"/> <Button android:id=\"@+id/btnEmojis\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Emojis\" app:layout_constraintEnd_toStartOf=\"@id/btnSend\" app:layout_constraintTop_toTopOf=\"@id/etEmoji\" app:layout_constraintBottom_toBottomOf=\"@id/etEmoji\"/> <Button android:id=\"@+id/btnSend\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Send\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintTop_toTopOf=\"@id/etEmoji\" app:layout_constraintBottom_toBottomOf=\"@id/etEmoji\"/> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 3437, "s": 1411, "text": null }, { "code": null, "e": 3493, "s": 3437, "text": "Step 4: Create a layout file called text_view_emoji.xml" }, { "code": null, "e": 3751, "s": 3493, "text": "Create a layout to define how the emoji should look like. Its main purpose is to define the size of the emoji. It will also display the messages which we send. Create a new layout by clicking: app ->res -> layout(right-click) -> New -> Layout Resource File." }, { "code": null, "e": 3829, "s": 3751, "text": "Name this as text_view_emoji. This is how the text_view_emoji.xml looks like:" }, { "code": null, "e": 3849, "s": 3829, "text": "text_view_emoji.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><com.vanniktech.emoji.EmojiTextView xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_marginBottom=\"16dp\" app:emojiSize=\"30sp\" android:textSize=\"30sp\" android:textColor=\"@android:color/white\"/>", "e": 4254, "s": 3849, "text": null }, { "code": null, "e": 4301, "s": 4254, "text": "Step 5: Create a class called EmojiApplication" }, { "code": null, "e": 4550, "s": 4301, "text": "Depending on which emoji set the user wants to have, set up the corresponding providing here. By setting up the EmojiManager here, make sure that the user can use them anywhere in the app. To create a new class, click on: File -> New -> Java Class." }, { "code": null, "e": 4631, "s": 4550, "text": "Name this as EmojiApplication. This is how the EmojiApplication.java looks like:" }, { "code": null, "e": 4653, "s": 4631, "text": "EmojiApplication.java" }, { "code": "import android.app.Application; import com.vanniktech.emoji.EmojiManager;import com.vanniktech.emoji.google.GoogleEmojiProvider; public class EmojiApplication extends Application { @Override public void onCreate() { super.onCreate(); EmojiManager.install(new GoogleEmojiProvider()); }}", "e": 4966, "s": 4653, "text": null }, { "code": null, "e": 5102, "s": 4966, "text": "Note: Do not forget to add this new class in the AndroidManifest.xml file. This is how the AndroidManifest.xml looks like after adding:" }, { "code": null, "e": 5122, "s": 5102, "text": "AndroidManifest.xml" }, { "code": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.emojigfg\"> <application android:name=\".EmojiApplication\" 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>", "e": 5825, "s": 5122, "text": null }, { "code": null, "e": 5873, "s": 5825, "text": "Step 6: Working with the MainActivity.java file" }, { "code": null, "e": 6157, "s": 5873, "text": "Here, write a function to inflate the EmojiTextView. The LayoutInfalter is used to convert a View or a ViewGroup written in XML to a View in Java which can use in the code. Also, set the onCreate() function here. After all these changes, this is how the MainActivity.java looks like:" }, { "code": null, "e": 6175, "s": 6157, "text": "MainActivity.java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import com.vanniktech.emoji.EmojiPopup;import com.vanniktech.emoji.EmojiTextView; public class MainActivity extends AppCompatActivity { EditText etEmoji; LinearLayout llTextViews; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etEmoji=findViewById(R.id.etEmoji); llTextViews=findViewById(R.id.llTextViews); final EmojiPopup popup = EmojiPopup.Builder .fromRootView(findViewById(R.id.rootView)).build(etEmoji); Button btnEmojis=findViewById(R.id.btnEmojis); btnEmojis.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { popup.toggle(); } }); Button btnSend=findViewById(R.id.btnSend); btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { llTextViews.addView(getEmojiTextView()); etEmoji.getText().clear(); } }); } private EmojiTextView getEmojiTextView() { EmojiTextView tvEmoji = (EmojiTextView) LayoutInflater .from(getApplicationContext()) .inflate(R.layout.text_view_emoji, llTextViews,false); tvEmoji.setText(etEmoji.getText().toString()); return tvEmoji; }}", "e": 7829, "s": 6175, "text": null }, { "code": null, "e": 7837, "s": 7829, "text": "android" }, { "code": null, "e": 7845, "s": 7837, "text": "Android" }, { "code": null, "e": 7852, "s": 7845, "text": "How To" }, { "code": null, "e": 7857, "s": 7852, "text": "Java" }, { "code": null, "e": 7862, "s": 7857, "text": "Java" }, { "code": null, "e": 7870, "s": 7862, "text": "Android" } ]
How to provide name to the TextBox in C#?
29 Nov, 2019 In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to assign a name to the TextBox control with the help of Name property of the TextBox. The default value of this property is an empty string. In Windows form, you can set this property in two different ways: 1. Design-Time: It is the simplest way to set the Name property of the TextBox as shown in the following steps: Step 1: Create a windows form. As shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the TextBox control from the ToolBox and drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. As shown in the below image: Step 3: After drag and drop you will go to the properties of the TextBox control to set the Name property of the TextBox. As shown in the below image:Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Name property of the TextBox programmatically with the help of given syntax: public string Name { get; set; } Here, the value of this property is of System.String type. Following steps are used to set the Name property of the TextBox: Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox TextBox Mytextbox = new TextBox(); // Creating textbox TextBox Mytextbox = new TextBox(); Step 2 : After creating TextBox, set the Name property of the TextBox provided by the TextBox class.// Set Name of the textbox Mytextbox1.Name = "text_box1"; // Set Name of the textbox Mytextbox1.Name = "text_box1"; Step 3 : And at last add this textbox control to from using Add() method.// Add this textbox to form this.Controls.Add(Mytextbox1); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel1 = new Label(); Mylablel1.Location = new Point(96, 54); Mylablel1.Text = "Enter First Name"; Mylablel1.AutoSize = true; Mylablel1.BackColor = Color.GreenYellow; // Add this label to form this.Controls.Add(Mylablel1); // Creating and setting the properties of TextBox1 TextBox Mytextbox1 = new TextBox(); Mytextbox1.Location = new Point(187, 51); Mytextbox1.BackColor = Color.GreenYellow; Mytextbox1.AutoSize = true; Mytextbox1.Name = "text_box1"; // Add this textbox to form this.Controls.Add(Mytextbox1); // Creating and setting the properties of Lable1 Label Mylablel2 = new Label(); Mylablel2.Location = new Point(96, 102); Mylablel2.Text = "Enter Last Name"; Mylablel2.AutoSize = true; Mylablel2.BackColor = Color.GreenYellow; // Add this label to form this.Controls.Add(Mylablel2); // Creating and setting the properties of TextBox2 TextBox Mytextbox2 = new TextBox(); Mytextbox2.Location = new Point(187, 99); Mytextbox2.BackColor = Color.GreenYellow; Mytextbox2.AutoSize = true; Mytextbox2.Name = "text_box2"; // Add this textbox to form this.Controls.Add(Mytextbox2); }}}Output: // Add this textbox to form this.Controls.Add(Mytextbox1); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel1 = new Label(); Mylablel1.Location = new Point(96, 54); Mylablel1.Text = "Enter First Name"; Mylablel1.AutoSize = true; Mylablel1.BackColor = Color.GreenYellow; // Add this label to form this.Controls.Add(Mylablel1); // Creating and setting the properties of TextBox1 TextBox Mytextbox1 = new TextBox(); Mytextbox1.Location = new Point(187, 51); Mytextbox1.BackColor = Color.GreenYellow; Mytextbox1.AutoSize = true; Mytextbox1.Name = "text_box1"; // Add this textbox to form this.Controls.Add(Mytextbox1); // Creating and setting the properties of Lable1 Label Mylablel2 = new Label(); Mylablel2.Location = new Point(96, 102); Mylablel2.Text = "Enter Last Name"; Mylablel2.AutoSize = true; Mylablel2.BackColor = Color.GreenYellow; // Add this label to form this.Controls.Add(Mylablel2); // Creating and setting the properties of TextBox2 TextBox Mytextbox2 = new TextBox(); Mytextbox2.Location = new Point(187, 99); Mytextbox2.BackColor = Color.GreenYellow; Mytextbox2.AutoSize = true; Mytextbox2.Name = "text_box2"; // Add this textbox to form this.Controls.Add(Mytextbox2); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2019" }, { "code": null, "e": 434, "s": 28, "text": "In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to assign a name to the TextBox control with the help of Name property of the TextBox. The default value of this property is an empty string. In Windows form, you can set this property in two different ways:" }, { "code": null, "e": 546, "s": 434, "text": "1. Design-Time: It is the simplest way to set the Name property of the TextBox as shown in the following steps:" }, { "code": null, "e": 663, "s": 546, "text": "Step 1: Create a windows form. As shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 850, "s": 663, "text": "Step 2: Drag the TextBox control from the ToolBox and drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. As shown in the below image:" }, { "code": null, "e": 1008, "s": 850, "text": "Step 3: After drag and drop you will go to the properties of the TextBox control to set the Name property of the TextBox. As shown in the below image:Output:" }, { "code": null, "e": 1016, "s": 1008, "text": "Output:" }, { "code": null, "e": 1189, "s": 1016, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Name property of the TextBox programmatically with the help of given syntax:" }, { "code": null, "e": 1222, "s": 1189, "text": "public string Name { get; set; }" }, { "code": null, "e": 1347, "s": 1222, "text": "Here, the value of this property is of System.String type. Following steps are used to set the Name property of the TextBox:" }, { "code": null, "e": 1491, "s": 1347, "text": "Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox\nTextBox Mytextbox = new TextBox();\n" }, { "code": null, "e": 1547, "s": 1491, "text": "// Creating textbox\nTextBox Mytextbox = new TextBox();\n" }, { "code": null, "e": 1706, "s": 1547, "text": "Step 2 : After creating TextBox, set the Name property of the TextBox provided by the TextBox class.// Set Name of the textbox\nMytextbox1.Name = \"text_box1\";\n" }, { "code": null, "e": 1765, "s": 1706, "text": "// Set Name of the textbox\nMytextbox1.Name = \"text_box1\";\n" }, { "code": null, "e": 3692, "s": 1765, "text": "Step 3 : And at last add this textbox control to from using Add() method.// Add this textbox to form\nthis.Controls.Add(Mytextbox1);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel1 = new Label(); Mylablel1.Location = new Point(96, 54); Mylablel1.Text = \"Enter First Name\"; Mylablel1.AutoSize = true; Mylablel1.BackColor = Color.GreenYellow; // Add this label to form this.Controls.Add(Mylablel1); // Creating and setting the properties of TextBox1 TextBox Mytextbox1 = new TextBox(); Mytextbox1.Location = new Point(187, 51); Mytextbox1.BackColor = Color.GreenYellow; Mytextbox1.AutoSize = true; Mytextbox1.Name = \"text_box1\"; // Add this textbox to form this.Controls.Add(Mytextbox1); // Creating and setting the properties of Lable1 Label Mylablel2 = new Label(); Mylablel2.Location = new Point(96, 102); Mylablel2.Text = \"Enter Last Name\"; Mylablel2.AutoSize = true; Mylablel2.BackColor = Color.GreenYellow; // Add this label to form this.Controls.Add(Mylablel2); // Creating and setting the properties of TextBox2 TextBox Mytextbox2 = new TextBox(); Mytextbox2.Location = new Point(187, 99); Mytextbox2.BackColor = Color.GreenYellow; Mytextbox2.AutoSize = true; Mytextbox2.Name = \"text_box2\"; // Add this textbox to form this.Controls.Add(Mytextbox2); }}}Output:" }, { "code": null, "e": 3752, "s": 3692, "text": "// Add this textbox to form\nthis.Controls.Add(Mytextbox1);\n" }, { "code": null, "e": 3761, "s": 3752, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel1 = new Label(); Mylablel1.Location = new Point(96, 54); Mylablel1.Text = \"Enter First Name\"; Mylablel1.AutoSize = true; Mylablel1.BackColor = Color.GreenYellow; // Add this label to form this.Controls.Add(Mylablel1); // Creating and setting the properties of TextBox1 TextBox Mytextbox1 = new TextBox(); Mytextbox1.Location = new Point(187, 51); Mytextbox1.BackColor = Color.GreenYellow; Mytextbox1.AutoSize = true; Mytextbox1.Name = \"text_box1\"; // Add this textbox to form this.Controls.Add(Mytextbox1); // Creating and setting the properties of Lable1 Label Mylablel2 = new Label(); Mylablel2.Location = new Point(96, 102); Mylablel2.Text = \"Enter Last Name\"; Mylablel2.AutoSize = true; Mylablel2.BackColor = Color.GreenYellow; // Add this label to form this.Controls.Add(Mylablel2); // Creating and setting the properties of TextBox2 TextBox Mytextbox2 = new TextBox(); Mytextbox2.Location = new Point(187, 99); Mytextbox2.BackColor = Color.GreenYellow; Mytextbox2.AutoSize = true; Mytextbox2.Name = \"text_box2\"; // Add this textbox to form this.Controls.Add(Mytextbox2); }}}", "e": 5541, "s": 3761, "text": null }, { "code": null, "e": 5549, "s": 5541, "text": "Output:" }, { "code": null, "e": 5580, "s": 5549, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 5583, "s": 5580, "text": "C#" } ]
Find the arrangement of queue at given time
27 May, 2022 n people are standing in a queue to buy entry ticket for the carnival. People present there strongly believe in chivalry. Therefore, at time = t, if a man at position x, finds a woman standing behind him then he exchanges his position with her and therefore, at time = t+1, woman is standing at position x while man is standing behind her. Given the total number of people standing in a queue as n, particular instant of time as t and the initial arrangement of the queue in the form of a string containing ‘M’ representing man at position i and ‘W’ representing woman is at position i, find out the arrangement of the queue at time = t. Examples : Input : n = 6, t = 2 BBGBBG Output: GBBGBB Explanation: At t = 1, 'B' at position 2 will swap with 'G' at position 3 and 'B' at position 5 will swap with 'G' at position 6. String after t = 1 changes to "BGBBGB". Now at t = 2, 'B' at position = 1 will swap with 'G' at position = 2 and 'B' at position = 4 will swap with 'G' at position 5. String changes to "GBBGBB". Since, we have to display arrangement at t = 2, the current arrangement is our answer. Input : n = 8, t = 3 BBGBGBGB Output: GGBGBBBB Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Approach: Traverse the entire string at every moment of time from 1 to t and if we find pairwise “BG” then swap them and move to check the next pair. Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // CPP program to find the arrangement// of queue at time = t#include <bits/stdc++.h>using namespace std; // prints the arrangement at time = tvoid solve(int n, int t, string s){ // Checking the entire queue for // every moment from time = 1 to // time = t. for (int i = 0; i < t; i++) for (int j = 0; j < n - 1; j++) /*If current index contains 'B' and next index contains 'G' then swap*/ if (s[j] == 'B' && s[j + 1] == 'G') { char temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; j++; } cout << s;} // Driver function for the programint main(){ int n = 6, t = 2; string s = "BBGBBG"; solve(n, t, s); return 0;} // Java program to find the arrangement// of queue at time = timport java.io.*; class Geek { // prints the arrangement at time = t static void solve(int n, int t, char s[]) { // Checking the entire queue for // every moment from time = 1 to // time = t. for (int i = 0; i < t; i++) for (int j = 0; j < n - 1; j++) /*If current index contains 'B' and next index contains 'G' then swap.*/ if (s[j] == 'B' && s[j + 1] == 'G') { char temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; j++; } System.out.print(s); } // Driver function public static void main(String args[]) { int n = 6, t = 2; String s = "BBGBBG"; char str[] = s.toCharArray(); solve(n, t, str); }} # Python program to find# the arrangement of# queue at time = t # prints the arrangement# at time = tdef solve(n, t, p) : s = list(p) # Checking the entire # queue for every # moment from time = 1 # to time = t. for i in range(0, t) : for j in range(0, n - 1) : # If current index # contains 'B' and # next index contains # 'G' then swap if (s[j] == 'B' and s[j + 1] == 'G') : temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; j = j + 1 print (''.join(s)) # Driver coden = 6t = 2p = "BBGBBG"solve(n, t, p) # This code is contributed by# Manish Shaw(manishshaw1) // C# program to find the arrangement// of queue at time = tusing System; class Geek { // prints the arrangement at time = t static void solve(int n, int t, char[] s) { // Checking the entire queue for // every moment from time = 1 to // time = t. for (int i = 0; i < t; i++) for (int j = 0; j < n - 1; j++) /*If current index contains 'B' and next index contains 'G' then swap.*/ if (s[j] == 'B' && s[j + 1] == 'G') { char temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; j++; } Console.Write(s); } // Driver function public static void Main(String[] args) { int n = 6, t = 2; String s = "BBGBBG"; char []str = s.ToCharArray(); solve(n, t, str); }} // This code is contributed by parashar... <?php// PHP program to find// the arrangement of// queue at time = t // prints the arrangement// at time = tfunction solve($n, $t, $s){ // Checking the entire // queue for every // moment from time = 1 // to time = t. for ($i = 0; $i < $t; $i++) { for ($j = 0; $j < $n - 1; $j++) { /*If current index contains 'B' and next index contains 'G' then swap*/ if ($s[$j] == 'B' && $s[$j + 1] == 'G') { $temp = $s[$j]; $s[$j] = $s[$j + 1]; $s[$j + 1] = $temp; $j++; } } } echo ($s);} // Driver code$n = 6; $t = 2;$s = "BBGBBG";solve($n, $t, $s); // This code is contributed by// Manish Shaw(manishshaw1)?> <script>// Javascript program to find the arrangement// of queue at time = t // prints the arrangement at time = tfunction solve( n, t, st){ // Checking the entire queue for // every moment from time = 1 to // time = t. let s = st.split(''); for (var i = 0; i < t; i++) for (var j = 0; j < n - 1; j++) /*If current index contains 'B' and next index contains 'G' then swap*/ if (s[j] == 'B' && s[j + 1] == 'G') { var temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; j++; } document.write(s.join(''));} // Driver function for the programvar n = 6, t = 2;var s = "BBGBBG";solve(n, t, s); //This code is contributed by Shubham Singh</script> Output: GBBGBB Time Complexity: O(n*t) Auxiliary Space: O(1) Find the arrangement of queue at given time | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersFind the arrangement of queue at given time | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:46•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=P3qzZtp2Jdg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> parashar manishshaw1 SHUBHAMSINGH10 shivamanandrj9 Competitive Programming Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n27 May, 2022" }, { "code": null, "e": 704, "s": 53, "text": "n people are standing in a queue to buy entry ticket for the carnival. People present there strongly believe in chivalry. Therefore, at time = t, if a man at position x, finds a woman standing behind him then he exchanges his position with her and therefore, at time = t+1, woman is standing at position x while man is standing behind her. Given the total number of people standing in a queue as n, particular instant of time as t and the initial arrangement of the queue in the form of a string containing ‘M’ representing man at position i and ‘W’ representing woman is at position i, find out the arrangement of the queue at time = t. Examples : " }, { "code": null, "e": 1230, "s": 704, "text": "Input : n = 6, t = 2\n BBGBBG\nOutput: GBBGBB\nExplanation:\nAt t = 1, 'B' at position 2 will swap\nwith 'G' at position 3 and 'B' at \nposition 5 will swap with 'G' at \nposition 6. String after t = 1 changes \nto \"BGBBGB\". Now at t = 2, 'B' at\nposition = 1 will swap with 'G' at \nposition = 2 and 'B' at position = 4 \nwill swap with 'G' at position 5. \nString changes to \"GBBGBB\". Since, \nwe have to display arrangement at\nt = 2, the current arrangement is \nour answer. \n\nInput : n = 8, t = 3\n BBGBGBGB\nOutput: GGBGBBBB" }, { "code": null, "e": 1241, "s": 1232, "text": "Chapters" }, { "code": null, "e": 1268, "s": 1241, "text": "descriptions off, selected" }, { "code": null, "e": 1318, "s": 1268, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1341, "s": 1318, "text": "captions off, selected" }, { "code": null, "e": 1349, "s": 1341, "text": "English" }, { "code": null, "e": 1373, "s": 1349, "text": "This is a modal window." }, { "code": null, "e": 1442, "s": 1373, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1464, "s": 1442, "text": "End of dialog window." }, { "code": null, "e": 1663, "s": 1464, "text": "Approach: Traverse the entire string at every moment of time from 1 to t and if we find pairwise “BG” then swap them and move to check the next pair. Below is the implementation of above approach: " }, { "code": null, "e": 1667, "s": 1663, "text": "C++" }, { "code": null, "e": 1672, "s": 1667, "text": "Java" }, { "code": null, "e": 1680, "s": 1672, "text": "Python3" }, { "code": null, "e": 1683, "s": 1680, "text": "C#" }, { "code": null, "e": 1687, "s": 1683, "text": "PHP" }, { "code": null, "e": 1698, "s": 1687, "text": "Javascript" }, { "code": "// CPP program to find the arrangement// of queue at time = t#include <bits/stdc++.h>using namespace std; // prints the arrangement at time = tvoid solve(int n, int t, string s){ // Checking the entire queue for // every moment from time = 1 to // time = t. for (int i = 0; i < t; i++) for (int j = 0; j < n - 1; j++) /*If current index contains 'B' and next index contains 'G' then swap*/ if (s[j] == 'B' && s[j + 1] == 'G') { char temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; j++; } cout << s;} // Driver function for the programint main(){ int n = 6, t = 2; string s = \"BBGBBG\"; solve(n, t, s); return 0;}", "e": 2484, "s": 1698, "text": null }, { "code": "// Java program to find the arrangement// of queue at time = timport java.io.*; class Geek { // prints the arrangement at time = t static void solve(int n, int t, char s[]) { // Checking the entire queue for // every moment from time = 1 to // time = t. for (int i = 0; i < t; i++) for (int j = 0; j < n - 1; j++) /*If current index contains 'B' and next index contains 'G' then swap.*/ if (s[j] == 'B' && s[j + 1] == 'G') { char temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; j++; } System.out.print(s); } // Driver function public static void main(String args[]) { int n = 6, t = 2; String s = \"BBGBBG\"; char str[] = s.toCharArray(); solve(n, t, str); }}", "e": 3434, "s": 2484, "text": null }, { "code": "# Python program to find# the arrangement of# queue at time = t # prints the arrangement# at time = tdef solve(n, t, p) : s = list(p) # Checking the entire # queue for every # moment from time = 1 # to time = t. for i in range(0, t) : for j in range(0, n - 1) : # If current index # contains 'B' and # next index contains # 'G' then swap if (s[j] == 'B' and s[j + 1] == 'G') : temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; j = j + 1 print (''.join(s)) # Driver coden = 6t = 2p = \"BBGBBG\"solve(n, t, p) # This code is contributed by# Manish Shaw(manishshaw1)", "e": 4216, "s": 3434, "text": null }, { "code": "// C# program to find the arrangement// of queue at time = tusing System; class Geek { // prints the arrangement at time = t static void solve(int n, int t, char[] s) { // Checking the entire queue for // every moment from time = 1 to // time = t. for (int i = 0; i < t; i++) for (int j = 0; j < n - 1; j++) /*If current index contains 'B' and next index contains 'G' then swap.*/ if (s[j] == 'B' && s[j + 1] == 'G') { char temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; j++; } Console.Write(s); } // Driver function public static void Main(String[] args) { int n = 6, t = 2; String s = \"BBGBBG\"; char []str = s.ToCharArray(); solve(n, t, str); }} // This code is contributed by parashar...", "e": 5211, "s": 4216, "text": null }, { "code": "<?php// PHP program to find// the arrangement of// queue at time = t // prints the arrangement// at time = tfunction solve($n, $t, $s){ // Checking the entire // queue for every // moment from time = 1 // to time = t. for ($i = 0; $i < $t; $i++) { for ($j = 0; $j < $n - 1; $j++) { /*If current index contains 'B' and next index contains 'G' then swap*/ if ($s[$j] == 'B' && $s[$j + 1] == 'G') { $temp = $s[$j]; $s[$j] = $s[$j + 1]; $s[$j + 1] = $temp; $j++; } } } echo ($s);} // Driver code$n = 6; $t = 2;$s = \"BBGBBG\";solve($n, $t, $s); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 6040, "s": 5211, "text": null }, { "code": "<script>// Javascript program to find the arrangement// of queue at time = t // prints the arrangement at time = tfunction solve( n, t, st){ // Checking the entire queue for // every moment from time = 1 to // time = t. let s = st.split(''); for (var i = 0; i < t; i++) for (var j = 0; j < n - 1; j++) /*If current index contains 'B' and next index contains 'G' then swap*/ if (s[j] == 'B' && s[j + 1] == 'G') { var temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; j++; } document.write(s.join(''));} // Driver function for the programvar n = 6, t = 2;var s = \"BBGBBG\";solve(n, t, s); //This code is contributed by Shubham Singh</script>", "e": 6842, "s": 6040, "text": null }, { "code": null, "e": 6852, "s": 6842, "text": "Output: " }, { "code": null, "e": 6859, "s": 6852, "text": "GBBGBB" }, { "code": null, "e": 6905, "s": 6859, "text": "Time Complexity: O(n*t) Auxiliary Space: O(1)" }, { "code": null, "e": 7809, "s": 6905, "text": "Find the arrangement of queue at given time | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersFind the arrangement of queue at given time | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:46•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=P3qzZtp2Jdg\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 7820, "s": 7811, "text": "parashar" }, { "code": null, "e": 7832, "s": 7820, "text": "manishshaw1" }, { "code": null, "e": 7847, "s": 7832, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 7862, "s": 7847, "text": "shivamanandrj9" }, { "code": null, "e": 7886, "s": 7862, "text": "Competitive Programming" }, { "code": null, "e": 7894, "s": 7886, "text": "Strings" }, { "code": null, "e": 7902, "s": 7894, "text": "Strings" } ]
C++ Program To Merge K Sorted Linked Lists Using Min Heap - Set 2 - GeeksforGeeks
10 Jan, 2022 Given k linked lists each of size n and each list is sorted in non-decreasing order, merge them into a single sorted (non-decreasing order) linked list and print the sorted linked list as output.Examples: Input: k = 3, n = 4 list1 = 1->3->5->7->NULL list2 = 2->4->6->8->NULL list3 = 0->9->10->11->NULL Output: 0->1->2->3->4->5->6->7->8->9->10->11 Merged lists in a sorted order where every element is greater than the previous element. Input: k = 3, n = 3 list1 = 1->3->7->NULL list2 = 2->4->8->NULL list3 = 9->10->11->NULL Output: 1->2->3->4->7->8->9->10->11 Merged lists in a sorted order where every element is greater than the previous element. Source: Merge K sorted Linked Lists | Method 2 An efficient solution for the problem has been discussed in Method 3 of this post. Approach: This solution is based on the MIN HEAP approach used to solve the problem ‘merge k sorted arrays’ which is discussed here. MinHeap: A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored at index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2. Create a min-heap and insert the first element of all the ‘k’ linked lists.As long as the min-heap is not empty, perform the following steps:Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap.Return the head node address of the merged list. Create a min-heap and insert the first element of all the ‘k’ linked lists. As long as the min-heap is not empty, perform the following steps:Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap. Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap. Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list. If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap. Return the head node address of the merged list. Below is the implementation of the above approach: C++ // C++ implementation to merge k// sorted linked lists// | Using MIN HEAP method#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* next;}; // Utility function to create a new nodestruct Node* newNode(int data){ // allocate node struct Node* new_node = new Node(); // put in the data new_node->data = data; new_node->next = NULL; return new_node;} // 'compare' function used to build up the// priority queuestruct compare { bool operator()( struct Node* a, struct Node* b) { return a->data > b->data; }}; // function to merge k sorted linked listsstruct Node* mergeKSortedLists( struct Node* arr[], int k){ // priority_queue 'pq' implemented // as min heap with the // help of 'compare' function priority_queue<Node*, vector<Node*>, compare> pq; // push the head nodes of all // the k lists in 'pq' for (int i = 0; i < k; i++) if (arr[i] != NULL) pq.push(arr[i]); // Handles the case when k = 0 // or lists have no elements in them if (pq.empty()) return NULL; struct Node *dummy = newNode(0); struct Node *last = dummy; // loop till 'pq' is not empty while (!pq.empty()) { // get the top element of 'pq' struct Node* curr = pq.top(); pq.pop(); // add the top element of 'pq' // to the resultant merged list last->next = curr; last = last->next; // check if there is a node // next to the 'top' node // in the list of which 'top' // node is a member if (curr->next != NULL) // push the next node of top node in 'pq' pq.push(curr->next); } // address of head node of the required merged list return dummy->next;} // function to print the singly linked listvoid printList(struct Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver program to test aboveint main(){ int k = 3; // Number of linked lists int n = 4; // Number of elements in each list // an array of pointers storing the head nodes // of the linked lists Node* arr[k]; // creating k = 3 sorted lists arr[0] = newNode(1); arr[0]->next = newNode(3); arr[0]->next->next = newNode(5); arr[0]->next->next->next = newNode(7); arr[1] = newNode(2); arr[1]->next = newNode(4); arr[1]->next->next = newNode(6); arr[1]->next->next->next = newNode(8); arr[2] = newNode(0); arr[2]->next = newNode(9); arr[2]->next->next = newNode(10); arr[2]->next->next->next = newNode(11); // merge the k sorted lists struct Node* head = mergeKSortedLists(arr, k); // print the merged list printList(head); return 0;} 0 1 2 3 4 5 6 7 8 9 10 11 Complexity Analysis: Time Complexity: O(N * log k) or O(n * k * log k), where, ‘N’ is the total number of elements among all the linked lists, ‘k’ is the total number of lists, and ‘n’ is the size of each linked list.Insertion and deletion operation will be performed in min-heap for all N nodes.Insertion and deletion in a min-heap require log k time. Auxiliary Space: O(k). The priority queue will have atmost ‘k’ number of elements at any point of time, hence the additional space required for our algorithm is O(k). Please refer complete article on Merge k sorted linked lists | Set 2 (Using Min Heap) for more details! Amazon VMWare C++ Programs Heap Linked List VMWare Amazon Linked List Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. cout in C++ Passing a function as a parameter in C++ Const keyword in C++ Creating array of pointers in C++ Dynamic _Cast in C++ HeapSort Binary Heap Huffman Coding | Greedy Algo-3 Insertion and Deletion in Heaps Max Heap in Java
[ { "code": null, "e": 25851, "s": 25823, "text": "\n10 Jan, 2022" }, { "code": null, "e": 26057, "s": 25851, "text": "Given k linked lists each of size n and each list is sorted in non-decreasing order, merge them into a single sorted (non-decreasing order) linked list and print the sorted linked list as output.Examples: " }, { "code": null, "e": 26510, "s": 26057, "text": "Input: k = 3, n = 4\nlist1 = 1->3->5->7->NULL\nlist2 = 2->4->6->8->NULL\nlist3 = 0->9->10->11->NULL\n\nOutput: 0->1->2->3->4->5->6->7->8->9->10->11\nMerged lists in a sorted order \nwhere every element is greater \nthan the previous element.\n\nInput: k = 3, n = 3\nlist1 = 1->3->7->NULL\nlist2 = 2->4->8->NULL\nlist3 = 9->10->11->NULL\n\nOutput: 1->2->3->4->7->8->9->10->11\nMerged lists in a sorted order \nwhere every element is greater \nthan the previous element." }, { "code": null, "e": 26557, "s": 26510, "text": "Source: Merge K sorted Linked Lists | Method 2" }, { "code": null, "e": 26640, "s": 26557, "text": "An efficient solution for the problem has been discussed in Method 3 of this post." }, { "code": null, "e": 27101, "s": 26640, "text": "Approach: This solution is based on the MIN HEAP approach used to solve the problem ‘merge k sorted arrays’ which is discussed here. MinHeap: A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored at index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2." }, { "code": null, "e": 27560, "s": 27101, "text": "Create a min-heap and insert the first element of all the ‘k’ linked lists.As long as the min-heap is not empty, perform the following steps:Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap.Return the head node address of the merged list." }, { "code": null, "e": 27636, "s": 27560, "text": "Create a min-heap and insert the first element of all the ‘k’ linked lists." }, { "code": null, "e": 27972, "s": 27636, "text": "As long as the min-heap is not empty, perform the following steps:Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap." }, { "code": null, "e": 28242, "s": 27972, "text": "Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap." }, { "code": null, "e": 28382, "s": 28242, "text": "Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list." }, { "code": null, "e": 28513, "s": 28382, "text": "If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap." }, { "code": null, "e": 28562, "s": 28513, "text": "Return the head node address of the merged list." }, { "code": null, "e": 28613, "s": 28562, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28617, "s": 28613, "text": "C++" }, { "code": "// C++ implementation to merge k// sorted linked lists// | Using MIN HEAP method#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* next;}; // Utility function to create a new nodestruct Node* newNode(int data){ // allocate node struct Node* new_node = new Node(); // put in the data new_node->data = data; new_node->next = NULL; return new_node;} // 'compare' function used to build up the// priority queuestruct compare { bool operator()( struct Node* a, struct Node* b) { return a->data > b->data; }}; // function to merge k sorted linked listsstruct Node* mergeKSortedLists( struct Node* arr[], int k){ // priority_queue 'pq' implemented // as min heap with the // help of 'compare' function priority_queue<Node*, vector<Node*>, compare> pq; // push the head nodes of all // the k lists in 'pq' for (int i = 0; i < k; i++) if (arr[i] != NULL) pq.push(arr[i]); // Handles the case when k = 0 // or lists have no elements in them if (pq.empty()) return NULL; struct Node *dummy = newNode(0); struct Node *last = dummy; // loop till 'pq' is not empty while (!pq.empty()) { // get the top element of 'pq' struct Node* curr = pq.top(); pq.pop(); // add the top element of 'pq' // to the resultant merged list last->next = curr; last = last->next; // check if there is a node // next to the 'top' node // in the list of which 'top' // node is a member if (curr->next != NULL) // push the next node of top node in 'pq' pq.push(curr->next); } // address of head node of the required merged list return dummy->next;} // function to print the singly linked listvoid printList(struct Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver program to test aboveint main(){ int k = 3; // Number of linked lists int n = 4; // Number of elements in each list // an array of pointers storing the head nodes // of the linked lists Node* arr[k]; // creating k = 3 sorted lists arr[0] = newNode(1); arr[0]->next = newNode(3); arr[0]->next->next = newNode(5); arr[0]->next->next->next = newNode(7); arr[1] = newNode(2); arr[1]->next = newNode(4); arr[1]->next->next = newNode(6); arr[1]->next->next->next = newNode(8); arr[2] = newNode(0); arr[2]->next = newNode(9); arr[2]->next->next = newNode(10); arr[2]->next->next->next = newNode(11); // merge the k sorted lists struct Node* head = mergeKSortedLists(arr, k); // print the merged list printList(head); return 0;}", "e": 31440, "s": 28617, "text": null }, { "code": null, "e": 31467, "s": 31440, "text": "0 1 2 3 4 5 6 7 8 9 10 11 " }, { "code": null, "e": 31489, "s": 31467, "text": "Complexity Analysis: " }, { "code": null, "e": 31821, "s": 31489, "text": "Time Complexity: O(N * log k) or O(n * k * log k), where, ‘N’ is the total number of elements among all the linked lists, ‘k’ is the total number of lists, and ‘n’ is the size of each linked list.Insertion and deletion operation will be performed in min-heap for all N nodes.Insertion and deletion in a min-heap require log k time." }, { "code": null, "e": 31988, "s": 31821, "text": "Auxiliary Space: O(k). The priority queue will have atmost ‘k’ number of elements at any point of time, hence the additional space required for our algorithm is O(k)." }, { "code": null, "e": 32092, "s": 31988, "text": "Please refer complete article on Merge k sorted linked lists | Set 2 (Using Min Heap) for more details!" }, { "code": null, "e": 32099, "s": 32092, "text": "Amazon" }, { "code": null, "e": 32106, "s": 32099, "text": "VMWare" }, { "code": null, "e": 32119, "s": 32106, "text": "C++ Programs" }, { "code": null, "e": 32124, "s": 32119, "text": "Heap" }, { "code": null, "e": 32136, "s": 32124, "text": "Linked List" }, { "code": null, "e": 32143, "s": 32136, "text": "VMWare" }, { "code": null, "e": 32150, "s": 32143, "text": "Amazon" }, { "code": null, "e": 32162, "s": 32150, "text": "Linked List" }, { "code": null, "e": 32167, "s": 32162, "text": "Heap" }, { "code": null, "e": 32265, "s": 32167, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32277, "s": 32265, "text": "cout in C++" }, { "code": null, "e": 32318, "s": 32277, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 32339, "s": 32318, "text": "Const keyword in C++" }, { "code": null, "e": 32373, "s": 32339, "text": "Creating array of pointers in C++" }, { "code": null, "e": 32394, "s": 32373, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 32403, "s": 32394, "text": "HeapSort" }, { "code": null, "e": 32415, "s": 32403, "text": "Binary Heap" }, { "code": null, "e": 32446, "s": 32415, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 32478, "s": 32446, "text": "Insertion and Deletion in Heaps" } ]
Program to print a rectangle pattern - GeeksforGeeks
04 Oct, 2018 Given height h and width w, print a rectangular pattern as shown in example below. Examples: Input : h = 4, w = 5 Output : @@@@@ @ @ @ @ @@@@@ Input : h = 7, w = 9 Output : @@@@@@@@ @ @ @ @ @ @ @ @ @ @ @@@@@@@@ The idea is to run two loops. One for number of rows to be printed and other for number of columns. Print a ‘@’ only when current row is first or last. OR current column is first or last. C++ Java Python3 C# PHP // CPP program to print a rectangular pattern#include<iostream>using namespace std; void printRectangle(int h, int w){ for (int i=0; i<h; i++) { cout << "\n"; for (int j=0; j<w; j++) { // Print @ if this is first row // or last row. Or this column // is first or last. if (i == 0 || i == h-1 || j== 0 || j == w-1) cout << "@"; else cout << " "; } }} // Driver codeint main(){ int h = 4, w = 5; printRectangle(h, w); return 0;} // JAVA program to print a rectangular // pattern class GFG { static void printRectangle(int h, int w) { for (int i = 0; i < h; i++) { System.out.println(); for (int j = 0; j < w; j++) { // Print @ if this is first // row or last row. Or this // column is first or last. if (i == 0 || i == h-1 || j== 0 || j == w-1) System.out.print("@"); else System.out.print(" "); } } } // Driver code public static void main(String args[]) { int h = 4, w = 5; printRectangle(h, w) ; }} /*This code is contributed by Nikita Tiwari.*/ # Python 3 program to print a rectangular# pattern def printRectangle(h, w) : for i in range(0, h) : print ("") for j in range(0, w) : # Print @ if this is first row # or last row. Or this column # is first or last. if (i == 0 or i == h-1 or j== 0 or j == w-1) : print("@",end="") else : print(" ",end="") # Driver codeh = 4w = 5printRectangle(h, w) # This code is contributed by Nikita Tiwari. // C# program to print a rectangular // patternusing System;class GFG { static void printRectangle(int h, int w) { for (int i = 0; i < h; i++) { Console.WriteLine(); for (int j = 0; j < w; j++) { // Print @ if this is first // row or last row. Or this // column is first or last. if (i == 0 || i == h-1 || j== 0 || j == w-1) Console.Write("@"); else Console.Write(" "); } } } // Driver code public static void Main() { int h = 4, w = 5; printRectangle(h, w) ; }} /*This code is contributed by vt_m.*/ <?php// php program to print // a rectangular pattern function printRectangle($h , $w){ for ($i = 0; $i < $h; $i++) { echo"\n"; for ($j = 0; $j < $w; $j++) { // Print @ if this is first row // or last row. Or this column // is first or last. if ($i == 0 || $i == $h - 1 || $j == 0 || $j == $w - 1) echo"@"; else echo" "; } }} // Driver code $h = 4; $w = 5; printRectangle($h, $w); // This code is contributed by mits ?> @@@@@ @ @ @ @ @@@@@ The time complexity is O(n2).This article is contributed by Anurag Rawat. 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. Mithun Kumar pattern-printing square-rectangle School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Classes and Objects Interfaces in Java Constructors in C++ Operator Overloading in C++ Copy Constructor in C++ Polymorphism in C++ C++ Data Types Friend class and function in C++ Introduction To PYTHON Types of Operating Systems
[ { "code": null, "e": 25647, "s": 25619, "text": "\n04 Oct, 2018" }, { "code": null, "e": 25730, "s": 25647, "text": "Given height h and width w, print a rectangular pattern as shown in example below." }, { "code": null, "e": 25740, "s": 25730, "text": "Examples:" }, { "code": null, "e": 25970, "s": 25740, "text": "Input : h = 4, w = 5\nOutput : @@@@@\n @ @\n @ @\n @@@@@\n\nInput : h = 7, w = 9\nOutput : @@@@@@@@\n @ @\n @ @\n @ @\n @ @\n @ @\n @@@@@@@@\n" }, { "code": null, "e": 26158, "s": 25970, "text": "The idea is to run two loops. One for number of rows to be printed and other for number of columns. Print a ‘@’ only when current row is first or last. OR current column is first or last." }, { "code": null, "e": 26162, "s": 26158, "text": "C++" }, { "code": null, "e": 26167, "s": 26162, "text": "Java" }, { "code": null, "e": 26175, "s": 26167, "text": "Python3" }, { "code": null, "e": 26178, "s": 26175, "text": "C#" }, { "code": null, "e": 26182, "s": 26178, "text": "PHP" }, { "code": "// CPP program to print a rectangular pattern#include<iostream>using namespace std; void printRectangle(int h, int w){ for (int i=0; i<h; i++) { cout << \"\\n\"; for (int j=0; j<w; j++) { // Print @ if this is first row // or last row. Or this column // is first or last. if (i == 0 || i == h-1 || j== 0 || j == w-1) cout << \"@\"; else cout << \" \"; } }} // Driver codeint main(){ int h = 4, w = 5; printRectangle(h, w); return 0;}", "e": 26759, "s": 26182, "text": null }, { "code": "// JAVA program to print a rectangular // pattern class GFG { static void printRectangle(int h, int w) { for (int i = 0; i < h; i++) { System.out.println(); for (int j = 0; j < w; j++) { // Print @ if this is first // row or last row. Or this // column is first or last. if (i == 0 || i == h-1 || j== 0 || j == w-1) System.out.print(\"@\"); else System.out.print(\" \"); } } } // Driver code public static void main(String args[]) { int h = 4, w = 5; printRectangle(h, w) ; }} /*This code is contributed by Nikita Tiwari.*/", "e": 27527, "s": 26759, "text": null }, { "code": "# Python 3 program to print a rectangular# pattern def printRectangle(h, w) : for i in range(0, h) : print (\"\") for j in range(0, w) : # Print @ if this is first row # or last row. Or this column # is first or last. if (i == 0 or i == h-1 or j== 0 or j == w-1) : print(\"@\",end=\"\") else : print(\" \",end=\"\") # Driver codeh = 4w = 5printRectangle(h, w) # This code is contributed by Nikita Tiwari.", "e": 28039, "s": 27527, "text": null }, { "code": "// C# program to print a rectangular // patternusing System;class GFG { static void printRectangle(int h, int w) { for (int i = 0; i < h; i++) { Console.WriteLine(); for (int j = 0; j < w; j++) { // Print @ if this is first // row or last row. Or this // column is first or last. if (i == 0 || i == h-1 || j== 0 || j == w-1) Console.Write(\"@\"); else Console.Write(\" \"); } } } // Driver code public static void Main() { int h = 4, w = 5; printRectangle(h, w) ; }} /*This code is contributed by vt_m.*/", "e": 28779, "s": 28039, "text": null }, { "code": "<?php// php program to print // a rectangular pattern function printRectangle($h , $w){ for ($i = 0; $i < $h; $i++) { echo\"\\n\"; for ($j = 0; $j < $w; $j++) { // Print @ if this is first row // or last row. Or this column // is first or last. if ($i == 0 || $i == $h - 1 || $j == 0 || $j == $w - 1) echo\"@\"; else echo\" \"; } }} // Driver code $h = 4; $w = 5; printRectangle($h, $w); // This code is contributed by mits ?>", "e": 29360, "s": 28779, "text": null }, { "code": null, "e": 29389, "s": 29360, "text": " \n@@@@@\n@ @\n@ @\n@@@@@\n" }, { "code": null, "e": 29718, "s": 29389, "text": "The time complexity is O(n2).This article is contributed by Anurag Rawat. 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": 29843, "s": 29718, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29856, "s": 29843, "text": "Mithun Kumar" }, { "code": null, "e": 29873, "s": 29856, "text": "pattern-printing" }, { "code": null, "e": 29890, "s": 29873, "text": "square-rectangle" }, { "code": null, "e": 29909, "s": 29890, "text": "School Programming" }, { "code": null, "e": 29926, "s": 29909, "text": "pattern-printing" }, { "code": null, "e": 30024, "s": 29926, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30048, "s": 30024, "text": "C++ Classes and Objects" }, { "code": null, "e": 30067, "s": 30048, "text": "Interfaces in Java" }, { "code": null, "e": 30087, "s": 30067, "text": "Constructors in C++" }, { "code": null, "e": 30115, "s": 30087, "text": "Operator Overloading in C++" }, { "code": null, "e": 30139, "s": 30115, "text": "Copy Constructor in C++" }, { "code": null, "e": 30159, "s": 30139, "text": "Polymorphism in C++" }, { "code": null, "e": 30174, "s": 30159, "text": "C++ Data Types" }, { "code": null, "e": 30207, "s": 30174, "text": "Friend class and function in C++" }, { "code": null, "e": 30230, "s": 30207, "text": "Introduction To PYTHON" } ]
Troubleshooting Questions on OS and Networking asked in Cloud based Interview - GeeksforGeeks
15 Feb, 2021 This article has a Top 5 Troubleshooting questions on Operating System and Networking that will help you clear any Cloud-based Interview like AMAZON CLOUD SUPPORT ASSOCIATE AND AMAZON DevOps. Firstly, what is troubleshooting? Troubleshooting is basically an art, the art of taking a problem into consideration gathering pieces of information about the problem, and understanding it. Finally, analyzing it using the information and most importantly solving it. Now, let’s start with some questions... Troubleshoot System running Slow. The first step to this problem is understanding the reason behind this problem. Possible reasons for this problem could beProcessor related issueDisk related issueNetworking related issueHardware related issue.Checking processor: Checking the memory stat and virtual memory stat gives an idea about which process is taking how much memory.Commands can be used: 1. top 2. free 3. lscpuChecking Disk: Sometimes the disk is full which leads to a system slow and delay in the processing of other processes. Checking disk stat will give the idea about what’s coming in and what’s going out.Commands can be used: 1. df-u 2. du 3. iostat 4. lsofChecking Network: Checking the network will you an idea about which port is listening to what and display the packets that are been transmitted and received.Commands can be used: 1. tcpdump 2. iftop 3. netstat 4. tracerouteChecking Hardware and other things: Checking the hardware for any kind of physical damage and also checking system uptime will give you an idea about how long the system hasn’t shut down which.Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptimeTroubleshoot Wi-Fi connectivity is slow.Check the speed of the internet. Before jumping to any conclusion, check the speed of the internet and match it with your internet pack.Reboot your Modem and Router. Sometimes, the router gets stuck in a bad state. The problem can be fixed with a reboot.Improve your Wi-Fi Position. It is highly recommended to place your router at a higher place because in some instances thicker walls or some metals may obstruct the signal.Using QoS to fix slow internet. Dividing available bandwidth on your Wi-Fi network between applications.Try changing DNS (Domain Name Server). DNS servers are provided by your ISP. But if they are slow and overloaded, switch DNS (Available DNS options: Google Public DNS & Open DNS)Troubleshoot Device is overheating. There can be two-dimension to this problem. External factors and internal factors.External Factors:Check and clean the fans.Elevate the device for proper ventilation.Keep the device away from heat.Internal Factors:Avoid using an intense process. Prioritize your process. Command can be used: 1. niceCheck for any kind of hardware-related issues. Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptime)Troubleshoot Running out of memoryIdentify the process causing the memory usage. Command can be used: 1. topKill or restart the process causing high memory utilization. Command can be used: 1. kill 2.systemctlC. Prioritize the process. Command can be used: 1. nice 2. reniceAdd Swap Space and extend Swap Space.Add memory physically and virtually.Troubleshoot Unable to connect to the internetLook for any physical connection cable-related issues.Check for Router light/ Restart your router.Check whether you are using the correct SSID (router name)Run Windows network troubleshooting if using Windows.Reset TCP/IPCommand can be used: netsh init ip resetFlush DNSCommand can be used: ipconfig/flushdnsRelease/ Reset IP.Command can be used: ipconfig/release ipconfig/renewReinstall network drivers. Troubleshoot System running Slow. The first step to this problem is understanding the reason behind this problem. Possible reasons for this problem could beProcessor related issueDisk related issueNetworking related issueHardware related issue.Checking processor: Checking the memory stat and virtual memory stat gives an idea about which process is taking how much memory.Commands can be used: 1. top 2. free 3. lscpuChecking Disk: Sometimes the disk is full which leads to a system slow and delay in the processing of other processes. Checking disk stat will give the idea about what’s coming in and what’s going out.Commands can be used: 1. df-u 2. du 3. iostat 4. lsofChecking Network: Checking the network will you an idea about which port is listening to what and display the packets that are been transmitted and received.Commands can be used: 1. tcpdump 2. iftop 3. netstat 4. tracerouteChecking Hardware and other things: Checking the hardware for any kind of physical damage and also checking system uptime will give you an idea about how long the system hasn’t shut down which.Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptime Troubleshoot System running Slow. The first step to this problem is understanding the reason behind this problem. Possible reasons for this problem could be Processor related issueDisk related issueNetworking related issueHardware related issue. Processor related issue Disk related issue Networking related issue Hardware related issue. Checking processor: Checking the memory stat and virtual memory stat gives an idea about which process is taking how much memory.Commands can be used: 1. top 2. free 3. lscpu Checking processor: Checking the memory stat and virtual memory stat gives an idea about which process is taking how much memory. Commands can be used: 1. top 2. free 3. lscpu Checking Disk: Sometimes the disk is full which leads to a system slow and delay in the processing of other processes. Checking disk stat will give the idea about what’s coming in and what’s going out.Commands can be used: 1. df-u 2. du 3. iostat 4. lsof Checking Disk: Sometimes the disk is full which leads to a system slow and delay in the processing of other processes. Checking disk stat will give the idea about what’s coming in and what’s going out. Commands can be used: 1. df-u 2. du 3. iostat 4. lsof Checking Network: Checking the network will you an idea about which port is listening to what and display the packets that are been transmitted and received.Commands can be used: 1. tcpdump 2. iftop 3. netstat 4. traceroute Checking Network: Checking the network will you an idea about which port is listening to what and display the packets that are been transmitted and received. Commands can be used: 1. tcpdump 2. iftop 3. netstat 4. traceroute Checking Hardware and other things: Checking the hardware for any kind of physical damage and also checking system uptime will give you an idea about how long the system hasn’t shut down which.Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptime Checking Hardware and other things: Checking the hardware for any kind of physical damage and also checking system uptime will give you an idea about how long the system hasn’t shut down which. Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptime Troubleshoot Wi-Fi connectivity is slow.Check the speed of the internet. Before jumping to any conclusion, check the speed of the internet and match it with your internet pack.Reboot your Modem and Router. Sometimes, the router gets stuck in a bad state. The problem can be fixed with a reboot.Improve your Wi-Fi Position. It is highly recommended to place your router at a higher place because in some instances thicker walls or some metals may obstruct the signal.Using QoS to fix slow internet. Dividing available bandwidth on your Wi-Fi network between applications.Try changing DNS (Domain Name Server). DNS servers are provided by your ISP. But if they are slow and overloaded, switch DNS (Available DNS options: Google Public DNS & Open DNS) Troubleshoot Wi-Fi connectivity is slow. Check the speed of the internet. Before jumping to any conclusion, check the speed of the internet and match it with your internet pack.Reboot your Modem and Router. Sometimes, the router gets stuck in a bad state. The problem can be fixed with a reboot.Improve your Wi-Fi Position. It is highly recommended to place your router at a higher place because in some instances thicker walls or some metals may obstruct the signal.Using QoS to fix slow internet. Dividing available bandwidth on your Wi-Fi network between applications.Try changing DNS (Domain Name Server). DNS servers are provided by your ISP. But if they are slow and overloaded, switch DNS (Available DNS options: Google Public DNS & Open DNS) Check the speed of the internet. Before jumping to any conclusion, check the speed of the internet and match it with your internet pack. Reboot your Modem and Router. Sometimes, the router gets stuck in a bad state. The problem can be fixed with a reboot. Improve your Wi-Fi Position. It is highly recommended to place your router at a higher place because in some instances thicker walls or some metals may obstruct the signal. Using QoS to fix slow internet. Dividing available bandwidth on your Wi-Fi network between applications. Try changing DNS (Domain Name Server). DNS servers are provided by your ISP. But if they are slow and overloaded, switch DNS (Available DNS options: Google Public DNS & Open DNS) Troubleshoot Device is overheating. There can be two-dimension to this problem. External factors and internal factors.External Factors:Check and clean the fans.Elevate the device for proper ventilation.Keep the device away from heat.Internal Factors:Avoid using an intense process. Prioritize your process. Command can be used: 1. niceCheck for any kind of hardware-related issues. Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptime) Troubleshoot Device is overheating. There can be two-dimension to this problem. External factors and internal factors. External Factors:Check and clean the fans.Elevate the device for proper ventilation.Keep the device away from heat. External Factors: Check and clean the fans. Elevate the device for proper ventilation. Keep the device away from heat. Internal Factors:Avoid using an intense process. Prioritize your process. Command can be used: 1. niceCheck for any kind of hardware-related issues. Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptime) Internal Factors: Avoid using an intense process. Prioritize your process. Command can be used: 1. nice Avoid using an intense process. Prioritize your process. Command can be used: 1. nice Check for any kind of hardware-related issues. Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptime) Check for any kind of hardware-related issues. Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptime) Troubleshoot Running out of memoryIdentify the process causing the memory usage. Command can be used: 1. topKill or restart the process causing high memory utilization. Command can be used: 1. kill 2.systemctlC. Prioritize the process. Command can be used: 1. nice 2. reniceAdd Swap Space and extend Swap Space.Add memory physically and virtually.Troubleshoot Unable to connect to the internetLook for any physical connection cable-related issues.Check for Router light/ Restart your router.Check whether you are using the correct SSID (router name)Run Windows network troubleshooting if using Windows.Reset TCP/IPCommand can be used: netsh init ip resetFlush DNSCommand can be used: ipconfig/flushdnsRelease/ Reset IP.Command can be used: ipconfig/release ipconfig/renewReinstall network drivers. Troubleshoot Running out of memory Identify the process causing the memory usage. Command can be used: 1. top Identify the process causing the memory usage. Command can be used: 1. top Kill or restart the process causing high memory utilization. Command can be used: 1. kill 2.systemctl Kill or restart the process causing high memory utilization. Command can be used: 1. kill 2.systemctl C. Prioritize the process. Command can be used: 1. nice 2. renice C. Prioritize the process. Command can be used: 1. nice 2. renice Add Swap Space and extend Swap Space. Add Swap Space and extend Swap Space. Add memory physically and virtually. Add memory physically and virtually. Troubleshoot Unable to connect to the internet Troubleshoot Unable to connect to the internet Look for any physical connection cable-related issues. Look for any physical connection cable-related issues. Check for Router light/ Restart your router. Check for Router light/ Restart your router. Check whether you are using the correct SSID (router name) Check whether you are using the correct SSID (router name) Run Windows network troubleshooting if using Windows. Run Windows network troubleshooting if using Windows. Reset TCP/IPCommand can be used: netsh init ip reset Reset TCP/IP Command can be used: netsh init ip reset Flush DNSCommand can be used: ipconfig/flushdns Flush DNS Command can be used: ipconfig/flushdns Release/ Reset IP.Command can be used: ipconfig/release ipconfig/renew Release/ Reset IP. Command can be used: ipconfig/release ipconfig/renew Reinstall network drivers. Reinstall network drivers. Thank You! Computer Networks Interview Experiences Operating Systems Operating Systems Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. RSA Algorithm in Cryptography Differences between TCP and UDP TCP Server-Client implementation in C Data encryption standard (DES) | Set 1 Differences between IPv4 and IPv6 Amazon Interview Questions Commonly Asked Java Programming Interview Questions | Set 2 Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Difference between ANN, CNN and RNN
[ { "code": null, "e": 26580, "s": 26552, "text": "\n15 Feb, 2021" }, { "code": null, "e": 26772, "s": 26580, "text": "This article has a Top 5 Troubleshooting questions on Operating System and Networking that will help you clear any Cloud-based Interview like AMAZON CLOUD SUPPORT ASSOCIATE AND AMAZON DevOps." }, { "code": null, "e": 26806, "s": 26772, "text": "Firstly, what is troubleshooting?" }, { "code": null, "e": 27040, "s": 26806, "text": "Troubleshooting is basically an art, the art of taking a problem into consideration gathering pieces of information about the problem, and understanding it. Finally, analyzing it using the information and most importantly solving it." }, { "code": null, "e": 27080, "s": 27040, "text": "Now, let’s start with some questions..." }, { "code": null, "e": 30231, "s": 27080, "text": "Troubleshoot System running Slow. The first step to this problem is understanding the reason behind this problem. Possible reasons for this problem could beProcessor related issueDisk related issueNetworking related issueHardware related issue.Checking processor: Checking the memory stat and virtual memory stat gives an idea about which process is taking how much memory.Commands can be used: 1. top 2. free 3. lscpuChecking Disk: Sometimes the disk is full which leads to a system slow and delay in the processing of other processes. Checking disk stat will give the idea about what’s coming in and what’s going out.Commands can be used: 1. df-u 2. du 3. iostat 4. lsofChecking Network: Checking the network will you an idea about which port is listening to what and display the packets that are been transmitted and received.Commands can be used: 1. tcpdump 2. iftop 3. netstat 4. tracerouteChecking Hardware and other things: Checking the hardware for any kind of physical damage and also checking system uptime will give you an idea about how long the system hasn’t shut down which.Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptimeTroubleshoot Wi-Fi connectivity is slow.Check the speed of the internet. Before jumping to any conclusion, check the speed of the internet and match it with your internet pack.Reboot your Modem and Router. Sometimes, the router gets stuck in a bad state. The problem can be fixed with a reboot.Improve your Wi-Fi Position. It is highly recommended to place your router at a higher place because in some instances thicker walls or some metals may obstruct the signal.Using QoS to fix slow internet. Dividing available bandwidth on your Wi-Fi network between applications.Try changing DNS (Domain Name Server). DNS servers are provided by your ISP. But if they are slow and overloaded, switch DNS (Available DNS options: Google Public DNS & Open DNS)Troubleshoot Device is overheating. There can be two-dimension to this problem. External factors and internal factors.External Factors:Check and clean the fans.Elevate the device for proper ventilation.Keep the device away from heat.Internal Factors:Avoid using an intense process. Prioritize your process. Command can be used: 1. niceCheck for any kind of hardware-related issues. Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptime)Troubleshoot Running out of memoryIdentify the process causing the memory usage. Command can be used: 1. topKill or restart the process causing high memory utilization. Command can be used: 1. kill 2.systemctlC. Prioritize the process. Command can be used: 1. nice 2. reniceAdd Swap Space and extend Swap Space.Add memory physically and virtually.Troubleshoot Unable to connect to the internetLook for any physical connection cable-related issues.Check for Router light/ Restart your router.Check whether you are using the correct SSID (router name)Run Windows network troubleshooting if using Windows.Reset TCP/IPCommand can be used: netsh init ip resetFlush DNSCommand can be used: ipconfig/flushdnsRelease/ Reset IP.Command can be used: ipconfig/release ipconfig/renewReinstall network drivers." }, { "code": null, "e": 31389, "s": 30231, "text": "Troubleshoot System running Slow. The first step to this problem is understanding the reason behind this problem. Possible reasons for this problem could beProcessor related issueDisk related issueNetworking related issueHardware related issue.Checking processor: Checking the memory stat and virtual memory stat gives an idea about which process is taking how much memory.Commands can be used: 1. top 2. free 3. lscpuChecking Disk: Sometimes the disk is full which leads to a system slow and delay in the processing of other processes. Checking disk stat will give the idea about what’s coming in and what’s going out.Commands can be used: 1. df-u 2. du 3. iostat 4. lsofChecking Network: Checking the network will you an idea about which port is listening to what and display the packets that are been transmitted and received.Commands can be used: 1. tcpdump 2. iftop 3. netstat 4. tracerouteChecking Hardware and other things: Checking the hardware for any kind of physical damage and also checking system uptime will give you an idea about how long the system hasn’t shut down which.Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptime" }, { "code": null, "e": 31546, "s": 31389, "text": "Troubleshoot System running Slow. The first step to this problem is understanding the reason behind this problem. Possible reasons for this problem could be" }, { "code": null, "e": 31635, "s": 31546, "text": "Processor related issueDisk related issueNetworking related issueHardware related issue." }, { "code": null, "e": 31659, "s": 31635, "text": "Processor related issue" }, { "code": null, "e": 31678, "s": 31659, "text": "Disk related issue" }, { "code": null, "e": 31703, "s": 31678, "text": "Networking related issue" }, { "code": null, "e": 31727, "s": 31703, "text": "Hardware related issue." }, { "code": null, "e": 31904, "s": 31727, "text": "Checking processor: Checking the memory stat and virtual memory stat gives an idea about which process is taking how much memory.Commands can be used: 1. top 2. free 3. lscpu" }, { "code": null, "e": 32034, "s": 31904, "text": "Checking processor: Checking the memory stat and virtual memory stat gives an idea about which process is taking how much memory." }, { "code": null, "e": 32057, "s": 32034, "text": "Commands can be used: " }, { "code": null, "e": 32083, "s": 32057, "text": "1. top 2. free 3. lscpu" }, { "code": null, "e": 32341, "s": 32083, "text": "Checking Disk: Sometimes the disk is full which leads to a system slow and delay in the processing of other processes. Checking disk stat will give the idea about what’s coming in and what’s going out.Commands can be used: 1. df-u 2. du 3. iostat 4. lsof" }, { "code": null, "e": 32543, "s": 32341, "text": "Checking Disk: Sometimes the disk is full which leads to a system slow and delay in the processing of other processes. Checking disk stat will give the idea about what’s coming in and what’s going out." }, { "code": null, "e": 32566, "s": 32543, "text": "Commands can be used: " }, { "code": null, "e": 32601, "s": 32566, "text": "1. df-u 2. du 3. iostat 4. lsof" }, { "code": null, "e": 32828, "s": 32601, "text": "Checking Network: Checking the network will you an idea about which port is listening to what and display the packets that are been transmitted and received.Commands can be used: 1. tcpdump 2. iftop 3. netstat 4. traceroute" }, { "code": null, "e": 32986, "s": 32828, "text": "Checking Network: Checking the network will you an idea about which port is listening to what and display the packets that are been transmitted and received." }, { "code": null, "e": 33009, "s": 32986, "text": "Commands can be used: " }, { "code": null, "e": 33057, "s": 33009, "text": "1. tcpdump 2. iftop 3. netstat 4. traceroute" }, { "code": null, "e": 33312, "s": 33057, "text": "Checking Hardware and other things: Checking the hardware for any kind of physical damage and also checking system uptime will give you an idea about how long the system hasn’t shut down which.Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptime" }, { "code": null, "e": 33506, "s": 33312, "text": "Checking Hardware and other things: Checking the hardware for any kind of physical damage and also checking system uptime will give you an idea about how long the system hasn’t shut down which." }, { "code": null, "e": 33529, "s": 33506, "text": "Commands can be used: " }, { "code": null, "e": 33569, "s": 33529, "text": "1. iscpu 2. isblk 3. ispci 4. uptime" }, { "code": null, "e": 34318, "s": 33569, "text": "Troubleshoot Wi-Fi connectivity is slow.Check the speed of the internet. Before jumping to any conclusion, check the speed of the internet and match it with your internet pack.Reboot your Modem and Router. Sometimes, the router gets stuck in a bad state. The problem can be fixed with a reboot.Improve your Wi-Fi Position. It is highly recommended to place your router at a higher place because in some instances thicker walls or some metals may obstruct the signal.Using QoS to fix slow internet. Dividing available bandwidth on your Wi-Fi network between applications.Try changing DNS (Domain Name Server). DNS servers are provided by your ISP. But if they are slow and overloaded, switch DNS (Available DNS options: Google Public DNS & Open DNS)" }, { "code": null, "e": 34359, "s": 34318, "text": "Troubleshoot Wi-Fi connectivity is slow." }, { "code": null, "e": 35068, "s": 34359, "text": "Check the speed of the internet. Before jumping to any conclusion, check the speed of the internet and match it with your internet pack.Reboot your Modem and Router. Sometimes, the router gets stuck in a bad state. The problem can be fixed with a reboot.Improve your Wi-Fi Position. It is highly recommended to place your router at a higher place because in some instances thicker walls or some metals may obstruct the signal.Using QoS to fix slow internet. Dividing available bandwidth on your Wi-Fi network between applications.Try changing DNS (Domain Name Server). DNS servers are provided by your ISP. But if they are slow and overloaded, switch DNS (Available DNS options: Google Public DNS & Open DNS)" }, { "code": null, "e": 35205, "s": 35068, "text": "Check the speed of the internet. Before jumping to any conclusion, check the speed of the internet and match it with your internet pack." }, { "code": null, "e": 35324, "s": 35205, "text": "Reboot your Modem and Router. Sometimes, the router gets stuck in a bad state. The problem can be fixed with a reboot." }, { "code": null, "e": 35497, "s": 35324, "text": "Improve your Wi-Fi Position. It is highly recommended to place your router at a higher place because in some instances thicker walls or some metals may obstruct the signal." }, { "code": null, "e": 35602, "s": 35497, "text": "Using QoS to fix slow internet. Dividing available bandwidth on your Wi-Fi network between applications." }, { "code": null, "e": 35781, "s": 35602, "text": "Try changing DNS (Domain Name Server). DNS servers are provided by your ISP. But if they are slow and overloaded, switch DNS (Available DNS options: Google Public DNS & Open DNS)" }, { "code": null, "e": 36227, "s": 35781, "text": "Troubleshoot Device is overheating. There can be two-dimension to this problem. External factors and internal factors.External Factors:Check and clean the fans.Elevate the device for proper ventilation.Keep the device away from heat.Internal Factors:Avoid using an intense process. Prioritize your process. Command can be used: 1. niceCheck for any kind of hardware-related issues. Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptime)" }, { "code": null, "e": 36346, "s": 36227, "text": "Troubleshoot Device is overheating. There can be two-dimension to this problem. External factors and internal factors." }, { "code": null, "e": 36462, "s": 36346, "text": "External Factors:Check and clean the fans.Elevate the device for proper ventilation.Keep the device away from heat." }, { "code": null, "e": 36480, "s": 36462, "text": "External Factors:" }, { "code": null, "e": 36506, "s": 36480, "text": "Check and clean the fans." }, { "code": null, "e": 36549, "s": 36506, "text": "Elevate the device for proper ventilation." }, { "code": null, "e": 36581, "s": 36549, "text": "Keep the device away from heat." }, { "code": null, "e": 36794, "s": 36581, "text": "Internal Factors:Avoid using an intense process. Prioritize your process. Command can be used: 1. niceCheck for any kind of hardware-related issues. Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptime)" }, { "code": null, "e": 36812, "s": 36794, "text": "Internal Factors:" }, { "code": null, "e": 36899, "s": 36812, "text": "Avoid using an intense process. Prioritize your process. Command can be used: 1. nice" }, { "code": null, "e": 36958, "s": 36899, "text": "Avoid using an intense process. Prioritize your process. " }, { "code": null, "e": 36980, "s": 36958, "text": "Command can be used: " }, { "code": null, "e": 36988, "s": 36980, "text": "1. nice" }, { "code": null, "e": 37098, "s": 36988, "text": "Check for any kind of hardware-related issues. Commands can be used: 1. iscpu 2. isblk 3. ispci 4. uptime)" }, { "code": null, "e": 37146, "s": 37098, "text": "Check for any kind of hardware-related issues. " }, { "code": null, "e": 37169, "s": 37146, "text": "Commands can be used: " }, { "code": null, "e": 37210, "s": 37169, "text": "1. iscpu 2. isblk 3. ispci 4. uptime)" }, { "code": null, "e": 38011, "s": 37210, "text": "Troubleshoot Running out of memoryIdentify the process causing the memory usage. Command can be used: 1. topKill or restart the process causing high memory utilization. Command can be used: 1. kill 2.systemctlC. Prioritize the process. Command can be used: 1. nice 2. reniceAdd Swap Space and extend Swap Space.Add memory physically and virtually.Troubleshoot Unable to connect to the internetLook for any physical connection cable-related issues.Check for Router light/ Restart your router.Check whether you are using the correct SSID (router name)Run Windows network troubleshooting if using Windows.Reset TCP/IPCommand can be used: netsh init ip resetFlush DNSCommand can be used: ipconfig/flushdnsRelease/ Reset IP.Command can be used: ipconfig/release ipconfig/renewReinstall network drivers." }, { "code": null, "e": 38046, "s": 38011, "text": "Troubleshoot Running out of memory" }, { "code": null, "e": 38121, "s": 38046, "text": "Identify the process causing the memory usage. Command can be used: 1. top" }, { "code": null, "e": 38169, "s": 38121, "text": "Identify the process causing the memory usage. " }, { "code": null, "e": 38191, "s": 38169, "text": "Command can be used: " }, { "code": null, "e": 38198, "s": 38191, "text": "1. top" }, { "code": null, "e": 38302, "s": 38198, "text": "Kill or restart the process causing high memory utilization. Command can be used: 1. kill 2.systemctl" }, { "code": null, "e": 38364, "s": 38302, "text": "Kill or restart the process causing high memory utilization. " }, { "code": null, "e": 38386, "s": 38364, "text": "Command can be used: " }, { "code": null, "e": 38408, "s": 38386, "text": "1. kill 2.systemctl" }, { "code": null, "e": 38475, "s": 38408, "text": "C. Prioritize the process. Command can be used: 1. nice 2. renice" }, { "code": null, "e": 38503, "s": 38475, "text": "C. Prioritize the process. " }, { "code": null, "e": 38525, "s": 38503, "text": "Command can be used: " }, { "code": null, "e": 38544, "s": 38525, "text": "1. nice 2. renice" }, { "code": null, "e": 38582, "s": 38544, "text": "Add Swap Space and extend Swap Space." }, { "code": null, "e": 38620, "s": 38582, "text": "Add Swap Space and extend Swap Space." }, { "code": null, "e": 38657, "s": 38620, "text": "Add memory physically and virtually." }, { "code": null, "e": 38694, "s": 38657, "text": "Add memory physically and virtually." }, { "code": null, "e": 38741, "s": 38694, "text": "Troubleshoot Unable to connect to the internet" }, { "code": null, "e": 38788, "s": 38741, "text": "Troubleshoot Unable to connect to the internet" }, { "code": null, "e": 38843, "s": 38788, "text": "Look for any physical connection cable-related issues." }, { "code": null, "e": 38898, "s": 38843, "text": "Look for any physical connection cable-related issues." }, { "code": null, "e": 38943, "s": 38898, "text": "Check for Router light/ Restart your router." }, { "code": null, "e": 38988, "s": 38943, "text": "Check for Router light/ Restart your router." }, { "code": null, "e": 39047, "s": 38988, "text": "Check whether you are using the correct SSID (router name)" }, { "code": null, "e": 39106, "s": 39047, "text": "Check whether you are using the correct SSID (router name)" }, { "code": null, "e": 39160, "s": 39106, "text": "Run Windows network troubleshooting if using Windows." }, { "code": null, "e": 39214, "s": 39160, "text": "Run Windows network troubleshooting if using Windows." }, { "code": null, "e": 39267, "s": 39214, "text": "Reset TCP/IPCommand can be used: netsh init ip reset" }, { "code": null, "e": 39280, "s": 39267, "text": "Reset TCP/IP" }, { "code": null, "e": 39302, "s": 39280, "text": "Command can be used: " }, { "code": null, "e": 39322, "s": 39302, "text": "netsh init ip reset" }, { "code": null, "e": 39370, "s": 39322, "text": "Flush DNSCommand can be used: ipconfig/flushdns" }, { "code": null, "e": 39380, "s": 39370, "text": "Flush DNS" }, { "code": null, "e": 39402, "s": 39380, "text": "Command can be used: " }, { "code": null, "e": 39420, "s": 39402, "text": "ipconfig/flushdns" }, { "code": null, "e": 39491, "s": 39420, "text": "Release/ Reset IP.Command can be used: ipconfig/release ipconfig/renew" }, { "code": null, "e": 39510, "s": 39491, "text": "Release/ Reset IP." }, { "code": null, "e": 39532, "s": 39510, "text": "Command can be used: " }, { "code": null, "e": 39564, "s": 39532, "text": "ipconfig/release ipconfig/renew" }, { "code": null, "e": 39591, "s": 39564, "text": "Reinstall network drivers." }, { "code": null, "e": 39618, "s": 39591, "text": "Reinstall network drivers." }, { "code": null, "e": 39629, "s": 39618, "text": "Thank You!" }, { "code": null, "e": 39647, "s": 39629, "text": "Computer Networks" }, { "code": null, "e": 39669, "s": 39647, "text": "Interview Experiences" }, { "code": null, "e": 39687, "s": 39669, "text": "Operating Systems" }, { "code": null, "e": 39705, "s": 39687, "text": "Operating Systems" }, { "code": null, "e": 39723, "s": 39705, "text": "Computer Networks" }, { "code": null, "e": 39821, "s": 39723, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39851, "s": 39821, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 39883, "s": 39851, "text": "Differences between TCP and UDP" }, { "code": null, "e": 39921, "s": 39883, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 39960, "s": 39921, "text": "Data encryption standard (DES) | Set 1" }, { "code": null, "e": 39994, "s": 39960, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 40021, "s": 39994, "text": "Amazon Interview Questions" }, { "code": null, "e": 40081, "s": 40021, "text": "Commonly Asked Java Programming Interview Questions | Set 2" }, { "code": null, "e": 40132, "s": 40081, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 40174, "s": 40132, "text": "Amazon AWS Interview Experience for SDE-1" } ]
How to pass variables and data from PHP to JavaScript ? - GeeksforGeeks
01 Aug, 2021 In this article, let’s see how to pass data and variables from PHP to JavaScript. We can pass data from PHP to JavaScript in two ways depending on the situation. First, we can pass the data using the simple assignment operator if we want to perform the operation on the same page. Else we can pass data from PHP to JavaScript using Cookies. Cookie work in client-side. Program 1: This program passes the variables and data from PHP to JavaScript using assignment operator. <!DOCTYPE html><html> <head> <title> How to pass variables and data from PHP to JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:green;">GeeksforGeeks</h1> <h4> How to pass variables and data from PHP to JavaScript? </h4> <?php $name = "Hello World"; ?> <script type="text/javascript"> var x = "<?php echo"$name"?>"; document.write(x); </script></body> <html> Output: Here, we just take input by statically or dynamically and pass it to JavaScript variable using the assignment operator. The PHP code in the JavaScript block will convert it into the resulting output and then pass it to the variable x and then the value of x is printed. Program 2: This program passes the variables and data from PHP to JavaScript using Cookies. <!DOCTYPE html><html> <head> <title> How to pass variables and data from PHP to JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:green;">GeeksforGeeks</h1> <h4> How to pass variables and data from PHP to JavaScript? </h4> <?php // Initialize cookie name $cookie_name = "user"; $cookie_value = "raj"; // Set cookie setcookie($cookie_name, $cookie_value); if(!isset($_COOKIES[$cookie_name])) { print("Cookie created | "); } ?> <script type="text/javascript"> var x = document.cookie; document.write(x); </script></body> <html> Output: PHP provides a method to set the cookie using the setCookie() method. Here, we can set the data or variable in PHP cookie and retrieve it from JavaScript using document.cookie. Steps to Run the program: Install local server like XAMPP server into your system. Save the file in htdocs folder using the name geeks.php Start Apache server. Open Browser and type localhost/geeks.php in address bar and hit Enter button. It will display the result. PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to call PHP function on the click of a Button ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP?
[ { "code": null, "e": 26702, "s": 26674, "text": "\n01 Aug, 2021" }, { "code": null, "e": 26784, "s": 26702, "text": "In this article, let’s see how to pass data and variables from PHP to JavaScript." }, { "code": null, "e": 27071, "s": 26784, "text": "We can pass data from PHP to JavaScript in two ways depending on the situation. First, we can pass the data using the simple assignment operator if we want to perform the operation on the same page. Else we can pass data from PHP to JavaScript using Cookies. Cookie work in client-side." }, { "code": null, "e": 27175, "s": 27071, "text": "Program 1: This program passes the variables and data from PHP to JavaScript using assignment operator." }, { "code": "<!DOCTYPE html><html> <head> <title> How to pass variables and data from PHP to JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h4> How to pass variables and data from PHP to JavaScript? </h4> <?php $name = \"Hello World\"; ?> <script type=\"text/javascript\"> var x = \"<?php echo\"$name\"?>\"; document.write(x); </script></body> <html>", "e": 27664, "s": 27175, "text": null }, { "code": null, "e": 27672, "s": 27664, "text": "Output:" }, { "code": null, "e": 27942, "s": 27672, "text": "Here, we just take input by statically or dynamically and pass it to JavaScript variable using the assignment operator. The PHP code in the JavaScript block will convert it into the resulting output and then pass it to the variable x and then the value of x is printed." }, { "code": null, "e": 28034, "s": 27942, "text": "Program 2: This program passes the variables and data from PHP to JavaScript using Cookies." }, { "code": "<!DOCTYPE html><html> <head> <title> How to pass variables and data from PHP to JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h4> How to pass variables and data from PHP to JavaScript? </h4> <?php // Initialize cookie name $cookie_name = \"user\"; $cookie_value = \"raj\"; // Set cookie setcookie($cookie_name, $cookie_value); if(!isset($_COOKIES[$cookie_name])) { print(\"Cookie created | \"); } ?> <script type=\"text/javascript\"> var x = document.cookie; document.write(x); </script></body> <html>", "e": 28771, "s": 28034, "text": null }, { "code": null, "e": 28779, "s": 28771, "text": "Output:" }, { "code": null, "e": 28956, "s": 28779, "text": "PHP provides a method to set the cookie using the setCookie() method. Here, we can set the data or variable in PHP cookie and retrieve it from JavaScript using document.cookie." }, { "code": null, "e": 28982, "s": 28956, "text": "Steps to Run the program:" }, { "code": null, "e": 29039, "s": 28982, "text": "Install local server like XAMPP server into your system." }, { "code": null, "e": 29095, "s": 29039, "text": "Save the file in htdocs folder using the name geeks.php" }, { "code": null, "e": 29116, "s": 29095, "text": "Start Apache server." }, { "code": null, "e": 29195, "s": 29116, "text": "Open Browser and type localhost/geeks.php in address bar and hit Enter button." }, { "code": null, "e": 29223, "s": 29195, "text": "It will display the result." }, { "code": null, "e": 29392, "s": 29223, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 29399, "s": 29392, "text": "Picked" }, { "code": null, "e": 29403, "s": 29399, "text": "PHP" }, { "code": null, "e": 29416, "s": 29403, "text": "PHP Programs" }, { "code": null, "e": 29433, "s": 29416, "text": "Web Technologies" }, { "code": null, "e": 29460, "s": 29433, "text": "Web technologies Questions" }, { "code": null, "e": 29464, "s": 29460, "text": "PHP" }, { "code": null, "e": 29562, "s": 29464, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29612, "s": 29562, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 29652, "s": 29612, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 29713, "s": 29652, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 29763, "s": 29713, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 29808, "s": 29763, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 29858, "s": 29808, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 29898, "s": 29858, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 29950, "s": 29898, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 30011, "s": 29950, "text": "How to Upload Image into Database and Display it using PHP ?" } ]
Minimize moves to make Array elements equal by incrementing and decrementing pairs - GeeksforGeeks
05 Aug, 2021 Given an array arr[] of size N, the task is to print the minimum number of moves needed to make all array elements equal by selecting any two distinct indices and then increment the element at the first selected index and decrement the element at the other selected index by 1 in each move. If it is impossible to make all the array elements equal then print “-1“. Examples: Input: arr[] = {5, 4, 1, 10}Output: 5Explanation: One of the possible way to perform operation is:Operation 1: Select the indices 1 and 3 and then increment arr[1] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 1, 9}.Operation 2: Select the indices 2 and 3 and then increment arr[2] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 2, 8}.Operation 3: Select the indices 2 and 3 and then increment arr[2] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 3, 7}.Operation 4: Select the indices 2 and 3 and then increment arr[2] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 4, 6}.Operation 5: Select the indices 2 and 3 and then increment arr[2] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 5, 5}.Therefore, the total number of move needed is 5. Also, it is the minimum possible moves needed. Input: arr[] = {1, 4}Output: -1 Approach: The given problem can be solved based on the following observations: It can be observed that in one move the sum of the array remains the same therefore, if the sum of the array is not divisible N then it is impossible to make all the array elements equal. Otherwise, each array element will be equal to the sum of the array divided by N. Therefore, the idea is to use the two pointer technique to find the minimum count of moves needed to make all the array elements equal to the sum/N. Follow the steps below to solve the problem: Initialize a variable, say ans as 0, to store the count of the moves needed. Find the sum of the array and store it in a variable say sum. Now if the sum is not divisible by N then print “-1“. Otherwise, update the sum as sum =sum/N. Sort the array in ascending order. Initialize variables, say i as 0 and j as N – 1 to iterate over the array. Iterate until i is less than j and perform the following steps:If increasing arr[i] to sum is less than decreasing arr[j] to sum then add sum – arr[i] to the ans, and then update arr[i], and arr[j] and then increment i by 1.Otherwise, add arr[j] – sum to the ans, and update arr[i] and arr[j] and then decrement j by 1. If increasing arr[i] to sum is less than decreasing arr[j] to sum then add sum – arr[i] to the ans, and then update arr[i], and arr[j] and then increment i by 1. Otherwise, add arr[j] – sum to the ans, and update arr[i] and arr[j] and then decrement j by 1. Finally, after completing the above steps, print the value of stored in ans. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program for the above approach#include <algorithm>#include <iostream>using namespace std; // Function to find the minimum// operations to make the array// elements equalint find(int arr[], int N){ // Stores the sum of the // array int Sum = 0; for (int i = 0; i < N; i++) { Sum += arr[i]; } if (Sum % N) { return -1; } // update sum Sum /= N; // sort array sort(arr, arr + N); // Store the minimum // needed moves int ans = 0; int i = 0, j = N - 1; // Iterate until i // is less than j while (i < j) { if (Sum - arr[i] < arr[j] - Sum) { // Increment ans by // Sum-arr[i] ans += (Sum - arr[i]); // update arr[i] += (Sum - arr[i]); arr[j] -= (Sum - arr[i]); // Increment i by 1 i++; } else { // Increment ans by //arr[j]-Sum ans += (arr[j] - Sum); // Update arr[i] += (arr[j] - Sum); arr[j] -= (arr[j] - Sum); // Decrement j by 1 j--; } } // Return the value in ans return ans;} // Driver codeint main(){ // Given input int arr[] = { 5, 4, 1, 10 }; int N = sizeof(arr) / sizeof(int); // Function call cout << find(arr, N); return 0;} // This code is contributed by Parth Manchanda import java.util.Arrays; // Java Program for the above approach class GFG { // Function to find the minimum // operations to make the array // elements equal public static int find(int arr[], int N) { // Stores the sum of the // array int Sum = 0; for (int i = 0; i < N; i++) { Sum += arr[i]; } if (Sum % N > 0) { return -1; } // update sum Sum /= N; // sort array Arrays.sort(arr); // Store the minimum // needed moves int ans = 0; int i = 0, j = N - 1; // Iterate until i // is less than j while (i < j) { if (Sum - arr[i] < arr[j] - Sum) { // Increment ans by // Sum-arr[i] ans += (Sum - arr[i]); // update arr[i] += (Sum - arr[i]); arr[j] -= (Sum - arr[i]); // Increment i by 1 i++; } else { // Increment ans by // arr[j]-Sum ans += (arr[j] - Sum); // Update arr[i] += (arr[j] - Sum); arr[j] -= (arr[j] - Sum); // Decrement j by 1 j--; } } // Return the value in ans return ans; } // Driver code public static void main(String args[]) { // Given input int arr[] = { 5, 4, 1, 10 }; int N = arr.length; // Function call System.out.println(find(arr, N)); }} // This code is contributed by gfgking # Python program for the above approach # Function to find the minimum# operations to make the array# elements equaldef find(arr, N): # Stores the sum of the # array Sum = sum(arr) # If sum is not divisible # by N if Sum % N: return -1 else: # Update sum Sum //= N # Sort the array arr.sort() # Store the minimum # needed moves ans = 0 i = 0 j = N-1 # Iterate until i # is less than j while i < j: # If the Sum-arr[i] # is less than the # arr[j]-sum if Sum-arr[i] < arr[j]-Sum: # Increment ans by # Sum-arr[i] ans += Sum-arr[i] # Update arr[i] += Sum-arr[i] arr[j] -= Sum-arr[i] # Increment i by 1 i += 1 # Otherwise, else: # Increment ans by # arr[j]-Sum ans += arr[j]-Sum # Update arr[i] += arr[j]-Sum arr[j] -= arr[j]-Sum # Decrement j by 1 j -= 1 # Return the value in ans return ans # Driver Codeif __name__ == '__main__': # Given Input arr = [5, 4, 1, 10] N = len(arr) # Function Call print(find(arr, N)) // C# program for the above approachusing System; class GFG{ // Function to find the minimum// operations to make the array// elements equalpublic static int find(int[] arr, int N){ // Stores the sum of the // array int Sum = 0; int i = 0; for(i = 0; i < N; i++) { Sum += arr[i]; } if (Sum % N > 0) { return -1; } // update sum Sum /= N; // sort array Array.Sort(arr); // Store the minimum // needed moves int ans = 0; i = 0; int j = N - 1; // Iterate until i // is less than j while (i < j) { if (Sum - arr[i] < arr[j] - Sum) { // Increment ans by // Sum-arr[i] ans += (Sum - arr[i]); // update arr[i] += (Sum - arr[i]); arr[j] -= (Sum - arr[i]); // Increment i by 1 i++; } else { // Increment ans by // arr[j]-Sum ans += (arr[j] - Sum); // Update arr[i] += (arr[j] - Sum); arr[j] -= (arr[j] - Sum); // Decrement j by 1 j--; } } // Return the value in ans return ans;} // Driver codestatic public void Main(){ // Given input int[] arr = { 5, 4, 1, 10 }; int N = arr.Length; // Function call Console.WriteLine(find(arr, N));}} // This code is contributed by target_2 <script> // JavaScript Program for the above approach // Function to find the minimum // operations to make the array // elements equal function find(arr, N) { // Stores the sum of the // array let Sum = 0; for (i = 0; i < arr.length; i++) { Sum = Sum + arr[i]; } // If sum is not divisible // by N if (Sum % N) return -1; else { // Update sum Sum = Math.floor(Sum / N); // Sort the array arr.sort(function (a, b) { return a - b }); // Store the minimum // needed moves ans = 0 i = 0 j = N - 1 // Iterate until i // is less than j while (i < j) { // If the Sum-arr[i] // is less than the // arr[j]-sum if (Sum - arr[i] < arr[j] - Sum) { // Increment ans by // Sum-arr[i] ans += Sum - arr[i] // Update arr[i] += Sum - arr[i] arr[j] -= Sum - arr[i] // Increment i by 1 i += 1 } // Otherwise, else { // Increment ans by // arr[j]-Sum ans += arr[j] - Sum // Update arr[i] += arr[j] - Sum arr[j] -= arr[j] - Sum // Decrement j by 1 j -= 1 } } } // Return the value in ans return ans; } // Driver Code // Given Input let arr = [5, 4, 1, 10]; let N = arr.length; // Function Call document.write(find(arr, N)); // This code is contributed by Potta Lokesh </script> 5 Time Complexity: O(N*log(N))Auxiliary Space: O(1) lokeshpotta20 parthmanchanda81 gfgking target_2 surinderdawra388 Arrays Greedy Sorting Arrays Greedy Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Reversal algorithm for array rotation Window Sliding Technique Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string
[ { "code": null, "e": 26177, "s": 26149, "text": "\n05 Aug, 2021" }, { "code": null, "e": 26542, "s": 26177, "text": "Given an array arr[] of size N, the task is to print the minimum number of moves needed to make all array elements equal by selecting any two distinct indices and then increment the element at the first selected index and decrement the element at the other selected index by 1 in each move. If it is impossible to make all the array elements equal then print “-1“." }, { "code": null, "e": 26553, "s": 26542, "text": "Examples: " }, { "code": null, "e": 27472, "s": 26553, "text": "Input: arr[] = {5, 4, 1, 10}Output: 5Explanation: One of the possible way to perform operation is:Operation 1: Select the indices 1 and 3 and then increment arr[1] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 1, 9}.Operation 2: Select the indices 2 and 3 and then increment arr[2] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 2, 8}.Operation 3: Select the indices 2 and 3 and then increment arr[2] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 3, 7}.Operation 4: Select the indices 2 and 3 and then increment arr[2] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 4, 6}.Operation 5: Select the indices 2 and 3 and then increment arr[2] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 5, 5}.Therefore, the total number of move needed is 5. Also, it is the minimum possible moves needed." }, { "code": null, "e": 27504, "s": 27472, "text": "Input: arr[] = {1, 4}Output: -1" }, { "code": null, "e": 27584, "s": 27504, "text": "Approach: The given problem can be solved based on the following observations: " }, { "code": null, "e": 27772, "s": 27584, "text": "It can be observed that in one move the sum of the array remains the same therefore, if the sum of the array is not divisible N then it is impossible to make all the array elements equal." }, { "code": null, "e": 27854, "s": 27772, "text": "Otherwise, each array element will be equal to the sum of the array divided by N." }, { "code": null, "e": 28003, "s": 27854, "text": "Therefore, the idea is to use the two pointer technique to find the minimum count of moves needed to make all the array elements equal to the sum/N." }, { "code": null, "e": 28048, "s": 28003, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 28125, "s": 28048, "text": "Initialize a variable, say ans as 0, to store the count of the moves needed." }, { "code": null, "e": 28187, "s": 28125, "text": "Find the sum of the array and store it in a variable say sum." }, { "code": null, "e": 28282, "s": 28187, "text": "Now if the sum is not divisible by N then print “-1“. Otherwise, update the sum as sum =sum/N." }, { "code": null, "e": 28317, "s": 28282, "text": "Sort the array in ascending order." }, { "code": null, "e": 28392, "s": 28317, "text": "Initialize variables, say i as 0 and j as N – 1 to iterate over the array." }, { "code": null, "e": 28713, "s": 28392, "text": "Iterate until i is less than j and perform the following steps:If increasing arr[i] to sum is less than decreasing arr[j] to sum then add sum – arr[i] to the ans, and then update arr[i], and arr[j] and then increment i by 1.Otherwise, add arr[j] – sum to the ans, and update arr[i] and arr[j] and then decrement j by 1." }, { "code": null, "e": 28876, "s": 28713, "text": "If increasing arr[i] to sum is less than decreasing arr[j] to sum then add sum – arr[i] to the ans, and then update arr[i], and arr[j] and then increment i by 1." }, { "code": null, "e": 28972, "s": 28876, "text": "Otherwise, add arr[j] – sum to the ans, and update arr[i] and arr[j] and then decrement j by 1." }, { "code": null, "e": 29049, "s": 28972, "text": "Finally, after completing the above steps, print the value of stored in ans." }, { "code": null, "e": 29100, "s": 29049, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29104, "s": 29100, "text": "C++" }, { "code": null, "e": 29109, "s": 29104, "text": "Java" }, { "code": null, "e": 29117, "s": 29109, "text": "Python3" }, { "code": null, "e": 29120, "s": 29117, "text": "C#" }, { "code": null, "e": 29131, "s": 29120, "text": "Javascript" }, { "code": "// C++ Program for the above approach#include <algorithm>#include <iostream>using namespace std; // Function to find the minimum// operations to make the array// elements equalint find(int arr[], int N){ // Stores the sum of the // array int Sum = 0; for (int i = 0; i < N; i++) { Sum += arr[i]; } if (Sum % N) { return -1; } // update sum Sum /= N; // sort array sort(arr, arr + N); // Store the minimum // needed moves int ans = 0; int i = 0, j = N - 1; // Iterate until i // is less than j while (i < j) { if (Sum - arr[i] < arr[j] - Sum) { // Increment ans by // Sum-arr[i] ans += (Sum - arr[i]); // update arr[i] += (Sum - arr[i]); arr[j] -= (Sum - arr[i]); // Increment i by 1 i++; } else { // Increment ans by //arr[j]-Sum ans += (arr[j] - Sum); // Update arr[i] += (arr[j] - Sum); arr[j] -= (arr[j] - Sum); // Decrement j by 1 j--; } } // Return the value in ans return ans;} // Driver codeint main(){ // Given input int arr[] = { 5, 4, 1, 10 }; int N = sizeof(arr) / sizeof(int); // Function call cout << find(arr, N); return 0;} // This code is contributed by Parth Manchanda", "e": 30355, "s": 29131, "text": null }, { "code": "import java.util.Arrays; // Java Program for the above approach class GFG { // Function to find the minimum // operations to make the array // elements equal public static int find(int arr[], int N) { // Stores the sum of the // array int Sum = 0; for (int i = 0; i < N; i++) { Sum += arr[i]; } if (Sum % N > 0) { return -1; } // update sum Sum /= N; // sort array Arrays.sort(arr); // Store the minimum // needed moves int ans = 0; int i = 0, j = N - 1; // Iterate until i // is less than j while (i < j) { if (Sum - arr[i] < arr[j] - Sum) { // Increment ans by // Sum-arr[i] ans += (Sum - arr[i]); // update arr[i] += (Sum - arr[i]); arr[j] -= (Sum - arr[i]); // Increment i by 1 i++; } else { // Increment ans by // arr[j]-Sum ans += (arr[j] - Sum); // Update arr[i] += (arr[j] - Sum); arr[j] -= (arr[j] - Sum); // Decrement j by 1 j--; } } // Return the value in ans return ans; } // Driver code public static void main(String args[]) { // Given input int arr[] = { 5, 4, 1, 10 }; int N = arr.length; // Function call System.out.println(find(arr, N)); }} // This code is contributed by gfgking", "e": 31980, "s": 30355, "text": null }, { "code": "# Python program for the above approach # Function to find the minimum# operations to make the array# elements equaldef find(arr, N): # Stores the sum of the # array Sum = sum(arr) # If sum is not divisible # by N if Sum % N: return -1 else: # Update sum Sum //= N # Sort the array arr.sort() # Store the minimum # needed moves ans = 0 i = 0 j = N-1 # Iterate until i # is less than j while i < j: # If the Sum-arr[i] # is less than the # arr[j]-sum if Sum-arr[i] < arr[j]-Sum: # Increment ans by # Sum-arr[i] ans += Sum-arr[i] # Update arr[i] += Sum-arr[i] arr[j] -= Sum-arr[i] # Increment i by 1 i += 1 # Otherwise, else: # Increment ans by # arr[j]-Sum ans += arr[j]-Sum # Update arr[i] += arr[j]-Sum arr[j] -= arr[j]-Sum # Decrement j by 1 j -= 1 # Return the value in ans return ans # Driver Codeif __name__ == '__main__': # Given Input arr = [5, 4, 1, 10] N = len(arr) # Function Call print(find(arr, N))", "e": 33379, "s": 31980, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find the minimum// operations to make the array// elements equalpublic static int find(int[] arr, int N){ // Stores the sum of the // array int Sum = 0; int i = 0; for(i = 0; i < N; i++) { Sum += arr[i]; } if (Sum % N > 0) { return -1; } // update sum Sum /= N; // sort array Array.Sort(arr); // Store the minimum // needed moves int ans = 0; i = 0; int j = N - 1; // Iterate until i // is less than j while (i < j) { if (Sum - arr[i] < arr[j] - Sum) { // Increment ans by // Sum-arr[i] ans += (Sum - arr[i]); // update arr[i] += (Sum - arr[i]); arr[j] -= (Sum - arr[i]); // Increment i by 1 i++; } else { // Increment ans by // arr[j]-Sum ans += (arr[j] - Sum); // Update arr[i] += (arr[j] - Sum); arr[j] -= (arr[j] - Sum); // Decrement j by 1 j--; } } // Return the value in ans return ans;} // Driver codestatic public void Main(){ // Given input int[] arr = { 5, 4, 1, 10 }; int N = arr.Length; // Function call Console.WriteLine(find(arr, N));}} // This code is contributed by target_2", "e": 34826, "s": 33379, "text": null }, { "code": "<script> // JavaScript Program for the above approach // Function to find the minimum // operations to make the array // elements equal function find(arr, N) { // Stores the sum of the // array let Sum = 0; for (i = 0; i < arr.length; i++) { Sum = Sum + arr[i]; } // If sum is not divisible // by N if (Sum % N) return -1; else { // Update sum Sum = Math.floor(Sum / N); // Sort the array arr.sort(function (a, b) { return a - b }); // Store the minimum // needed moves ans = 0 i = 0 j = N - 1 // Iterate until i // is less than j while (i < j) { // If the Sum-arr[i] // is less than the // arr[j]-sum if (Sum - arr[i] < arr[j] - Sum) { // Increment ans by // Sum-arr[i] ans += Sum - arr[i] // Update arr[i] += Sum - arr[i] arr[j] -= Sum - arr[i] // Increment i by 1 i += 1 } // Otherwise, else { // Increment ans by // arr[j]-Sum ans += arr[j] - Sum // Update arr[i] += arr[j] - Sum arr[j] -= arr[j] - Sum // Decrement j by 1 j -= 1 } } } // Return the value in ans return ans; } // Driver Code // Given Input let arr = [5, 4, 1, 10]; let N = arr.length; // Function Call document.write(find(arr, N)); // This code is contributed by Potta Lokesh </script>", "e": 36977, "s": 34826, "text": null }, { "code": null, "e": 36979, "s": 36977, "text": "5" }, { "code": null, "e": 37029, "s": 36979, "text": "Time Complexity: O(N*log(N))Auxiliary Space: O(1)" }, { "code": null, "e": 37043, "s": 37029, "text": "lokeshpotta20" }, { "code": null, "e": 37060, "s": 37043, "text": "parthmanchanda81" }, { "code": null, "e": 37068, "s": 37060, "text": "gfgking" }, { "code": null, "e": 37077, "s": 37068, "text": "target_2" }, { "code": null, "e": 37094, "s": 37077, "text": "surinderdawra388" }, { "code": null, "e": 37101, "s": 37094, "text": "Arrays" }, { "code": null, "e": 37108, "s": 37101, "text": "Greedy" }, { "code": null, "e": 37116, "s": 37108, "text": "Sorting" }, { "code": null, "e": 37123, "s": 37116, "text": "Arrays" }, { "code": null, "e": 37130, "s": 37123, "text": "Greedy" }, { "code": null, "e": 37138, "s": 37130, "text": "Sorting" }, { "code": null, "e": 37236, "s": 37138, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37267, "s": 37236, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 37305, "s": 37267, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 37330, "s": 37305, "text": "Window Sliding Technique" }, { "code": null, "e": 37351, "s": 37330, "text": "Next Greater Element" }, { "code": null, "e": 37409, "s": 37351, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 37460, "s": 37409, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 37518, "s": 37460, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 37569, "s": 37518, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 37600, "s": 37569, "text": "Huffman Coding | Greedy Algo-3" } ]
Guide to Conda for TensorFlow and PyTorch | by Eric Hofesmann | Towards Data Science
It’s a real shame that the first experience that most people have with deep learning is having to spend days trying to figure out why the model they downloaded off of GitHub just... won’t... run.... Dependency issues are incredibly common when trying to run an off-the-shelf model. The most problematic of which is needing to have the correct version of CUDA for TensorFlow. TensorFlow has been prominent for a number of years meaning that even new models that are released could use an old version of TensorFlow. This wouldn’t be an issue except that it feels like every version of TensorFlow needs a specific version of CUDA where anything else is incompatible. Sadly, installing multiple versions of CUDA on the same machine can be a real pain! After many years of headaches, thanks to the help of Anaconda I finally realized that installing TensorFlow and exactly the right CUDA version can be as easy as: conda create --name tfconda activate tfconda install tensorflow-gpu I had previously only used pip due to a shoddy understanding of the difference between pip and conda. Really just knowing that pip is the “official” Python package manager. The primary difference between the two is that conda environments are not only for Python packages. Libraries like CUDA can be installed in your isolated environment. On the other hand, some packages do not exist in conda and you will have to install them through pip which is one reason that people might stray away from conda. Using both conda and pip together can be tricky at times, but I provide some tips to handle that later in this post. If you want to start using conda, follow the anaconda installation instructions in this link. Basic commands for things like creating, activating, and deleting environments are very similar between pip and conda. # pipvirtualenv env_name# condaconda create --name env_name # pipsource /path/to/env_name/bin/activate# condaconda activate env_name Note: After installing anaconda, it automatically creates and activates a base environment. It is recommended you create new environments yourself. Turn off the automatic activation with this command: conda config --set auto_activate_base false # pipcd /path/to/env_namerm -rf env_name# condaconda env remove -n env_name Below are a few examples of how to load TensorFlow and PyTorch models that exist in the FiftyOne model zoo. FiftyOne is an open-source tool for machine learning engineers to store their data, labels, and model predictions in a way that can be easily modified, visualized, and analyzed. Included in FiftyOne is a zoo of computer vision models that are available with a single line of code and will serve to easily test our conda environment setups. Note: Installing TensorFlow with GPU functionality requires a CUDA enabled card. Here is a list of CUDA capable GPUs. conda create --name tf2conda activate tf2conda install tensorflow-gpu FiftyOne supports image and video datasets in various formats. In these examples, I just have a directory of images that I will be loading into FiftyOne to generate model predictions on. You can use your own directory of images if you pass in the /path/to/dataset and specify that you are using a dataset type of fiftone.types.ImageDirectory. I am using the FiftyOne command-line interface (CLI) for most of the work in this example. pip install fiftyone# Create a dataset from the given data on diskfiftyone datasets create \ --name my_dataset \ --dataset-dir /path/to/dataset \ --type fiftyone.types.ImageDirectory I can download the model I want to use and then check if the requirements for it are satisfied. # Download a model from the zoofiftyone zoo models download centernet-hg104-512-coco-tf2# Ensure you installed all requirementsfiftyone zoo models requirements \ --ensure centernet-hg104-512-coco-tf2# This model is from the TF2 Model Zoo which must be installedeta install models I will then apply the model to the dataset to generate predictions and visualize them in the FiftyOne App. # Apply a model from the zoo to your datasetfiftyone zoo models apply \ centernet-hg104-512-coco-tf2 \ my_dataset \ predictions # Launch the FiftyOne App to visualize your datasetfiftyone app launch my_dataset conda create --name tf1conda activate tf1 You can search for available packages and then choose which TensorFlow version to install. This will install the corresponding CUDA version in your conda environment. conda search tensorflow-gpuconda install tensorflow-gpu=1.15 I will be using the same procedure as in the TensorFlow 2 example except with a model that uses TensorFlow 1. pip install fiftyone# Download a model from the zoofiftyone zoo models download mask-rcnn-resnet101-atrous-coco-tf# Create a dataset from the given data on diskfiftyone datasets create \ --name my_dataset \ --dataset-dir /path/to/dataset \ --type fiftyone.types.ImageDirectory# Apply a model from the zoo to your datasetfiftyone zoo models apply \ --error-level 1 \ mask-rcnn-resnet101-atrous-coco-tf \ my_dataset \ predictions # Launch the FiftyOne App to visualize your datasetfiftyone app launch my_dataset Installing PyTorch is a bit easier because it is compiled with multiple versions of CUDA. This gives us the freedom to use whatever version of CUDA we want. The default installation instructions at the time of writing (January 2021) recommend CUDA 10.2 but there is a CUDA 11 compatible version of PyTorch. conda create --name pytconda activate pytconda install pytorch torchvision torchaudio cudatoolkit=10.2 \ -c pytorchpip install fiftyone For this example, I’ll use the FiftyOne Python API to perform nearly the same steps as we did previously using the command line. The only difference is the model we are using and that we are loading a dataset from the FiftyOne dataset zoo. Note: Install PyTorch from source if you are using a Mac and need GPU support. Three issues came up when I switched from pip to conda that took a bit of time to figure out. If a package you want to use only exists in pip, you can use pip to install it inside of your conda environment. However, pip and conda don’t always play nice together. The primary issue is that conda is not able to control packages that it did not install. So if pip is used inside of a conda environment, conda is unaware of the changes and may break the environment. Follow these tips from Johnathan Helmus when using pip and conda together: Never use conda after pip. Install everything that you can with conda , then install remaining packages with pip Create new conda environments. Using pip can result in a broken environment, so always make a new isolated conda environment before installing pip packages. If you need to install aconda package after having used pip, it is better to just make a new environment and reinstall everything in the correct order. The default behavior when creating apip virtual environment is that when inside the new environment, you do not have access to globally installed pip packages. If you want access to global packages, you need to initialize your virtual environment with: virtualenv env --system-site-packages conda , on the other hand, lets you access global system packages by default. If you want the environment to be completely isolated from these global packages like with pip, you can create the conda environment based on a clone of an empty pip virtualenv. virtualenv empty_envconda create -n env --clone empty_env Ideally, you should avoid installing global pip packages anyway so this shouldn’t be an issue. If you have a system-wide install of CUDA, then the LD_LIBRARY_PATH environment variable may point to the wrong location after installing CUDA inside of your conda environment. To fix this, you will want to update LD_LIBRARY_PATH to point to the directory containing cuda within conda when you enter your conda environment (generally that directory is /path/to/conda/pkgs/). Then you’ll want to point it back to the system-wide install of CUDA when you leave the conda environment. First, navigate to your conda environment location and create the following files and folders: cd /path/to/anaconda/envs/my_envmkdir -p ./etc/conda/activate.dmkdir -p ./etc/conda/deactivate.dtouch ./etc/conda/activate.d/env_vars.shtouch ./etc/conda/deactivate.d/env_vars.sh In activate.d/env_vars.sh add the following lines. Substitute /your/path with the path to the installation of CUDA in your conda environment. #!/bin/bashexport OLD_LD_LIBRARY_PATH=${LD_LIBRARY_PATH}export LD_LIBRARY_PATH=/your/path:${LD_LIBRARY_PATH} Generally, this /your/path would be something like: export LD_LIBRARY_PATH=/home/user/conda/pkgs/cudatoolkit-10.2/lib:${LD_LIBRARY_PATH} Then add the following lines in deactivate.d/env_vars.sh: #!/bin/bashexport LD_LIBRARY_PATH=${OLD_LD_LIBRARY_PATH}unset OLD_LD_LIBRARY_PATH Being able to install non-Python packages, like CUDA, in only a few commands with conda is a godsend. Using conda in conjunction with the FiftyOne model zoo means you can generate predictions from dozens of models in minutes. However, switching from pip virtual environments to conda environments can result in some unexpected behavior if you’re not prepared.
[ { "code": null, "e": 371, "s": 172, "text": "It’s a real shame that the first experience that most people have with deep learning is having to spend days trying to figure out why the model they downloaded off of GitHub just... won’t... run...." }, { "code": null, "e": 920, "s": 371, "text": "Dependency issues are incredibly common when trying to run an off-the-shelf model. The most problematic of which is needing to have the correct version of CUDA for TensorFlow. TensorFlow has been prominent for a number of years meaning that even new models that are released could use an old version of TensorFlow. This wouldn’t be an issue except that it feels like every version of TensorFlow needs a specific version of CUDA where anything else is incompatible. Sadly, installing multiple versions of CUDA on the same machine can be a real pain!" }, { "code": null, "e": 1082, "s": 920, "text": "After many years of headaches, thanks to the help of Anaconda I finally realized that installing TensorFlow and exactly the right CUDA version can be as easy as:" }, { "code": null, "e": 1150, "s": 1082, "text": "conda create --name tfconda activate tfconda install tensorflow-gpu" }, { "code": null, "e": 1323, "s": 1150, "text": "I had previously only used pip due to a shoddy understanding of the difference between pip and conda. Really just knowing that pip is the “official” Python package manager." }, { "code": null, "e": 1769, "s": 1323, "text": "The primary difference between the two is that conda environments are not only for Python packages. Libraries like CUDA can be installed in your isolated environment. On the other hand, some packages do not exist in conda and you will have to install them through pip which is one reason that people might stray away from conda. Using both conda and pip together can be tricky at times, but I provide some tips to handle that later in this post." }, { "code": null, "e": 1982, "s": 1769, "text": "If you want to start using conda, follow the anaconda installation instructions in this link. Basic commands for things like creating, activating, and deleting environments are very similar between pip and conda." }, { "code": null, "e": 2042, "s": 1982, "text": "# pipvirtualenv env_name# condaconda create --name env_name" }, { "code": null, "e": 2115, "s": 2042, "text": "# pipsource /path/to/env_name/bin/activate# condaconda activate env_name" }, { "code": null, "e": 2316, "s": 2115, "text": "Note: After installing anaconda, it automatically creates and activates a base environment. It is recommended you create new environments yourself. Turn off the automatic activation with this command:" }, { "code": null, "e": 2360, "s": 2316, "text": "conda config --set auto_activate_base false" }, { "code": null, "e": 2436, "s": 2360, "text": "# pipcd /path/to/env_namerm -rf env_name# condaconda env remove -n env_name" }, { "code": null, "e": 2884, "s": 2436, "text": "Below are a few examples of how to load TensorFlow and PyTorch models that exist in the FiftyOne model zoo. FiftyOne is an open-source tool for machine learning engineers to store their data, labels, and model predictions in a way that can be easily modified, visualized, and analyzed. Included in FiftyOne is a zoo of computer vision models that are available with a single line of code and will serve to easily test our conda environment setups." }, { "code": null, "e": 3002, "s": 2884, "text": "Note: Installing TensorFlow with GPU functionality requires a CUDA enabled card. Here is a list of CUDA capable GPUs." }, { "code": null, "e": 3072, "s": 3002, "text": "conda create --name tf2conda activate tf2conda install tensorflow-gpu" }, { "code": null, "e": 3415, "s": 3072, "text": "FiftyOne supports image and video datasets in various formats. In these examples, I just have a directory of images that I will be loading into FiftyOne to generate model predictions on. You can use your own directory of images if you pass in the /path/to/dataset and specify that you are using a dataset type of fiftone.types.ImageDirectory." }, { "code": null, "e": 3506, "s": 3415, "text": "I am using the FiftyOne command-line interface (CLI) for most of the work in this example." }, { "code": null, "e": 3698, "s": 3506, "text": "pip install fiftyone# Create a dataset from the given data on diskfiftyone datasets create \\ --name my_dataset \\ --dataset-dir /path/to/dataset \\ --type fiftyone.types.ImageDirectory" }, { "code": null, "e": 3794, "s": 3698, "text": "I can download the model I want to use and then check if the requirements for it are satisfied." }, { "code": null, "e": 4077, "s": 3794, "text": "# Download a model from the zoofiftyone zoo models download centernet-hg104-512-coco-tf2# Ensure you installed all requirementsfiftyone zoo models requirements \\ --ensure centernet-hg104-512-coco-tf2# This model is from the TF2 Model Zoo which must be installedeta install models" }, { "code": null, "e": 4184, "s": 4077, "text": "I will then apply the model to the dataset to generate predictions and visualize them in the FiftyOne App." }, { "code": null, "e": 4445, "s": 4184, "text": "# Apply a model from the zoo to your datasetfiftyone zoo models apply \\ centernet-hg104-512-coco-tf2 \\ my_dataset \\ predictions # Launch the FiftyOne App to visualize your datasetfiftyone app launch my_dataset" }, { "code": null, "e": 4487, "s": 4445, "text": "conda create --name tf1conda activate tf1" }, { "code": null, "e": 4654, "s": 4487, "text": "You can search for available packages and then choose which TensorFlow version to install. This will install the corresponding CUDA version in your conda environment." }, { "code": null, "e": 4715, "s": 4654, "text": "conda search tensorflow-gpuconda install tensorflow-gpu=1.15" }, { "code": null, "e": 4825, "s": 4715, "text": "I will be using the same procedure as in the TensorFlow 2 example except with a model that uses TensorFlow 1." }, { "code": null, "e": 5421, "s": 4825, "text": "pip install fiftyone# Download a model from the zoofiftyone zoo models download mask-rcnn-resnet101-atrous-coco-tf# Create a dataset from the given data on diskfiftyone datasets create \\ --name my_dataset \\ --dataset-dir /path/to/dataset \\ --type fiftyone.types.ImageDirectory# Apply a model from the zoo to your datasetfiftyone zoo models apply \\ --error-level 1 \\ mask-rcnn-resnet101-atrous-coco-tf \\ my_dataset \\ predictions # Launch the FiftyOne App to visualize your datasetfiftyone app launch my_dataset" }, { "code": null, "e": 5728, "s": 5421, "text": "Installing PyTorch is a bit easier because it is compiled with multiple versions of CUDA. This gives us the freedom to use whatever version of CUDA we want. The default installation instructions at the time of writing (January 2021) recommend CUDA 10.2 but there is a CUDA 11 compatible version of PyTorch." }, { "code": null, "e": 5867, "s": 5728, "text": "conda create --name pytconda activate pytconda install pytorch torchvision torchaudio cudatoolkit=10.2 \\ -c pytorchpip install fiftyone" }, { "code": null, "e": 6107, "s": 5867, "text": "For this example, I’ll use the FiftyOne Python API to perform nearly the same steps as we did previously using the command line. The only difference is the model we are using and that we are loading a dataset from the FiftyOne dataset zoo." }, { "code": null, "e": 6186, "s": 6107, "text": "Note: Install PyTorch from source if you are using a Mac and need GPU support." }, { "code": null, "e": 6280, "s": 6186, "text": "Three issues came up when I switched from pip to conda that took a bit of time to figure out." }, { "code": null, "e": 6449, "s": 6280, "text": "If a package you want to use only exists in pip, you can use pip to install it inside of your conda environment. However, pip and conda don’t always play nice together." }, { "code": null, "e": 6650, "s": 6449, "text": "The primary issue is that conda is not able to control packages that it did not install. So if pip is used inside of a conda environment, conda is unaware of the changes and may break the environment." }, { "code": null, "e": 6725, "s": 6650, "text": "Follow these tips from Johnathan Helmus when using pip and conda together:" }, { "code": null, "e": 6838, "s": 6725, "text": "Never use conda after pip. Install everything that you can with conda , then install remaining packages with pip" }, { "code": null, "e": 6995, "s": 6838, "text": "Create new conda environments. Using pip can result in a broken environment, so always make a new isolated conda environment before installing pip packages." }, { "code": null, "e": 7147, "s": 6995, "text": "If you need to install aconda package after having used pip, it is better to just make a new environment and reinstall everything in the correct order." }, { "code": null, "e": 7400, "s": 7147, "text": "The default behavior when creating apip virtual environment is that when inside the new environment, you do not have access to globally installed pip packages. If you want access to global packages, you need to initialize your virtual environment with:" }, { "code": null, "e": 7438, "s": 7400, "text": "virtualenv env --system-site-packages" }, { "code": null, "e": 7694, "s": 7438, "text": "conda , on the other hand, lets you access global system packages by default. If you want the environment to be completely isolated from these global packages like with pip, you can create the conda environment based on a clone of an empty pip virtualenv." }, { "code": null, "e": 7752, "s": 7694, "text": "virtualenv empty_envconda create -n env --clone empty_env" }, { "code": null, "e": 7847, "s": 7752, "text": "Ideally, you should avoid installing global pip packages anyway so this shouldn’t be an issue." }, { "code": null, "e": 8024, "s": 7847, "text": "If you have a system-wide install of CUDA, then the LD_LIBRARY_PATH environment variable may point to the wrong location after installing CUDA inside of your conda environment." }, { "code": null, "e": 8329, "s": 8024, "text": "To fix this, you will want to update LD_LIBRARY_PATH to point to the directory containing cuda within conda when you enter your conda environment (generally that directory is /path/to/conda/pkgs/). Then you’ll want to point it back to the system-wide install of CUDA when you leave the conda environment." }, { "code": null, "e": 8424, "s": 8329, "text": "First, navigate to your conda environment location and create the following files and folders:" }, { "code": null, "e": 8603, "s": 8424, "text": "cd /path/to/anaconda/envs/my_envmkdir -p ./etc/conda/activate.dmkdir -p ./etc/conda/deactivate.dtouch ./etc/conda/activate.d/env_vars.shtouch ./etc/conda/deactivate.d/env_vars.sh" }, { "code": null, "e": 8745, "s": 8603, "text": "In activate.d/env_vars.sh add the following lines. Substitute /your/path with the path to the installation of CUDA in your conda environment." }, { "code": null, "e": 8854, "s": 8745, "text": "#!/bin/bashexport OLD_LD_LIBRARY_PATH=${LD_LIBRARY_PATH}export LD_LIBRARY_PATH=/your/path:${LD_LIBRARY_PATH}" }, { "code": null, "e": 8906, "s": 8854, "text": "Generally, this /your/path would be something like:" }, { "code": null, "e": 8991, "s": 8906, "text": "export LD_LIBRARY_PATH=/home/user/conda/pkgs/cudatoolkit-10.2/lib:${LD_LIBRARY_PATH}" }, { "code": null, "e": 9049, "s": 8991, "text": "Then add the following lines in deactivate.d/env_vars.sh:" }, { "code": null, "e": 9131, "s": 9049, "text": "#!/bin/bashexport LD_LIBRARY_PATH=${OLD_LD_LIBRARY_PATH}unset OLD_LD_LIBRARY_PATH" } ]
Difference between Iterators and Pointers in C/C++ with Examples - GeeksforGeeks
04 Aug, 2021 Pointer: A pointer is a variable which contains the address of another variable, i.e., address of the memory location of the variable. Like any variable or constant, we must declare a pointer before using it to store any variable address.Syntax: type* var_name; Example: C // The output of this program can be different// in different runs. Note that the program// prints address of a variable and a variable// can be assigned different address in different// runs.#include <stdio.h> int main(){ int x; // Prints address of x printf("%p", &x); return 0;} 0x7ffcac5ae824 Iterator: An iterator is any object that, pointing to some element in a range of elements (such as an array or a container), has the ability to iterate through the elements of that range. Syntax: type_container :: iterator var_name; Example: CPP // C++ program to demonstrate iterators#include <iostream>#include <vector>using namespace std;int main(){ // Declaring a vector vector<int> v = { 1, 2, 3 }; // Declaring an iterator vector<int>::iterator i; int j; cout << "Without iterators = "; // Accessing the elements without using iterators for (j = 0; j < 3; ++j) { cout << v[j] << " "; } cout << "\nWith iterators = "; // Accessing the elements using iterators for (i = v.begin(); i != v.end(); ++i) { cout << *i << " "; } // Adding one more element to vector v.push_back(4); cout << "\nWithout iterators = "; // Accessing the elements without using iterators for (j = 0; j < 4; ++j) { cout << v[j] << " "; } cout << "\nWith iterators = "; // Accessing the elements using iterators for (i = v.begin(); i != v.end(); ++i) { cout << *i << " "; } return 0;} Without iterators = 1 2 3 With iterators = 1 2 3 Without iterators = 1 2 3 4 With iterators = 1 2 3 4 Difference between Iterators and Pointers: Iterators and pointers are similar in that we can dereference them to get a value. However, there are key differences as follows: hp21 varshagumber28 C-Pointers cpp-iterator cpp-pointer Pointers C Language C++ Difference Between Pointers CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Left Shift and Right Shift Operators in C/C++ Function Pointer in C rand() and srand() in C/C++ Substring in C++ fork() in C Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) C++ Classes and Objects Virtual Function in C++
[ { "code": null, "e": 25773, "s": 25745, "text": "\n04 Aug, 2021" }, { "code": null, "e": 26021, "s": 25773, "text": "Pointer: A pointer is a variable which contains the address of another variable, i.e., address of the memory location of the variable. Like any variable or constant, we must declare a pointer before using it to store any variable address.Syntax: " }, { "code": null, "e": 26037, "s": 26021, "text": "type* var_name;" }, { "code": null, "e": 26047, "s": 26037, "text": "Example: " }, { "code": null, "e": 26049, "s": 26047, "text": "C" }, { "code": "// The output of this program can be different// in different runs. Note that the program// prints address of a variable and a variable// can be assigned different address in different// runs.#include <stdio.h> int main(){ int x; // Prints address of x printf(\"%p\", &x); return 0;}", "e": 26345, "s": 26049, "text": null }, { "code": null, "e": 26360, "s": 26345, "text": "0x7ffcac5ae824" }, { "code": null, "e": 26560, "s": 26362, "text": "Iterator: An iterator is any object that, pointing to some element in a range of elements (such as an array or a container), has the ability to iterate through the elements of that range. Syntax: " }, { "code": null, "e": 26597, "s": 26560, "text": "type_container :: iterator var_name;" }, { "code": null, "e": 26607, "s": 26597, "text": "Example: " }, { "code": null, "e": 26611, "s": 26607, "text": "CPP" }, { "code": "// C++ program to demonstrate iterators#include <iostream>#include <vector>using namespace std;int main(){ // Declaring a vector vector<int> v = { 1, 2, 3 }; // Declaring an iterator vector<int>::iterator i; int j; cout << \"Without iterators = \"; // Accessing the elements without using iterators for (j = 0; j < 3; ++j) { cout << v[j] << \" \"; } cout << \"\\nWith iterators = \"; // Accessing the elements using iterators for (i = v.begin(); i != v.end(); ++i) { cout << *i << \" \"; } // Adding one more element to vector v.push_back(4); cout << \"\\nWithout iterators = \"; // Accessing the elements without using iterators for (j = 0; j < 4; ++j) { cout << v[j] << \" \"; } cout << \"\\nWith iterators = \"; // Accessing the elements using iterators for (i = v.begin(); i != v.end(); ++i) { cout << *i << \" \"; } return 0;}", "e": 27536, "s": 26611, "text": null }, { "code": null, "e": 27641, "s": 27536, "text": "Without iterators = 1 2 3 \nWith iterators = 1 2 3 \nWithout iterators = 1 2 3 4 \nWith iterators = 1 2 3 4" }, { "code": null, "e": 27817, "s": 27643, "text": "Difference between Iterators and Pointers: Iterators and pointers are similar in that we can dereference them to get a value. However, there are key differences as follows: " }, { "code": null, "e": 27824, "s": 27819, "text": "hp21" }, { "code": null, "e": 27839, "s": 27824, "text": "varshagumber28" }, { "code": null, "e": 27850, "s": 27839, "text": "C-Pointers" }, { "code": null, "e": 27863, "s": 27850, "text": "cpp-iterator" }, { "code": null, "e": 27875, "s": 27863, "text": "cpp-pointer" }, { "code": null, "e": 27884, "s": 27875, "text": "Pointers" }, { "code": null, "e": 27895, "s": 27884, "text": "C Language" }, { "code": null, "e": 27899, "s": 27895, "text": "C++" }, { "code": null, "e": 27918, "s": 27899, "text": "Difference Between" }, { "code": null, "e": 27927, "s": 27918, "text": "Pointers" }, { "code": null, "e": 27931, "s": 27927, "text": "CPP" }, { "code": null, "e": 28029, "s": 27931, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28075, "s": 28029, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 28097, "s": 28075, "text": "Function Pointer in C" }, { "code": null, "e": 28125, "s": 28097, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 28142, "s": 28125, "text": "Substring in C++" }, { "code": null, "e": 28154, "s": 28142, "text": "fork() in C" }, { "code": null, "e": 28173, "s": 28154, "text": "Inheritance in C++" }, { "code": null, "e": 28219, "s": 28173, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 28262, "s": 28219, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 28286, "s": 28262, "text": "C++ Classes and Objects" } ]
How to count set bits in a floating point number in C?
21 Jun, 2022 Given a floating point number, write a function to count set bits in its binary representation. For example, floating point representation of 0.15625 has 6 set bits (See this). A typical C compiler uses single precision floating point format. We can use the idea discussed here. The idea is to take address of the given floating point number in a pointer variable, typecast the pointer to char * type and process individual bytes one by one. We can easily count set bits in a char using the techniques discussed here. Following is C implementation of the above idea. C #include <stdio.h> // A utility function to count set bits in a char.// Refer http://goo.gl/eHF6Y8 for details of this function.unsigned int countSetBitsChar(char n){ unsigned int count = 0; while (n) { n &= (n-1); count++; } return count;} // Returns set bits in binary representation of xunsigned int countSetBitsFloat(float x){ // Count number of chars (or bytes) in binary representation of float unsigned int n = sizeof(float)/sizeof(char); // typecast address of x to a char pointer char *ptr = (char *)&x; int count = 0; // To store the result for (int i = 0; i < n; i++) { count += countSetBitsChar(*ptr); ptr++; } return count;} // Driver program to test above functionint main(){ float x = 0.15625; printf ("Binary representation of %f has %u set bits ", x, countSetBitsFloat(x)); return 0;} Output: Binary representation of 0.156250 has 6 set bits Time Complexity: O(nlogn) Auxiliary Space: O(1) This article is contributed by Vineet Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above surindertarika1234 sooda367 tarakki100 cpp-puzzle C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) Priority Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 620, "s": 52, "text": "Given a floating point number, write a function to count set bits in its binary representation. For example, floating point representation of 0.15625 has 6 set bits (See this). A typical C compiler uses single precision floating point format. We can use the idea discussed here. The idea is to take address of the given floating point number in a pointer variable, typecast the pointer to char * type and process individual bytes one by one. We can easily count set bits in a char using the techniques discussed here. Following is C implementation of the above idea. " }, { "code": null, "e": 622, "s": 620, "text": "C" }, { "code": "#include <stdio.h> // A utility function to count set bits in a char.// Refer http://goo.gl/eHF6Y8 for details of this function.unsigned int countSetBitsChar(char n){ unsigned int count = 0; while (n) { n &= (n-1); count++; } return count;} // Returns set bits in binary representation of xunsigned int countSetBitsFloat(float x){ // Count number of chars (or bytes) in binary representation of float unsigned int n = sizeof(float)/sizeof(char); // typecast address of x to a char pointer char *ptr = (char *)&x; int count = 0; // To store the result for (int i = 0; i < n; i++) { count += countSetBitsChar(*ptr); ptr++; } return count;} // Driver program to test above functionint main(){ float x = 0.15625; printf (\"Binary representation of %f has %u set bits \", x, countSetBitsFloat(x)); return 0;}", "e": 1518, "s": 622, "text": null }, { "code": null, "e": 1527, "s": 1518, "text": "Output: " }, { "code": null, "e": 1576, "s": 1527, "text": "Binary representation of 0.156250 has 6 set bits" }, { "code": null, "e": 1602, "s": 1576, "text": "Time Complexity: O(nlogn)" }, { "code": null, "e": 1624, "s": 1602, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 1794, "s": 1624, "text": "This article is contributed by Vineet Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 1813, "s": 1794, "text": "surindertarika1234" }, { "code": null, "e": 1822, "s": 1813, "text": "sooda367" }, { "code": null, "e": 1833, "s": 1822, "text": "tarakki100" }, { "code": null, "e": 1844, "s": 1833, "text": "cpp-puzzle" }, { "code": null, "e": 1855, "s": 1844, "text": "C Language" }, { "code": null, "e": 1859, "s": 1855, "text": "C++" }, { "code": null, "e": 1863, "s": 1859, "text": "CPP" }, { "code": null, "e": 1961, "s": 1863, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1978, "s": 1961, "text": "Substring in C++" }, { "code": null, "e": 2013, "s": 1978, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 2035, "s": 2013, "text": "Function Pointer in C" }, { "code": null, "e": 2081, "s": 2035, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 2126, "s": 2081, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 2144, "s": 2126, "text": "Vector in C++ STL" }, { "code": null, "e": 2187, "s": 2144, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 2233, "s": 2187, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 2276, "s": 2233, "text": "Set in C++ Standard Template Library (STL)" } ]
Android GPS, Location Manager tutorial
This example demonstrates how to access Android GPS, Location Manager Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/btn_start_location_updates" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:onClick="startLocationButtonClick" android:text="@string/start_updates" /> <Button android:id="@+id/btn_stop_location_updates" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:enabled="false" android:onClick="stopLocationButtonClick" android:text="@string/stop_updates" /> <Button android:id="@+id/btn_get_last_location" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:onClick="showLastKnownLocation" android:text="@string/get_last_location" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:gravity="center_horizontal" android:text="Location updates will be received only when app is foreground" /> <TextView android:id="@+id/location_result" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:textColor="#333" android:textSize="18sp" /> <TextView android:id="@+id/updated_on" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:textSize="12sp" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java package app.com.sample; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.IntentSender; import android.content.pm.PackageManager; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.os.Looper; import android.provider.Settings; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.ResolvableApiException; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResponse; import com.google.android.gms.location.LocationSettingsStatusCodes; import com.google.android.gms.location.SettingsClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.karumi.dexter.Dexter; import com.karumi.dexter.PermissionToken; import com.karumi.dexter.listener.PermissionDeniedResponse; import com.karumi.dexter.listener.PermissionGrantedResponse; import com.karumi.dexter.listener.PermissionRequest; import com.karumi.dexter.listener.single.PermissionListener; import java.text.DateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); TextView txtLocationResult; TextView txtUpdatedOn; Button btnStartUpdates; Button btnStopUpdates; // location last updated time private String mLastUpdateTime; // location updates interval - 10sec private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; // fastest updates interval - 5 sec // location updates will be received if another app is requesting the locations // than your app can handle private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 5000; private static final int REQUEST_CHECK_SETTINGS = 100; // bunch of location related apis private FusedLocationProviderClient mFusedLocationClient; private SettingsClient mSettingsClient; private LocationRequest mLocationRequest; private LocationSettingsRequest mLocationSettingsRequest; private LocationCallback mLocationCallback; private Location mCurrentLocation; // boolean flag to toggle the ui private Boolean mRequestingLocationUpdates; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialize the necessary libraries init(); // restore the values from saved instance state restoreValuesFromBundle(savedInstanceState); } private void init() { txtLocationResult = findViewById(R.id.location_result); txtUpdatedOn = findViewById(R.id.updated_on); btnStartUpdates = findViewById(R.id.btn_start_location_updates); btnStopUpdates = findViewById(R.id.btn_stop_location_updates); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); mSettingsClient = LocationServices.getSettingsClient(this); mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { super.onLocationResult(locationResult); // location is received mCurrentLocation = locationResult.getLastLocation(); mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateLocationUI(); } }; mRequestingLocationUpdates = false; mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(mLocationRequest); mLocationSettingsRequest = builder.build(); } /** * Restoring values from saved instance state */ private void restoreValuesFromBundle(Bundle savedInstanceState) { if (savedInstanceState != null) { if (savedInstanceState.containsKey("is_requesting_updates")) { mRequestingLocationUpdates = savedInstanceState.getBoolean("is_requesting_updates"); } if (savedInstanceState.containsKey("last_known_location")) { mCurrentLocation = savedInstanceState.getParcelable("last_known_location"); } if (savedInstanceState.containsKey("last_updated_on")) { mLastUpdateTime = savedInstanceState.getString("last_updated_on"); } } updateLocationUI(); } /** * Update the UI displaying the location data * and toggling the buttons */ private void updateLocationUI() { if (mCurrentLocation != null) { txtLocationResult.setText( "Lat: " + mCurrentLocation.getLatitude() + ", " + "Lng: " + mCurrentLocation.getLongitude() ); // giving a blink animation on TextView txtLocationResult.setAlpha(0); txtLocationResult.animate().alpha(1).setDuration(300); // location last updated time txtUpdatedOn.setText("Last updated on: " + mLastUpdateTime); } toggleButtons(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean("is_requesting_updates", mRequestingLocationUpdates); outState.putParcelable("last_known_location", mCurrentLocation); outState.putString("last_updated_on", mLastUpdateTime); } private void toggleButtons() { if (mRequestingLocationUpdates) { btnStartUpdates.setEnabled(false); btnStopUpdates.setEnabled(true); } else { btnStartUpdates.setEnabled(true); btnStopUpdates.setEnabled(false); } } /** * Starting location updates * Check whether location settings are satisfied and then * location updates will be requested */ private void startLocationUpdates() { mSettingsClient .checkLocationSettings(mLocationSettingsRequest) .addOnSuccessListener(this, new OnSuccessListener() { @SuppressLint("MissingPermission") @Override public void onSuccess(LocationSettingsResponse locationSettingsResponse) { Log.i(TAG, "All location settings are satisfied."); Toast.makeText(getApplicationContext(), "Started location updates!", Toast.LENGTH_SHORT).show(); //noinspection MissingPermission mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper()); updateLocationUI(); } }) .addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { int statusCode = ((ApiException) e).getStatusCode(); switch (statusCode) { case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " + "location settings "); try { // Show the dialog by calling startResolutionForResult(), and check the // result in onActivityResult(). ResolvableApiException rae = (ResolvableApiException) e; rae.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException sie) { Log.i(TAG, "PendingIntent unable to execute request."); } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: String errorMessage = "Location settings are inadequate, and cannot be " + "fixed here. Fix in Settings."; Log.e(TAG, errorMessage); Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show(); } updateLocationUI(); } }); } public void startLocationButtonClick(View view) { // Requesting ACCESS_FINE_LOCATION using Dexter library Dexter.withActivity(this) .withPermission(Manifest.permission.ACCESS_FINE_LOCATION) .withListener(new PermissionListener() { @Override public void onPermissionGranted(PermissionGrantedResponse response) { mRequestingLocationUpdates = true; startLocationUpdates(); } @Override public void onPermissionDenied(PermissionDeniedResponse response) { if (response.isPermanentlyDenied()) { // open device settings when the permission is // denied permanently openSettings(); } } @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { token.continuePermissionRequest(); } }).check(); } public void stopLocationButtonClick(View view) { mRequestingLocationUpdates = false; stopLocationUpdates(); } public void stopLocationUpdates() { // Removing location updates mFusedLocationClient .removeLocationUpdates(mLocationCallback) .addOnCompleteListener(this, new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { Toast.makeText(getApplicationContext(), "Location updates stopped!", Toast.LENGTH_SHORT).show(); toggleButtons(); } }); } public void showLastKnownLocation(View view) { if (mCurrentLocation != null) { Toast.makeText(getApplicationContext(), "Lat: " + mCurrentLocation.getLatitude() + ", Lng: " + mCurrentLocation.getLongitude(), Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Last known location is not available!", Toast.LENGTH_SHORT).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Check for the integer request code originally supplied to startResolutionForResult(). if (requestCode == REQUEST_CHECK_SETTINGS) { switch (resultCode) { case Activity.RESULT_OK: Log.e(TAG, "User agreed to make required location settings changes."); // Nothing to do. startLocationupdates() gets called in onResume again. break; case Activity.RESULT_CANCELED: Log.e(TAG, "User chose not to make required location settings changes."); mRequestingLocationUpdates = false; break; } } } private void openSettings() { Intent intent = new Intent(); intent.setAction( Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null); intent.setData(uri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } @Override public void onResume() { super.onResume(); // Resuming location updates depending on button state and // allowed permissions if (mRequestingLocationUpdates && checkPermissions()) { startLocationUpdates(); } updateLocationUI(); } private boolean checkPermissions() { int permissionState = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); return permissionState == PackageManager.PERMISSION_GRANTED; } @Override protected void onPause() { super.onPause(); if (mRequestingLocationUpdates) { // pausing location updates stopLocationUpdates(); } } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <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 the 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": 1257, "s": 1187, "text": "This example demonstrates how to access Android GPS, Location Manager" }, { "code": null, "e": 1386, "s": 1257, "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": 1451, "s": 1386, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3263, "s": 1451, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center_horizontal\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n<Button\n android:id=\"@+id/btn_start_location_updates\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"40dp\"\n android:onClick=\"startLocationButtonClick\"\n android:text=\"@string/start_updates\" />\n<Button\n android:id=\"@+id/btn_stop_location_updates\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"10dp\"\n android:enabled=\"false\"\n android:onClick=\"stopLocationButtonClick\"\n android:text=\"@string/stop_updates\" />\n<Button\n android:id=\"@+id/btn_get_last_location\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"10dp\"\n android:onClick=\"showLastKnownLocation\"\n android:text=\"@string/get_last_location\" />\n<TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"50dp\"\n android:gravity=\"center_horizontal\"\n android:text=\"Location updates will be received only when app is foreground\" />\n<TextView\n android:id=\"@+id/location_result\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"20dp\"\n android:textColor=\"#333\"\n android:textSize=\"18sp\" />\n<TextView\n android:id=\"@+id/updated_on\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"30dp\"\n android:textSize=\"12sp\" />\n</LinearLayout>" }, { "code": null, "e": 3320, "s": 3263, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 15959, "s": 3320, "text": "package app.com.sample;\nimport androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.core.app.ActivityCompat;\nimport android.Manifest;\nimport android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.content.IntentSender;\nimport android.content.pm.PackageManager;\nimport android.location.Location;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.os.Looper;\nimport android.provider.Settings;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport com.google.android.gms.common.api.ApiException;\nimport com.google.android.gms.common.api.ResolvableApiException;\nimport com.google.android.gms.location.FusedLocationProviderClient;\nimport com.google.android.gms.location.LocationCallback;\nimport com.google.android.gms.location.LocationRequest;\nimport com.google.android.gms.location.LocationResult;\nimport com.google.android.gms.location.LocationServices;\nimport com.google.android.gms.location.LocationSettingsRequest;\nimport com.google.android.gms.location.LocationSettingsResponse;\nimport com.google.android.gms.location.LocationSettingsStatusCodes;\nimport com.google.android.gms.location.SettingsClient;\nimport com.google.android.gms.tasks.OnCompleteListener;\nimport com.google.android.gms.tasks.OnFailureListener;\nimport com.google.android.gms.tasks.OnSuccessListener;\nimport com.google.android.gms.tasks.Task;\nimport com.karumi.dexter.Dexter;\nimport com.karumi.dexter.PermissionToken;\nimport com.karumi.dexter.listener.PermissionDeniedResponse;\nimport com.karumi.dexter.listener.PermissionGrantedResponse;\nimport com.karumi.dexter.listener.PermissionRequest;\nimport com.karumi.dexter.listener.single.PermissionListener;\nimport java.text.DateFormat;\nimport java.util.Date;\npublic class MainActivity extends AppCompatActivity {\n private static final String TAG = MainActivity.class.getSimpleName();\n TextView txtLocationResult;\n TextView txtUpdatedOn;\n Button btnStartUpdates;\n Button btnStopUpdates;\n // location last updated time\n private String mLastUpdateTime;\n // location updates interval - 10sec\n private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;\n // fastest updates interval - 5 sec\n // location updates will be received if another app is requesting the locations\n // than your app can handle\n private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 5000;\n private static final int REQUEST_CHECK_SETTINGS = 100;\n // bunch of location related apis\n private FusedLocationProviderClient mFusedLocationClient;\n private SettingsClient mSettingsClient;\n private LocationRequest mLocationRequest;\n private LocationSettingsRequest mLocationSettingsRequest;\n private LocationCallback mLocationCallback;\n private Location mCurrentLocation;\n // boolean flag to toggle the ui\n private Boolean mRequestingLocationUpdates;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n // initialize the necessary libraries\n init();\n // restore the values from saved instance state\n restoreValuesFromBundle(savedInstanceState);\n }\n private void init() {\n txtLocationResult = findViewById(R.id.location_result);\n txtUpdatedOn = findViewById(R.id.updated_on);\n btnStartUpdates = findViewById(R.id.btn_start_location_updates);\n btnStopUpdates = findViewById(R.id.btn_stop_location_updates);\n mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);\n mSettingsClient = LocationServices.getSettingsClient(this);\n mLocationCallback = new LocationCallback() {\n @Override\n public void onLocationResult(LocationResult locationResult) {\n super.onLocationResult(locationResult);\n // location is received\n mCurrentLocation = locationResult.getLastLocation();\n mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());\n updateLocationUI();\n }\n };\n mRequestingLocationUpdates = false;\n mLocationRequest = new LocationRequest();\n mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);\n mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);\n mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);\n LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();\n builder.addLocationRequest(mLocationRequest);\n mLocationSettingsRequest = builder.build();\n }\n/**\n* Restoring values from saved instance state\n*/\n private void restoreValuesFromBundle(Bundle savedInstanceState) {\n if (savedInstanceState != null) {\n if (savedInstanceState.containsKey(\"is_requesting_updates\")) {\n mRequestingLocationUpdates = savedInstanceState.getBoolean(\"is_requesting_updates\");\n }\n if (savedInstanceState.containsKey(\"last_known_location\")) {\n mCurrentLocation = savedInstanceState.getParcelable(\"last_known_location\");\n }\n if (savedInstanceState.containsKey(\"last_updated_on\")) {\n mLastUpdateTime = savedInstanceState.getString(\"last_updated_on\");\n }\n }\n updateLocationUI();\n }\n/**\n* Update the UI displaying the location data\n* and toggling the buttons\n*/\n private void updateLocationUI() {\n if (mCurrentLocation != null) {\n txtLocationResult.setText(\n \"Lat: \" + mCurrentLocation.getLatitude() + \", \" +\n \"Lng: \" + mCurrentLocation.getLongitude()\n );\n // giving a blink animation on TextView\n txtLocationResult.setAlpha(0);\n txtLocationResult.animate().alpha(1).setDuration(300);\n // location last updated time\n txtUpdatedOn.setText(\"Last updated on: \" + mLastUpdateTime);\n }\n toggleButtons();\n }\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n outState.putBoolean(\"is_requesting_updates\", mRequestingLocationUpdates);\n outState.putParcelable(\"last_known_location\", mCurrentLocation);\n outState.putString(\"last_updated_on\", mLastUpdateTime);\n }\n private void toggleButtons() {\n if (mRequestingLocationUpdates) {\n btnStartUpdates.setEnabled(false);\n btnStopUpdates.setEnabled(true);\n }\n else {\n btnStartUpdates.setEnabled(true);\n btnStopUpdates.setEnabled(false);\n }\n }\n/**\n* Starting location updates\n* Check whether location settings are satisfied and then\n* location updates will be requested\n*/\n private void startLocationUpdates() {\n mSettingsClient\n .checkLocationSettings(mLocationSettingsRequest)\n .addOnSuccessListener(this, new OnSuccessListener() {\n @SuppressLint(\"MissingPermission\")\n @Override\n public void onSuccess(LocationSettingsResponse locationSettingsResponse) {\n Log.i(TAG, \"All location settings are satisfied.\");\n Toast.makeText(getApplicationContext(), \"Started location updates!\",\n Toast.LENGTH_SHORT).show();\n //noinspection MissingPermission\n mFusedLocationClient.requestLocationUpdates(mLocationRequest,\n mLocationCallback, Looper.myLooper());\n updateLocationUI();\n }\n })\n .addOnFailureListener(this, new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n int statusCode = ((ApiException) e).getStatusCode();\n switch (statusCode) {\n case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:\n Log.i(TAG, \"Location settings are not satisfied. Attempting to upgrade \" + \"location settings \");\n try {\n // Show the dialog by calling startResolutionForResult(), and check the\n // result in onActivityResult().\n ResolvableApiException rae = (ResolvableApiException) e;\n rae.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);\n }\n catch (IntentSender.SendIntentException sie) {\n Log.i(TAG, \"PendingIntent unable to execute request.\");\n }\n break;\n case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:\n String errorMessage = \"Location settings are inadequate, and cannot be \" + \"fixed here. Fix in Settings.\";\n Log.e(TAG, errorMessage);\n Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();\n }\n updateLocationUI();\n }\n });\n }\n public void startLocationButtonClick(View view) {\n // Requesting ACCESS_FINE_LOCATION using Dexter library\n Dexter.withActivity(this)\n .withPermission(Manifest.permission.ACCESS_FINE_LOCATION)\n .withListener(new PermissionListener() {\n @Override\n public void onPermissionGranted(PermissionGrantedResponse response) {\n mRequestingLocationUpdates = true;\n startLocationUpdates();\n }\n @Override\n public void onPermissionDenied(PermissionDeniedResponse response) {\n if (response.isPermanentlyDenied()) {\n // open device settings when the permission is\n // denied permanently\n openSettings();\n }\n }\n @Override\n public void onPermissionRationaleShouldBeShown(PermissionRequest permission,\n PermissionToken token) {\n token.continuePermissionRequest();\n }\n }).check();\n }\n public void stopLocationButtonClick(View view) {\n mRequestingLocationUpdates = false;\n stopLocationUpdates();\n }\n public void stopLocationUpdates() {\n // Removing location updates\n mFusedLocationClient\n .removeLocationUpdates(mLocationCallback)\n .addOnCompleteListener(this, new OnCompleteListener() {\n @Override\n public void onComplete(@NonNull Task task) {\n Toast.makeText(getApplicationContext(), \"Location updates stopped!\",\n Toast.LENGTH_SHORT).show();\n toggleButtons();\n }\n });\n }\n public void showLastKnownLocation(View view) {\n if (mCurrentLocation != null) {\n Toast.makeText(getApplicationContext(), \"Lat: \" + mCurrentLocation.getLatitude() + \", Lng: \" + mCurrentLocation.getLongitude(), Toast.LENGTH_LONG).show();\n }\n else {\n Toast.makeText(getApplicationContext(), \"Last known location is not available!\",\n Toast.LENGTH_SHORT).show();\n }\n }\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n // Check for the integer request code originally supplied to startResolutionForResult().\n if (requestCode == REQUEST_CHECK_SETTINGS) {\n switch (resultCode) {\n case Activity.RESULT_OK:\n Log.e(TAG, \"User agreed to make required location settings changes.\");\n // Nothing to do. startLocationupdates() gets called in onResume again.\n break;\n case Activity.RESULT_CANCELED:\n Log.e(TAG, \"User chose not to make required location settings changes.\");\n mRequestingLocationUpdates = false;\n break;\n }\n }\n }\n private void openSettings() {\n Intent intent = new Intent();\n intent.setAction(\n Settings.ACTION_APPLICATION_DETAILS_SETTINGS);\n Uri uri = Uri.fromParts(\"package\",\n BuildConfig.APPLICATION_ID, null);\n intent.setData(uri);\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n startActivity(intent);\n }\n @Override\n public void onResume() {\n super.onResume();\n // Resuming location updates depending on button state and\n // allowed permissions\n if (mRequestingLocationUpdates && checkPermissions()) {\n startLocationUpdates();\n }\n updateLocationUI();\n }\n private boolean checkPermissions() {\n int permissionState = ActivityCompat.checkSelfPermission(this,\n Manifest.permission.ACCESS_FINE_LOCATION);\n return permissionState == PackageManager.PERMISSION_GRANTED;\n }\n @Override\n protected void onPause() {\n super.onPause();\n if (mRequestingLocationUpdates) {\n // pausing location updates\n stopLocationUpdates();\n }\n }\n }" }, { "code": null, "e": 16014, "s": 15959, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 16797, "s": 16014, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/>\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": 17148, "s": 16797, "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 the 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 −" } ]
How to show current location on a Google Map on Android using Kotlin?
This example demonstrates how to show current location on a Google Map on Android using Kotlin. 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. <fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/myMap" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" /> Step 3 − Add the given dependency in the build.gradle (Module: app) implementation 'com.google.android.gms:play-services-maps:17.0.0' implementation 'com.google.android.gms:play-services-location:17.0.0' implementation 'com.google.android.gms:play-services-maps:17.0.0' Step 4 − Add the following code to src/MainActivity.kt import android.Manifest import android.content.pm.PackageManager import android.location.Location import android.os.Bundle import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.fragment.app.FragmentActivity import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions class MainActivity : FragmentActivity(), OnMapReadyCallback { private lateinit var currentLocation: Location private lateinit var fusedLocationProviderClient: FusedLocationProviderClient private val permissionCode = 101 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this@MainActivity) fetchLocation() } private fun fetchLocation() { if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), permissionCode) return } val task = fusedLocationProviderClient.lastLocation task.addOnSuccessListener { location −> if (location != null) { currentLocation = location Toast.makeText(applicationContext, currentLocation.latitude.toString() + "" + currentLocation.longitude, Toast.LENGTH_SHORT).show() val supportMapFragment = (supportFragmentManager.findFragmentById(R.id.myMap) as SupportMapFragment?)!! supportMapFragment.getMapAsync(this@MainActivity) } } } override fun onMapReady(googleMap: GoogleMap?) { val latLng = LatLng(currentLocation.latitude, currentLocation.longitude) val markerOptions = MarkerOptions().position(latLng).title("I am here!") googleMap?.animateCamera(CameraUpdateFactory.newLatLng(latLng)) googleMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5f)) googleMap?.addMarker(markerOptions) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>, grantResults: IntArray) { when (requestCode) { permissionCode −> if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { fetchLocation() } } } } Step 5 − To get the google API key (map_key), kindly follow the steps below Visit the Google Cloud Platform Console. Click the project drop−down and select or create the project for which you want to add an API key. Click the project drop−down and select or create the project for which you want to add an API key. Click the menu button and select APIs & Services > Credentials. Click the menu button and select APIs & Services > Credentials. On the Credentials page, click Create credentials > API key. The API key created dialog displays your newly created API key. On the Credentials page, click Create credentials > API key. The API key created dialog displays your newly created API key. Click Close. Click Close. The new API key is listed on the Credentials page under API keys. (Remember to restrict the API key before using it in production.) The new API key is listed on the Credentials page under API keys. (Remember to restrict the API key before using it in production.) Add the API key in the manifest file <meta−data></meta−data> as shown in the step 6 Add the API key in the manifest file <meta−data></meta−data> as shown in the step 6 Step 6 − 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.q15"> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <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> <meta-data android:name="com.google.android.geo.API_KEY" android:value="AIzaSyCiSh4VnnI1jemtZTytDoj2X7Wl6evey30" /> </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 the 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": 1283, "s": 1187, "text": "This example demonstrates how to show current location on a Google Map on Android using Kotlin." }, { "code": null, "e": 1412, "s": 1283, "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": 1477, "s": 1412, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1803, "s": 1477, "text": "<fragment xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/myMap\"\n android:name=\"com.google.android.gms.maps.SupportMapFragment\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\" />" }, { "code": null, "e": 1871, "s": 1803, "text": "Step 3 − Add the given dependency in the build.gradle (Module: app)" }, { "code": null, "e": 2073, "s": 1871, "text": "implementation 'com.google.android.gms:play-services-maps:17.0.0'\nimplementation 'com.google.android.gms:play-services-location:17.0.0'\nimplementation 'com.google.android.gms:play-services-maps:17.0.0'" }, { "code": null, "e": 2128, "s": 2073, "text": "Step 4 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 5045, "s": 2128, "text": "import android.Manifest\nimport android.content.pm.PackageManager\nimport android.location.Location\nimport android.os.Bundle\nimport android.widget.Toast\nimport androidx.core.app.ActivityCompat\nimport androidx.fragment.app.FragmentActivity\nimport com.google.android.gms.location.FusedLocationProviderClient\nimport com.google.android.gms.location.LocationServices\nimport com.google.android.gms.maps.CameraUpdateFactory\nimport com.google.android.gms.maps.GoogleMap\nimport com.google.android.gms.maps.OnMapReadyCallback\nimport com.google.android.gms.maps.SupportMapFragment\nimport com.google.android.gms.maps.model.LatLng\nimport com.google.android.gms.maps.model.MarkerOptions\nclass MainActivity : FragmentActivity(), OnMapReadyCallback {\n private lateinit var currentLocation: Location\n private lateinit var fusedLocationProviderClient: FusedLocationProviderClient\n private val permissionCode = 101\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this@MainActivity)\n fetchLocation()\n }\n private fun fetchLocation() {\n if (ActivityCompat.checkSelfPermission(\n this, Manifest.permission.ACCESS_FINE_LOCATION) !=\n PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(\n this, Manifest.permission.ACCESS_COARSE_LOCATION) !=\n PackageManager.PERMISSION_GRANTED) {\n ActivityCompat.requestPermissions(this,\n arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), permissionCode)\n return\n }\n val task = fusedLocationProviderClient.lastLocation\n task.addOnSuccessListener { location −>\n if (location != null) {\n currentLocation = location\n Toast.makeText(applicationContext, currentLocation.latitude.toString() + \"\" +\n currentLocation.longitude, Toast.LENGTH_SHORT).show()\n val supportMapFragment = (supportFragmentManager.findFragmentById(R.id.myMap) as\n SupportMapFragment?)!!\n supportMapFragment.getMapAsync(this@MainActivity)\n }\n }\n }\n override fun onMapReady(googleMap: GoogleMap?) {\n val latLng = LatLng(currentLocation.latitude, currentLocation.longitude)\n val markerOptions = MarkerOptions().position(latLng).title(\"I am here!\")\n googleMap?.animateCamera(CameraUpdateFactory.newLatLng(latLng))\n googleMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5f))\n googleMap?.addMarker(markerOptions)\n }\n override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>,\n grantResults: IntArray) {\n when (requestCode) {\n permissionCode −> if (grantResults.isNotEmpty() && grantResults[0] ==\n PackageManager.PERMISSION_GRANTED) {\n fetchLocation()\n } \n }\n }\n}" }, { "code": null, "e": 5121, "s": 5045, "text": "Step 5 − To get the google API key (map_key), kindly follow the steps below" }, { "code": null, "e": 5162, "s": 5121, "text": "Visit the Google Cloud Platform Console." }, { "code": null, "e": 5261, "s": 5162, "text": "Click the project drop−down and select or create the project for which you want to add an API key." }, { "code": null, "e": 5360, "s": 5261, "text": "Click the project drop−down and select or create the project for which you want to add an API key." }, { "code": null, "e": 5424, "s": 5360, "text": "Click the menu button and select APIs & Services > Credentials." }, { "code": null, "e": 5488, "s": 5424, "text": "Click the menu button and select APIs & Services > Credentials." }, { "code": null, "e": 5613, "s": 5488, "text": "On the Credentials page, click Create credentials > API key. The API key created dialog displays your newly created API key." }, { "code": null, "e": 5738, "s": 5613, "text": "On the Credentials page, click Create credentials > API key. The API key created dialog displays your newly created API key." }, { "code": null, "e": 5751, "s": 5738, "text": "Click Close." }, { "code": null, "e": 5764, "s": 5751, "text": "Click Close." }, { "code": null, "e": 5897, "s": 5764, "text": "The new API key is listed on the Credentials page under API keys. (Remember to restrict the API key before using it in production.)" }, { "code": null, "e": 6030, "s": 5897, "text": "The new API key is listed on the Credentials page under API keys. (Remember to restrict the API key before using it in production.)" }, { "code": null, "e": 6114, "s": 6030, "text": "Add the API key in the manifest file <meta−data></meta−data> as shown in the step 6" }, { "code": null, "e": 6198, "s": 6114, "text": "Add the API key in the manifest file <meta−data></meta−data> as shown in the step 6" }, { "code": null, "e": 6253, "s": 6198, "text": "Step 6 − Add the following code to androidManifest.xml" }, { "code": null, "e": 7215, "s": 6253, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q15\">\n <uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\" />\n <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/>\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 <meta-data\n android:name=\"com.google.android.geo.API_KEY\"\n android:value=\"AIzaSyCiSh4VnnI1jemtZTytDoj2X7Wl6evey30\" />\n </application>\n</manifest>" }, { "code": null, "e": 7563, "s": 7215, "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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Understanding file sizes | Bytes, KB, MB, GB, TB, PB, EB, ZB, YB
15 Apr, 2021 Introduction Memory of a Computer is any physical device that is capable of storing information whether it is large or small and stores it temporarily or permanently. For example, Random Access Memory (RAM), is a type of volatile memory that stores information for a short interval of time, on an integrated circuit used by the operating system. Memory can be either volatile or non-volatile. Volatile memory is a type of memory that loses its contents when the computer or hardware device is switched off. RAM is an example of a volatile memory i.e. why if your computer gets rebooted while working on a program, you lose all the unsaved data. Non-volatile memory is a memory that keeps its contents saved even in the case of power loss. EPROM((Erasable Programmable ROM) is an example of non-volatile memory. Characteristics of Main Memory Known as the main memory. Semiconductor memories. Faster than secondary memories. A computer cannot run without the primary memory. It is the working memory of the computer. Usually volatile memory. Data is lost in case power is switched off. Units of Memory A computer processor is made up of multiple decisive circuits, each one of which may be either OFF or ON. These two states in terms of memory are represented by a 0 or 1. In order to count higher than 1, such bits (BInary digiTS) are suspended together. A group of eight bits is known as a byte. 1 byte can represent numbers between zero (00000000) and 255 (11111111), or 28 = 256 distinct positions. Of course, these bytes may also be combined to represent larger numbers. The computer represents all characters and numbers internally in the same fashion. In practice, memory is measured in KiloBytes (KB) or MegaBytes (MB). A kilobyte is not exactly, as one might expect, of 1000 bytes. Rather, the correct amount is 210 i.e. 1024 bytes. Similarly, a megabyte is not 10002 i.e. 1, 000, 000 bytes, but instead 10242 i.e. 1, 048, 576 bytes. This is a remarkable difference. By the time we reach to a gigabyte (i.e. 10243 bytes), the difference between the base two and base ten amounts is almost 71 MegaByte. Both computer memory and disk space are measured in these units. But it’s important not to confuse between these two. “12800 KB RAM” refers to the amount of main memory the computer provides to its CPU whereas “128 MB disk” symbolizes the amount of space that is available for the storage of files, data, and other types of permanent information. Types of various Units of Memory- Byte Kilo Byte Mega Byte Giga Byte Tera Byte Peta Byte Exa Byte Zetta Byte Yotta Byte Byte In computer systems, a unit of data that is eight binary digits long is known as a byte. A byte is a unit that computers use to represent a character such as a letter, number, or a typographic symbol (for example, “h”, “7”, or “$”). A byte can also grasp a string of bits that need to be used in some larger units of application processes (e.g., the stream of bits that composes a visual image for a program that represents images or the string of bits that composes the machine code of a computer program). A byte is abbreviated with a big “B” whereas a bit is abbreviated with a small “b”. Computer storage is generally measured in multiples of the byte. For example, a 640 MB hard drive holds a nominal 640 million bytes – or megabytes – of data. Byte multiples are made up of exponents of 2 and generally expressed as a “rounded off” decimal number. For example, two megabytes or 2 million bytes are actually 2, 097, 152 (decimal) bytes. The Conflict Once a KiloByte was considered truly massive at a time. Some felt that writing 210 was a bit unwisely and also might also confuse others. 1,024 bytes appeared to be slightly awkward, and for ease of use, the kilobyte began to be referred to simply as 1,000 bytes of data and just ignore the left 24 Bytes. The majority might assume that the KiloByte is just 1, 000 Bytes of data but that’s not the case. This was done as the people with no knowledge of binary will not get the extra 24 bytes of storage. As time passed, and we started to use MegaByte (MB), it became harder to neglect 24 KB of data, but not hard enough. when GigaByte was started to use it became very hard to ignore 24 MB of storage. Now imagine ignoring 24 GB or even 24 TB of data. The Solution Since it was hard to ignore such a large amount of data, they started to call KB as 1024 Bytes, 1 GB as 1024 MB, etc. But now it was too late, people now know that the KB was 1, 000 Bytes and not 1, 024 Bytes. An effort was set by the American organization NIST (National Institute of Standards and Time) and the International Electrotechnical Commission (IEC) to resolve the issue. As it was very difficult to make small modifications as it tends to big changes to the world of science and technology, it was decided in 1998 that “kibibyte (KiB)” would be used to signify 1,024 bytes while that the KiloByte would be retained solely for 1,000 bytes. Similarly “mebibyte (MiB)” would be used to represent 1,048,576 bytes while megabyte (MB) still referred to 1,000,000 bytes. Unfortunately, it seems that the actions of these regulators have not helped to clarify the difference between the kilobyte and the kibibyte. The fact that the word “kilobyte” has simply become too deep-rooted in international culture. KiloByte The kilobyte is the smallest unit of memory measurement but greater than a byte. A kilobyte is 103 or 1, 000 bytes abbreviated as ‘K’ or ‘KB’. It antecedes the MegaByte, which contains 1, 000, 000 bytes. One kilobyte is technically 1, 000 bytes, therefore, kilobytes are often used synonymously with kibibytes, which contain exactly 1, 024 bytes (210). Kilobytes are mostly used to measure the size of small files. For example, a simple text document may contain 10 KB of data and therefore it would have a file size of 10 kilobytes. Graphics of small websites are often between 5 KB and 100 KB in size. Individual files typically take up a minimum of four kilobytes of disk space. MegaByte One megabyte is equal to 1, 000 KBs and antecedes the gigabyte (GB) unit of memory measurement. A megabyte is 106 or 1, 000, 000 bytes and is abbreviated as “MB”. 1 MB is technically 1, 000, 000 bytes, therefore, megabytes are often used synonymously with mebibytes, which contain exactly 1, 048, 576 bytes (220). Megabytes are mostly used to measure the size of large files. For example, a high-resolution JPEG image might range in size from 1-5 megabytes. A 3-minute song saved in a compressed version may be roughly 3MB in size, and the uncompressed version may take up to 30 MB of disk space. Compact Disk’s capacity is measured in megabytes (approx 700 to 800 MB), whereas the capacity of most other forms of media drives, such as hard drives and flash drives, is generally measured in gigabytes or terabytes. GigaByte One gigabyte is equal to 1, 000 MBs and precedes the terabyte(TB) unit of memory measurement. A gigabyte is 109 or 1, 000, 000, 000 bytes and is abbreviated as “GB”. 1 GB is technically 1, 000, 000, 000 bytes, therefore, gigabytes are used synonymously with gibibytes, which contain exactly 1, 073, 741, 824 bytes (230). Gigabytes, are sometimes also abbreviated as “gigs, ” and are often used to measure storage device’s capacity. e.g., a standard DVD drive can hold 4.7 GBs of data. Storage devices that hold 1, 000 GB of data or more are measured in terabytes. TeraByte One terabyte is equal to 1, 000 GBs and precedes the petabyte(PB) unit of memory measurement. A terabyte is 1012 or 1, 000, 000, 000, 000 bytes and is abbreviated as “TB”. 1 TB is technically 1 trillion bytes, therefore, terabytes and tebibytes are used synonymously, which contains exactly 1, 099, 511, 627, 776 bytes (1, 024 GB) (240). Mostly the storage capacity of large storage devices is measured in TeraBytes. Around 2007, consumer hard drives reached a capacity of 1 TeraByte. Now, HDDs are measured in Terabytes e.g., a typical internal HDD may hold 2 Terabytes of data whereas some servers and high-end workstations that contain multiple hard drives may even have a total storage capacity of over 10 Terabytes. Peta Byte One petabyte is equal to 1, 000 TBs and precedes the exabyte unit of memory measurement. A petabyte is 1015 or 1, 000, 000, 000, 000, 000 bytes and is abbreviated as “PB”. A petabyte is lesser in size than a pebibyte, which contains exactly 1, 125, 899, 906, 842, 624 (250) bytes. Most of the storage devices can hold a maximum of a few TBs, therefore, petabytes are rarely used to measure memory capacity of a single device. Instead, PetaBytes are used to measure the total data stored in large networks or server farms. For example, Internet Giants like Google and Facebook store more than over 100 PBs of data on their data servers. Exa Byte One exabyte is equal to 1, 000 PBs and precedes the zettabyte unit of memory measurement. An exabyte is 1018 or 1, 000, 000, 000, 000, 000, 000 bytes and is abbreviated as “EB”. Exabytes are lesser than exbibytes, which contain exactly 1, 152, 921, 504, 606, 846, 976 (260) bytes. The exabyte unit of memory measurement is so large, that it is not used to measure the capacity of storage devices. Even the data storage capacity of the biggest cloud storage centers is measured in PetaBytes, which is a fraction of 1 EB. Instead, exabytes measure the amount of data over multiple data storage networks or the amount of data that is being transferred over the Internet for a certain amount of time. E.g., several hundred exabytes of data is transferred over the Internet every year. Zetta Byte One zettabyte is equal to 1, 000 exabytes or 1021 or 1, 000, 000, 000, 000, 000, 000, 000 bytes. A zettabyte is a little bit smaller than zebibyte that contains 1, 180, 591, 620, 717, 411, 303, 424 (270) bytes, and is abbreviated as “ZB”. One zettabyte contains one billion TBs or one sextillion bytes which means it will take one billion one terabyte hard drives to store one zettabyte of data. Generally, Zettabyte is used to measure the large amounts of data and all the data in the world is just a few zettabytes. Yotta Byte One yottabyte is equal to 1, 000 zettabytes. It is the largest SI unit of memory measurement. A yottabyte is 1024 ZettaBytes or 1, 000, 000, 000, 000, 000, 000, 000, 000 bytes and is abbreviated as “YB”. It is a little bit smaller than yobibyte, which contains exactly 1, 208, 925, 819, 614, 629, 174, 706, 176 bytes (280) bytes. 1 yottabyte contains one septillion bytes which are exactly the same as one trillion TBs. It is a very large number that humans can evaluate. There is no practical use of such a large measurement unit because all the data in the world made of just a few zettabytes. Some Misconceptions The size on a disk with one KB is 1024 Bytes although it signifies 1, 000 Bytes of data. It’s just the old standard everyone remembers. The download speed Kbps is 1, 000 Bits per second, not 1, 024 Bits per second. Tabular Representation of various Memory Sizes trivediabhay2 anveshakarn2405 CBSE - Class 11 Operating Systems-Memory Management school-programming School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction To PYTHON Interfaces in Java C++ Classes and Objects C++ Data Types Operator Overloading in C++ Polymorphism in C++ Types of Operating Systems Constructors in C++ Constructors in Java Exceptions in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Apr, 2021" }, { "code": null, "e": 65, "s": 52, "text": "Introduction" }, { "code": null, "e": 399, "s": 65, "text": "Memory of a Computer is any physical device that is capable of storing information whether it is large or small and stores it temporarily or permanently. For example, Random Access Memory (RAM), is a type of volatile memory that stores information for a short interval of time, on an integrated circuit used by the operating system. " }, { "code": null, "e": 865, "s": 399, "text": "Memory can be either volatile or non-volatile. Volatile memory is a type of memory that loses its contents when the computer or hardware device is switched off. RAM is an example of a volatile memory i.e. why if your computer gets rebooted while working on a program, you lose all the unsaved data. Non-volatile memory is a memory that keeps its contents saved even in the case of power loss. EPROM((Erasable Programmable ROM) is an example of non-volatile memory. " }, { "code": null, "e": 897, "s": 865, "text": "Characteristics of Main Memory " }, { "code": null, "e": 923, "s": 897, "text": "Known as the main memory." }, { "code": null, "e": 947, "s": 923, "text": "Semiconductor memories." }, { "code": null, "e": 979, "s": 947, "text": "Faster than secondary memories." }, { "code": null, "e": 1029, "s": 979, "text": "A computer cannot run without the primary memory." }, { "code": null, "e": 1071, "s": 1029, "text": "It is the working memory of the computer." }, { "code": null, "e": 1096, "s": 1071, "text": "Usually volatile memory." }, { "code": null, "e": 1140, "s": 1096, "text": "Data is lost in case power is switched off." }, { "code": null, "e": 1156, "s": 1140, "text": "Units of Memory" }, { "code": null, "e": 1714, "s": 1156, "text": "A computer processor is made up of multiple decisive circuits, each one of which may be either OFF or ON. These two states in terms of memory are represented by a 0 or 1. In order to count higher than 1, such bits (BInary digiTS) are suspended together. A group of eight bits is known as a byte. 1 byte can represent numbers between zero (00000000) and 255 (11111111), or 28 = 256 distinct positions. Of course, these bytes may also be combined to represent larger numbers. The computer represents all characters and numbers internally in the same fashion. " }, { "code": null, "e": 2167, "s": 1714, "text": "In practice, memory is measured in KiloBytes (KB) or MegaBytes (MB). A kilobyte is not exactly, as one might expect, of 1000 bytes. Rather, the correct amount is 210 i.e. 1024 bytes. Similarly, a megabyte is not 10002 i.e. 1, 000, 000 bytes, but instead 10242 i.e. 1, 048, 576 bytes. This is a remarkable difference. By the time we reach to a gigabyte (i.e. 10243 bytes), the difference between the base two and base ten amounts is almost 71 MegaByte. " }, { "code": null, "e": 2515, "s": 2167, "text": "Both computer memory and disk space are measured in these units. But it’s important not to confuse between these two. “12800 KB RAM” refers to the amount of main memory the computer provides to its CPU whereas “128 MB disk” symbolizes the amount of space that is available for the storage of files, data, and other types of permanent information. " }, { "code": null, "e": 2550, "s": 2515, "text": "Types of various Units of Memory- " }, { "code": null, "e": 2555, "s": 2550, "text": "Byte" }, { "code": null, "e": 2565, "s": 2555, "text": "Kilo Byte" }, { "code": null, "e": 2575, "s": 2565, "text": "Mega Byte" }, { "code": null, "e": 2585, "s": 2575, "text": "Giga Byte" }, { "code": null, "e": 2595, "s": 2585, "text": "Tera Byte" }, { "code": null, "e": 2605, "s": 2595, "text": "Peta Byte" }, { "code": null, "e": 2614, "s": 2605, "text": "Exa Byte" }, { "code": null, "e": 2625, "s": 2614, "text": "Zetta Byte" }, { "code": null, "e": 2636, "s": 2625, "text": "Yotta Byte" }, { "code": null, "e": 2641, "s": 2636, "text": "Byte" }, { "code": null, "e": 3584, "s": 2641, "text": "In computer systems, a unit of data that is eight binary digits long is known as a byte. A byte is a unit that computers use to represent a character such as a letter, number, or a typographic symbol (for example, “h”, “7”, or “$”). A byte can also grasp a string of bits that need to be used in some larger units of application processes (e.g., the stream of bits that composes a visual image for a program that represents images or the string of bits that composes the machine code of a computer program). A byte is abbreviated with a big “B” whereas a bit is abbreviated with a small “b”. Computer storage is generally measured in multiples of the byte. For example, a 640 MB hard drive holds a nominal 640 million bytes – or megabytes – of data. Byte multiples are made up of exponents of 2 and generally expressed as a “rounded off” decimal number. For example, two megabytes or 2 million bytes are actually 2, 097, 152 (decimal) bytes. " }, { "code": null, "e": 3597, "s": 3584, "text": "The Conflict" }, { "code": null, "e": 4101, "s": 3597, "text": "Once a KiloByte was considered truly massive at a time. Some felt that writing 210 was a bit unwisely and also might also confuse others. 1,024 bytes appeared to be slightly awkward, and for ease of use, the kilobyte began to be referred to simply as 1,000 bytes of data and just ignore the left 24 Bytes. The majority might assume that the KiloByte is just 1, 000 Bytes of data but that’s not the case. This was done as the people with no knowledge of binary will not get the extra 24 bytes of storage." }, { "code": null, "e": 4349, "s": 4101, "text": "As time passed, and we started to use MegaByte (MB), it became harder to neglect 24 KB of data, but not hard enough. when GigaByte was started to use it became very hard to ignore 24 MB of storage. Now imagine ignoring 24 GB or even 24 TB of data." }, { "code": null, "e": 4362, "s": 4349, "text": "The Solution" }, { "code": null, "e": 4746, "s": 4362, "text": "Since it was hard to ignore such a large amount of data, they started to call KB as 1024 Bytes, 1 GB as 1024 MB, etc. But now it was too late, people now know that the KB was 1, 000 Bytes and not 1, 024 Bytes. An effort was set by the American organization NIST (National Institute of Standards and Time) and the International Electrotechnical Commission (IEC) to resolve the issue. " }, { "code": null, "e": 5139, "s": 4746, "text": "As it was very difficult to make small modifications as it tends to big changes to the world of science and technology, it was decided in 1998 that “kibibyte (KiB)” would be used to signify 1,024 bytes while that the KiloByte would be retained solely for 1,000 bytes. Similarly “mebibyte (MiB)” would be used to represent 1,048,576 bytes while megabyte (MB) still referred to 1,000,000 bytes." }, { "code": null, "e": 5375, "s": 5139, "text": "Unfortunately, it seems that the actions of these regulators have not helped to clarify the difference between the kilobyte and the kibibyte. The fact that the word “kilobyte” has simply become too deep-rooted in international culture." }, { "code": null, "e": 5384, "s": 5375, "text": "KiloByte" }, { "code": null, "e": 6068, "s": 5384, "text": "The kilobyte is the smallest unit of memory measurement but greater than a byte. A kilobyte is 103 or 1, 000 bytes abbreviated as ‘K’ or ‘KB’. It antecedes the MegaByte, which contains 1, 000, 000 bytes. One kilobyte is technically 1, 000 bytes, therefore, kilobytes are often used synonymously with kibibytes, which contain exactly 1, 024 bytes (210). Kilobytes are mostly used to measure the size of small files. For example, a simple text document may contain 10 KB of data and therefore it would have a file size of 10 kilobytes. Graphics of small websites are often between 5 KB and 100 KB in size. Individual files typically take up a minimum of four kilobytes of disk space. " }, { "code": null, "e": 6077, "s": 6068, "text": "MegaByte" }, { "code": null, "e": 6893, "s": 6077, "text": "One megabyte is equal to 1, 000 KBs and antecedes the gigabyte (GB) unit of memory measurement. A megabyte is 106 or 1, 000, 000 bytes and is abbreviated as “MB”. 1 MB is technically 1, 000, 000 bytes, therefore, megabytes are often used synonymously with mebibytes, which contain exactly 1, 048, 576 bytes (220). Megabytes are mostly used to measure the size of large files. For example, a high-resolution JPEG image might range in size from 1-5 megabytes. A 3-minute song saved in a compressed version may be roughly 3MB in size, and the uncompressed version may take up to 30 MB of disk space. Compact Disk’s capacity is measured in megabytes (approx 700 to 800 MB), whereas the capacity of most other forms of media drives, such as hard drives and flash drives, is generally measured in gigabytes or terabytes. " }, { "code": null, "e": 6902, "s": 6893, "text": "GigaByte" }, { "code": null, "e": 7467, "s": 6902, "text": "One gigabyte is equal to 1, 000 MBs and precedes the terabyte(TB) unit of memory measurement. A gigabyte is 109 or 1, 000, 000, 000 bytes and is abbreviated as “GB”. 1 GB is technically 1, 000, 000, 000 bytes, therefore, gigabytes are used synonymously with gibibytes, which contain exactly 1, 073, 741, 824 bytes (230). Gigabytes, are sometimes also abbreviated as “gigs, ” and are often used to measure storage device’s capacity. e.g., a standard DVD drive can hold 4.7 GBs of data. Storage devices that hold 1, 000 GB of data or more are measured in terabytes. " }, { "code": null, "e": 7476, "s": 7467, "text": "TeraByte" }, { "code": null, "e": 8198, "s": 7476, "text": "One terabyte is equal to 1, 000 GBs and precedes the petabyte(PB) unit of memory measurement. A terabyte is 1012 or 1, 000, 000, 000, 000 bytes and is abbreviated as “TB”. 1 TB is technically 1 trillion bytes, therefore, terabytes and tebibytes are used synonymously, which contains exactly 1, 099, 511, 627, 776 bytes (1, 024 GB) (240). Mostly the storage capacity of large storage devices is measured in TeraBytes. Around 2007, consumer hard drives reached a capacity of 1 TeraByte. Now, HDDs are measured in Terabytes e.g., a typical internal HDD may hold 2 Terabytes of data whereas some servers and high-end workstations that contain multiple hard drives may even have a total storage capacity of over 10 Terabytes. " }, { "code": null, "e": 8208, "s": 8198, "text": "Peta Byte" }, { "code": null, "e": 8846, "s": 8208, "text": "One petabyte is equal to 1, 000 TBs and precedes the exabyte unit of memory measurement. A petabyte is 1015 or 1, 000, 000, 000, 000, 000 bytes and is abbreviated as “PB”. A petabyte is lesser in size than a pebibyte, which contains exactly 1, 125, 899, 906, 842, 624 (250) bytes. Most of the storage devices can hold a maximum of a few TBs, therefore, petabytes are rarely used to measure memory capacity of a single device. Instead, PetaBytes are used to measure the total data stored in large networks or server farms. For example, Internet Giants like Google and Facebook store more than over 100 PBs of data on their data servers. " }, { "code": null, "e": 8855, "s": 8846, "text": "Exa Byte" }, { "code": null, "e": 9638, "s": 8855, "text": "One exabyte is equal to 1, 000 PBs and precedes the zettabyte unit of memory measurement. An exabyte is 1018 or 1, 000, 000, 000, 000, 000, 000 bytes and is abbreviated as “EB”. Exabytes are lesser than exbibytes, which contain exactly 1, 152, 921, 504, 606, 846, 976 (260) bytes. The exabyte unit of memory measurement is so large, that it is not used to measure the capacity of storage devices. Even the data storage capacity of the biggest cloud storage centers is measured in PetaBytes, which is a fraction of 1 EB. Instead, exabytes measure the amount of data over multiple data storage networks or the amount of data that is being transferred over the Internet for a certain amount of time. E.g., several hundred exabytes of data is transferred over the Internet every year. " }, { "code": null, "e": 9649, "s": 9638, "text": "Zetta Byte" }, { "code": null, "e": 10169, "s": 9649, "text": "One zettabyte is equal to 1, 000 exabytes or 1021 or 1, 000, 000, 000, 000, 000, 000, 000 bytes. A zettabyte is a little bit smaller than zebibyte that contains 1, 180, 591, 620, 717, 411, 303, 424 (270) bytes, and is abbreviated as “ZB”. One zettabyte contains one billion TBs or one sextillion bytes which means it will take one billion one terabyte hard drives to store one zettabyte of data. Generally, Zettabyte is used to measure the large amounts of data and all the data in the world is just a few zettabytes. " }, { "code": null, "e": 10180, "s": 10169, "text": "Yotta Byte" }, { "code": null, "e": 10511, "s": 10180, "text": "One yottabyte is equal to 1, 000 zettabytes. It is the largest SI unit of memory measurement. A yottabyte is 1024 ZettaBytes or 1, 000, 000, 000, 000, 000, 000, 000, 000 bytes and is abbreviated as “YB”. It is a little bit smaller than yobibyte, which contains exactly 1, 208, 925, 819, 614, 629, 174, 706, 176 bytes (280) bytes. " }, { "code": null, "e": 10778, "s": 10511, "text": "1 yottabyte contains one septillion bytes which are exactly the same as one trillion TBs. It is a very large number that humans can evaluate. There is no practical use of such a large measurement unit because all the data in the world made of just a few zettabytes. " }, { "code": null, "e": 10798, "s": 10778, "text": "Some Misconceptions" }, { "code": null, "e": 10934, "s": 10798, "text": "The size on a disk with one KB is 1024 Bytes although it signifies 1, 000 Bytes of data. It’s just the old standard everyone remembers." }, { "code": null, "e": 11013, "s": 10934, "text": "The download speed Kbps is 1, 000 Bits per second, not 1, 024 Bits per second." }, { "code": null, "e": 11061, "s": 11013, "text": "Tabular Representation of various Memory Sizes " }, { "code": null, "e": 11077, "s": 11063, "text": "trivediabhay2" }, { "code": null, "e": 11093, "s": 11077, "text": "anveshakarn2405" }, { "code": null, "e": 11109, "s": 11093, "text": "CBSE - Class 11" }, { "code": null, "e": 11145, "s": 11109, "text": "Operating Systems-Memory Management" }, { "code": null, "e": 11164, "s": 11145, "text": "school-programming" }, { "code": null, "e": 11183, "s": 11164, "text": "School Programming" }, { "code": null, "e": 11281, "s": 11183, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11304, "s": 11281, "text": "Introduction To PYTHON" }, { "code": null, "e": 11323, "s": 11304, "text": "Interfaces in Java" }, { "code": null, "e": 11347, "s": 11323, "text": "C++ Classes and Objects" }, { "code": null, "e": 11362, "s": 11347, "text": "C++ Data Types" }, { "code": null, "e": 11390, "s": 11362, "text": "Operator Overloading in C++" }, { "code": null, "e": 11410, "s": 11390, "text": "Polymorphism in C++" }, { "code": null, "e": 11437, "s": 11410, "text": "Types of Operating Systems" }, { "code": null, "e": 11457, "s": 11437, "text": "Constructors in C++" }, { "code": null, "e": 11478, "s": 11457, "text": "Constructors in Java" } ]
Check if count of Alphabets and count of Numbers are equal in the given String
20 May, 2021 Given the alphanumeric string str, the task is to check if the count of Alphabets and count of Numbers are equal or not. Examples: Input: str = “GeeKs01234” Output: Yes Explanation: The count of alphabets and numbers are equal to 5. Input: str = “Gfg01234” Output: No Explanation: The count of the alphabet is 3, whereas the count of numbers is 5. Approach: The idea is to use the ASCII values of the characters to distinguish between a number and an alphabet. After distinguishing the characters, two counters are maintained to count the number of alphabets and numbers respectively. Finally, both the counters are checked for equality. The ASCII ranges of the characters are as follows: Lowercase characters: 97 to 122 Uppercase characters: 65 to 90 Digits: 48 to 57 Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to check if the count of// alphabets and numbers in a string// are equal or not. #include <iostream>using namespace std; // Function to count the// number of alphabetsint countOfLetters(string str){ // Counter to store the number // of alphabets in the string int letter = 0; // Every character in the string // is iterated for (int i = 0; i < str.length(); i++) { // To check if the character is // an alphabet or not if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) letter++; } return letter;} // Function to count the number of numbersint countOfNumbers(string str){ // Counter to store the number // of alphabets in the string int number = 0; // Every character in the string is iterated for (int i = 0; i < str.length(); i++) { // To check if the character is // a digit or not if (str[i] >= '0' && str[i] <= '9') number++; } return number;} // Function to check if the// count of alphabets is equal to// the count of numbers or notvoid check(string str){ if (countOfLetters(str) == countOfNumbers(str)) cout << "Yes\n"; else cout << "No\n";} // Driver codeint main(){ string str = "GeeKs01324"; check(str); return 0;} // Java program to check if the count of// alphabets and numbers in a String// are equal or not.class GFG{ // Function to count the// number of alphabetsstatic int countOfLetters(String str){ // Counter to store the number // of alphabets in the String int letter = 0; // Every character in the String // is iterated for (int i = 0; i < str.length(); i++) { // To check if the character is // an alphabet or not if ((str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') || (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')) letter++; } return letter;} // Function to count the number of numbersstatic int countOfNumbers(String str){ // Counter to store the number // of alphabets in the String int number = 0; // Every character in the String is iterated for (int i = 0; i < str.length(); i++) { // To check if the character is // a digit or not if (str.charAt(i) >= '0' && str.charAt(i) <= '9') number++; } return number;} // Function to check if the// count of alphabets is equal to// the count of numbers or notstatic void check(String str){ if (countOfLetters(str) == countOfNumbers(str)) System.out.print("Yes\n"); else System.out.print("No\n");} // Driver codepublic static void main(String[] args){ String str = "GeeKs01324"; check(str);}} // This code is contributed by 29AjayKumar # Python3 program to check if the count of# alphabets and numbers in a string# are equal or not. # Function to count the# number of alphabetsdef countOfLetters(string ) : # Counter to store the number # of alphabets in the string letter = 0; # Every character in the string # is iterated for i in range(len(string)) : # To check if the character is # an alphabet or not if ((string[i] >= 'A' and string[i] <= 'Z') or (string[i] >= 'a' and string[i] <= 'z')) : letter += 1; return letter; # Function to count the number of numbersdef countOfNumbers(string ) : # Counter to store the number # of alphabets in the string number = 0; # Every character in the string is iterated for i in range(len(string)) : # To check if the character is # a digit or not if (string[i] >= '0' and string[i] <= '9') : number += 1; return number; # Function to check if the# count of alphabets is equal to# the count of numbers or notdef check(string) : if (countOfLetters(string) == countOfNumbers(string)) : print("Yes"); else : print("No"); # Driver codeif __name__ == "__main__" : string = "GeeKs01324"; check(string); # This code is contributed by AnkitRai01 // C# program to check if the count of// alphabets and numbers in a String// are equal or not.using System; class GFG{ // Function to count the// number of alphabetsstatic int countOfLetters(String str){ // Counter to store the number // of alphabets in the String int letter = 0; // Every character in the String // is iterated for (int i = 0; i < str.Length; i++) { // To check if the character is // an alphabet or not if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) letter++; } return letter;} // Function to count the number of numbersstatic int countOfNumbers(String str){ // Counter to store the number // of alphabets in the String int number = 0; // Every character in the String is iterated for (int i = 0; i < str.Length; i++) { // To check if the character is // a digit or not if (str[i] >= '0' && str[i] <= '9') number++; } return number;} // Function to check if the// count of alphabets is equal to// the count of numbers or notstatic void check(String str){ if (countOfLetters(str) == countOfNumbers(str)) Console.Write("Yes\n"); else Console.Write("No\n");} // Driver codepublic static void Main(String[] args){ String str = "GeeKs01324"; check(str);}} // This code is contributed by 29AjayKumar <script>// Javascript program to check if the count of// alphabets and numbers in a string// are equal or not. // Function to count the// number of alphabetsfunction countOfLetters( str){ // Counter to store the number // of alphabets in the string var letter = 0; // Every character in the string // is iterated for (var i = 0; i < str.length; i++) { // To check if the character is // an alphabet or not if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) letter++; } return letter;} // Function to count the number of numbersfunction countOfNumbers( str){ // Counter to store the number // of alphabets in the string var number = 0; // Every character in the string is iterated for (var i = 0; i < str.length; i++) { // To check if the character is // a digit or not if (str[i] >= '0' && str[i] <= '9') number++; } return number;} // Function to check if the// count of alphabets is equal to// the count of numbers or notfunction check( str){ if (countOfLetters(str) == countOfNumbers(str)) document.write( "Yes<br>"); else document.write( "No<br>");} var str = "GeeKs01324";check(str); // This code is contributed by SoumikMondal</script> Yes 29AjayKumar ankthon SoumikMondal School Programming Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Constructors in Java Exceptions in Java Python Exception Handling Python Try Except Ternary Operator in Python Write a program to reverse an array or string Write a program to print all permutations of a given string Check for Balanced Brackets in an expression (well-formedness) using Stack Longest Common Subsequence | DP-4 KMP Algorithm for Pattern Searching
[ { "code": null, "e": 53, "s": 25, "text": "\n20 May, 2021" }, { "code": null, "e": 175, "s": 53, "text": "Given the alphanumeric string str, the task is to check if the count of Alphabets and count of Numbers are equal or not. " }, { "code": null, "e": 187, "s": 175, "text": "Examples: " }, { "code": null, "e": 290, "s": 187, "text": "Input: str = “GeeKs01234” Output: Yes Explanation: The count of alphabets and numbers are equal to 5. " }, { "code": null, "e": 407, "s": 290, "text": "Input: str = “Gfg01234” Output: No Explanation: The count of the alphabet is 3, whereas the count of numbers is 5. " }, { "code": null, "e": 750, "s": 407, "text": "Approach: The idea is to use the ASCII values of the characters to distinguish between a number and an alphabet. After distinguishing the characters, two counters are maintained to count the number of alphabets and numbers respectively. Finally, both the counters are checked for equality. The ASCII ranges of the characters are as follows: " }, { "code": null, "e": 782, "s": 750, "text": "Lowercase characters: 97 to 122" }, { "code": null, "e": 813, "s": 782, "text": "Uppercase characters: 65 to 90" }, { "code": null, "e": 830, "s": 813, "text": "Digits: 48 to 57" }, { "code": null, "e": 882, "s": 830, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 886, "s": 882, "text": "C++" }, { "code": null, "e": 891, "s": 886, "text": "Java" }, { "code": null, "e": 899, "s": 891, "text": "Python3" }, { "code": null, "e": 902, "s": 899, "text": "C#" }, { "code": null, "e": 913, "s": 902, "text": "Javascript" }, { "code": "// C++ program to check if the count of// alphabets and numbers in a string// are equal or not. #include <iostream>using namespace std; // Function to count the// number of alphabetsint countOfLetters(string str){ // Counter to store the number // of alphabets in the string int letter = 0; // Every character in the string // is iterated for (int i = 0; i < str.length(); i++) { // To check if the character is // an alphabet or not if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) letter++; } return letter;} // Function to count the number of numbersint countOfNumbers(string str){ // Counter to store the number // of alphabets in the string int number = 0; // Every character in the string is iterated for (int i = 0; i < str.length(); i++) { // To check if the character is // a digit or not if (str[i] >= '0' && str[i] <= '9') number++; } return number;} // Function to check if the// count of alphabets is equal to// the count of numbers or notvoid check(string str){ if (countOfLetters(str) == countOfNumbers(str)) cout << \"Yes\\n\"; else cout << \"No\\n\";} // Driver codeint main(){ string str = \"GeeKs01324\"; check(str); return 0;}", "e": 2239, "s": 913, "text": null }, { "code": "// Java program to check if the count of// alphabets and numbers in a String// are equal or not.class GFG{ // Function to count the// number of alphabetsstatic int countOfLetters(String str){ // Counter to store the number // of alphabets in the String int letter = 0; // Every character in the String // is iterated for (int i = 0; i < str.length(); i++) { // To check if the character is // an alphabet or not if ((str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') || (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')) letter++; } return letter;} // Function to count the number of numbersstatic int countOfNumbers(String str){ // Counter to store the number // of alphabets in the String int number = 0; // Every character in the String is iterated for (int i = 0; i < str.length(); i++) { // To check if the character is // a digit or not if (str.charAt(i) >= '0' && str.charAt(i) <= '9') number++; } return number;} // Function to check if the// count of alphabets is equal to// the count of numbers or notstatic void check(String str){ if (countOfLetters(str) == countOfNumbers(str)) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\");} // Driver codepublic static void main(String[] args){ String str = \"GeeKs01324\"; check(str);}} // This code is contributed by 29AjayKumar", "e": 3684, "s": 2239, "text": null }, { "code": "# Python3 program to check if the count of# alphabets and numbers in a string# are equal or not. # Function to count the# number of alphabetsdef countOfLetters(string ) : # Counter to store the number # of alphabets in the string letter = 0; # Every character in the string # is iterated for i in range(len(string)) : # To check if the character is # an alphabet or not if ((string[i] >= 'A' and string[i] <= 'Z') or (string[i] >= 'a' and string[i] <= 'z')) : letter += 1; return letter; # Function to count the number of numbersdef countOfNumbers(string ) : # Counter to store the number # of alphabets in the string number = 0; # Every character in the string is iterated for i in range(len(string)) : # To check if the character is # a digit or not if (string[i] >= '0' and string[i] <= '9') : number += 1; return number; # Function to check if the# count of alphabets is equal to# the count of numbers or notdef check(string) : if (countOfLetters(string) == countOfNumbers(string)) : print(\"Yes\"); else : print(\"No\"); # Driver codeif __name__ == \"__main__\" : string = \"GeeKs01324\"; check(string); # This code is contributed by AnkitRai01", "e": 4984, "s": 3684, "text": null }, { "code": "// C# program to check if the count of// alphabets and numbers in a String// are equal or not.using System; class GFG{ // Function to count the// number of alphabetsstatic int countOfLetters(String str){ // Counter to store the number // of alphabets in the String int letter = 0; // Every character in the String // is iterated for (int i = 0; i < str.Length; i++) { // To check if the character is // an alphabet or not if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) letter++; } return letter;} // Function to count the number of numbersstatic int countOfNumbers(String str){ // Counter to store the number // of alphabets in the String int number = 0; // Every character in the String is iterated for (int i = 0; i < str.Length; i++) { // To check if the character is // a digit or not if (str[i] >= '0' && str[i] <= '9') number++; } return number;} // Function to check if the// count of alphabets is equal to// the count of numbers or notstatic void check(String str){ if (countOfLetters(str) == countOfNumbers(str)) Console.Write(\"Yes\\n\"); else Console.Write(\"No\\n\");} // Driver codepublic static void Main(String[] args){ String str = \"GeeKs01324\"; check(str);}} // This code is contributed by 29AjayKumar", "e": 6389, "s": 4984, "text": null }, { "code": "<script>// Javascript program to check if the count of// alphabets and numbers in a string// are equal or not. // Function to count the// number of alphabetsfunction countOfLetters( str){ // Counter to store the number // of alphabets in the string var letter = 0; // Every character in the string // is iterated for (var i = 0; i < str.length; i++) { // To check if the character is // an alphabet or not if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) letter++; } return letter;} // Function to count the number of numbersfunction countOfNumbers( str){ // Counter to store the number // of alphabets in the string var number = 0; // Every character in the string is iterated for (var i = 0; i < str.length; i++) { // To check if the character is // a digit or not if (str[i] >= '0' && str[i] <= '9') number++; } return number;} // Function to check if the// count of alphabets is equal to// the count of numbers or notfunction check( str){ if (countOfLetters(str) == countOfNumbers(str)) document.write( \"Yes<br>\"); else document.write( \"No<br>\");} var str = \"GeeKs01324\";check(str); // This code is contributed by SoumikMondal</script>", "e": 7700, "s": 6389, "text": null }, { "code": null, "e": 7704, "s": 7700, "text": "Yes" }, { "code": null, "e": 7718, "s": 7706, "text": "29AjayKumar" }, { "code": null, "e": 7726, "s": 7718, "text": "ankthon" }, { "code": null, "e": 7739, "s": 7726, "text": "SoumikMondal" }, { "code": null, "e": 7758, "s": 7739, "text": "School Programming" }, { "code": null, "e": 7766, "s": 7758, "text": "Strings" }, { "code": null, "e": 7774, "s": 7766, "text": "Strings" }, { "code": null, "e": 7872, "s": 7774, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7893, "s": 7872, "text": "Constructors in Java" }, { "code": null, "e": 7912, "s": 7893, "text": "Exceptions in Java" }, { "code": null, "e": 7938, "s": 7912, "text": "Python Exception Handling" }, { "code": null, "e": 7956, "s": 7938, "text": "Python Try Except" }, { "code": null, "e": 7983, "s": 7956, "text": "Ternary Operator in Python" }, { "code": null, "e": 8029, "s": 7983, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 8089, "s": 8029, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 8164, "s": 8089, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 8198, "s": 8164, "text": "Longest Common Subsequence | DP-4" } ]
How to validate an IP address using Regular Expressions in Java
10 Jun, 2021 Given an IP address, the task is to validate this IP address with the help of Regular Expressions.The IP address is a string in the form “A.B.C.D”, where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can’t be greater than 3.Examples: Input: str = "000.12.12.034" Output: True Input: str = "000.12.234.23.23" Output: False Input: str = "121.234.12.12" Output: True Input: str = "I.Am.not.an.ip" Output: False Approach: In this article, the IP address is validated with the help of Regular Expressions or Regex. Below are the steps to solve this problem using ReGex: Get the string.Regular expression to validate an IP address: Get the string. Regular expression to validate an IP address: // ReGex to numbers from 0 to 255 zeroTo255 -> (\\d{1, 2}|(0|1)\\d{2}|2[0-4]\\d|25[0-5]) // ReGex to validate complete IP address IPAddress -> zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255; where: \d represents digits in regular expressions, same as [0-9]\\d{1, 2} catches any one or two-digit number(0|1)\\d{2} catches any three-digit number starting with 0 or 1.2[0-4]\\d catches numbers between 200 and 249.25[0-5] catches numbers between 250 and 255.Match the string with the Regex. In Java, this can be done using Pattern.matcher(). Return true if the string matches with the given regex, else return false. where: \d represents digits in regular expressions, same as [0-9]\\d{1, 2} catches any one or two-digit number(0|1)\\d{2} catches any three-digit number starting with 0 or 1.2[0-4]\\d catches numbers between 200 and 249.25[0-5] catches numbers between 250 and 255. \d represents digits in regular expressions, same as [0-9] \\d{1, 2} catches any one or two-digit number (0|1)\\d{2} catches any three-digit number starting with 0 or 1. 2[0-4]\\d catches numbers between 200 and 249. 25[0-5] catches numbers between 250 and 255. Match the string with the Regex. In Java, this can be done using Pattern.matcher(). Return true if the string matches with the given regex, else return false. Below is the implementation of the above approach: Java // Java program to validate an IP address// using Regular Expression or ReGex import java.util.regex.*; class IPAddressValidation { // Function to validate the IPs address. public static boolean isValidIPAddress(String ip) { // Regex for digit from 0 to 255. String zeroTo255 = "(\\d{1,2}|(0|1)\\" + "d{2}|2[0-4]\\d|25[0-5])"; // Regex for a digit from 0 to 255 and // followed by a dot, repeat 4 times. // this is the regex to validate an IP address. String regex = zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the IP address is empty // return false if (ip == null) { return false; } // Pattern class contains matcher() method // to find matching between given IP address // and regular expression. Matcher m = p.matcher(ip); // Return if the IP address // matched the ReGex return m.matches(); } // Driver code public static void main(String args[]) { // Checking for True case. // Test Case: 1 System.out.println("Test Case 1:"); String str1 = "000.12.12.034"; System.out.println("Input: " + str1); System.out.println( "Output: " + isValidIPAddress(str1)); // Test Case: 2 System.out.println("\nTest Case 2:"); String str2 = "121.234.12.12"; System.out.println("Input: " + str2); System.out.println( "Output: " + isValidIPAddress(str2)); // Checking for False case. // Test Case: 3 System.out.println("\nTest Case 3:"); String str3 = "000.12.234.23.23"; System.out.println("Input: " + str3); System.out.println( "Output: " + isValidIPAddress(str3)); // Test Case: 4 System.out.println("\nTest Case 4:"); String str4 = "I.Am.not.an.ip"; System.out.println("Input: " + str4); System.out.println( "Output: " + isValidIPAddress(str4)); }} Test Case 1: Input: 000.12.12.034 Output: true Test Case 2: Input: 121.234.12.12 Output: true Test Case 3: Input: 000.12.234.23.23 Output: false Test Case 4: Input: I.Am.not.an.ip Output: false clintra java-regular-expression Technical Scripter 2019 Computer Networks Java Technical Scripter Java Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between TCP and UDP Types of Network Topology RSA Algorithm in Cryptography TCP Server-Client implementation in C Socket Programming in Python Arrays in Java Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Jun, 2021" }, { "code": null, "e": 350, "s": 52, "text": "Given an IP address, the task is to validate this IP address with the help of Regular Expressions.The IP address is a string in the form “A.B.C.D”, where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can’t be greater than 3.Examples: " }, { "code": null, "e": 527, "s": 350, "text": "Input: str = \"000.12.12.034\"\nOutput: True\n\nInput: str = \"000.12.234.23.23\"\nOutput: False\n\nInput: str = \"121.234.12.12\"\nOutput: True\n\nInput: str = \"I.Am.not.an.ip\"\nOutput: False" }, { "code": null, "e": 687, "s": 529, "text": "Approach: In this article, the IP address is validated with the help of Regular Expressions or Regex. Below are the steps to solve this problem using ReGex: " }, { "code": null, "e": 750, "s": 687, "text": "Get the string.Regular expression to validate an IP address: " }, { "code": null, "e": 766, "s": 750, "text": "Get the string." }, { "code": null, "e": 814, "s": 766, "text": "Regular expression to validate an IP address: " }, { "code": null, "e": 1063, "s": 814, "text": "// ReGex to numbers from 0 to 255\nzeroTo255 -> (\\\\d{1, 2}|(0|1)\\\\d{2}|2[0-4]\\\\d|25[0-5])\n\n// ReGex to validate complete IP address\nIPAddress -> zeroTo255 + \"\\\\.\" + zeroTo255 \n + \"\\\\.\" + zeroTo255 \n + \"\\\\.\" + zeroTo255;" }, { "code": null, "e": 1487, "s": 1063, "text": "where: \\d represents digits in regular expressions, same as [0-9]\\\\d{1, 2} catches any one or two-digit number(0|1)\\\\d{2} catches any three-digit number starting with 0 or 1.2[0-4]\\\\d catches numbers between 200 and 249.25[0-5] catches numbers between 250 and 255.Match the string with the Regex. In Java, this can be done using Pattern.matcher(). Return true if the string matches with the given regex, else return false." }, { "code": null, "e": 1752, "s": 1487, "text": "where: \\d represents digits in regular expressions, same as [0-9]\\\\d{1, 2} catches any one or two-digit number(0|1)\\\\d{2} catches any three-digit number starting with 0 or 1.2[0-4]\\\\d catches numbers between 200 and 249.25[0-5] catches numbers between 250 and 255." }, { "code": null, "e": 1811, "s": 1752, "text": "\\d represents digits in regular expressions, same as [0-9]" }, { "code": null, "e": 1857, "s": 1811, "text": "\\\\d{1, 2} catches any one or two-digit number" }, { "code": null, "e": 1922, "s": 1857, "text": "(0|1)\\\\d{2} catches any three-digit number starting with 0 or 1." }, { "code": null, "e": 1969, "s": 1922, "text": "2[0-4]\\\\d catches numbers between 200 and 249." }, { "code": null, "e": 2014, "s": 1969, "text": "25[0-5] catches numbers between 250 and 255." }, { "code": null, "e": 2100, "s": 2014, "text": "Match the string with the Regex. In Java, this can be done using Pattern.matcher(). " }, { "code": null, "e": 2175, "s": 2100, "text": "Return true if the string matches with the given regex, else return false." }, { "code": null, "e": 2227, "s": 2175, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2232, "s": 2227, "text": "Java" }, { "code": "// Java program to validate an IP address// using Regular Expression or ReGex import java.util.regex.*; class IPAddressValidation { // Function to validate the IPs address. public static boolean isValidIPAddress(String ip) { // Regex for digit from 0 to 255. String zeroTo255 = \"(\\\\d{1,2}|(0|1)\\\\\" + \"d{2}|2[0-4]\\\\d|25[0-5])\"; // Regex for a digit from 0 to 255 and // followed by a dot, repeat 4 times. // this is the regex to validate an IP address. String regex = zeroTo255 + \"\\\\.\" + zeroTo255 + \"\\\\.\" + zeroTo255 + \"\\\\.\" + zeroTo255; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the IP address is empty // return false if (ip == null) { return false; } // Pattern class contains matcher() method // to find matching between given IP address // and regular expression. Matcher m = p.matcher(ip); // Return if the IP address // matched the ReGex return m.matches(); } // Driver code public static void main(String args[]) { // Checking for True case. // Test Case: 1 System.out.println(\"Test Case 1:\"); String str1 = \"000.12.12.034\"; System.out.println(\"Input: \" + str1); System.out.println( \"Output: \" + isValidIPAddress(str1)); // Test Case: 2 System.out.println(\"\\nTest Case 2:\"); String str2 = \"121.234.12.12\"; System.out.println(\"Input: \" + str2); System.out.println( \"Output: \" + isValidIPAddress(str2)); // Checking for False case. // Test Case: 3 System.out.println(\"\\nTest Case 3:\"); String str3 = \"000.12.234.23.23\"; System.out.println(\"Input: \" + str3); System.out.println( \"Output: \" + isValidIPAddress(str3)); // Test Case: 4 System.out.println(\"\\nTest Case 4:\"); String str4 = \"I.Am.not.an.ip\"; System.out.println(\"Input: \" + str4); System.out.println( \"Output: \" + isValidIPAddress(str4)); }}", "e": 4455, "s": 2232, "text": null }, { "code": null, "e": 4652, "s": 4455, "text": "Test Case 1:\nInput: 000.12.12.034\nOutput: true\n\nTest Case 2:\nInput: 121.234.12.12\nOutput: true\n\nTest Case 3:\nInput: 000.12.234.23.23\nOutput: false\n\nTest Case 4:\nInput: I.Am.not.an.ip\nOutput: false" }, { "code": null, "e": 4662, "s": 4654, "text": "clintra" }, { "code": null, "e": 4686, "s": 4662, "text": "java-regular-expression" }, { "code": null, "e": 4710, "s": 4686, "text": "Technical Scripter 2019" }, { "code": null, "e": 4728, "s": 4710, "text": "Computer Networks" }, { "code": null, "e": 4733, "s": 4728, "text": "Java" }, { "code": null, "e": 4752, "s": 4733, "text": "Technical Scripter" }, { "code": null, "e": 4757, "s": 4752, "text": "Java" }, { "code": null, "e": 4775, "s": 4757, "text": "Computer Networks" }, { "code": null, "e": 4873, "s": 4775, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4905, "s": 4873, "text": "Differences between TCP and UDP" }, { "code": null, "e": 4931, "s": 4905, "text": "Types of Network Topology" }, { "code": null, "e": 4961, "s": 4931, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 4999, "s": 4961, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 5028, "s": 4999, "text": "Socket Programming in Python" }, { "code": null, "e": 5043, "s": 5028, "text": "Arrays in Java" }, { "code": null, "e": 5079, "s": 5043, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 5123, "s": 5079, "text": "Split() String method in Java with examples" }, { "code": null, "e": 5148, "s": 5123, "text": "Reverse a string in Java" } ]
Python pytz
13 Jan, 2021 Pytz brings the Olson tz database into Python and thus supports almost all time zones. This module serves the date-time conversion functionalities and helps user serving international client’s base. It enables time-zone calculations in our Python applications and also allows us to create timezone aware datetime instances. Python pytz module can be installed in the given way. Using command line: pip install pytz Using tarball, run the following command as an administrative user: python setup.py install Using setuptools, the latest version will be downloaded for you from the Python package index: easy_install --upgrade pytz By using astimezone() function we can convert the time into a different timezone. Syntax: astimezone(t) Parameter: t is time to be converted Return: Converted timezone Example: Python3 from datetime import datetimefrom pytz import timezone format = "%Y-%m-%d %H:%M:%S %Z%z" # Current time in UTCnow_utc = datetime.now(timezone('UTC'))print(now_utc.strftime(format)) # Convert to Asia/Kolkata time zonenow_asia = now_utc.astimezone(timezone('Asia/Kolkata'))print(now_asia.strftime(format)) Output 2020-12-30 04:38:16 UTC+0000 2020-12-30 10:08:16 IST+0530 There are some attributes in pytz module to help us find the supported timezone strings. These attributes will help understand this module better. all_timezones It returns the list all the available timezones with pytz.all_timezones: Python3 import pytz print('the supported timezones by the pytz module:', pytz.all_timezones, '\n') Output: The above output is showing some values, because the list is very large. all_timezones_set It returns the set of all the available timezones with pytz.all_timezones_set: Python3 import pytz print('all the supported timezones set:', pytz.all_timezones_set, '\n') Output The output order will be different in your system because it is a set. Common_timezones, Common_timezones_set It returns the list and set of commonly used timezones with pytz.common_timezones, pytz.common_timezones_set. Python3 import pytz print('Commonly used time-zones:', pytz.common_timezones, '\n') print('Commonly used time-zones-set:', pytz.common_timezones_set, '\n') Output country_names It returns a dict of country ISO Alpha-2 Code and country name as a key-value pair. Python3 import pytz print('country_names =') for key, val in pytz.country_names.items(): print(key, '=', val, end=',') print('\n')print('equivalent country name to the input code: =', pytz.country_names['IN']) Output country_names =AD = Andorra,AE = United Arab Emirates,TD = Chad,....,ZA = South Africa,ZM = Zambia,ZW = Zimbabwe,equivalent country name to the input code: India country_timezones It returns a dictionary of country ISO Alpha-2 Code as key and list of supported time-zones for a particular input key (country code) as value Python3 import pytz print('country_timezones =') for key, val in pytz.country_timezones.items(): print(key, '=', val, end=',') print('\n')print('Time-zones supported by Antartica =', pytz.country_timezones['AQ']) Output country_timezones =AD = [‘Europe/Andorra’],AE = [‘Asia/Dubai’],AF = [‘Asia/Kabul’],.....,ZM = [‘Africa/Lusaka’],ZW = [‘Africa/Harare’],Time-zones supported by Antartica = [‘Antarctica/McMurdo’, ‘Antarctica/Casey’, ‘Antarctica/Davis’, ‘Antarctica/DumontDUrville’, ‘Antarctica/Mawson’, ‘Antarctica/Palmer’, ‘Antarctica/Rothera’, ‘Antarctica/Syowa’, ‘Antarctica/Troll’, ‘Antarctica/Vostok’] Given below are certain examples to show how this module can be put to use. Example 1: creating datetime instance with timezone information. Python3 # import the modulesimport pytzimport datetimefrom datetime import datetime # getting utc timezoneutc = pytz.utc # getting timezone by namekiev_tz = pytz.timezone('Europe/Kiev')print('UTC Time =', datetime.now(tz=utc))print('IST Time =', datetime.now(tz=kiev_tz)) Output UTC Time = 2020-12-15 08:23:17.063960+00:00 IST Time = 2020-12-15 10:23:17.063988+02:00 Example 2: Python3 # import the modulesimport pytzimport datetime d = datetime.datetime(1984, 1, 10, 23, 30) # strftime method allows you to print a string # formatted using a series of formatting directivesd1 = d.strftime("%B %d, %Y") # isoformat method used for quickly generating # an ISO 8601 formatted date/timed2 = d.isoformat()print(d1)print(d2) Output January 10, 1984 1984-01-10T23:30:00 localize() is the correct function to use for creating datetime aware objects with an initial fixed datetime value. The resulting datetime aware object will have the original datetime value. This function is provided by python library. pytz.localize() is useful for making a naive timezone aware. it is useful when a front-end client sends a datetime to the backend to be treated as a particular timezone (usually UTC). Example : Python3 import pytzimport datetimefrom datetime import datetime # using localize() function, my system is on IST timezoneist = pytz.timezone('Asia/Kolkata')utc = pytz.utclocal_datetime = ist.localize(datetime.now()) print('IST Current Time =', local_datetime.strftime('%Y-%m-%d %H:%M:%S %Z%z'))print('Wrong UTC Current Time =', utc.localize( datetime.now()).strftime('%Y-%m-%d %H:%M:%S %Z%z')) Output IST Current Time = 2020-12-15 08:49:56 IST+0530 Wrong UTC Current Time = 2020-12-15 08:49:56 UTC+0000 Example Python3 from datetime import datetimefrom pytz import timezone # Set the time to noon on 2019-08-19naive = datetime(2019, 8, 19, 12, 0) # Let's treat this time as being in the UTC timezoneaware = timezone('UTC').localize(naive)print(aware) Output 2019-08-19 12:00:00+00:00 Picked python-modules Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Get unique values from a list Defaultdict in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jan, 2021" }, { "code": null, "e": 353, "s": 28, "text": "Pytz brings the Olson tz database into Python and thus supports almost all time zones. This module serves the date-time conversion functionalities and helps user serving international client’s base. It enables time-zone calculations in our Python applications and also allows us to create timezone aware datetime instances. " }, { "code": null, "e": 407, "s": 353, "text": "Python pytz module can be installed in the given way." }, { "code": null, "e": 427, "s": 407, "text": "Using command line:" }, { "code": null, "e": 444, "s": 427, "text": "pip install pytz" }, { "code": null, "e": 512, "s": 444, "text": "Using tarball, run the following command as an administrative user:" }, { "code": null, "e": 536, "s": 512, "text": "python setup.py install" }, { "code": null, "e": 631, "s": 536, "text": "Using setuptools, the latest version will be downloaded for you from the Python package index:" }, { "code": null, "e": 659, "s": 631, "text": "easy_install --upgrade pytz" }, { "code": null, "e": 741, "s": 659, "text": "By using astimezone() function we can convert the time into a different timezone." }, { "code": null, "e": 763, "s": 741, "text": "Syntax: astimezone(t)" }, { "code": null, "e": 800, "s": 763, "text": "Parameter: t is time to be converted" }, { "code": null, "e": 827, "s": 800, "text": "Return: Converted timezone" }, { "code": null, "e": 837, "s": 827, "text": "Example: " }, { "code": null, "e": 845, "s": 837, "text": "Python3" }, { "code": "from datetime import datetimefrom pytz import timezone format = \"%Y-%m-%d %H:%M:%S %Z%z\" # Current time in UTCnow_utc = datetime.now(timezone('UTC'))print(now_utc.strftime(format)) # Convert to Asia/Kolkata time zonenow_asia = now_utc.astimezone(timezone('Asia/Kolkata'))print(now_asia.strftime(format))", "e": 1152, "s": 845, "text": null }, { "code": null, "e": 1159, "s": 1152, "text": "Output" }, { "code": null, "e": 1189, "s": 1159, "text": "2020-12-30 04:38:16 UTC+0000 " }, { "code": null, "e": 1218, "s": 1189, "text": "2020-12-30 10:08:16 IST+0530" }, { "code": null, "e": 1365, "s": 1218, "text": "There are some attributes in pytz module to help us find the supported timezone strings. These attributes will help understand this module better." }, { "code": null, "e": 1379, "s": 1365, "text": "all_timezones" }, { "code": null, "e": 1452, "s": 1379, "text": "It returns the list all the available timezones with pytz.all_timezones:" }, { "code": null, "e": 1460, "s": 1452, "text": "Python3" }, { "code": "import pytz print('the supported timezones by the pytz module:', pytz.all_timezones, '\\n')", "e": 1559, "s": 1460, "text": null }, { "code": null, "e": 1567, "s": 1559, "text": "Output:" }, { "code": null, "e": 1640, "s": 1567, "text": "The above output is showing some values, because the list is very large." }, { "code": null, "e": 1659, "s": 1640, "text": " all_timezones_set" }, { "code": null, "e": 1738, "s": 1659, "text": "It returns the set of all the available timezones with pytz.all_timezones_set:" }, { "code": null, "e": 1746, "s": 1738, "text": "Python3" }, { "code": "import pytz print('all the supported timezones set:', pytz.all_timezones_set, '\\n')", "e": 1838, "s": 1746, "text": null }, { "code": null, "e": 1845, "s": 1838, "text": "Output" }, { "code": null, "e": 1916, "s": 1845, "text": "The output order will be different in your system because it is a set." }, { "code": null, "e": 1956, "s": 1916, "text": "Common_timezones, Common_timezones_set " }, { "code": null, "e": 2066, "s": 1956, "text": "It returns the list and set of commonly used timezones with pytz.common_timezones, pytz.common_timezones_set." }, { "code": null, "e": 2074, "s": 2066, "text": "Python3" }, { "code": "import pytz print('Commonly used time-zones:', pytz.common_timezones, '\\n') print('Commonly used time-zones-set:', pytz.common_timezones_set, '\\n')", "e": 2235, "s": 2074, "text": null }, { "code": null, "e": 2242, "s": 2235, "text": "Output" }, { "code": null, "e": 2257, "s": 2242, "text": "country_names " }, { "code": null, "e": 2341, "s": 2257, "text": "It returns a dict of country ISO Alpha-2 Code and country name as a key-value pair." }, { "code": null, "e": 2349, "s": 2341, "text": "Python3" }, { "code": "import pytz print('country_names =') for key, val in pytz.country_names.items(): print(key, '=', val, end=',') print('\\n')print('equivalent country name to the input code: =', pytz.country_names['IN'])", "e": 2568, "s": 2349, "text": null }, { "code": null, "e": 2575, "s": 2568, "text": "Output" }, { "code": null, "e": 2738, "s": 2575, "text": "country_names =AD = Andorra,AE = United Arab Emirates,TD = Chad,....,ZA = South Africa,ZM = Zambia,ZW = Zimbabwe,equivalent country name to the input code: India" }, { "code": null, "e": 2757, "s": 2738, "text": " country_timezones" }, { "code": null, "e": 2900, "s": 2757, "text": "It returns a dictionary of country ISO Alpha-2 Code as key and list of supported time-zones for a particular input key (country code) as value" }, { "code": null, "e": 2908, "s": 2900, "text": "Python3" }, { "code": "import pytz print('country_timezones =') for key, val in pytz.country_timezones.items(): print(key, '=', val, end=',') print('\\n')print('Time-zones supported by Antartica =', pytz.country_timezones['AQ'])", "e": 3125, "s": 2908, "text": null }, { "code": null, "e": 3132, "s": 3125, "text": "Output" }, { "code": null, "e": 3520, "s": 3132, "text": "country_timezones =AD = [‘Europe/Andorra’],AE = [‘Asia/Dubai’],AF = [‘Asia/Kabul’],.....,ZM = [‘Africa/Lusaka’],ZW = [‘Africa/Harare’],Time-zones supported by Antartica = [‘Antarctica/McMurdo’, ‘Antarctica/Casey’, ‘Antarctica/Davis’, ‘Antarctica/DumontDUrville’, ‘Antarctica/Mawson’, ‘Antarctica/Palmer’, ‘Antarctica/Rothera’, ‘Antarctica/Syowa’, ‘Antarctica/Troll’, ‘Antarctica/Vostok’]" }, { "code": null, "e": 3596, "s": 3520, "text": "Given below are certain examples to show how this module can be put to use." }, { "code": null, "e": 3661, "s": 3596, "text": "Example 1: creating datetime instance with timezone information." }, { "code": null, "e": 3669, "s": 3661, "text": "Python3" }, { "code": "# import the modulesimport pytzimport datetimefrom datetime import datetime # getting utc timezoneutc = pytz.utc # getting timezone by namekiev_tz = pytz.timezone('Europe/Kiev')print('UTC Time =', datetime.now(tz=utc))print('IST Time =', datetime.now(tz=kiev_tz))", "e": 3937, "s": 3669, "text": null }, { "code": null, "e": 3944, "s": 3937, "text": "Output" }, { "code": null, "e": 3989, "s": 3944, "text": "UTC Time = 2020-12-15 08:23:17.063960+00:00 " }, { "code": null, "e": 4033, "s": 3989, "text": "IST Time = 2020-12-15 10:23:17.063988+02:00" }, { "code": null, "e": 4045, "s": 4033, "text": "Example 2: " }, { "code": null, "e": 4053, "s": 4045, "text": "Python3" }, { "code": "# import the modulesimport pytzimport datetime d = datetime.datetime(1984, 1, 10, 23, 30) # strftime method allows you to print a string # formatted using a series of formatting directivesd1 = d.strftime(\"%B %d, %Y\") # isoformat method used for quickly generating # an ISO 8601 formatted date/timed2 = d.isoformat()print(d1)print(d2)", "e": 4392, "s": 4053, "text": null }, { "code": null, "e": 4399, "s": 4392, "text": "Output" }, { "code": null, "e": 4417, "s": 4399, "text": "January 10, 1984 " }, { "code": null, "e": 4437, "s": 4417, "text": "1984-01-10T23:30:00" }, { "code": null, "e": 4857, "s": 4437, "text": "localize() is the correct function to use for creating datetime aware objects with an initial fixed datetime value. The resulting datetime aware object will have the original datetime value. This function is provided by python library. pytz.localize() is useful for making a naive timezone aware. it is useful when a front-end client sends a datetime to the backend to be treated as a particular timezone (usually UTC)." }, { "code": null, "e": 4867, "s": 4857, "text": "Example :" }, { "code": null, "e": 4875, "s": 4867, "text": "Python3" }, { "code": "import pytzimport datetimefrom datetime import datetime # using localize() function, my system is on IST timezoneist = pytz.timezone('Asia/Kolkata')utc = pytz.utclocal_datetime = ist.localize(datetime.now()) print('IST Current Time =', local_datetime.strftime('%Y-%m-%d %H:%M:%S %Z%z'))print('Wrong UTC Current Time =', utc.localize( datetime.now()).strftime('%Y-%m-%d %H:%M:%S %Z%z'))", "e": 5268, "s": 4875, "text": null }, { "code": null, "e": 5275, "s": 5268, "text": "Output" }, { "code": null, "e": 5324, "s": 5275, "text": "IST Current Time = 2020-12-15 08:49:56 IST+0530 " }, { "code": null, "e": 5378, "s": 5324, "text": "Wrong UTC Current Time = 2020-12-15 08:49:56 UTC+0000" }, { "code": null, "e": 5386, "s": 5378, "text": "Example" }, { "code": null, "e": 5394, "s": 5386, "text": "Python3" }, { "code": "from datetime import datetimefrom pytz import timezone # Set the time to noon on 2019-08-19naive = datetime(2019, 8, 19, 12, 0) # Let's treat this time as being in the UTC timezoneaware = timezone('UTC').localize(naive)print(aware)", "e": 5630, "s": 5394, "text": null }, { "code": null, "e": 5637, "s": 5630, "text": "Output" }, { "code": null, "e": 5663, "s": 5637, "text": "2019-08-19 12:00:00+00:00" }, { "code": null, "e": 5670, "s": 5663, "text": "Picked" }, { "code": null, "e": 5685, "s": 5670, "text": "python-modules" }, { "code": null, "e": 5709, "s": 5685, "text": "Technical Scripter 2020" }, { "code": null, "e": 5716, "s": 5709, "text": "Python" }, { "code": null, "e": 5735, "s": 5716, "text": "Technical Scripter" }, { "code": null, "e": 5833, "s": 5735, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5865, "s": 5833, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5892, "s": 5865, "text": "Python Classes and Objects" }, { "code": null, "e": 5913, "s": 5892, "text": "Python OOPs Concepts" }, { "code": null, "e": 5936, "s": 5913, "text": "Introduction To PYTHON" }, { "code": null, "e": 5992, "s": 5936, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 6034, "s": 5992, "text": "Check if element exists in list in Python" }, { "code": null, "e": 6065, "s": 6034, "text": "Python | os.path.join() method" }, { "code": null, "e": 6107, "s": 6065, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 6146, "s": 6107, "text": "Python | Get unique values from a list" } ]
Python Data Type - GeeksforGeeks
26 Oct, 2020 A hash function takes a message of arbitrary length and generates a fixed length code.A hash function takes a message of fixed length and generates a code of variable length.A hash function may give the same hash value for distinct messages. A hash function takes a message of arbitrary length and generates a fixed length code. A hash function takes a message of fixed length and generates a code of variable length. A hash function may give the same hash value for distinct messages. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 29577, "s": 29549, "text": "\n26 Oct, 2020" }, { "code": null, "e": 29819, "s": 29577, "text": "A hash function takes a message of arbitrary length and generates a fixed length code.A hash function takes a message of fixed length and generates a code of variable length.A hash function may give the same hash value for distinct messages." }, { "code": null, "e": 29906, "s": 29819, "text": "A hash function takes a message of arbitrary length and generates a fixed length code." }, { "code": null, "e": 29995, "s": 29906, "text": "A hash function takes a message of fixed length and generates a code of variable length." }, { "code": null, "e": 30063, "s": 29995, "text": "A hash function may give the same hash value for distinct messages." } ]
How to transform a JavaScript iterator into an array?
11 Aug, 2021 The task is to convert an iterator into an array This can be performed by iterating each value of the iterator and storing the value into another array Method: To make an iterator for an array: const it = array[Symbol.iterator](); So first we make an iterator for the “array” named “it”. After creating the iterator we iterate to each value stored in that iterator and push it in another array named “p” with the use of the following code p.push(word) where the word is the value corresponding to the array elements stored in the iterator. After iterating through each of the element we get our final array where all the values of the iterator get stored in p. Example: javascript <script> const array = ['Geeks', 'for', 'Geeks']; p=[] const it = array[Symbol.iterator](); document.write(it); document.write("<br>"); for(let word of it) { p.push(word) }document.write("After the conversion the array becomes");document.write("<br>");document.write(p);</script> Output: [object Array Iterator] After the conversion the array becomes ["Geeks", "for", "Geeks"] sweetyty javascript-array Picked JavaScript 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": "\n11 Aug, 2021" }, { "code": null, "e": 77, "s": 28, "text": "The task is to convert an iterator into an array" }, { "code": null, "e": 181, "s": 77, "text": "This can be performed by iterating each value of the iterator and storing the value into another array " }, { "code": null, "e": 190, "s": 181, "text": "Method: " }, { "code": null, "e": 224, "s": 190, "text": "To make an iterator for an array:" }, { "code": null, "e": 262, "s": 224, "text": "const it = array[Symbol.iterator](); " }, { "code": null, "e": 471, "s": 262, "text": "So first we make an iterator for the “array” named “it”. After creating the iterator we iterate to each value stored in that iterator and push it in another array named “p” with the use of the following code" }, { "code": null, "e": 485, "s": 471, "text": "p.push(word) " }, { "code": null, "e": 694, "s": 485, "text": "where the word is the value corresponding to the array elements stored in the iterator. After iterating through each of the element we get our final array where all the values of the iterator get stored in p." }, { "code": null, "e": 705, "s": 694, "text": "Example: " }, { "code": null, "e": 716, "s": 705, "text": "javascript" }, { "code": "<script> const array = ['Geeks', 'for', 'Geeks']; p=[] const it = array[Symbol.iterator](); document.write(it); document.write(\"<br>\"); for(let word of it) { p.push(word) }document.write(\"After the conversion the array becomes\");document.write(\"<br>\");document.write(p);</script>", "e": 1027, "s": 716, "text": null }, { "code": null, "e": 1035, "s": 1027, "text": "Output:" }, { "code": null, "e": 1124, "s": 1035, "text": "[object Array Iterator]\nAfter the conversion the array becomes\n[\"Geeks\", \"for\", \"Geeks\"]" }, { "code": null, "e": 1133, "s": 1124, "text": "sweetyty" }, { "code": null, "e": 1150, "s": 1133, "text": "javascript-array" }, { "code": null, "e": 1157, "s": 1150, "text": "Picked" }, { "code": null, "e": 1168, "s": 1157, "text": "JavaScript" }, { "code": null, "e": 1185, "s": 1168, "text": "Web Technologies" } ]
How to check if a C# list is empty?
Use the Any method to find whether the list is empty or not. Set the list − var subjects = new List<string>(); subjects.Add("Maths"); subjects.Add("Java"); subjects.Add("English"); subjects.Add("Science"); subjects.Add("Physics"); subjects.Add("Chemistry"); Now set the following condition to check whether the list is empty or not − bool isEmpty = !subjects.Any(); if(isEmpty) { Console.WriteLine("Empty"); }else { Console.WriteLine("List is not empty"); } The following is the complete code − Live Demo using System; using System.Collections.Generic; using System.Linq; public class Demo { public static void Main(string[] args) { var subjects = new List<string>(); subjects.Add("Maths"); subjects.Add("Java"); subjects.Add("English"); subjects.Add("Science"); subjects.Add("Physics"); subjects.Add("Chemistry"); foreach (var sub in subjects) { Console.WriteLine(sub); } bool isEmpty = !subjects.Any(); if(isEmpty) { Console.WriteLine("Empty"); } else { Console.WriteLine("List is not empty"); } } }
[ { "code": null, "e": 1248, "s": 1187, "text": "Use the Any method to find whether the list is empty or not." }, { "code": null, "e": 1263, "s": 1248, "text": "Set the list −" }, { "code": null, "e": 1445, "s": 1263, "text": "var subjects = new List<string>();\nsubjects.Add(\"Maths\");\nsubjects.Add(\"Java\");\nsubjects.Add(\"English\");\nsubjects.Add(\"Science\");\nsubjects.Add(\"Physics\");\nsubjects.Add(\"Chemistry\");" }, { "code": null, "e": 1521, "s": 1445, "text": "Now set the following condition to check whether the list is empty or not −" }, { "code": null, "e": 1663, "s": 1521, "text": "bool isEmpty = !subjects.Any();\nif(isEmpty) {\n Console.WriteLine(\"Empty\");\n }else {\n Console.WriteLine(\"List is not empty\");\n }" }, { "code": null, "e": 1700, "s": 1663, "text": "The following is the complete code −" }, { "code": null, "e": 1711, "s": 1700, "text": " Live Demo" }, { "code": null, "e": 2322, "s": 1711, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Demo {\n public static void Main(string[] args) {\n var subjects = new List<string>();\n subjects.Add(\"Maths\");\n subjects.Add(\"Java\");\n subjects.Add(\"English\");\n subjects.Add(\"Science\");\n subjects.Add(\"Physics\");\n subjects.Add(\"Chemistry\");\n\n foreach (var sub in subjects) {\n Console.WriteLine(sub);\n }\n\n bool isEmpty = !subjects.Any();\n if(isEmpty) {\n Console.WriteLine(\"Empty\");\n } else {\n Console.WriteLine(\"List is not empty\");\n }\n }\n}" } ]
Which characters are valid in CSS class names/selectors?
26 Sep, 2021 It is very easy to choose a valid class name or selectors in CSS just follow the rule. A valid name should start with an underscore (_), a hyphen (-) or a letter (a-z)/(A-Z) which is followed by any numbers, hyphens, underscores, letters. It cannot start with a digit, starting with the digit is acceptable by HTML5 but not acceptable by CSS. Two hyphens followed by a number is valid. Example 1: This example describes the list of valid id selectors using CSS. html <!DOCTYPE html><html> <head> <title> Valid id Selectors </title> <style> #main { border:2px solid green; text-align:center; } #1st { color:green; font-size:30px; } #_st { color:green; font-size:30px; } #-st { color:green; font-size:30px; } #st { color:green; font-size:30px; } #St { color:green; font-size:30px; } #--1 { color:green; font-size:30px; } #s { color:green; font-size:30px; } #_1 { color:green; font-size:30px; } #- { color:green; font-size:30px; } #-- { color:green; font-size:30px; } #_ { color:green; font-size:30px; } #__ { color:green; font-size:30px; } </style></head> <body> <div id="main"> <div id="1st">Starting with digit GeeksforGeeks</div> <div id="_st">Starting with underscore</div> <div id="-st">Starting with hyphen</div> <div id="st">Starting with lower case alphabet</div> <div id="St">Starting with upper case alphabet</div> <div id="--1">Starting with double hyphen</div> <div id="s">only one alphabet</div> <div id="_1">underscore before digit</div> <div id="-">only hyphen</div> <div id="--">double hyphen</div> <div id="_">only underscore</div> <div id="__">double underscore</div> </div></body> </html> Output: Example 2: This example describes the list of valid class selectors using CSS. html <!DOCTYPE html><html> <head> <style> .main { border:2px solid green; } .1st { color:green; font-size:30px; background-color:#9400D3; } ._st { color:green; font-size:30px; background-color:#4B0082; } .-st { color:green; font-size:30px; background-color:#0000FF; } .st { color:green; font-size:30px; background-color:##00FF00; } .St { color:green; font-size:30px; background-color:#FFFF00; } .--1st { color:green; font-size:30px; background-color:#FF7F00; } .s { color:green; font-size:30px; background-color:#FF0000; } ._1 { color:green; font-size:30px; background-color:#9400D3; } .- { color:green; font-size:30px; background-color:#4B0082; } .-- { color:green; font-size:30px; background-color:#0000FF; } ._ { color:green; font-size:30px; background-color:##00FF00; } .__{ color:green; font-size:30px; background-color:#FFFF00; } </style></head> <body> <div class="main"> <h1 style="color:green; text-align:center;"> GeeksforGeeks </h1> <hr> <div class="1st">Starting with digit </div> <div class="_st">Starting with underscore</div> <div class="-st">Starting with hyphen</div> <div class="st">Starting with lower case alphabet</div> <div class="St">Starting with upper case alphabet</div> <div class="--1st">Starting with double hyphen</div> <div class="s">only one alphabet</div> <div class="_1">underscore before digit</div> <div class="-">only hyphen</div> <div class="--">double hyphen</div> <div class="_">only underscore</div> <div class="__">double underscore</div> </div></body> </html> Output: ManasChhabra2 anikaseth98 CSS-Misc Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Sep, 2021" }, { "code": null, "e": 117, "s": 28, "text": "It is very easy to choose a valid class name or selectors in CSS just follow the rule. " }, { "code": null, "e": 269, "s": 117, "text": "A valid name should start with an underscore (_), a hyphen (-) or a letter (a-z)/(A-Z) which is followed by any numbers, hyphens, underscores, letters." }, { "code": null, "e": 373, "s": 269, "text": "It cannot start with a digit, starting with the digit is acceptable by HTML5 but not acceptable by CSS." }, { "code": null, "e": 416, "s": 373, "text": "Two hyphens followed by a number is valid." }, { "code": null, "e": 494, "s": 416, "text": "Example 1: This example describes the list of valid id selectors using CSS. " }, { "code": null, "e": 499, "s": 494, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> Valid id Selectors </title> <style> #main { border:2px solid green; text-align:center; } #1st { color:green; font-size:30px; } #_st { color:green; font-size:30px; } #-st { color:green; font-size:30px; } #st { color:green; font-size:30px; } #St { color:green; font-size:30px; } #--1 { color:green; font-size:30px; } #s { color:green; font-size:30px; } #_1 { color:green; font-size:30px; } #- { color:green; font-size:30px; } #-- { color:green; font-size:30px; } #_ { color:green; font-size:30px; } #__ { color:green; font-size:30px; } </style></head> <body> <div id=\"main\"> <div id=\"1st\">Starting with digit GeeksforGeeks</div> <div id=\"_st\">Starting with underscore</div> <div id=\"-st\">Starting with hyphen</div> <div id=\"st\">Starting with lower case alphabet</div> <div id=\"St\">Starting with upper case alphabet</div> <div id=\"--1\">Starting with double hyphen</div> <div id=\"s\">only one alphabet</div> <div id=\"_1\">underscore before digit</div> <div id=\"-\">only hyphen</div> <div id=\"--\">double hyphen</div> <div id=\"_\">only underscore</div> <div id=\"__\">double underscore</div> </div></body> </html>", "e": 2224, "s": 499, "text": null }, { "code": null, "e": 2234, "s": 2224, "text": "Output: " }, { "code": null, "e": 2315, "s": 2234, "text": "Example 2: This example describes the list of valid class selectors using CSS. " }, { "code": null, "e": 2320, "s": 2315, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <style> .main { border:2px solid green; } .1st { color:green; font-size:30px; background-color:#9400D3; } ._st { color:green; font-size:30px; background-color:#4B0082; } .-st { color:green; font-size:30px; background-color:#0000FF; } .st { color:green; font-size:30px; background-color:##00FF00; } .St { color:green; font-size:30px; background-color:#FFFF00; } .--1st { color:green; font-size:30px; background-color:#FF7F00; } .s { color:green; font-size:30px; background-color:#FF0000; } ._1 { color:green; font-size:30px; background-color:#9400D3; } .- { color:green; font-size:30px; background-color:#4B0082; } .-- { color:green; font-size:30px; background-color:#0000FF; } ._ { color:green; font-size:30px; background-color:##00FF00; } .__{ color:green; font-size:30px; background-color:#FFFF00; } </style></head> <body> <div class=\"main\"> <h1 style=\"color:green; text-align:center;\"> GeeksforGeeks </h1> <hr> <div class=\"1st\">Starting with digit </div> <div class=\"_st\">Starting with underscore</div> <div class=\"-st\">Starting with hyphen</div> <div class=\"st\">Starting with lower case alphabet</div> <div class=\"St\">Starting with upper case alphabet</div> <div class=\"--1st\">Starting with double hyphen</div> <div class=\"s\">only one alphabet</div> <div class=\"_1\">underscore before digit</div> <div class=\"-\">only hyphen</div> <div class=\"--\">double hyphen</div> <div class=\"_\">only underscore</div> <div class=\"__\">double underscore</div> </div></body> </html> ", "e": 4590, "s": 2320, "text": null }, { "code": null, "e": 4600, "s": 4590, "text": "Output: " }, { "code": null, "e": 4616, "s": 4602, "text": "ManasChhabra2" }, { "code": null, "e": 4628, "s": 4616, "text": "anikaseth98" }, { "code": null, "e": 4637, "s": 4628, "text": "CSS-Misc" }, { "code": null, "e": 4644, "s": 4637, "text": "Picked" }, { "code": null, "e": 4648, "s": 4644, "text": "CSS" }, { "code": null, "e": 4653, "s": 4648, "text": "HTML" }, { "code": null, "e": 4670, "s": 4653, "text": "Web Technologies" }, { "code": null, "e": 4675, "s": 4670, "text": "HTML" }, { "code": null, "e": 4773, "s": 4675, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4812, "s": 4773, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 4851, "s": 4812, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 4890, "s": 4851, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 4927, "s": 4890, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 4956, "s": 4927, "text": "Form validation using jQuery" }, { "code": null, "e": 4980, "s": 4956, "text": "REST API (Introduction)" }, { "code": null, "e": 5033, "s": 4980, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 5093, "s": 5033, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 5154, "s": 5093, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
How To Use Jupyter Notebook – An Ultimate Guide
28 Mar, 2022 The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more. Jupyter has support for over 40 different programming languages and Python is one of them. Python is a requirement (Python 3.3 or greater, or Python 2.7) for installing the Jupyter Notebook itself. Table Of Content Installation Starting Jupyter Notebook Creating a Notebook Hello World in Jupyter Notebook Cells in Jupyter Notebook Kernel Naming the notebook Notebook Extensions Install Python and Jupyter using the Anaconda Distribution, which includes Python, the Jupyter Notebook, and other commonly used packages for scientific computing and data science. You can download Anaconda’s latest Python3 version from here. Now, install the downloaded version of Anaconda. Installing Jupyter Notebook using pip: python3 -m pip install --upgrade pip python3 -m pip install jupyter To start the jupyter notebook, type the below command in the terminal. jupyter notebook This will print some information about the notebook server in your terminal, including the URL of the web application (by default, http://localhost:8888) and then open your default web browser to this URL. After the notebook is opened, you’ll see the Notebook Dashboard, which will show a list of the notebooks, files, and subdirectories in the directory where the notebook server was started. Most of the time, you will wish to start a notebook server in the highest level directory containing notebooks. Often this will be your home directory. To create a new notebook, click on the new button at the top right corner. Click it to open a drop-down list and then if you’ll click on Python3, it will open a new notebook. The web page should look like this: After successfully installing and creating a notebook in Jupyter Notebook, let’s see how to write code in it. Jupyter notebook provides a cell for writing code in it. The type of code depends on the type of notebook you created. For example, if you created a Python3 notebook then you can write Python3 code in the cell. Now, let’s add the following code – Python3 print("Hello World") To run a cell either click the run button or press shift ⇧ + enter ⏎ after selecting the cell you want to execute. After writing the above code in the jupyter notebook, the output was: Note: When a cell has executed the label on the left i.e. ln[] changes to ln[1]. If the cell is still under execution the label remains ln[*]. Cells can be considered as the body of the Jupyter. In the above screenshot, the box with the green outline is a cell. There are 3 types of cell: Code Markup Raw NBConverter This is where the code is typed and when executed the code will display the output below the cell. The type of code depends on the type of the notebook you have created. For example, if the notebook of Python3 is created then the code of Python3 can be added. Consider the below example, where a simple code of the Fibonacci series is created and this code also takes input from the user. Example: The tex bar in the above code is prompted for taking input from the user. The output of the above code is as follows: Output: Markdown is a popular markup language that is the superset of the HTML. Jupyter Notebook also supports markdown. The cell type can be changed to markdown using the cell menu. Adding Headers: Heading can be added by prefixing any line by single or multiple ‘#’ followed by space. Example: Output: Adding List: Adding List is really simple in Jupyter Notebook. The list can be added by using ‘*’ sign. And the Nested list can be created by using indentation. Example: Output: Adding Latex Equations: Latex expressions can be added by surrounding the latex code by ‘$’ and for writing the expressions in the middle, surrounds the latex code by ‘$$’. Example: Output: Adding Table: A table can be added by writing the content in the following format. Output: Note: The text can be made bold or italic by enclosing the text in ‘**’ and ‘*’ respectively. Raw cells are provided to write the output directly. This cell is not evaluated by Jupyter notebook. After passing through nbconvert the raw cells arrives in the destination folder without any modification. For example, one can write full Python into a raw cell that can only be rendered by Python only after conversion by nbconvert. A kernel runs behind every notebook. Whenever a cell is executed, the code inside the cell is executed within the kernel and the output is returned back to the cell to be displayed. The kernel continues to exist to the document as a whole and not for individual cells. For example, if a module is imported in one cell then, that module will be available for the whole document. See the below example for better understanding. Example: Note: The order of execution of each cell is stated to the left of the cell. In the above example, the cell with In[1] is executed first then the cell with In[2] is executed. Options for kernels: Jupyter Notebook provides various options for kernels. This can be useful if you want to reset things. The options are: Restart: This will restart the kernels i.e. clearing all the variables that were defined, clearing the modules that were imported, etc. Restart and Clear Output: This will do the same as above but will also clear all the output that was displayed below the cell. Restart and Run All: This is also the same as above but will also run all the cells in the top-down order. Interrupt: This option will interrupt the kernel execution. It can be useful in the case where the programs continue for execution or the kernel is stuck over some computation. When the notebook is created, Jupyter Notebook names the notebook as Untitled as default. However, the notebook can be renamed. To rename the notebook just click on the word Untitled. This will prompt a dialogue box titled Rename Notebook. Enter the valid name for your notebook in the text bar, then click ok. New functionality can be added to Jupyter through extensions. Extensions are javascript module. You can even write your own extension that can access the page’s DOM and the Jupyter Javascript API. Jupyter supports four types of extensions. Kernel IPyhton Kernel Notebook Notebook server Most of the extensions can be installed using Python’s pip tool. If an extension can not be installed using pip, then install the extension using the below command. jupyter nbextension install extension_name The above only installs the extension but does not enables it. To enable it type the below command in the terminal. jupyter nbextension enable extension_name varshagumber28 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Supervised and Unsupervised learning Decision Tree Introduction with example Search Algorithms in AI Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Mar, 2022" }, { "code": null, "e": 566, "s": 52, "text": "The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more. Jupyter has support for over 40 different programming languages and Python is one of them. Python is a requirement (Python 3.3 or greater, or Python 2.7) for installing the Jupyter Notebook itself." }, { "code": null, "e": 583, "s": 566, "text": "Table Of Content" }, { "code": null, "e": 596, "s": 583, "text": "Installation" }, { "code": null, "e": 622, "s": 596, "text": "Starting Jupyter Notebook" }, { "code": null, "e": 642, "s": 622, "text": "Creating a Notebook" }, { "code": null, "e": 674, "s": 642, "text": "Hello World in Jupyter Notebook" }, { "code": null, "e": 700, "s": 674, "text": "Cells in Jupyter Notebook" }, { "code": null, "e": 707, "s": 700, "text": "Kernel" }, { "code": null, "e": 727, "s": 707, "text": "Naming the notebook" }, { "code": null, "e": 747, "s": 727, "text": "Notebook Extensions" }, { "code": null, "e": 1078, "s": 747, "text": "Install Python and Jupyter using the Anaconda Distribution, which includes Python, the Jupyter Notebook, and other commonly used packages for scientific computing and data science. You can download Anaconda’s latest Python3 version from here. Now, install the downloaded version of Anaconda. Installing Jupyter Notebook using pip:" }, { "code": null, "e": 1146, "s": 1078, "text": "python3 -m pip install --upgrade pip\npython3 -m pip install jupyter" }, { "code": null, "e": 1217, "s": 1146, "text": "To start the jupyter notebook, type the below command in the terminal." }, { "code": null, "e": 1234, "s": 1217, "text": "jupyter notebook" }, { "code": null, "e": 1782, "s": 1234, "text": "This will print some information about the notebook server in your terminal, including the URL of the web application (by default, http://localhost:8888) and then open your default web browser to this URL. After the notebook is opened, you’ll see the Notebook Dashboard, which will show a list of the notebooks, files, and subdirectories in the directory where the notebook server was started. Most of the time, you will wish to start a notebook server in the highest level directory containing notebooks. Often this will be your home directory. " }, { "code": null, "e": 1995, "s": 1782, "text": "To create a new notebook, click on the new button at the top right corner. Click it to open a drop-down list and then if you’ll click on Python3, it will open a new notebook. The web page should look like this: " }, { "code": null, "e": 2353, "s": 1995, "text": "After successfully installing and creating a notebook in Jupyter Notebook, let’s see how to write code in it. Jupyter notebook provides a cell for writing code in it. The type of code depends on the type of notebook you created. For example, if you created a Python3 notebook then you can write Python3 code in the cell. Now, let’s add the following code – " }, { "code": null, "e": 2361, "s": 2353, "text": "Python3" }, { "code": "print(\"Hello World\")", "e": 2382, "s": 2361, "text": null }, { "code": null, "e": 2711, "s": 2382, "text": "To run a cell either click the run button or press shift ⇧ + enter ⏎ after selecting the cell you want to execute. After writing the above code in the jupyter notebook, the output was: Note: When a cell has executed the label on the left i.e. ln[] changes to ln[1]. If the cell is still under execution the label remains ln[*]." }, { "code": null, "e": 2857, "s": 2711, "text": "Cells can be considered as the body of the Jupyter. In the above screenshot, the box with the green outline is a cell. There are 3 types of cell:" }, { "code": null, "e": 2862, "s": 2857, "text": "Code" }, { "code": null, "e": 2869, "s": 2862, "text": "Markup" }, { "code": null, "e": 2885, "s": 2869, "text": "Raw NBConverter" }, { "code": null, "e": 3411, "s": 2885, "text": "This is where the code is typed and when executed the code will display the output below the cell. The type of code depends on the type of the notebook you have created. For example, if the notebook of Python3 is created then the code of Python3 can be added. Consider the below example, where a simple code of the Fibonacci series is created and this code also takes input from the user. Example: The tex bar in the above code is prompted for taking input from the user. The output of the above code is as follows: Output: " }, { "code": null, "e": 4269, "s": 3411, "text": "Markdown is a popular markup language that is the superset of the HTML. Jupyter Notebook also supports markdown. The cell type can be changed to markdown using the cell menu. Adding Headers: Heading can be added by prefixing any line by single or multiple ‘#’ followed by space. Example: Output: Adding List: Adding List is really simple in Jupyter Notebook. The list can be added by using ‘*’ sign. And the Nested list can be created by using indentation. Example: Output: Adding Latex Equations: Latex expressions can be added by surrounding the latex code by ‘$’ and for writing the expressions in the middle, surrounds the latex code by ‘$$’. Example: Output: Adding Table: A table can be added by writing the content in the following format. Output: Note: The text can be made bold or italic by enclosing the text in ‘**’ and ‘*’ respectively." }, { "code": null, "e": 4603, "s": 4269, "text": "Raw cells are provided to write the output directly. This cell is not evaluated by Jupyter notebook. After passing through nbconvert the raw cells arrives in the destination folder without any modification. For example, one can write full Python into a raw cell that can only be rendered by Python only after conversion by nbconvert." }, { "code": null, "e": 5355, "s": 4603, "text": "A kernel runs behind every notebook. Whenever a cell is executed, the code inside the cell is executed within the kernel and the output is returned back to the cell to be displayed. The kernel continues to exist to the document as a whole and not for individual cells. For example, if a module is imported in one cell then, that module will be available for the whole document. See the below example for better understanding. Example: Note: The order of execution of each cell is stated to the left of the cell. In the above example, the cell with In[1] is executed first then the cell with In[2] is executed. Options for kernels: Jupyter Notebook provides various options for kernels. This can be useful if you want to reset things. The options are:" }, { "code": null, "e": 5491, "s": 5355, "text": "Restart: This will restart the kernels i.e. clearing all the variables that were defined, clearing the modules that were imported, etc." }, { "code": null, "e": 5618, "s": 5491, "text": "Restart and Clear Output: This will do the same as above but will also clear all the output that was displayed below the cell." }, { "code": null, "e": 5725, "s": 5618, "text": "Restart and Run All: This is also the same as above but will also run all the cells in the top-down order." }, { "code": null, "e": 5902, "s": 5725, "text": "Interrupt: This option will interrupt the kernel execution. It can be useful in the case where the programs continue for execution or the kernel is stuck over some computation." }, { "code": null, "e": 6214, "s": 5902, "text": "When the notebook is created, Jupyter Notebook names the notebook as Untitled as default. However, the notebook can be renamed. To rename the notebook just click on the word Untitled. This will prompt a dialogue box titled Rename Notebook. Enter the valid name for your notebook in the text bar, then click ok. " }, { "code": null, "e": 6454, "s": 6214, "text": "New functionality can be added to Jupyter through extensions. Extensions are javascript module. You can even write your own extension that can access the page’s DOM and the Jupyter Javascript API. Jupyter supports four types of extensions." }, { "code": null, "e": 6461, "s": 6454, "text": "Kernel" }, { "code": null, "e": 6476, "s": 6461, "text": "IPyhton Kernel" }, { "code": null, "e": 6485, "s": 6476, "text": "Notebook" }, { "code": null, "e": 6501, "s": 6485, "text": "Notebook server" }, { "code": null, "e": 6666, "s": 6501, "text": "Most of the extensions can be installed using Python’s pip tool. If an extension can not be installed using pip, then install the extension using the below command." }, { "code": null, "e": 6709, "s": 6666, "text": "jupyter nbextension install extension_name" }, { "code": null, "e": 6825, "s": 6709, "text": "The above only installs the extension but does not enables it. To enable it type the below command in the terminal." }, { "code": null, "e": 6867, "s": 6825, "text": "jupyter nbextension enable extension_name" }, { "code": null, "e": 6882, "s": 6867, "text": "varshagumber28" }, { "code": null, "e": 6899, "s": 6882, "text": "Machine Learning" }, { "code": null, "e": 6906, "s": 6899, "text": "Python" }, { "code": null, "e": 6923, "s": 6906, "text": "Machine Learning" }, { "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": 7044, "s": 7021, "text": "ML | Linear Regression" }, { "code": null, "e": 7067, "s": 7044, "text": "Reinforcement learning" }, { "code": null, "e": 7104, "s": 7067, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 7144, "s": 7104, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 7168, "s": 7144, "text": "Search Algorithms in AI" }, { "code": null, "e": 7196, "s": 7168, "text": "Read JSON file using Python" }, { "code": null, "e": 7246, "s": 7196, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 7268, "s": 7246, "text": "Python map() function" } ]
Programs for printing pyramid patterns in Java
30 Jun, 2022 This article is aimed at giving a Java implementation for pattern printing. Simple pyramid pattern Java import java.io.*; // Java code to demonstrate star patternspublic class GeeksForGeeks{ // Function to demonstrate printing pattern public static void printStars(int n) { int i, j; // outer loop to handle number of rows // n in this case for(i=0; i<n; i++) { // inner loop to handle number of columns // values changing acc. to outer loop for(j=0; j<=i; j++) { // printing stars System.out.print("* "); } // ending line after each row System.out.println(); } } // Driver Function public static void main(String args[]) { int n = 5; printStars(n); }} * * * * * * * * * * * * * * * Java // java program to print simple pyramid pattern using while// loop import java.io.*; class GFG { public static void main(String[] args) { int r = 1, c = 0, n = 5; // the while loop check the conditions until the // condition is false. if it is true then enter in // to loop and execute the statements while (r <= n) { while (c <= r - 1) { // printing the required pattern System.out.print("* "); c++; } r++; c = 0; // new line after each row System.out.println(); } }} // this code is contributed by gangarajula laxmi * * * * * * * * * * * * * * * After 180 degree rotation Java import java.io.*; // Java code to demonstrate star patternpublic class GeeksForGeeks{ // Function to demonstrate printing pattern public static void printStars(int n) { int i, j; // outer loop to handle number of rows // n in this case for(i=0; i<n; i++) { // inner loop to handle number spaces // values changing acc. to requirement for(j=2*(n-i); j>=0; j--) { // printing spaces System.out.print(" "); } // inner loop to handle number of columns // values changing acc. to outer loop for(j=0; j<=i; j++) { // printing stars System.out.print("* "); } // ending line after each row System.out.println(); } } // Driver Function public static void main(String args[]) { int n = 5; printStars(n); }} * * * * * * * * * * * * * * * Printing Triangle Java import java.io.*; // Java code to demonstrate star patternpublic class GeeksForGeeks{ // Function to demonstrate printing pattern public static void printTriangle(int n) { // outer loop to handle number of rows // n in this case for (int i=0; i<n; i++) { // inner loop to handle number spaces // values changing acc. to requirement for (int j=n-i; j>1; j--) { // printing spaces System.out.print(" "); } // inner loop to handle number of columns // values changing acc. to outer loop for (int j=0; j<=i; j++ ) { // printing stars System.out.print("* "); } // ending line after each row System.out.println(); } } // Driver Function public static void main(String args[]) { int n = 5; printTriangle(n); }} * * * * * * * * * * * * * * * Print Reverse Of Pyramid Java //MainFunctionpublic class ReversePyramid{ public static void main(String[] args) { int rows = 6; // Number of Rows we want to print //Printing the pattern for (int i = 1; i <= rows; i++) { for (int j = 1; j < i; j++) { System.out.print(" "); } for (int j = i; j <= rows; j++) { System.out.print(j+" "); } System.out.println(); } } } 1 2 3 4 5 6 2 3 4 5 6 3 4 5 6 4 5 6 5 6 6 Pattern of Number with Mirror Image Java //MainFunctionpublic class ReversePattern{ public static void main(String[] args) { int rows = 7; // Number of Rows we want to print //Printing the pattern for (int i = 1; i <= rows; i++) { for (int j = 1; j < i; j++) { System.out.print(" "); } for (int j = i; j <= rows; j++) { System.out.print(j+" "); } System.out.println(); } //Printing the reverse pattern for (int i = rows-1; i >= 1; i--) { for (int j = 1; j < i; j++) { System.out.print(" "); } for (int j = i; j <= rows; j++) { System.out.print(j+" "); } System.out.println(); } }} 1 2 3 4 5 6 7 2 3 4 5 6 7 3 4 5 6 7 4 5 6 7 5 6 7 6 7 7 6 7 5 6 7 4 5 6 7 3 4 5 6 7 2 3 4 5 6 7 1 2 3 4 5 6 7 Number Pattern Java import java.io.*; // Java code to demonstrate number patternpublic class GeeksForGeeks{ // Function to demonstrate printing pattern public static void printNums(int n) { int i, j,num; // outer loop to handle number of rows // n in this case for(i=0; i<n; i++) { // initialising starting number num=1; // inner loop to handle number of columns // values changing acc. to outer loop for(j=0; j<=i; j++) { // printing num with a space System.out.print(num+ " "); //incrementing value of num num++; } // ending line after each row System.out.println(); } } // Driver Function public static void main(String args[]) { int n = 5; printNums(n); }} 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 Numbers without re assigning Java import java.io.*; // Java code to demonstrate star patternpublic class GeeksForGeeks{ // Function to demonstrate printing pattern public static void printNums(int n) { // initialising starting number int i, j, num=1; // outer loop to handle number of rows // n in this case for(i=0; i<n; i++) { // without re assigning num // num = 1; for(j=0; j<=i; j++) { // printing num with a space System.out.print(num+ " "); // incrementing num at each column num = num + 1; } // ending line after each row System.out.println(); } } // Driver Function public static void main(String args[]) { int n = 5; printNums(n); }} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Printing Christmas Tree Using Pyramid Java class PrintChristmasTree{ //Value 5 is permanently provided to height variable public static final int height = 5; //Main Function public static void main(String[] args) { //Assigning Width int width = 5; //Assigning Space int space = width*5; int x = 1; //Code to Print Upper Part of the Tree i.e. Pyramids. for(int a = 1;a <= height ;a++){ for(int i = x;i <= width;i++){ for(int j = space;j >= i;j--){ System.out.print(" "); } for(int k = 1;k <= i;k++){ System.out.print("* "); } System.out.println(); } x = x+2; width = width+2; } //Printing Branch of Christmas Tree for(int i = 1;i <= 4;i++){ for(int j = space-3;j >= 1;j--){ System.out.print(" "); } for(int k= 1;k <= 4;k++){ System.out.print("* "); } System.out.println(); } }} * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This article is contributed by Nikhil Meherwal(S. Shafaq). 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. GirishKumarPatel jagroopofficial simmytarika5 laxmigangarajula03 sagar0719kumar pattern-printing Java School Programming pattern-printing Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Python Dictionary Arrays in C/C++ Introduction To PYTHON Interfaces in Java Inheritance in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 129, "s": 52, "text": "This article is aimed at giving a Java implementation for pattern printing. " }, { "code": null, "e": 152, "s": 129, "text": "Simple pyramid pattern" }, { "code": null, "e": 157, "s": 152, "text": "Java" }, { "code": "import java.io.*; // Java code to demonstrate star patternspublic class GeeksForGeeks{ // Function to demonstrate printing pattern public static void printStars(int n) { int i, j; // outer loop to handle number of rows // n in this case for(i=0; i<n; i++) { // inner loop to handle number of columns // values changing acc. to outer loop for(j=0; j<=i; j++) { // printing stars System.out.print(\"* \"); } // ending line after each row System.out.println(); } } // Driver Function public static void main(String args[]) { int n = 5; printStars(n); }}", "e": 902, "s": 157, "text": null }, { "code": null, "e": 937, "s": 902, "text": "* \n* * \n* * * \n* * * * \n* * * * * " }, { "code": null, "e": 942, "s": 937, "text": "Java" }, { "code": "// java program to print simple pyramid pattern using while// loop import java.io.*; class GFG { public static void main(String[] args) { int r = 1, c = 0, n = 5; // the while loop check the conditions until the // condition is false. if it is true then enter in // to loop and execute the statements while (r <= n) { while (c <= r - 1) { // printing the required pattern System.out.print(\"* \"); c++; } r++; c = 0; // new line after each row System.out.println(); } }} // this code is contributed by gangarajula laxmi", "e": 1622, "s": 942, "text": null }, { "code": null, "e": 1657, "s": 1622, "text": "* \n* * \n* * * \n* * * * \n* * * * * " }, { "code": null, "e": 1683, "s": 1657, "text": "After 180 degree rotation" }, { "code": null, "e": 1688, "s": 1683, "text": "Java" }, { "code": "import java.io.*; // Java code to demonstrate star patternpublic class GeeksForGeeks{ // Function to demonstrate printing pattern public static void printStars(int n) { int i, j; // outer loop to handle number of rows // n in this case for(i=0; i<n; i++) { // inner loop to handle number spaces // values changing acc. to requirement for(j=2*(n-i); j>=0; j--) { // printing spaces System.out.print(\" \"); } // inner loop to handle number of columns // values changing acc. to outer loop for(j=0; j<=i; j++) { // printing stars System.out.print(\"* \"); } // ending line after each row System.out.println(); } } // Driver Function public static void main(String args[]) { int n = 5; printStars(n); }}", "e": 2688, "s": 1688, "text": null }, { "code": null, "e": 2758, "s": 2688, "text": " * \n * * \n * * * \n * * * * \n * * * * * " }, { "code": null, "e": 2776, "s": 2758, "text": "Printing Triangle" }, { "code": null, "e": 2781, "s": 2776, "text": "Java" }, { "code": "import java.io.*; // Java code to demonstrate star patternpublic class GeeksForGeeks{ // Function to demonstrate printing pattern public static void printTriangle(int n) { // outer loop to handle number of rows // n in this case for (int i=0; i<n; i++) { // inner loop to handle number spaces // values changing acc. to requirement for (int j=n-i; j>1; j--) { // printing spaces System.out.print(\" \"); } // inner loop to handle number of columns // values changing acc. to outer loop for (int j=0; j<=i; j++ ) { // printing stars System.out.print(\"* \"); } // ending line after each row System.out.println(); } } // Driver Function public static void main(String args[]) { int n = 5; printTriangle(n); }}", "e": 3763, "s": 2781, "text": null }, { "code": null, "e": 3808, "s": 3763, "text": " * \n * * \n * * * \n * * * * \n* * * * * " }, { "code": null, "e": 3833, "s": 3808, "text": "Print Reverse Of Pyramid" }, { "code": null, "e": 3838, "s": 3833, "text": "Java" }, { "code": "//MainFunctionpublic class ReversePyramid{ public static void main(String[] args) { int rows = 6; // Number of Rows we want to print //Printing the pattern for (int i = 1; i <= rows; i++) { for (int j = 1; j < i; j++) { System.out.print(\" \"); } for (int j = i; j <= rows; j++) { System.out.print(j+\" \"); } System.out.println(); } } }", "e": 4379, "s": 3838, "text": null }, { "code": null, "e": 4442, "s": 4379, "text": "1 2 3 4 5 6 \n 2 3 4 5 6 \n 3 4 5 6 \n 4 5 6 \n 5 6 \n 6 " }, { "code": null, "e": 4478, "s": 4442, "text": "Pattern of Number with Mirror Image" }, { "code": null, "e": 4483, "s": 4478, "text": "Java" }, { "code": "//MainFunctionpublic class ReversePattern{ public static void main(String[] args) { int rows = 7; // Number of Rows we want to print //Printing the pattern for (int i = 1; i <= rows; i++) { for (int j = 1; j < i; j++) { System.out.print(\" \"); } for (int j = i; j <= rows; j++) { System.out.print(j+\" \"); } System.out.println(); } //Printing the reverse pattern for (int i = rows-1; i >= 1; i--) { for (int j = 1; j < i; j++) { System.out.print(\" \"); } for (int j = i; j <= rows; j++) { System.out.print(j+\" \"); } System.out.println(); } }}", "e": 5348, "s": 4483, "text": null }, { "code": null, "e": 5507, "s": 5348, "text": "1 2 3 4 5 6 7 \n 2 3 4 5 6 7 \n 3 4 5 6 7 \n 4 5 6 7 \n 5 6 7 \n 6 7 \n 7 \n 6 7 \n 5 6 7 \n 4 5 6 7 \n 3 4 5 6 7 \n 2 3 4 5 6 7 \n1 2 3 4 5 6 7 " }, { "code": null, "e": 5522, "s": 5507, "text": "Number Pattern" }, { "code": null, "e": 5527, "s": 5522, "text": "Java" }, { "code": "import java.io.*; // Java code to demonstrate number patternpublic class GeeksForGeeks{ // Function to demonstrate printing pattern public static void printNums(int n) { int i, j,num; // outer loop to handle number of rows // n in this case for(i=0; i<n; i++) { // initialising starting number num=1; // inner loop to handle number of columns // values changing acc. to outer loop for(j=0; j<=i; j++) { // printing num with a space System.out.print(num+ \" \"); //incrementing value of num num++; } // ending line after each row System.out.println(); } } // Driver Function public static void main(String args[]) { int n = 5; printNums(n); }}", "e": 6415, "s": 5527, "text": null }, { "code": null, "e": 6450, "s": 6415, "text": "1 \n1 2 \n1 2 3 \n1 2 3 4 \n1 2 3 4 5 " }, { "code": null, "e": 6479, "s": 6450, "text": "Numbers without re assigning" }, { "code": null, "e": 6484, "s": 6479, "text": "Java" }, { "code": "import java.io.*; // Java code to demonstrate star patternpublic class GeeksForGeeks{ // Function to demonstrate printing pattern public static void printNums(int n) { // initialising starting number int i, j, num=1; // outer loop to handle number of rows // n in this case for(i=0; i<n; i++) { // without re assigning num // num = 1; for(j=0; j<=i; j++) { // printing num with a space System.out.print(num+ \" \"); // incrementing num at each column num = num + 1; } // ending line after each row System.out.println(); } } // Driver Function public static void main(String args[]) { int n = 5; printNums(n); }}", "e": 7351, "s": 6484, "text": null }, { "code": null, "e": 7392, "s": 7351, "text": "1 \n2 3 \n4 5 6 \n7 8 9 10 \n11 12 13 14 15 " }, { "code": null, "e": 7430, "s": 7392, "text": "Printing Christmas Tree Using Pyramid" }, { "code": null, "e": 7435, "s": 7430, "text": "Java" }, { "code": "class PrintChristmasTree{ //Value 5 is permanently provided to height variable public static final int height = 5; //Main Function public static void main(String[] args) { //Assigning Width int width = 5; //Assigning Space int space = width*5; int x = 1; //Code to Print Upper Part of the Tree i.e. Pyramids. for(int a = 1;a <= height ;a++){ for(int i = x;i <= width;i++){ for(int j = space;j >= i;j--){ System.out.print(\" \"); } for(int k = 1;k <= i;k++){ System.out.print(\"* \"); } System.out.println(); } x = x+2; width = width+2; } //Printing Branch of Christmas Tree for(int i = 1;i <= 4;i++){ for(int j = space-3;j >= 1;j--){ System.out.print(\" \"); } for(int k= 1;k <= 4;k++){ System.out.print(\"* \"); } System.out.println(); } }}", "e": 8357, "s": 7435, "text": null }, { "code": null, "e": 9331, "s": 8357, "text": " * \n * * \n * * * \n * * * * \n * * * * * \n * * * \n * * * * \n * * * * * \n * * * * * * \n * * * * * * * \n * * * * * \n * * * * * * \n * * * * * * * \n * * * * * * * * \n * * * * * * * * * \n * * * * * * * \n * * * * * * * * \n * * * * * * * * * \n * * * * * * * * * * \n * * * * * * * * * * * \n * * * * * * * * * \n * * * * * * * * * * \n * * * * * * * * * * * \n * * * * * * * * * * * * \n * * * * * * * * * * * * * \n * * * * \n * * * * \n * * * * \n * * * * " }, { "code": null, "e": 9766, "s": 9331, "text": "This article is contributed by Nikhil Meherwal(S. Shafaq). 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": 9783, "s": 9766, "text": "GirishKumarPatel" }, { "code": null, "e": 9799, "s": 9783, "text": "jagroopofficial" }, { "code": null, "e": 9812, "s": 9799, "text": "simmytarika5" }, { "code": null, "e": 9831, "s": 9812, "text": "laxmigangarajula03" }, { "code": null, "e": 9846, "s": 9831, "text": "sagar0719kumar" }, { "code": null, "e": 9863, "s": 9846, "text": "pattern-printing" }, { "code": null, "e": 9868, "s": 9863, "text": "Java" }, { "code": null, "e": 9887, "s": 9868, "text": "School Programming" }, { "code": null, "e": 9904, "s": 9887, "text": "pattern-printing" }, { "code": null, "e": 9909, "s": 9904, "text": "Java" }, { "code": null, "e": 10007, "s": 9909, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10026, "s": 10007, "text": "Interfaces in Java" }, { "code": null, "e": 10041, "s": 10026, "text": "Stream In Java" }, { "code": null, "e": 10059, "s": 10041, "text": "ArrayList in Java" }, { "code": null, "e": 10079, "s": 10059, "text": "Collections in Java" }, { "code": null, "e": 10103, "s": 10079, "text": "Singleton Class in Java" }, { "code": null, "e": 10121, "s": 10103, "text": "Python Dictionary" }, { "code": null, "e": 10137, "s": 10121, "text": "Arrays in C/C++" }, { "code": null, "e": 10160, "s": 10137, "text": "Introduction To PYTHON" }, { "code": null, "e": 10179, "s": 10160, "text": "Interfaces in Java" } ]
Python | os.getlogin() method
20 May, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.getlogin() method in Python is used to get the name of the user logged in on the controlling terminal of the process. Syntax: os.getlogin() Parameter: Not required Return Type: This method returns a string that denotes the name of the user logged in on the controlling terminal of the process. Code #1: use of os.getlogin() method # Python program to explain os.getlogin() method # importing os module import os # Get the name of the user# logged in on the controlling # terminal of the process.user = os.getlogin() # Print the name of the user# logged in on the controlling # terminal of the process.print(user) ihritik python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n20 May, 2019" }, { "code": null, "e": 247, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality." }, { "code": null, "e": 368, "s": 247, "text": "os.getlogin() method in Python is used to get the name of the user logged in on the controlling terminal of the process." }, { "code": null, "e": 390, "s": 368, "text": "Syntax: os.getlogin()" }, { "code": null, "e": 414, "s": 390, "text": "Parameter: Not required" }, { "code": null, "e": 544, "s": 414, "text": "Return Type: This method returns a string that denotes the name of the user logged in on the controlling terminal of the process." }, { "code": null, "e": 581, "s": 544, "text": "Code #1: use of os.getlogin() method" }, { "code": "# Python program to explain os.getlogin() method # importing os module import os # Get the name of the user# logged in on the controlling # terminal of the process.user = os.getlogin() # Print the name of the user# logged in on the controlling # terminal of the process.print(user) ", "e": 872, "s": 581, "text": null }, { "code": null, "e": 881, "s": 872, "text": "ihritik\n" }, { "code": null, "e": 898, "s": 881, "text": "python-os-module" }, { "code": null, "e": 905, "s": 898, "text": "Python" }, { "code": null, "e": 1003, "s": 905, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1035, "s": 1003, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1062, "s": 1035, "text": "Python Classes and Objects" }, { "code": null, "e": 1083, "s": 1062, "text": "Python OOPs Concepts" }, { "code": null, "e": 1106, "s": 1083, "text": "Introduction To PYTHON" }, { "code": null, "e": 1162, "s": 1106, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1193, "s": 1162, "text": "Python | os.path.join() method" }, { "code": null, "e": 1235, "s": 1193, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1277, "s": 1235, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1316, "s": 1277, "text": "Python | Get unique values from a list" } ]
CSS | conic-gradient() Function
22 Jun, 2020 The conic-gradient() function is an inbuilt function in CSS which is used to set a conic gradient as the background image. The conic gradient angle starts from 0 degrees – 360 degrees. Conic are circular and use the center of the element as the source point for color stop. Conic Gradients include pie charts and color wheels. The result of the conic-gradient() function is an object of the data type, which is a special kind of image. Syntax: Background image: conic-gradient(color degree, color degree, ...) Conic gradients are similar to radial gradients, except that the color stops are on the outer edge of the circle that gets created. Example: RADIAL GRADIENT: CONIC GRADIENT: Below example illustrates the conic-gradient() function in CSS: Program 1: <!DOCTYPE html><html><head> <title>conic gradient</title> <style> .box { background-color: yellow; height: 200px; width: 200px; float: left; margin: 20px; border-radius: 50%; } .a { background-image: conic-gradient(red, yellow, green); } </style></head><body> <div class="box a"></div></body></html> Output: Program 2: <!DOCTYPE html><html><head> <title>conic gradient</title> <style> .box { background-color: yellow; height: 200px; width: 200px; float: left; margin: 20px; border-radius: 50%; } .b { background-image: conic-gradient( from 60deg, red, yellow, green); } </style></head><body> <div class="box b"></div></body></html> Output: Program 3: <!DOCTYPE html><html><head> <title>conic gradient</title> <style> .box { background-color: yellow; height: 200px; width: 200px; float: left; margin: 20px; border-radius: 50%; } .c { background-image: conic-gradient(red, yellow, green, red); } </style></head><body> <div class="box c"></div></body></html Output: Program 4: <!DOCTYPE html><html><head> <title>conic gradient</title> <style> .box { background-color: yellow; height: 200px; width: 200px; float: left; margin: 20px; border-radius: 50%; } .d { background-image: repeating-conic-gradient( red 0deg, red 10deg, yellow 10deg, yellow 20deg); } </style></head><body> <div class="box d"></div></body></html> Output: Program 5: <!DOCTYPE html><html><head> <title>conic gradient</title> <style> .box { background-color: yellow; height: 200px; width: 200px; float: left; margin: 20px; border-radius: 50%; } .e { background-image: conic-gradient( red 0deg, red 90deg, yellow 90deg, yellow 180deg, green 180deg, green 270deg, blue 270deg, blue 360deg); } </style></head><body> <div class="box e"></div></body></html> Output: CSS-Functions CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2020" }, { "code": null, "e": 490, "s": 54, "text": "The conic-gradient() function is an inbuilt function in CSS which is used to set a conic gradient as the background image. The conic gradient angle starts from 0 degrees – 360 degrees. Conic are circular and use the center of the element as the source point for color stop. Conic Gradients include pie charts and color wheels. The result of the conic-gradient() function is an object of the data type, which is a special kind of image." }, { "code": null, "e": 500, "s": 490, "text": "Syntax: " }, { "code": null, "e": 569, "s": 500, "text": " Background image: conic-gradient(color degree, color degree, ...) " }, { "code": null, "e": 701, "s": 569, "text": "Conic gradients are similar to radial gradients, except that the color stops are on the outer edge of the circle that gets created." }, { "code": null, "e": 710, "s": 701, "text": "Example:" }, { "code": null, "e": 727, "s": 710, "text": "RADIAL GRADIENT:" }, { "code": null, "e": 743, "s": 727, "text": "CONIC GRADIENT:" }, { "code": null, "e": 807, "s": 743, "text": "Below example illustrates the conic-gradient() function in CSS:" }, { "code": null, "e": 818, "s": 807, "text": "Program 1:" }, { "code": "<!DOCTYPE html><html><head> <title>conic gradient</title> <style> .box { background-color: yellow; height: 200px; width: 200px; float: left; margin: 20px; border-radius: 50%; } .a { background-image: conic-gradient(red, yellow, green); } </style></head><body> <div class=\"box a\"></div></body></html>", "e": 1211, "s": 818, "text": null }, { "code": null, "e": 1219, "s": 1211, "text": "Output:" }, { "code": null, "e": 1230, "s": 1219, "text": "Program 2:" }, { "code": "<!DOCTYPE html><html><head> <title>conic gradient</title> <style> .box { background-color: yellow; height: 200px; width: 200px; float: left; margin: 20px; border-radius: 50%; } .b { background-image: conic-gradient( from 60deg, red, yellow, green); } </style></head><body> <div class=\"box b\"></div></body></html>", "e": 1639, "s": 1230, "text": null }, { "code": null, "e": 1647, "s": 1639, "text": "Output:" }, { "code": null, "e": 1658, "s": 1647, "text": "Program 3:" }, { "code": "<!DOCTYPE html><html><head> <title>conic gradient</title> <style> .box { background-color: yellow; height: 200px; width: 200px; float: left; margin: 20px; border-radius: 50%; } .c { background-image: conic-gradient(red, yellow, green, red); } </style></head><body> <div class=\"box c\"></div></body></html", "e": 2057, "s": 1658, "text": null }, { "code": null, "e": 2065, "s": 2057, "text": "Output:" }, { "code": null, "e": 2076, "s": 2065, "text": "Program 4:" }, { "code": "<!DOCTYPE html><html><head> <title>conic gradient</title> <style> .box { background-color: yellow; height: 200px; width: 200px; float: left; margin: 20px; border-radius: 50%; } .d { background-image: repeating-conic-gradient( red 0deg, red 10deg, yellow 10deg, yellow 20deg); } </style></head><body> <div class=\"box d\"></div></body></html>", "e": 2513, "s": 2076, "text": null }, { "code": null, "e": 2521, "s": 2513, "text": "Output:" }, { "code": null, "e": 2532, "s": 2521, "text": "Program 5:" }, { "code": "<!DOCTYPE html><html><head> <title>conic gradient</title> <style> .box { background-color: yellow; height: 200px; width: 200px; float: left; margin: 20px; border-radius: 50%; } .e { background-image: conic-gradient( red 0deg, red 90deg, yellow 90deg, yellow 180deg, green 180deg, green 270deg, blue 270deg, blue 360deg); } </style></head><body> <div class=\"box e\"></div></body></html>", "e": 3102, "s": 2532, "text": null }, { "code": null, "e": 3110, "s": 3102, "text": "Output:" }, { "code": null, "e": 3124, "s": 3110, "text": "CSS-Functions" }, { "code": null, "e": 3128, "s": 3124, "text": "CSS" }, { "code": null, "e": 3133, "s": 3128, "text": "HTML" }, { "code": null, "e": 3150, "s": 3133, "text": "Web Technologies" }, { "code": null, "e": 3155, "s": 3150, "text": "HTML" }, { "code": null, "e": 3253, "s": 3155, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3290, "s": 3253, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 3329, "s": 3290, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3368, "s": 3329, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3432, "s": 3368, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 3493, "s": 3432, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 3517, "s": 3493, "text": "REST API (Introduction)" }, { "code": null, "e": 3570, "s": 3517, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3630, "s": 3570, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 3691, "s": 3630, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python program to multiply all the items in a dictionary
26 Nov, 2020 Python program to illustrate multiply all the items in a dictionary could be done by creating a dictionary which will store all the key-value pairs, multiplying the value of all the keys and storing it in a variable. Example: Input: dict = {‘value1’:5, ‘value2’:4, ‘value3’:3, ‘value4’:2, ‘value5’:1}Output: ans = 120 Input: dict = {‘v1’:10, ‘v2’:7, ‘v3’:2}Output: ans = 140 Approach: Create a dictionary d and store key-value pairs in it. Create a variable answer initialized to 1. Run a loop to traverse through the dictionary d Multiply each value of key with answer and store the result in answer itself. Print answer. Below are the examples of above approach. Example 1: Python3 # create a dictionaryd = { 'value1': 5, 'value2': 4, 'value3': 3, 'value4': 2, 'value5': 1,} # create a variable to store resultanswer = 1 # run a loopfor i in d: answer = answer*d[i] # print answerprint(answer) 120 Example 2: Python3 # create a dictionaryd = { 'a': 10, 'b': 7, 'c': 2,} # create a variable to store resultanswer = 1 # run a loopfor i in d: answer = answer*d[i] # print answerprint(answer) 140 Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Nov, 2020" }, { "code": null, "e": 245, "s": 28, "text": "Python program to illustrate multiply all the items in a dictionary could be done by creating a dictionary which will store all the key-value pairs, multiplying the value of all the keys and storing it in a variable." }, { "code": null, "e": 254, "s": 245, "text": "Example:" }, { "code": null, "e": 346, "s": 254, "text": "Input: dict = {‘value1’:5, ‘value2’:4, ‘value3’:3, ‘value4’:2, ‘value5’:1}Output: ans = 120" }, { "code": null, "e": 403, "s": 346, "text": "Input: dict = {‘v1’:10, ‘v2’:7, ‘v3’:2}Output: ans = 140" }, { "code": null, "e": 413, "s": 403, "text": "Approach:" }, { "code": null, "e": 468, "s": 413, "text": "Create a dictionary d and store key-value pairs in it." }, { "code": null, "e": 511, "s": 468, "text": "Create a variable answer initialized to 1." }, { "code": null, "e": 559, "s": 511, "text": "Run a loop to traverse through the dictionary d" }, { "code": null, "e": 637, "s": 559, "text": "Multiply each value of key with answer and store the result in answer itself." }, { "code": null, "e": 651, "s": 637, "text": "Print answer." }, { "code": null, "e": 693, "s": 651, "text": "Below are the examples of above approach." }, { "code": null, "e": 704, "s": 693, "text": "Example 1:" }, { "code": null, "e": 712, "s": 704, "text": "Python3" }, { "code": "# create a dictionaryd = { 'value1': 5, 'value2': 4, 'value3': 3, 'value4': 2, 'value5': 1,} # create a variable to store resultanswer = 1 # run a loopfor i in d: answer = answer*d[i] # print answerprint(answer)", "e": 945, "s": 712, "text": null }, { "code": null, "e": 950, "s": 945, "text": "120\n" }, { "code": null, "e": 961, "s": 950, "text": "Example 2:" }, { "code": null, "e": 969, "s": 961, "text": "Python3" }, { "code": "# create a dictionaryd = { 'a': 10, 'b': 7, 'c': 2,} # create a variable to store resultanswer = 1 # run a loopfor i in d: answer = answer*d[i] # print answerprint(answer)", "e": 1156, "s": 969, "text": null }, { "code": null, "e": 1161, "s": 1156, "text": "140\n" }, { "code": null, "e": 1188, "s": 1161, "text": "Python dictionary-programs" }, { "code": null, "e": 1195, "s": 1188, "text": "Python" }, { "code": null, "e": 1211, "s": 1195, "text": "Python Programs" }, { "code": null, "e": 1309, "s": 1211, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1341, "s": 1309, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1368, "s": 1341, "text": "Python Classes and Objects" }, { "code": null, "e": 1389, "s": 1368, "text": "Python OOPs Concepts" }, { "code": null, "e": 1412, "s": 1389, "text": "Introduction To PYTHON" }, { "code": null, "e": 1468, "s": 1412, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1490, "s": 1468, "text": "Defaultdict in Python" }, { "code": null, "e": 1529, "s": 1490, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1567, "s": 1529, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 1604, "s": 1567, "text": "Python Program for Fibonacci numbers" } ]
Python - Tkinter pack() Method
This geometry manager organizes widgets in blocks before placing them in the parent widget. widget.pack( pack_options ) Here is the list of possible options − expand − When set to true, widget expands to fill any space not otherwise used in widget's parent. expand − When set to true, widget expands to fill any space not otherwise used in widget's parent. fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH (fill both horizontally and vertically). fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH (fill both horizontally and vertically). side − Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT. side − Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT. Try the following example by moving cursor on different buttons − from Tkinter import * root = Tk() frame = Frame(root) frame.pack() bottomframe = Frame(root) bottomframe.pack( side = BOTTOM ) redbutton = Button(frame, text="Red", fg="red") redbutton.pack( side = LEFT) greenbutton = Button(frame, text="green", fg="green") greenbutton.pack( side = LEFT ) bluebutton = Button(frame, text="Blue", fg="blue") bluebutton.pack( side = LEFT ) blackbutton = Button(bottomframe, text="Black", fg="black") blackbutton.pack( side = BOTTOM) root.mainloop() When the above code is executed, it produces the following result −
[ { "code": null, "e": 2470, "s": 2378, "text": "This geometry manager organizes widgets in blocks before placing them in the parent widget." }, { "code": null, "e": 2499, "s": 2470, "text": "widget.pack( pack_options )\n" }, { "code": null, "e": 2539, "s": 2499, "text": "Here is the list of possible options −" }, { "code": null, "e": 2638, "s": 2539, "text": "expand − When set to true, widget expands to fill any space not otherwise used in widget's parent." }, { "code": null, "e": 2737, "s": 2638, "text": "expand − When set to true, widget expands to fill any space not otherwise used in widget's parent." }, { "code": null, "e": 2979, "s": 2737, "text": "fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH (fill both horizontally and vertically)." }, { "code": null, "e": 3221, "s": 2979, "text": "fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH (fill both horizontally and vertically)." }, { "code": null, "e": 3325, "s": 3221, "text": "side − Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT." }, { "code": null, "e": 3429, "s": 3325, "text": "side − Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT." }, { "code": null, "e": 3495, "s": 3429, "text": "Try the following example by moving cursor on different buttons −" }, { "code": null, "e": 3983, "s": 3495, "text": "from Tkinter import *\n\nroot = Tk()\nframe = Frame(root)\nframe.pack()\n\nbottomframe = Frame(root)\nbottomframe.pack( side = BOTTOM )\n\nredbutton = Button(frame, text=\"Red\", fg=\"red\")\nredbutton.pack( side = LEFT)\n\ngreenbutton = Button(frame, text=\"green\", fg=\"green\")\ngreenbutton.pack( side = LEFT )\n\nbluebutton = Button(frame, text=\"Blue\", fg=\"blue\")\nbluebutton.pack( side = LEFT )\n\nblackbutton = Button(bottomframe, text=\"Black\", fg=\"black\")\nblackbutton.pack( side = BOTTOM)\n\nroot.mainloop()" } ]
Output of C Program | Set 23
08 May, 2020 Predict the output of following C Program. #include <stdio.h>#define R 4#define C 4 void modifyMatrix(int mat[][C]){ mat++; mat[1][1] = 100; mat++; mat[1][1] = 200;} void printMatrix(int mat[][C]){ int i, j; for (i = 0; i < R; i++) { for (j = 0; j < C; j++) printf("%3d ", mat[i][j]); printf("\n"); }} int main(){ int mat[R][C] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; printf("Original Matrix \n"); printMatrix(mat); modifyMatrix(mat); printf("Matrix after modification \n"); printMatrix(mat); return 0;} Output: The program compiles fine and produces following output: Original Matrix 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Matrix after modification 1 2 3 4 5 6 7 8 9 100 11 12 13 200 15 16 At first look, the line “mat++;” in modifyMatrix() seems invalid. But this is a valid C line as array parameters are always pointers (see this and this for details). In modifyMatrix(), mat is just a pointer that points to block of size C*sizeof(int). So following function prototype is same as “void modifyMatrix(int mat[][C])” void modifyMatrix(int (*mat)[C]); When we do mat++, mat starts pointing to next row, and mat[1][1] starts referring to value 10. mat[1][1] (value 10) is changed to 100 by the statement “mat[1][1] = 100;”. mat is again incremented and mat[1][1] (now value 14) is changed to 200 by next couple of statements in modifyMatrix(). The line “mat[1][1] = 100;” is valid as pointer arithmetic and array indexing are equivalent in C. On a side note, we can’t do mat++ in main() as mat is 2 D array in main(), not a pointer. Please write comments if you find above answer/explanation incorrect, or you want to share more information about the topic discussed above cshivam718 C-Output Output of C Programs Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Runtime Errors Different ways to copy a string in C/C++ Output of C++ Program | Set 1 Output of Java Program | Set 3 Output of Java Programs | Set 12 Output of C++ programs | Set 47 (Pointers) Output of Java Program | Set 7 Output of C programs | Set 59 (Loops and Control Statements) Output of C Programs | Set 3 unsigned specifier (%u) in C with Examples
[ { "code": null, "e": 54, "s": 26, "text": "\n08 May, 2020" }, { "code": null, "e": 97, "s": 54, "text": "Predict the output of following C Program." }, { "code": "#include <stdio.h>#define R 4#define C 4 void modifyMatrix(int mat[][C]){ mat++; mat[1][1] = 100; mat++; mat[1][1] = 200;} void printMatrix(int mat[][C]){ int i, j; for (i = 0; i < R; i++) { for (j = 0; j < C; j++) printf(\"%3d \", mat[i][j]); printf(\"\\n\"); }} int main(){ int mat[R][C] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; printf(\"Original Matrix \\n\"); printMatrix(mat); modifyMatrix(mat); printf(\"Matrix after modification \\n\"); printMatrix(mat); return 0;}", "e": 686, "s": 97, "text": null }, { "code": null, "e": 751, "s": 686, "text": "Output: The program compiles fine and produces following output:" }, { "code": null, "e": 922, "s": 751, "text": "Original Matrix\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n 13 14 15 16\nMatrix after modification\n 1 2 3 4\n 5 6 7 8\n 9 100 11 12\n 13 200 15 16\n" }, { "code": null, "e": 1250, "s": 922, "text": "At first look, the line “mat++;” in modifyMatrix() seems invalid. But this is a valid C line as array parameters are always pointers (see this and this for details). In modifyMatrix(), mat is just a pointer that points to block of size C*sizeof(int). So following function prototype is same as “void modifyMatrix(int mat[][C])”" }, { "code": "void modifyMatrix(int (*mat)[C]);", "e": 1284, "s": 1250, "text": null }, { "code": null, "e": 1575, "s": 1284, "text": "When we do mat++, mat starts pointing to next row, and mat[1][1] starts referring to value 10. mat[1][1] (value 10) is changed to 100 by the statement “mat[1][1] = 100;”. mat is again incremented and mat[1][1] (now value 14) is changed to 200 by next couple of statements in modifyMatrix()." }, { "code": null, "e": 1674, "s": 1575, "text": "The line “mat[1][1] = 100;” is valid as pointer arithmetic and array indexing are equivalent in C." }, { "code": null, "e": 1764, "s": 1674, "text": "On a side note, we can’t do mat++ in main() as mat is 2 D array in main(), not a pointer." }, { "code": null, "e": 1904, "s": 1764, "text": "Please write comments if you find above answer/explanation incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 1915, "s": 1904, "text": "cshivam718" }, { "code": null, "e": 1924, "s": 1915, "text": "C-Output" }, { "code": null, "e": 1945, "s": 1924, "text": "Output of C Programs" }, { "code": null, "e": 1960, "s": 1945, "text": "Program Output" }, { "code": null, "e": 2058, "s": 1960, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2073, "s": 2058, "text": "Runtime Errors" }, { "code": null, "e": 2114, "s": 2073, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 2144, "s": 2114, "text": "Output of C++ Program | Set 1" }, { "code": null, "e": 2175, "s": 2144, "text": "Output of Java Program | Set 3" }, { "code": null, "e": 2208, "s": 2175, "text": "Output of Java Programs | Set 12" }, { "code": null, "e": 2251, "s": 2208, "text": "Output of C++ programs | Set 47 (Pointers)" }, { "code": null, "e": 2282, "s": 2251, "text": "Output of Java Program | Set 7" }, { "code": null, "e": 2343, "s": 2282, "text": "Output of C programs | Set 59 (Loops and Control Statements)" }, { "code": null, "e": 2372, "s": 2343, "text": "Output of C Programs | Set 3" } ]
Populating Matplotlib subplots through a loop and a function
To populate matplotlib subplots through a loop and a function, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Create a figure and a set of subplots with number of rows = 3 and number of columns = 2. Create a figure and a set of subplots with number of rows = 3 and number of columns = 2. Make a function to iterate the columns of each row and plot the x data points using plot() method at each column index. Make a function to iterate the columns of each row and plot the x data points using plot() method at each column index. Iterate rows (Step 2) and create random x data points and call iterate_columns() function (Step 3). Iterate rows (Step 2) and create random x data points and call iterate_columns() function (Step 3). To display the figure, use show() method. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig, axes = plt.subplots(3, 2) """ Iterate column's axes""" def iterate_columns(cols, x): for col in cols: col.plot(x, color='red') """ Iterate row's axes""" for row in axes: x = np.random.normal(0, 1, 100).cumsum() iterate_columns(row, x) plt.show()
[ { "code": null, "e": 1284, "s": 1187, "text": "To populate matplotlib subplots through a loop and a function, we can take the following steps −" }, { "code": null, "e": 1360, "s": 1284, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1436, "s": 1360, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1525, "s": 1436, "text": "Create a figure and a set of subplots with number of rows = 3 and number of columns = 2." }, { "code": null, "e": 1614, "s": 1525, "text": "Create a figure and a set of subplots with number of rows = 3 and number of columns = 2." }, { "code": null, "e": 1734, "s": 1614, "text": "Make a function to iterate the columns of each row and plot the x data points using plot() method at each column index." }, { "code": null, "e": 1854, "s": 1734, "text": "Make a function to iterate the columns of each row and plot the x data points using plot() method at each column index." }, { "code": null, "e": 1954, "s": 1854, "text": "Iterate rows (Step 2) and create random x data points and call iterate_columns() function (Step 3)." }, { "code": null, "e": 2054, "s": 1954, "text": "Iterate rows (Step 2) and create random x data points and call iterate_columns() function (Step 3)." }, { "code": null, "e": 2096, "s": 2054, "text": "To display the figure, use show() method." }, { "code": null, "e": 2138, "s": 2096, "text": "To display the figure, use show() method." }, { "code": null, "e": 2547, "s": 2138, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig, axes = plt.subplots(3, 2)\n\n\"\"\" Iterate column's axes\"\"\"\ndef iterate_columns(cols, x):\n for col in cols:\n col.plot(x, color='red')\n\n\"\"\" Iterate row's axes\"\"\"\nfor row in axes:\n x = np.random.normal(0, 1, 100).cumsum()\n iterate_columns(row, x)\n\nplt.show()" } ]
MTX Interview Experience for Trainee Consultant | On-Campus 2021
05 Mar, 2021 Round 1 Online Test (Hackerearth platform): Programming questions: 3(Data structures and algorithms) Multiple Choice Questions: 67(Aptitude, programming, HTML, CSS, JavaScript, OOPs, Java, SQL) Test duration: 2 hrs Round 2 (Technical Interview Round 1): This round started with a project discussion. The interviewer asked questions on each skill that I have mentioned in my resume. This round mainly focuses on Data Structures and Object-Oriented Programming. Some questions related to HTML, CSS, and SQL were also asked. What is sorting? Tell some algorithm of sorting with their time complexities? Implement any sorting algorithm in the language of your choice (I implemented quick sort in C++)? When will you prefer quick sort over merge sort?Write SQL command for finding all the student name that ends with ‘a’ in student_name column?What is the difference between truncate, drop, and delete?Write a program to find factorial of a numberSwap two numbers without taking a third variable, can we swap numbers using bitwise operation, if yes them implement?What is the difference between class and id in HTML? What is sorting? Tell some algorithm of sorting with their time complexities? Implement any sorting algorithm in the language of your choice (I implemented quick sort in C++)? When will you prefer quick sort over merge sort? Write SQL command for finding all the student name that ends with ‘a’ in student_name column? What is the difference between truncate, drop, and delete? Write a program to find factorial of a number Swap two numbers without taking a third variable, can we swap numbers using bitwise operation, if yes them implement? What is the difference between class and id in HTML? Questions were easy, I managed to solve all the question, few other theory questions were asked on SQL, DBMS, and OOPs Round 3 (Technical Interview Round 2): This round was completely DSA based, I was provided with an Online IDE and have to compile the code. Print this pattern.ABCDEF ABCDE ABCD ABC AB A AB ABC ABCD ABCDE ABCDEFWrite a program to find out duplicate characters in a String.Given a number find the square root of it in O(log n).Find an element that is present in the first array and not in the second.Check if the given list is a circular Linked List without using extra space.Given the root node of a tree, find the height of that tree. Print this pattern.ABCDEF ABCDE ABCD ABC AB A AB ABC ABCD ABCDE ABCDEF Print this pattern. ABCDEF ABCDE ABCD ABC AB A AB ABC ABCD ABCDE ABCDEF Write a program to find out duplicate characters in a String. Given a number find the square root of it in O(log n). Find an element that is present in the first array and not in the second. Check if the given list is a circular Linked List without using extra space. Given the root node of a tree, find the height of that tree. Round 4 (HR Round): This round was basic, and they were just checking your confidence level. Tell me about yourself.What do you know about MTX?What are your hobbies?Explain your strengths and weaknesses.Do you have any questions for me? Tell me about yourself. What do you know about MTX? What are your hobbies? Explain your strengths and weaknesses. Do you have any questions for me? The interview process was seamless and very well managed by the HR team. Final Verdict: Selected Marketing MTX On-Campus Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCS Digital Interview Questions Google SWE Interview Experience (Google Online Coding Challenge) 2022 Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Amazon Interview Experience for SDE 1 Google Interview Questions Amazon Interview Experience SDE-2 (3 Years Experienced) TCS Ninja Interview Experience (2020 batch) Write It Up: Share Your Interview Experiences Samsung RnD Coding Round Questions How I cracked TCS Digital
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Mar, 2021" }, { "code": null, "e": 98, "s": 54, "text": "Round 1 Online Test (Hackerearth platform):" }, { "code": null, "e": 155, "s": 98, "text": "Programming questions: 3(Data structures and algorithms)" }, { "code": null, "e": 248, "s": 155, "text": "Multiple Choice Questions: 67(Aptitude, programming, HTML, CSS, JavaScript, OOPs, Java, SQL)" }, { "code": null, "e": 269, "s": 248, "text": "Test duration: 2 hrs" }, { "code": null, "e": 576, "s": 269, "text": "Round 2 (Technical Interview Round 1): This round started with a project discussion. The interviewer asked questions on each skill that I have mentioned in my resume. This round mainly focuses on Data Structures and Object-Oriented Programming. Some questions related to HTML, CSS, and SQL were also asked." }, { "code": null, "e": 1166, "s": 576, "text": "What is sorting? Tell some algorithm of sorting with their time complexities? Implement any sorting algorithm in the language of your choice (I implemented quick sort in C++)? When will you prefer quick sort over merge sort?Write SQL command for finding all the student name that ends with ‘a’ in student_name column?What is the difference between truncate, drop, and delete?Write a program to find factorial of a numberSwap two numbers without taking a third variable, can we swap numbers using bitwise operation, if yes them implement?What is the difference between class and id in HTML?" }, { "code": null, "e": 1391, "s": 1166, "text": "What is sorting? Tell some algorithm of sorting with their time complexities? Implement any sorting algorithm in the language of your choice (I implemented quick sort in C++)? When will you prefer quick sort over merge sort?" }, { "code": null, "e": 1485, "s": 1391, "text": "Write SQL command for finding all the student name that ends with ‘a’ in student_name column?" }, { "code": null, "e": 1544, "s": 1485, "text": "What is the difference between truncate, drop, and delete?" }, { "code": null, "e": 1590, "s": 1544, "text": "Write a program to find factorial of a number" }, { "code": null, "e": 1708, "s": 1590, "text": "Swap two numbers without taking a third variable, can we swap numbers using bitwise operation, if yes them implement?" }, { "code": null, "e": 1761, "s": 1708, "text": "What is the difference between class and id in HTML?" }, { "code": null, "e": 1880, "s": 1761, "text": "Questions were easy, I managed to solve all the question, few other theory questions were asked on SQL, DBMS, and OOPs" }, { "code": null, "e": 2020, "s": 1880, "text": "Round 3 (Technical Interview Round 2): This round was completely DSA based, I was provided with an Online IDE and have to compile the code." }, { "code": null, "e": 2415, "s": 2020, "text": "Print this pattern.ABCDEF\nABCDE\nABCD\nABC\nAB\nA\nAB\nABC\nABCD\nABCDE\nABCDEFWrite a program to find out duplicate characters in a String.Given a number find the square root of it in O(log n).Find an element that is present in the first array and not in the second.Check if the given list is a circular Linked List without using extra space.Given the root node of a tree, find the height of that tree." }, { "code": null, "e": 2486, "s": 2415, "text": "Print this pattern.ABCDEF\nABCDE\nABCD\nABC\nAB\nA\nAB\nABC\nABCD\nABCDE\nABCDEF" }, { "code": null, "e": 2506, "s": 2486, "text": "Print this pattern." }, { "code": null, "e": 2558, "s": 2506, "text": "ABCDEF\nABCDE\nABCD\nABC\nAB\nA\nAB\nABC\nABCD\nABCDE\nABCDEF" }, { "code": null, "e": 2620, "s": 2558, "text": "Write a program to find out duplicate characters in a String." }, { "code": null, "e": 2675, "s": 2620, "text": "Given a number find the square root of it in O(log n)." }, { "code": null, "e": 2749, "s": 2675, "text": "Find an element that is present in the first array and not in the second." }, { "code": null, "e": 2826, "s": 2749, "text": "Check if the given list is a circular Linked List without using extra space." }, { "code": null, "e": 2887, "s": 2826, "text": "Given the root node of a tree, find the height of that tree." }, { "code": null, "e": 2980, "s": 2887, "text": "Round 4 (HR Round): This round was basic, and they were just checking your confidence level." }, { "code": null, "e": 3124, "s": 2980, "text": "Tell me about yourself.What do you know about MTX?What are your hobbies?Explain your strengths and weaknesses.Do you have any questions for me?" }, { "code": null, "e": 3148, "s": 3124, "text": "Tell me about yourself." }, { "code": null, "e": 3176, "s": 3148, "text": "What do you know about MTX?" }, { "code": null, "e": 3199, "s": 3176, "text": "What are your hobbies?" }, { "code": null, "e": 3238, "s": 3199, "text": "Explain your strengths and weaknesses." }, { "code": null, "e": 3272, "s": 3238, "text": "Do you have any questions for me?" }, { "code": null, "e": 3346, "s": 3272, "text": "The interview process was seamless and very well managed by the HR team. " }, { "code": null, "e": 3372, "s": 3346, "text": "Final Verdict: Selected " }, { "code": null, "e": 3382, "s": 3372, "text": "Marketing" }, { "code": null, "e": 3386, "s": 3382, "text": "MTX" }, { "code": null, "e": 3396, "s": 3386, "text": "On-Campus" }, { "code": null, "e": 3418, "s": 3396, "text": "Interview Experiences" }, { "code": null, "e": 3516, "s": 3418, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3548, "s": 3516, "text": "TCS Digital Interview Questions" }, { "code": null, "e": 3618, "s": 3548, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 3691, "s": 3618, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 3729, "s": 3691, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 3756, "s": 3729, "text": "Google Interview Questions" }, { "code": null, "e": 3812, "s": 3756, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 3856, "s": 3812, "text": "TCS Ninja Interview Experience (2020 batch)" }, { "code": null, "e": 3902, "s": 3856, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 3937, "s": 3902, "text": "Samsung RnD Coding Round Questions" } ]
click method – Action Chains in Selenium Python
11 May, 2020 Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around click method on Action Chains in Python Selenium. click method is used to click on an element or current position. Syntax – click(on_element=None) Example – <input type ="text" name ="passwd" id ="passwd-id" /> To find an element one needs to use one of the locating strategies, For example, element = driver.find_element_by_id("passwd-id")element = driver.find_element_by_name("passwd") Now one can use click method as an Action chain as below – click(on_element=element) To demonstrate, click method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element. Program – # import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_link_text("Courses") # create action chain objectaction = ActionChains(driver) # click the itemaction.click(on_element = element) # perform the operationaction.perform() Output – Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n11 May, 2020" }, { "code": null, "e": 595, "s": 28, "text": "Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around click method on Action Chains in Python Selenium. click method is used to click on an element or current position." }, { "code": null, "e": 604, "s": 595, "text": "Syntax –" }, { "code": null, "e": 627, "s": 604, "text": "click(on_element=None)" }, { "code": null, "e": 637, "s": 627, "text": "Example –" }, { "code": "<input type =\"text\" name =\"passwd\" id =\"passwd-id\" />", "e": 691, "s": 637, "text": null }, { "code": null, "e": 772, "s": 691, "text": "To find an element one needs to use one of the locating strategies, For example," }, { "code": "element = driver.find_element_by_id(\"passwd-id\")element = driver.find_element_by_name(\"passwd\")", "e": 868, "s": 772, "text": null }, { "code": null, "e": 927, "s": 868, "text": "Now one can use click method as an Action chain as below –" }, { "code": null, "e": 954, "s": 927, "text": "click(on_element=element)\n" }, { "code": null, "e": 1091, "s": 954, "text": "To demonstrate, click method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element." }, { "code": null, "e": 1101, "s": 1091, "text": "Program –" }, { "code": "# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_link_text(\"Courses\") # create action chain objectaction = ActionChains(driver) # click the itemaction.click(on_element = element) # perform the operationaction.perform()", "e": 1584, "s": 1101, "text": null }, { "code": null, "e": 1593, "s": 1584, "text": "Output –" }, { "code": null, "e": 1609, "s": 1593, "text": "Python-selenium" }, { "code": null, "e": 1618, "s": 1609, "text": "selenium" }, { "code": null, "e": 1625, "s": 1618, "text": "Python" }, { "code": null, "e": 1723, "s": 1625, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1741, "s": 1723, "text": "Python Dictionary" }, { "code": null, "e": 1783, "s": 1741, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1805, "s": 1783, "text": "Enumerate() in Python" }, { "code": null, "e": 1840, "s": 1805, "text": "Read a file line by line in Python" }, { "code": null, "e": 1866, "s": 1840, "text": "Python String | replace()" }, { "code": null, "e": 1898, "s": 1866, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1927, "s": 1898, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1957, "s": 1927, "text": "Iterate over a list in Python" }, { "code": null, "e": 1984, "s": 1957, "text": "Python Classes and Objects" } ]
gunzip command in Linux with examples
30 Sep, 2019 gunzip command is used to compress or expand a file or a list of files in Linux. It accepts all the files having extension as .gz, .z, _z, -gz, -z , .Z, .taz or.tgz and replace the compressed file with the original file by default. The files after uncompression retain its actual extension. Syntax: gunzip [Option] [archive name/file name] Example 1: The argument that is passed here is: geeksforgeeks.txt which is a compressed text file. Input: Output: geeksforgeeks.txt.gz Example 2: The argument that is passed here is: geeksforgeeks.txt.gz which is a compressed file. Input: Output: geeksforgeeks.txt If a file is compressed using gzip command, a suffix i.e. .gz will be added to the file name after compression. Hence while uncompressing this file we can either use the original file name as shown in Example 1 or the filename with the suffix .gz as shown in Example 2 as an argument. Example 3: In order to uncompress multiple files using the gunzip command, we can pass multiple file names as an argument as shown in the below example: Syntax: gunzip [file1] [file2] [file3]... Input: Output: geeksforgeeks.txt, gfg.txt Options: -c: This option is used to view the text within a compressed file without uncompressing it. The ASCII/EBCDIC conversion is automatically done if it is suitable. The compressed file has to be a text file only.Example:gunzip -c geeksforgeeks.txt.tar.gzOutput: Example: gunzip -c geeksforgeeks.txt.tar.gz Output: -f: To decompress a file forcefully.Example:gunzip -f geeksforgeeks.txt.tar.gzOutput: The file will be forcefully extracted.geeksforgeeks.txt Example: gunzip -f geeksforgeeks.txt.tar.gz Output: The file will be forcefully extracted. geeksforgeeks.txt -k: This option can be used when we want to keep both the file i.e. the uncompressed and the original file after the uncompression.Example:gunzip -k geeksforgeeks.txt.tar.gzOutput: An extracted file will be added to the directory. Example: gunzip -k geeksforgeeks.txt.tar.gz Output: An extracted file will be added to the directory. -l: This option is used to get the information of a compressed or an uncompressed file.Example:gunzip -l geeksforgeeks.txt.tar.gzOutput: Example: gunzip -l geeksforgeeks.txt.tar.gz Output: -L: This option displays the software license and exit.Example:Output: Example: Output: -r: This option is used to uncompress all the files within the folder and subfolder recursively.Syntax:gunzip -r [Directory/Folder path]Example:This will extract all the compressed files recursively within the path /home/sc. Syntax: gunzip -r [Directory/Folder path] Example: This will extract all the compressed files recursively within the path /home/sc. -t: To test whether the file is valid or not.Syntax:gunzip -t [File name] Syntax: gunzip -t [File name] -v: This option is used to get verbose information such as the file name, decompression percentage, etc.Example:gunzip -v geeksforgeeks.txt.gzOutput: Example: gunzip -v geeksforgeeks.txt.gz Output: -V: This option is used to display version number. -a: This option uses ASCII text mode to convert End-of-line characters using local conversion. This option is only supported on MS-DOS systems. When -a option is used on a Unix system, it decompresses the file ignoring the –ascii option.Example: Example: -d: This option simply decompresses a file.Example:Output: The compressed file gets replaced by the original file i.e. geeksforgeeks.txt. Example: Output: The compressed file gets replaced by the original file i.e. geeksforgeeks.txt. -h: This option displays the help information available and quits. -n: This option does not save or restore the original name and time stamp while decompressing a file. -N: This option saves or restore the original name and time stamp while decompression. -q: This option suppresses all the warnings that arise during the execution of the command. -s: This option use suffix SUF on compressed files. -#: This option is used to control the speed and the amount of compression, where # can be any number between -1 to -9. -1 ensures the faster compression by decreasing the amount of compression while -9 ensures the best compression but takes more time comparatively. shubham_singh linux-command Linux-file-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Sep, 2019" }, { "code": null, "e": 343, "s": 52, "text": "gunzip command is used to compress or expand a file or a list of files in Linux. It accepts all the files having extension as .gz, .z, _z, -gz, -z , .Z, .taz or.tgz and replace the compressed file with the original file by default. The files after uncompression retain its actual extension." }, { "code": null, "e": 351, "s": 343, "text": "Syntax:" }, { "code": null, "e": 392, "s": 351, "text": "gunzip [Option] [archive name/file name]" }, { "code": null, "e": 491, "s": 392, "text": "Example 1: The argument that is passed here is: geeksforgeeks.txt which is a compressed text file." }, { "code": null, "e": 498, "s": 491, "text": "Input:" }, { "code": null, "e": 506, "s": 498, "text": "Output:" }, { "code": null, "e": 527, "s": 506, "text": "geeksforgeeks.txt.gz" }, { "code": null, "e": 624, "s": 527, "text": "Example 2: The argument that is passed here is: geeksforgeeks.txt.gz which is a compressed file." }, { "code": null, "e": 631, "s": 624, "text": "Input:" }, { "code": null, "e": 639, "s": 631, "text": "Output:" }, { "code": null, "e": 657, "s": 639, "text": "geeksforgeeks.txt" }, { "code": null, "e": 942, "s": 657, "text": "If a file is compressed using gzip command, a suffix i.e. .gz will be added to the file name after compression. Hence while uncompressing this file we can either use the original file name as shown in Example 1 or the filename with the suffix .gz as shown in Example 2 as an argument." }, { "code": null, "e": 1095, "s": 942, "text": "Example 3: In order to uncompress multiple files using the gunzip command, we can pass multiple file names as an argument as shown in the below example:" }, { "code": null, "e": 1103, "s": 1095, "text": "Syntax:" }, { "code": null, "e": 1137, "s": 1103, "text": "gunzip [file1] [file2] [file3]..." }, { "code": null, "e": 1144, "s": 1137, "text": "Input:" }, { "code": null, "e": 1152, "s": 1144, "text": "Output:" }, { "code": null, "e": 1179, "s": 1152, "text": "geeksforgeeks.txt, gfg.txt" }, { "code": null, "e": 1188, "s": 1179, "text": "Options:" }, { "code": null, "e": 1446, "s": 1188, "text": "-c: This option is used to view the text within a compressed file without uncompressing it. The ASCII/EBCDIC conversion is automatically done if it is suitable. The compressed file has to be a text file only.Example:gunzip -c geeksforgeeks.txt.tar.gzOutput:" }, { "code": null, "e": 1455, "s": 1446, "text": "Example:" }, { "code": null, "e": 1490, "s": 1455, "text": "gunzip -c geeksforgeeks.txt.tar.gz" }, { "code": null, "e": 1498, "s": 1490, "text": "Output:" }, { "code": null, "e": 1640, "s": 1498, "text": "-f: To decompress a file forcefully.Example:gunzip -f geeksforgeeks.txt.tar.gzOutput: The file will be forcefully extracted.geeksforgeeks.txt" }, { "code": null, "e": 1649, "s": 1640, "text": "Example:" }, { "code": null, "e": 1684, "s": 1649, "text": "gunzip -f geeksforgeeks.txt.tar.gz" }, { "code": null, "e": 1731, "s": 1684, "text": "Output: The file will be forcefully extracted." }, { "code": null, "e": 1749, "s": 1731, "text": "geeksforgeeks.txt" }, { "code": null, "e": 1980, "s": 1749, "text": "-k: This option can be used when we want to keep both the file i.e. the uncompressed and the original file after the uncompression.Example:gunzip -k geeksforgeeks.txt.tar.gzOutput: An extracted file will be added to the directory." }, { "code": null, "e": 1989, "s": 1980, "text": "Example:" }, { "code": null, "e": 2024, "s": 1989, "text": "gunzip -k geeksforgeeks.txt.tar.gz" }, { "code": null, "e": 2082, "s": 2024, "text": "Output: An extracted file will be added to the directory." }, { "code": null, "e": 2219, "s": 2082, "text": "-l: This option is used to get the information of a compressed or an uncompressed file.Example:gunzip -l geeksforgeeks.txt.tar.gzOutput:" }, { "code": null, "e": 2228, "s": 2219, "text": "Example:" }, { "code": null, "e": 2263, "s": 2228, "text": "gunzip -l geeksforgeeks.txt.tar.gz" }, { "code": null, "e": 2271, "s": 2263, "text": "Output:" }, { "code": null, "e": 2342, "s": 2271, "text": "-L: This option displays the software license and exit.Example:Output:" }, { "code": null, "e": 2351, "s": 2342, "text": "Example:" }, { "code": null, "e": 2359, "s": 2351, "text": "Output:" }, { "code": null, "e": 2584, "s": 2359, "text": "-r: This option is used to uncompress all the files within the folder and subfolder recursively.Syntax:gunzip -r [Directory/Folder path]Example:This will extract all the compressed files recursively within the path /home/sc." }, { "code": null, "e": 2592, "s": 2584, "text": "Syntax:" }, { "code": null, "e": 2626, "s": 2592, "text": "gunzip -r [Directory/Folder path]" }, { "code": null, "e": 2635, "s": 2626, "text": "Example:" }, { "code": null, "e": 2716, "s": 2635, "text": "This will extract all the compressed files recursively within the path /home/sc." }, { "code": null, "e": 2790, "s": 2716, "text": "-t: To test whether the file is valid or not.Syntax:gunzip -t [File name]" }, { "code": null, "e": 2798, "s": 2790, "text": "Syntax:" }, { "code": null, "e": 2820, "s": 2798, "text": "gunzip -t [File name]" }, { "code": null, "e": 2970, "s": 2820, "text": "-v: This option is used to get verbose information such as the file name, decompression percentage, etc.Example:gunzip -v geeksforgeeks.txt.gzOutput:" }, { "code": null, "e": 2979, "s": 2970, "text": "Example:" }, { "code": null, "e": 3010, "s": 2979, "text": "gunzip -v geeksforgeeks.txt.gz" }, { "code": null, "e": 3018, "s": 3010, "text": "Output:" }, { "code": null, "e": 3069, "s": 3018, "text": "-V: This option is used to display version number." }, { "code": null, "e": 3315, "s": 3069, "text": "-a: This option uses ASCII text mode to convert End-of-line characters using local conversion. This option is only supported on MS-DOS systems. When -a option is used on a Unix system, it decompresses the file ignoring the –ascii option.Example:" }, { "code": null, "e": 3324, "s": 3315, "text": "Example:" }, { "code": null, "e": 3462, "s": 3324, "text": "-d: This option simply decompresses a file.Example:Output: The compressed file gets replaced by the original file i.e. geeksforgeeks.txt." }, { "code": null, "e": 3471, "s": 3462, "text": "Example:" }, { "code": null, "e": 3558, "s": 3471, "text": "Output: The compressed file gets replaced by the original file i.e. geeksforgeeks.txt." }, { "code": null, "e": 3625, "s": 3558, "text": "-h: This option displays the help information available and quits." }, { "code": null, "e": 3727, "s": 3625, "text": "-n: This option does not save or restore the original name and time stamp while decompressing a file." }, { "code": null, "e": 3814, "s": 3727, "text": "-N: This option saves or restore the original name and time stamp while decompression." }, { "code": null, "e": 3906, "s": 3814, "text": "-q: This option suppresses all the warnings that arise during the execution of the command." }, { "code": null, "e": 3958, "s": 3906, "text": "-s: This option use suffix SUF on compressed files." }, { "code": null, "e": 4225, "s": 3958, "text": "-#: This option is used to control the speed and the amount of compression, where # can be any number between -1 to -9. -1 ensures the faster compression by decreasing the amount of compression while -9 ensures the best compression but takes more time comparatively." }, { "code": null, "e": 4239, "s": 4225, "text": "shubham_singh" }, { "code": null, "e": 4253, "s": 4239, "text": "linux-command" }, { "code": null, "e": 4273, "s": 4253, "text": "Linux-file-commands" }, { "code": null, "e": 4280, "s": 4273, "text": "Picked" }, { "code": null, "e": 4291, "s": 4280, "text": "Linux-Unix" } ]
Matplotlib.pyplot.fill_between() in Python
19 Apr, 2020 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The matplotlib.pyplot.fill_between() is used to fill area between two horizontal curves. Two points (x, y1) and (x, y2) define the curves. this creates one or more polygons describing the filled areas. The ‘where’ parameter can be used to selectively fill some areas. By default, edges connect the given points directly. The ‘step’ parameter is used if the filling needs to be a step function. Syntax: matplotlib.pyplot.fill_between(x, y1, y2=0, where=None, step=None, interpolate=False, *, data=None, **kwargs) Parameters: x: It is array of length N. These are the y coordinates of the nodes that define the curves.y1:It is an array of length N or a scalar. This represents the x coordinates of the nodes that define the first curve.y2: It is an array of length N and is optional in nature. Its default value is 0. This represents the x coordinates of the nodes that define the second curve.where: it is an array of boolean values of length N. It is defined if there is a need to exclude some vertical regions from being filled. It is important to note that this definition means that an isolated true value in between two two false values is where it will not do the filling. Adjacent False values results in not filling both sides of the True value.interpolate: It is an optional parameter that accepts boolean values. It is only relevant if where is used and two curves are crossing each other. Semantically where if generally used for y1>y2 or similar cases. By default the filled regions will be placed at the x-array positions defining a filled polygonal area. The section of x that has the intersection are simply clipped. Setting this parameter to True results in calculation of the actual point of intersection and extends to the filled regions till the points.step: This is an optional parameter that accepts one of the three values namely, ‘pre’, ‘post’ and ‘mid’. This is used to specify where the steps will occur.pre: From every y position the x value is continued constantlyto the left, ie, the interval (x[i-1], x[i]) has the value y[i].post:From every y position the x value is continued constantly to the right, ie, the interval (x[i], x[i+1]) has the value y[i].mid: Half way between the x positions these steps occur. x: It is array of length N. These are the y coordinates of the nodes that define the curves. y1:It is an array of length N or a scalar. This represents the x coordinates of the nodes that define the first curve. y2: It is an array of length N and is optional in nature. Its default value is 0. This represents the x coordinates of the nodes that define the second curve. where: it is an array of boolean values of length N. It is defined if there is a need to exclude some vertical regions from being filled. It is important to note that this definition means that an isolated true value in between two two false values is where it will not do the filling. Adjacent False values results in not filling both sides of the True value. interpolate: It is an optional parameter that accepts boolean values. It is only relevant if where is used and two curves are crossing each other. Semantically where if generally used for y1>y2 or similar cases. By default the filled regions will be placed at the x-array positions defining a filled polygonal area. The section of x that has the intersection are simply clipped. Setting this parameter to True results in calculation of the actual point of intersection and extends to the filled regions till the points. step: This is an optional parameter that accepts one of the three values namely, ‘pre’, ‘post’ and ‘mid’. This is used to specify where the steps will occur.pre: From every y position the x value is continued constantlyto the left, ie, the interval (x[i-1], x[i]) has the value y[i].post:From every y position the x value is continued constantly to the right, ie, the interval (x[i], x[i+1]) has the value y[i].mid: Half way between the x positions these steps occur. pre: From every y position the x value is continued constantlyto the left, ie, the interval (x[i-1], x[i]) has the value y[i]. post:From every y position the x value is continued constantly to the right, ie, the interval (x[i], x[i+1]) has the value y[i]. mid: Half way between the x positions these steps occur. Returns: It returns a plotted polygon from the PolyCollection. other Parameters: **kwargs contains keywords from PolyCollection that controls the polygon properties; Example 1: import matplotlib.pyplot as pltimport numpy as np x = np.arange(0,10,0.1) # plotting the linesa1 = 4 - 2*xa2 = 3 - 0.5*xa3 = 1 -x # The upper edge of# polygona4 = np.minimum(a1, a2) # Setting the y-limitplt.ylim(0, 5) # Plot the linesplt.plot(x, a1, x, a2, x, a3) # Filling between line a3 # and line a4plt.fill_between(x, a3, a4, color='green', alpha=0.5)plt.show() Output: Example 2: import matplotlib.pyplot as pltimport numpy as np a = np.linspace(0,2*3.14,50)b = np.sin(a) plt.fill_between(a, b, 0, where = (a > 2) & (a <= 3), color = 'g')plt.plot(a,b) Output: Python-matplotlib Python Write From Home 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() 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 Similarities and Difference between Java and C++
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Apr, 2020" }, { "code": null, "e": 266, "s": 54, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack." }, { "code": null, "e": 660, "s": 266, "text": "The matplotlib.pyplot.fill_between() is used to fill area between two horizontal curves. Two points (x, y1) and (x, y2) define the curves. this creates one or more polygons describing the filled areas. The ‘where’ parameter can be used to selectively fill some areas. By default, edges connect the given points directly. The ‘step’ parameter is used if the filling needs to be a step function." }, { "code": null, "e": 778, "s": 660, "text": "Syntax: matplotlib.pyplot.fill_between(x, y1, y2=0, where=None, step=None, interpolate=False, *, data=None, **kwargs)" }, { "code": null, "e": 790, "s": 778, "text": "Parameters:" }, { "code": null, "e": 2505, "s": 790, "text": "x: It is array of length N. These are the y coordinates of the nodes that define the curves.y1:It is an array of length N or a scalar. This represents the x coordinates of the nodes that define the first curve.y2: It is an array of length N and is optional in nature. Its default value is 0. This represents the x coordinates of the nodes that define the second curve.where: it is an array of boolean values of length N. It is defined if there is a need to exclude some vertical regions from being filled. It is important to note that this definition means that an isolated true value in between two two false values is where it will not do the filling. Adjacent False values results in not filling both sides of the True value.interpolate: It is an optional parameter that accepts boolean values. It is only relevant if where is used and two curves are crossing each other. Semantically where if generally used for y1>y2 or similar cases. By default the filled regions will be placed at the x-array positions defining a filled polygonal area. The section of x that has the intersection are simply clipped. Setting this parameter to True results in calculation of the actual point of intersection and extends to the filled regions till the points.step: This is an optional parameter that accepts one of the three values namely, ‘pre’, ‘post’ and ‘mid’. This is used to specify where the steps will occur.pre: From every y position the x value is continued constantlyto the left, ie, the interval (x[i-1], x[i]) has the value y[i].post:From every y position the x value is continued constantly to the right, ie, the interval (x[i], x[i+1]) has the value y[i].mid: Half way between the x positions these steps occur." }, { "code": null, "e": 2598, "s": 2505, "text": "x: It is array of length N. These are the y coordinates of the nodes that define the curves." }, { "code": null, "e": 2717, "s": 2598, "text": "y1:It is an array of length N or a scalar. This represents the x coordinates of the nodes that define the first curve." }, { "code": null, "e": 2876, "s": 2717, "text": "y2: It is an array of length N and is optional in nature. Its default value is 0. This represents the x coordinates of the nodes that define the second curve." }, { "code": null, "e": 3237, "s": 2876, "text": "where: it is an array of boolean values of length N. It is defined if there is a need to exclude some vertical regions from being filled. It is important to note that this definition means that an isolated true value in between two two false values is where it will not do the filling. Adjacent False values results in not filling both sides of the True value." }, { "code": null, "e": 3757, "s": 3237, "text": "interpolate: It is an optional parameter that accepts boolean values. It is only relevant if where is used and two curves are crossing each other. Semantically where if generally used for y1>y2 or similar cases. By default the filled regions will be placed at the x-array positions defining a filled polygonal area. The section of x that has the intersection are simply clipped. Setting this parameter to True results in calculation of the actual point of intersection and extends to the filled regions till the points." }, { "code": null, "e": 4225, "s": 3757, "text": "step: This is an optional parameter that accepts one of the three values namely, ‘pre’, ‘post’ and ‘mid’. This is used to specify where the steps will occur.pre: From every y position the x value is continued constantlyto the left, ie, the interval (x[i-1], x[i]) has the value y[i].post:From every y position the x value is continued constantly to the right, ie, the interval (x[i], x[i+1]) has the value y[i].mid: Half way between the x positions these steps occur." }, { "code": null, "e": 4352, "s": 4225, "text": "pre: From every y position the x value is continued constantlyto the left, ie, the interval (x[i-1], x[i]) has the value y[i]." }, { "code": null, "e": 4481, "s": 4352, "text": "post:From every y position the x value is continued constantly to the right, ie, the interval (x[i], x[i+1]) has the value y[i]." }, { "code": null, "e": 4538, "s": 4481, "text": "mid: Half way between the x positions these steps occur." }, { "code": null, "e": 4601, "s": 4538, "text": "Returns: It returns a plotted polygon from the PolyCollection." }, { "code": null, "e": 4704, "s": 4601, "text": "other Parameters: **kwargs contains keywords from PolyCollection that controls the polygon properties;" }, { "code": null, "e": 4715, "s": 4704, "text": "Example 1:" }, { "code": "import matplotlib.pyplot as pltimport numpy as np x = np.arange(0,10,0.1) # plotting the linesa1 = 4 - 2*xa2 = 3 - 0.5*xa3 = 1 -x # The upper edge of# polygona4 = np.minimum(a1, a2) # Setting the y-limitplt.ylim(0, 5) # Plot the linesplt.plot(x, a1, x, a2, x, a3) # Filling between line a3 # and line a4plt.fill_between(x, a3, a4, color='green', alpha=0.5)plt.show()", "e": 5118, "s": 4715, "text": null }, { "code": null, "e": 5126, "s": 5118, "text": "Output:" }, { "code": null, "e": 5137, "s": 5126, "text": "Example 2:" }, { "code": "import matplotlib.pyplot as pltimport numpy as np a = np.linspace(0,2*3.14,50)b = np.sin(a) plt.fill_between(a, b, 0, where = (a > 2) & (a <= 3), color = 'g')plt.plot(a,b)", "e": 5345, "s": 5137, "text": null }, { "code": null, "e": 5353, "s": 5345, "text": "Output:" }, { "code": null, "e": 5371, "s": 5353, "text": "Python-matplotlib" }, { "code": null, "e": 5378, "s": 5371, "text": "Python" }, { "code": null, "e": 5394, "s": 5378, "text": "Write From Home" }, { "code": null, "e": 5492, "s": 5394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5510, "s": 5492, "text": "Python Dictionary" }, { "code": null, "e": 5552, "s": 5510, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5574, "s": 5552, "text": "Enumerate() in Python" }, { "code": null, "e": 5609, "s": 5574, "text": "Read a file line by line in Python" }, { "code": null, "e": 5635, "s": 5609, "text": "Python String | replace()" }, { "code": null, "e": 5671, "s": 5635, "text": "Convert integer to string in Python" }, { "code": null, "e": 5707, "s": 5671, "text": "Convert string to integer in Python" }, { "code": null, "e": 5768, "s": 5707, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 5784, "s": 5768, "text": "Python infinity" } ]
Unique element in an array where all elements occur k times except one
21 Jun, 2022 Given an array that contains all elements occurring k times, but one occurs only once. Find that unique element.Examples: Input : arr[] = {6, 2, 5, 2, 2, 6, 6} k = 3Output : 5Explanation: Every element appears 3 times accept 5. Input : arr[] = {2, 2, 2, 10, 2} k = 4Output: 10Explanation: Every element appears 4 times accept 10. A Simple Solution is to use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present k times or not. If present, then ignores the element, else prints the element. The Time Complexity of the above solution is O(n2). We can Use Sorting to solve the problem in O(nLogn) time. The idea is simple, the first sort the array so that all occurrences of every element become consecutive. Once the occurrences become consecutive, we can traverse the sorted array and print the unique element in O(n) time.We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the given array from left to right and keep track of visited elements in a hash table. Finally, print the element with count 1.The hashing-based solution requires O(n) extra space. We can use bitwise AND to find the unique element in O(n) time and constant extra space. Create an array count[] of size equal to number of bits in binary representations of numbers.Fill count array such that count[i] stores count of array elements with i-th bit set.Form result using count array. We put 1 at a position i in result if count[i] is not multiple of k. Else we put 0. Create an array count[] of size equal to number of bits in binary representations of numbers. Fill count array such that count[i] stores count of array elements with i-th bit set.Form result using count array. We put 1 at a position i in result if count[i] is not multiple of k. Else we put 0. Form result using count array. We put 1 at a position i in result if count[i] is not multiple of k. Else we put 0. Form result using count array. We put 1 at a position i in result if count[i] is not multiple of k. Else we put 0. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP program to find unique element where// every element appears k times except one#include <bits/stdc++.h>using namespace std; int findUnique(unsigned int a[], int n, int k){ // Create a count array to store count of // numbers that have a particular bit set. // count[i] stores count of array elements // with i-th bit set. int INT_SIZE = 8 * sizeof(unsigned int); int count[INT_SIZE]; memset(count, 0, sizeof(count)); // AND(bitwise) each element of the array // with each set digit (one at a time) // to get the count of set bits at each // position for (int i = 0; i < INT_SIZE; i++) for (int j = 0; j < n; j++) if ((a[j] & (1 << i)) != 0) count[i] += 1; // Now consider all bits whose count is // not multiple of k to form the required // number. unsigned res = 0; for (int i = 0; i < INT_SIZE; i++) res += (count[i] % k) * (1 << i); // Before returning the res we need // to check the occurrence of that // unique element and divide it res = res / (n % k); return res;} // Driver Codeint main(){ unsigned int a[] = { 6, 2, 5, 2, 2, 6, 6 }; int n = sizeof(a) / sizeof(a[0]); int k = 3; cout << findUnique(a, n, k); return 0;} // Java program to find unique element where// every element appears k times except one class GFG { static int findUnique(int a[], int n, int k) { // Create a count array to store count of // numbers that have a particular bit set. // count[i] stores count of array elements // with i-th bit set. byte sizeof_int = 4; int INT_SIZE = 8 * sizeof_int; int count[] = new int[INT_SIZE]; // AND(bitwise) each element of the array // with each set digit (one at a time) // to get the count of set bits at each // position for (int i = 0; i < INT_SIZE; i++) for (int j = 0; j < n; j++) if ((a[j] & (1 << i)) != 0) count[i] += 1; // Now consider all bits whose count is // not multiple of k to form the required // number. int res = 0; for (int i = 0; i < INT_SIZE; i++) res += (count[i] % k) * (1 << i); // Before returning the res we need // to check the occurrence of that // unique element and divide it res = res / (n % k); return res; } // Driver Code public static void main(String[] args) { int a[] = { 6, 2, 5, 2, 2, 6, 6 }; int n = a.length; int k = 3; System.out.println(findUnique(a, n, k)); }} // This code is contributed by 29AjayKumar # Python 3 program to find unique element where# every element appears k times except oneimport sys def findUnique(a, n, k): # Create a count array to store count of # numbers that have a particular bit set. # count[i] stores count of array elements # with i-th bit set. INT_SIZE = 8 * sys.getsizeof(int) count = [0] * INT_SIZE # AND(bitwise) each element of the array # with each set digit (one at a time) # to get the count of set bits at each # position for i in range(INT_SIZE): for j in range(n): if ((a[j] & (1 << i)) != 0): count[i] += 1 # Now consider all bits whose count is # not multiple of k to form the required # number. res = 0 for i in range(INT_SIZE): res += (count[i] % k) * (1 << i) # Before returning the res we need # to check the occurrence of that # unique element and divide it res = res / (n % k) return res # Driver Codeif __name__ == '__main__': a = [6, 2, 5, 2, 2, 6, 6] n = len(a) k = 3 print(findUnique(a, n, k)) # This code is contributed by# Surendra_Gangwar // C# program to find unique element where// every element appears k times except oneusing System; class GFG { static int findUnique(int[] a, int n, int k) { // Create a count array to store count of // numbers that have a particular bit set. // count[i] stores count of array elements // with i-th bit set. byte sizeof_int = 4; int INT_SIZE = 8 * sizeof_int; int[] count = new int[INT_SIZE]; // AND(bitwise) each element of the array // with each set digit (one at a time) // to get the count of set bits at each // position for (int i = 0; i < INT_SIZE; i++) for (int j = 0; j < n; j++) if ((a[j] & (1 << i)) != 0) count[i] += 1; // Now consider all bits whose count is // not multiple of k to form the required // number. int res = 0; for (int i = 0; i < INT_SIZE; i++) res += (count[i] % k) * (1 << i); // Before returning the res we need // to check the occurrence of that // unique element and divide it res = res / (n % k); return res; } // Driver Code public static void Main(String[] args) { int[] a = { 6, 2, 5, 2, 2, 6, 6 }; int n = a.Length; int k = 3; Console.WriteLine(findUnique(a, n, k)); }} // This code is contributed by PrinciRaj1992 <?php//PHP program to find unique element where// every element appears k times except one function findUnique($a, $n, $k){ // Create a count array to store count of // numbers that have a particular bit set. // count[i] stores count of array elements // with i-th bit set. $INT_SIZE = 8 * PHP_INT_SIZE; $count = array(); for($i=0; $i< $INT_SIZE; $i++) $count[$i] = 0; // AND(bitwise) each element of the array // with each set digit (one at a time) // to get the count of set bits at each // position for ( $i = 0; $i < $INT_SIZE; $i++) for ( $j = 0; $j < $n; $j++) if (($a[$j] & (1 << $i)) != 0) $count[$i] += 1; // Now consider all bits whose count is // not multiple of k to form the required // number. $res = 0; for ($i = 0; $i < $INT_SIZE; $i++) $res += ($count[$i] % $k) * (1 << $i); // Before returning the res we need // to check the occurrence of that // unique element and divide it $res = $res / ($n % $k); return $res;} // Driver Code $a = array( 6, 2, 5, 2, 2, 6, 6 ); $n = count($a); $k = 3; echo findUnique($a, $n, $k); // This code is contributed by Rajput-Ji?> <script>// Javascript program to find unique element where// every element appears k times except one function findUnique(a, n, k){ // Create a count array to store count of // numbers that have a particular bit set. // count[i] stores count of array elements // with i-th bit set. let sizeof_let = 4; let LET_SIZE = 8 * sizeof_let; let count = Array.from({length: LET_SIZE}, (_, i) => 0); // AND(bitwise) each element of the array // with each set digit (one at a time) // to get the count of set bits at each // position for (let i = 0; i < LET_SIZE; i++) for (let j = 0; j < n; j++) if ((a[j] & (1 << i)) != 0) count[i] += 1; // Now consider all bits whose count is // not multiple of k to form the required // number. let res = 0; for (let i = 0; i < LET_SIZE; i++) res += (count[i] % k) * (1 << i); // Before returning the res we need // to check the occurrence of that // unique element and divide it res = res / (n % k); return res;} // driver function let a = [ 6, 2, 5, 2, 2, 6, 6 ]; let n = a.length; let k = 3; document.write(findUnique(a, n, k)); </script> 5 Time Complexity: O(n) Auxiliary Space: O(1) This article is contributed by Dhiman Mayank. 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. 29AjayKumar princiraj1992 SURENDRA_GANGWAR Rajput-Ji sanjoy_62 harendrakumar123 ranjanrohit840 Arrays Bit Magic Hash Arrays Hash Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2022" }, { "code": null, "e": 177, "s": 54, "text": "Given an array that contains all elements occurring k times, but one occurs only once. Find that unique element.Examples: " }, { "code": null, "e": 295, "s": 177, "text": "Input : arr[] = {6, 2, 5, 2, 2, 6, 6} k = 3Output : 5Explanation: Every element appears 3 times accept 5." }, { "code": null, "e": 410, "s": 295, "text": "Input : arr[] = {2, 2, 2, 10, 2} k = 4Output: 10Explanation: Every element appears 4 times accept 10. " }, { "code": null, "e": 1347, "s": 410, "text": "A Simple Solution is to use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present k times or not. If present, then ignores the element, else prints the element. The Time Complexity of the above solution is O(n2). We can Use Sorting to solve the problem in O(nLogn) time. The idea is simple, the first sort the array so that all occurrences of every element become consecutive. Once the occurrences become consecutive, we can traverse the sorted array and print the unique element in O(n) time.We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the given array from left to right and keep track of visited elements in a hash table. Finally, print the element with count 1.The hashing-based solution requires O(n) extra space. We can use bitwise AND to find the unique element in O(n) time and constant extra space. " }, { "code": null, "e": 1640, "s": 1347, "text": "Create an array count[] of size equal to number of bits in binary representations of numbers.Fill count array such that count[i] stores count of array elements with i-th bit set.Form result using count array. We put 1 at a position i in result if count[i] is not multiple of k. Else we put 0." }, { "code": null, "e": 1734, "s": 1640, "text": "Create an array count[] of size equal to number of bits in binary representations of numbers." }, { "code": null, "e": 1934, "s": 1734, "text": "Fill count array such that count[i] stores count of array elements with i-th bit set.Form result using count array. We put 1 at a position i in result if count[i] is not multiple of k. Else we put 0." }, { "code": null, "e": 2049, "s": 1934, "text": "Form result using count array. We put 1 at a position i in result if count[i] is not multiple of k. Else we put 0." }, { "code": null, "e": 2164, "s": 2049, "text": "Form result using count array. We put 1 at a position i in result if count[i] is not multiple of k. Else we put 0." }, { "code": null, "e": 2215, "s": 2164, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2219, "s": 2215, "text": "C++" }, { "code": null, "e": 2224, "s": 2219, "text": "Java" }, { "code": null, "e": 2232, "s": 2224, "text": "Python3" }, { "code": null, "e": 2235, "s": 2232, "text": "C#" }, { "code": null, "e": 2239, "s": 2235, "text": "PHP" }, { "code": null, "e": 2250, "s": 2239, "text": "Javascript" }, { "code": "// CPP program to find unique element where// every element appears k times except one#include <bits/stdc++.h>using namespace std; int findUnique(unsigned int a[], int n, int k){ // Create a count array to store count of // numbers that have a particular bit set. // count[i] stores count of array elements // with i-th bit set. int INT_SIZE = 8 * sizeof(unsigned int); int count[INT_SIZE]; memset(count, 0, sizeof(count)); // AND(bitwise) each element of the array // with each set digit (one at a time) // to get the count of set bits at each // position for (int i = 0; i < INT_SIZE; i++) for (int j = 0; j < n; j++) if ((a[j] & (1 << i)) != 0) count[i] += 1; // Now consider all bits whose count is // not multiple of k to form the required // number. unsigned res = 0; for (int i = 0; i < INT_SIZE; i++) res += (count[i] % k) * (1 << i); // Before returning the res we need // to check the occurrence of that // unique element and divide it res = res / (n % k); return res;} // Driver Codeint main(){ unsigned int a[] = { 6, 2, 5, 2, 2, 6, 6 }; int n = sizeof(a) / sizeof(a[0]); int k = 3; cout << findUnique(a, n, k); return 0;}", "e": 3510, "s": 2250, "text": null }, { "code": "// Java program to find unique element where// every element appears k times except one class GFG { static int findUnique(int a[], int n, int k) { // Create a count array to store count of // numbers that have a particular bit set. // count[i] stores count of array elements // with i-th bit set. byte sizeof_int = 4; int INT_SIZE = 8 * sizeof_int; int count[] = new int[INT_SIZE]; // AND(bitwise) each element of the array // with each set digit (one at a time) // to get the count of set bits at each // position for (int i = 0; i < INT_SIZE; i++) for (int j = 0; j < n; j++) if ((a[j] & (1 << i)) != 0) count[i] += 1; // Now consider all bits whose count is // not multiple of k to form the required // number. int res = 0; for (int i = 0; i < INT_SIZE; i++) res += (count[i] % k) * (1 << i); // Before returning the res we need // to check the occurrence of that // unique element and divide it res = res / (n % k); return res; } // Driver Code public static void main(String[] args) { int a[] = { 6, 2, 5, 2, 2, 6, 6 }; int n = a.length; int k = 3; System.out.println(findUnique(a, n, k)); }} // This code is contributed by 29AjayKumar", "e": 4917, "s": 3510, "text": null }, { "code": "# Python 3 program to find unique element where# every element appears k times except oneimport sys def findUnique(a, n, k): # Create a count array to store count of # numbers that have a particular bit set. # count[i] stores count of array elements # with i-th bit set. INT_SIZE = 8 * sys.getsizeof(int) count = [0] * INT_SIZE # AND(bitwise) each element of the array # with each set digit (one at a time) # to get the count of set bits at each # position for i in range(INT_SIZE): for j in range(n): if ((a[j] & (1 << i)) != 0): count[i] += 1 # Now consider all bits whose count is # not multiple of k to form the required # number. res = 0 for i in range(INT_SIZE): res += (count[i] % k) * (1 << i) # Before returning the res we need # to check the occurrence of that # unique element and divide it res = res / (n % k) return res # Driver Codeif __name__ == '__main__': a = [6, 2, 5, 2, 2, 6, 6] n = len(a) k = 3 print(findUnique(a, n, k)) # This code is contributed by# Surendra_Gangwar", "e": 6030, "s": 4917, "text": null }, { "code": "// C# program to find unique element where// every element appears k times except oneusing System; class GFG { static int findUnique(int[] a, int n, int k) { // Create a count array to store count of // numbers that have a particular bit set. // count[i] stores count of array elements // with i-th bit set. byte sizeof_int = 4; int INT_SIZE = 8 * sizeof_int; int[] count = new int[INT_SIZE]; // AND(bitwise) each element of the array // with each set digit (one at a time) // to get the count of set bits at each // position for (int i = 0; i < INT_SIZE; i++) for (int j = 0; j < n; j++) if ((a[j] & (1 << i)) != 0) count[i] += 1; // Now consider all bits whose count is // not multiple of k to form the required // number. int res = 0; for (int i = 0; i < INT_SIZE; i++) res += (count[i] % k) * (1 << i); // Before returning the res we need // to check the occurrence of that // unique element and divide it res = res / (n % k); return res; } // Driver Code public static void Main(String[] args) { int[] a = { 6, 2, 5, 2, 2, 6, 6 }; int n = a.Length; int k = 3; Console.WriteLine(findUnique(a, n, k)); }} // This code is contributed by PrinciRaj1992", "e": 7447, "s": 6030, "text": null }, { "code": "<?php//PHP program to find unique element where// every element appears k times except one function findUnique($a, $n, $k){ // Create a count array to store count of // numbers that have a particular bit set. // count[i] stores count of array elements // with i-th bit set. $INT_SIZE = 8 * PHP_INT_SIZE; $count = array(); for($i=0; $i< $INT_SIZE; $i++) $count[$i] = 0; // AND(bitwise) each element of the array // with each set digit (one at a time) // to get the count of set bits at each // position for ( $i = 0; $i < $INT_SIZE; $i++) for ( $j = 0; $j < $n; $j++) if (($a[$j] & (1 << $i)) != 0) $count[$i] += 1; // Now consider all bits whose count is // not multiple of k to form the required // number. $res = 0; for ($i = 0; $i < $INT_SIZE; $i++) $res += ($count[$i] % $k) * (1 << $i); // Before returning the res we need // to check the occurrence of that // unique element and divide it $res = $res / ($n % $k); return $res;} // Driver Code $a = array( 6, 2, 5, 2, 2, 6, 6 ); $n = count($a); $k = 3; echo findUnique($a, $n, $k); // This code is contributed by Rajput-Ji?>", "e": 8668, "s": 7447, "text": null }, { "code": "<script>// Javascript program to find unique element where// every element appears k times except one function findUnique(a, n, k){ // Create a count array to store count of // numbers that have a particular bit set. // count[i] stores count of array elements // with i-th bit set. let sizeof_let = 4; let LET_SIZE = 8 * sizeof_let; let count = Array.from({length: LET_SIZE}, (_, i) => 0); // AND(bitwise) each element of the array // with each set digit (one at a time) // to get the count of set bits at each // position for (let i = 0; i < LET_SIZE; i++) for (let j = 0; j < n; j++) if ((a[j] & (1 << i)) != 0) count[i] += 1; // Now consider all bits whose count is // not multiple of k to form the required // number. let res = 0; for (let i = 0; i < LET_SIZE; i++) res += (count[i] % k) * (1 << i); // Before returning the res we need // to check the occurrence of that // unique element and divide it res = res / (n % k); return res;} // driver function let a = [ 6, 2, 5, 2, 2, 6, 6 ]; let n = a.length; let k = 3; document.write(findUnique(a, n, k)); </script>", "e": 9884, "s": 8668, "text": null }, { "code": null, "e": 9886, "s": 9884, "text": "5" }, { "code": null, "e": 9908, "s": 9886, "text": "Time Complexity: O(n)" }, { "code": null, "e": 9930, "s": 9908, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 10352, "s": 9930, "text": "This article is contributed by Dhiman Mayank. 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": 10364, "s": 10352, "text": "29AjayKumar" }, { "code": null, "e": 10378, "s": 10364, "text": "princiraj1992" }, { "code": null, "e": 10395, "s": 10378, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 10405, "s": 10395, "text": "Rajput-Ji" }, { "code": null, "e": 10415, "s": 10405, "text": "sanjoy_62" }, { "code": null, "e": 10432, "s": 10415, "text": "harendrakumar123" }, { "code": null, "e": 10447, "s": 10432, "text": "ranjanrohit840" }, { "code": null, "e": 10454, "s": 10447, "text": "Arrays" }, { "code": null, "e": 10464, "s": 10454, "text": "Bit Magic" }, { "code": null, "e": 10469, "s": 10464, "text": "Hash" }, { "code": null, "e": 10476, "s": 10469, "text": "Arrays" }, { "code": null, "e": 10481, "s": 10476, "text": "Hash" }, { "code": null, "e": 10491, "s": 10481, "text": "Bit Magic" }, { "code": null, "e": 10589, "s": 10491, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10657, "s": 10589, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 10701, "s": 10657, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 10733, "s": 10701, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 10781, "s": 10733, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 10795, "s": 10781, "text": "Linear Search" }, { "code": null, "e": 10822, "s": 10795, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 10868, "s": 10822, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 10936, "s": 10868, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 10965, "s": 10936, "text": "Count set bits in an integer" } ]
JSON with Python - GeeksforGeeks
19 Nov, 2021 JSON (JavaScript Object Notation) is a file that is mainly used to store and transfer data mostly between a server and a web application. It is popularly used for representing structured data. In this article, we will discuss how to handle JSON data using Python. Python provides a module called json which comes with Python’s standard built-in utility. Note: In Python, JSON data is usually represented as a string. To use any module in Python it is always needed to import that module. We can import json module by using the import statement. Example: Importing JSON module Python3 # importing json moduleimport json The load() and loads() functions of the json module makes it easier to parse JSON object. The loads() method is used to parse JSON strings in Python and the result will be a Python dictionary. Syntax: json.loads(json_string) Example: Converting JSON to a dictionary Python3 # Python program to convert JSON to Dict import json # JSON stringemployee ='{"name": "Nitin", "department":"Finance",\"company":"GFG"}' # Convert string to Python dictemployee_dict = json.loads(employee)print("Data after conversion")print(employee_dict)print(employee_dict['department']) print("\nType of data")print(type(employee_dict)) Data after conversion {'name': 'Nitin', 'department': 'Finance', 'company': 'GFG'} Finance Type of data <class 'dict'> Note: For more information, refer to Parse Data From JSON into Python load() method can read a file that contains a JSON object. Suppose you have a file named student.json that contains student data and we want to read that file. Syntax: json.load(file_object) Example: Reading JSON file using Python Let’s suppose the file looks like this. Python3 # Python program to read# json file import json # Opening JSON filef = open('data.json',) # returns JSON object as# a dictionarydata = json.load(f) # Iterating through the json# listfor i in data: print(i) # Closing filef.close() Output: Note: JSON data is converted to a List of dictionaries in Python In the above example, we have used to open() and close() function for opening and closing JSON file. If you are not familiar with file handling in Python, please refer to File Handling in Python. For more information about readon JSON file, refer to Read JSON file using Python dump() and dumps() method of json module can be used to convert from Python object to JSON. The following types of Python objects can be converted into JSON strings: dict list tuple string int float True False None Python objects and their equivalent conversion to JSON: dumps() method can convert a Python object into a JSON string. Syntax: json.dumps(dict, indent) It takes two parameters: dictionary: name of dictionary which should be converted to JSON object. indent: defines the number of units for indentation Example: Converting Python dictionary to JSON string Python3 # Python program to convert# Python to JSON import json # Data to be writtendictionary = { "name": "sunil", "department": "HR", "Company": 'GFG'} # Serializing jsonjson_object = json.dumps(dictionary)print(json_object) {"name": "sunil", "department": "HR", "Company": "GFG"} Note: For more information about converting JSON to string, refer to Python – Convert to JSON string dump() method can be used for writing to JSON file. Syntax: json.dump(dict, file_pointer) It takes 2 parameters: dictionary: name of a dictionary which should be converted to a JSON object. file pointer: pointer of the file opened in write or append mode. Example: Writing to JSON File Python3 # Python program to write JSON# to a file import json # Data to be writtendictionary ={ "name" : "Nisha", "rollno" : 420, "cgpa" : 10.10, "phonenumber" : "1234567890"} with open("sample.json", "w") as outfile: json.dump(dictionary, outfile) Output: In the above example, you must have seen that when you convert the Python object to JSON it does not get formatted and output comes in a straight line. We can format the JSON by passing the indent parameter to the dumps() method. Example: Formatting JSON Python3 # Import required librariesimport json # Initialize JSON datajson_data = '[ {"studentid": 1, "name": "Nikhil", "subjects": ["Python", "Data Structures"]},\{"studentid": 2, "name": "Nisha", "subjects": ["Java", "C++", "R Lang"]} ]' # Create Python object from JSON string# datadata = json.loads(json_data) # Pretty Print JSONjson_formatted_str = json.dumps(data, indent=4)print(json_formatted_str) [ { "studentid": 1, "name": "Nikhil", "subjects": [ "Python", "Data Structures" ] }, { "studentid": 2, "name": "Nisha", "subjects": [ "Java", "C++", "R Lang" ] } ] Note: For more information, refer to Pretty Print JSON in Python We can sort the JSON data with the help of the sort_keys parameter of the dumps() method. This parameter takes a boolean value and returns the sorted JSON if the value passed is True. By default, the value passed is False. Example: Sorting JSON Python3 # Import required librariesimport json # Initialize JSON datajson_data = '[ {"studentid": 1, "name": "Nikhil", "subjects":\["Python", "Data Structures"], "company":"GFG"},\{"studentid": 2, "name": "Nisha", "subjects":\["Java", "C++", "R Lang"], "company":"GFG"} ]' # Create Python object from JSON string# datadata = json.loads(json_data) # Pretty Print JSONjson_formatted_str = json.dumps(data, indent=4, sort_keys=True)print(json_formatted_str) [ { "company": "GFG", "name": "Nikhil", "studentid": 1, "subjects": [ "Python", "Data Structures" ] }, { "company": "GFG", "name": "Nisha", "studentid": 2, "subjects": [ "Java", "C++", "R Lang" ] } ] prachisoda1234 simmytarika5 Python-json Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n19 Nov, 2021" }, { "code": null, "e": 24567, "s": 24212, "text": "JSON (JavaScript Object Notation) is a file that is mainly used to store and transfer data mostly between a server and a web application. It is popularly used for representing structured data. In this article, we will discuss how to handle JSON data using Python. Python provides a module called json which comes with Python’s standard built-in utility." }, { "code": null, "e": 24630, "s": 24567, "text": "Note: In Python, JSON data is usually represented as a string." }, { "code": null, "e": 24758, "s": 24630, "text": "To use any module in Python it is always needed to import that module. We can import json module by using the import statement." }, { "code": null, "e": 24789, "s": 24758, "text": "Example: Importing JSON module" }, { "code": null, "e": 24797, "s": 24789, "text": "Python3" }, { "code": "# importing json moduleimport json", "e": 24832, "s": 24797, "text": null }, { "code": null, "e": 24926, "s": 24835, "text": "The load() and loads() functions of the json module makes it easier to parse JSON object. " }, { "code": null, "e": 25029, "s": 24926, "text": "The loads() method is used to parse JSON strings in Python and the result will be a Python dictionary." }, { "code": null, "e": 25037, "s": 25029, "text": "Syntax:" }, { "code": null, "e": 25061, "s": 25037, "text": "json.loads(json_string)" }, { "code": null, "e": 25102, "s": 25061, "text": "Example: Converting JSON to a dictionary" }, { "code": null, "e": 25110, "s": 25102, "text": "Python3" }, { "code": "# Python program to convert JSON to Dict import json # JSON stringemployee ='{\"name\": \"Nitin\", \"department\":\"Finance\",\\\"company\":\"GFG\"}' # Convert string to Python dictemployee_dict = json.loads(employee)print(\"Data after conversion\")print(employee_dict)print(employee_dict['department']) print(\"\\nType of data\")print(type(employee_dict))", "e": 25450, "s": 25110, "text": null }, { "code": null, "e": 25570, "s": 25450, "text": "Data after conversion\n{'name': 'Nitin', 'department': 'Finance', 'company': 'GFG'}\nFinance\n\nType of data\n<class 'dict'>" }, { "code": null, "e": 25642, "s": 25572, "text": "Note: For more information, refer to Parse Data From JSON into Python" }, { "code": null, "e": 25802, "s": 25642, "text": "load() method can read a file that contains a JSON object. Suppose you have a file named student.json that contains student data and we want to read that file." }, { "code": null, "e": 25810, "s": 25802, "text": "Syntax:" }, { "code": null, "e": 25833, "s": 25810, "text": "json.load(file_object)" }, { "code": null, "e": 25873, "s": 25833, "text": "Example: Reading JSON file using Python" }, { "code": null, "e": 25913, "s": 25873, "text": "Let’s suppose the file looks like this." }, { "code": null, "e": 25923, "s": 25915, "text": "Python3" }, { "code": "# Python program to read# json file import json # Opening JSON filef = open('data.json',) # returns JSON object as# a dictionarydata = json.load(f) # Iterating through the json# listfor i in data: print(i) # Closing filef.close()", "e": 26157, "s": 25923, "text": null }, { "code": null, "e": 26165, "s": 26157, "text": "Output:" }, { "code": null, "e": 26172, "s": 26165, "text": "Note: " }, { "code": null, "e": 26231, "s": 26172, "text": "JSON data is converted to a List of dictionaries in Python" }, { "code": null, "e": 26427, "s": 26231, "text": "In the above example, we have used to open() and close() function for opening and closing JSON file. If you are not familiar with file handling in Python, please refer to File Handling in Python." }, { "code": null, "e": 26509, "s": 26427, "text": "For more information about readon JSON file, refer to Read JSON file using Python" }, { "code": null, "e": 26601, "s": 26509, "text": "dump() and dumps() method of json module can be used to convert from Python object to JSON." }, { "code": null, "e": 26675, "s": 26601, "text": "The following types of Python objects can be converted into JSON strings:" }, { "code": null, "e": 26680, "s": 26675, "text": "dict" }, { "code": null, "e": 26685, "s": 26680, "text": "list" }, { "code": null, "e": 26691, "s": 26685, "text": "tuple" }, { "code": null, "e": 26698, "s": 26691, "text": "string" }, { "code": null, "e": 26702, "s": 26698, "text": "int" }, { "code": null, "e": 26708, "s": 26702, "text": "float" }, { "code": null, "e": 26713, "s": 26708, "text": "True" }, { "code": null, "e": 26719, "s": 26713, "text": "False" }, { "code": null, "e": 26724, "s": 26719, "text": "None" }, { "code": null, "e": 26780, "s": 26724, "text": "Python objects and their equivalent conversion to JSON:" }, { "code": null, "e": 26843, "s": 26780, "text": "dumps() method can convert a Python object into a JSON string." }, { "code": null, "e": 26851, "s": 26843, "text": "Syntax:" }, { "code": null, "e": 26876, "s": 26851, "text": "json.dumps(dict, indent)" }, { "code": null, "e": 26901, "s": 26876, "text": "It takes two parameters:" }, { "code": null, "e": 26974, "s": 26901, "text": "dictionary: name of dictionary which should be converted to JSON object." }, { "code": null, "e": 27026, "s": 26974, "text": "indent: defines the number of units for indentation" }, { "code": null, "e": 27079, "s": 27026, "text": "Example: Converting Python dictionary to JSON string" }, { "code": null, "e": 27087, "s": 27079, "text": "Python3" }, { "code": "# Python program to convert# Python to JSON import json # Data to be writtendictionary = { \"name\": \"sunil\", \"department\": \"HR\", \"Company\": 'GFG'} # Serializing jsonjson_object = json.dumps(dictionary)print(json_object)", "e": 27316, "s": 27087, "text": null }, { "code": null, "e": 27373, "s": 27316, "text": "{\"name\": \"sunil\", \"department\": \"HR\", \"Company\": \"GFG\"}\n" }, { "code": null, "e": 27474, "s": 27373, "text": "Note: For more information about converting JSON to string, refer to Python – Convert to JSON string" }, { "code": null, "e": 27526, "s": 27474, "text": "dump() method can be used for writing to JSON file." }, { "code": null, "e": 27534, "s": 27526, "text": "Syntax:" }, { "code": null, "e": 27564, "s": 27534, "text": "json.dump(dict, file_pointer)" }, { "code": null, "e": 27587, "s": 27564, "text": "It takes 2 parameters:" }, { "code": null, "e": 27664, "s": 27587, "text": "dictionary: name of a dictionary which should be converted to a JSON object." }, { "code": null, "e": 27730, "s": 27664, "text": "file pointer: pointer of the file opened in write or append mode." }, { "code": null, "e": 27760, "s": 27730, "text": "Example: Writing to JSON File" }, { "code": null, "e": 27768, "s": 27760, "text": "Python3" }, { "code": "# Python program to write JSON# to a file import json # Data to be writtendictionary ={ \"name\" : \"Nisha\", \"rollno\" : 420, \"cgpa\" : 10.10, \"phonenumber\" : \"1234567890\"} with open(\"sample.json\", \"w\") as outfile: json.dump(dictionary, outfile)", "e": 28025, "s": 27768, "text": null }, { "code": null, "e": 28033, "s": 28025, "text": "Output:" }, { "code": null, "e": 28263, "s": 28033, "text": "In the above example, you must have seen that when you convert the Python object to JSON it does not get formatted and output comes in a straight line. We can format the JSON by passing the indent parameter to the dumps() method." }, { "code": null, "e": 28288, "s": 28263, "text": "Example: Formatting JSON" }, { "code": null, "e": 28296, "s": 28288, "text": "Python3" }, { "code": "# Import required librariesimport json # Initialize JSON datajson_data = '[ {\"studentid\": 1, \"name\": \"Nikhil\", \"subjects\": [\"Python\", \"Data Structures\"]},\\{\"studentid\": 2, \"name\": \"Nisha\", \"subjects\": [\"Java\", \"C++\", \"R Lang\"]} ]' # Create Python object from JSON string# datadata = json.loads(json_data) # Pretty Print JSONjson_formatted_str = json.dumps(data, indent=4)print(json_formatted_str)", "e": 28693, "s": 28296, "text": null }, { "code": null, "e": 28997, "s": 28693, "text": "[\n {\n \"studentid\": 1,\n \"name\": \"Nikhil\",\n \"subjects\": [\n \"Python\",\n \"Data Structures\"\n ]\n },\n {\n \"studentid\": 2,\n \"name\": \"Nisha\",\n \"subjects\": [\n \"Java\",\n \"C++\",\n \"R Lang\"\n ]\n }\n]" }, { "code": null, "e": 29062, "s": 28997, "text": "Note: For more information, refer to Pretty Print JSON in Python" }, { "code": null, "e": 29285, "s": 29062, "text": "We can sort the JSON data with the help of the sort_keys parameter of the dumps() method. This parameter takes a boolean value and returns the sorted JSON if the value passed is True. By default, the value passed is False." }, { "code": null, "e": 29307, "s": 29285, "text": "Example: Sorting JSON" }, { "code": null, "e": 29315, "s": 29307, "text": "Python3" }, { "code": "# Import required librariesimport json # Initialize JSON datajson_data = '[ {\"studentid\": 1, \"name\": \"Nikhil\", \"subjects\":\\[\"Python\", \"Data Structures\"], \"company\":\"GFG\"},\\{\"studentid\": 2, \"name\": \"Nisha\", \"subjects\":\\[\"Java\", \"C++\", \"R Lang\"], \"company\":\"GFG\"} ]' # Create Python object from JSON string# datadata = json.loads(json_data) # Pretty Print JSONjson_formatted_str = json.dumps(data, indent=4, sort_keys=True)print(json_formatted_str)", "e": 29762, "s": 29315, "text": null }, { "code": null, "e": 30118, "s": 29762, "text": "[\n {\n \"company\": \"GFG\",\n \"name\": \"Nikhil\",\n \"studentid\": 1,\n \"subjects\": [\n \"Python\",\n \"Data Structures\"\n ]\n },\n {\n \"company\": \"GFG\",\n \"name\": \"Nisha\",\n \"studentid\": 2,\n \"subjects\": [\n \"Java\",\n \"C++\",\n \"R Lang\"\n ]\n }\n]" }, { "code": null, "e": 30133, "s": 30118, "text": "prachisoda1234" }, { "code": null, "e": 30146, "s": 30133, "text": "simmytarika5" }, { "code": null, "e": 30158, "s": 30146, "text": "Python-json" }, { "code": null, "e": 30165, "s": 30158, "text": "Python" }, { "code": null, "e": 30263, "s": 30165, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30272, "s": 30263, "text": "Comments" }, { "code": null, "e": 30285, "s": 30272, "text": "Old Comments" }, { "code": null, "e": 30317, "s": 30285, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30373, "s": 30317, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30394, "s": 30373, "text": "Python OOPs Concepts" }, { "code": null, "e": 30433, "s": 30394, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30475, "s": 30433, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30502, "s": 30475, "text": "Python Classes and Objects" }, { "code": null, "e": 30533, "s": 30502, "text": "Python | os.path.join() method" }, { "code": null, "e": 30575, "s": 30533, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30611, "s": 30575, "text": "Python | Pandas dataframe.groupby()" } ]
BigIntegerMath factorial() function | Guava | Java - GeeksforGeeks
26 Jul, 2021 The method factorial(int n) of Guava’s BigIntegerMath class is used to find the factorial of the given number. It returns n!, that is, the product of the first n positive integers.Syntax: public static BigInteger factorial(int n) Parameters: This method takes the number n as parameter whose factorial is to be found.Return Value: This method returns the factorial of the given number n.Exceptions: This method throws IllegalArgumentException if n < 0.Note: The method returns 1 if n == 0. The result takes O(n log n) space, so use cautiously. This uses an efficient binary recursive algorithm to compute the factorial with balanced multiplies. Below examples illustrates the BigIntegerMath.factorial() method:Example 1: Java // Java code to show implementation of// factorial() method of Guava's BigIntegerMath class import java.math.*;import com.google.common.math.BigIntegerMath; class GFG { // Driver code public static void main(String args[]) { int n1 = 10; // Using factorial(int n) method of // Guava's BigIntegerMath class BigInteger ans1 = BigIntegerMath.factorial(n1); System.out.println("Factorial of " + n1 + " is: " + ans1); int n2 = 12; // Using factorial(int n) method of // Guava's BigIntegerMath class BigInteger ans2 = BigIntegerMath.factorial(n2); System.out.println("Factorial of " + n2 + " is: " + ans2); }} Factorial of 10 is: 3628800 Factorial of 12 is: 479001600 Example 2: Java // Java code to show implementation of// factorial() method of Guava's BigIntegerMath class import java.math.*;import com.google.common.math.BigIntegerMath; class GFG { // Driver code public static void main(String args[]) { try { int n1 = -5; // Using factorial(int n) method of // Guava's BigIntegerMath class // This should throw "IllegalArgumentException" // as n < 0 BigInteger ans1 = BigIntegerMath.factorial(n1); System.out.println("Factorial of " + n1 + " is: " + ans1); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.IllegalArgumentException: n (-5) must be >= 0 Reference: https://google.github.io/guava/releases/21.0/api/docs/com/google/common/math/BigIntegerMath.html#factorial-int- manikarora059 Java-BigInteger java-guava Java Java-BigInteger Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 24213, "s": 24185, "text": "\n26 Jul, 2021" }, { "code": null, "e": 24403, "s": 24213, "text": "The method factorial(int n) of Guava’s BigIntegerMath class is used to find the factorial of the given number. It returns n!, that is, the product of the first n positive integers.Syntax: " }, { "code": null, "e": 24445, "s": 24403, "text": "public static BigInteger factorial(int n)" }, { "code": null, "e": 24675, "s": 24445, "text": "Parameters: This method takes the number n as parameter whose factorial is to be found.Return Value: This method returns the factorial of the given number n.Exceptions: This method throws IllegalArgumentException if n < 0.Note: " }, { "code": null, "e": 24707, "s": 24675, "text": "The method returns 1 if n == 0." }, { "code": null, "e": 24761, "s": 24707, "text": "The result takes O(n log n) space, so use cautiously." }, { "code": null, "e": 24862, "s": 24761, "text": "This uses an efficient binary recursive algorithm to compute the factorial with balanced multiplies." }, { "code": null, "e": 24939, "s": 24862, "text": "Below examples illustrates the BigIntegerMath.factorial() method:Example 1: " }, { "code": null, "e": 24944, "s": 24939, "text": "Java" }, { "code": "// Java code to show implementation of// factorial() method of Guava's BigIntegerMath class import java.math.*;import com.google.common.math.BigIntegerMath; class GFG { // Driver code public static void main(String args[]) { int n1 = 10; // Using factorial(int n) method of // Guava's BigIntegerMath class BigInteger ans1 = BigIntegerMath.factorial(n1); System.out.println(\"Factorial of \" + n1 + \" is: \" + ans1); int n2 = 12; // Using factorial(int n) method of // Guava's BigIntegerMath class BigInteger ans2 = BigIntegerMath.factorial(n2); System.out.println(\"Factorial of \" + n2 + \" is: \" + ans2); }}", "e": 25688, "s": 24944, "text": null }, { "code": null, "e": 25746, "s": 25688, "text": "Factorial of 10 is: 3628800\nFactorial of 12 is: 479001600" }, { "code": null, "e": 25760, "s": 25748, "text": "Example 2: " }, { "code": null, "e": 25765, "s": 25760, "text": "Java" }, { "code": "// Java code to show implementation of// factorial() method of Guava's BigIntegerMath class import java.math.*;import com.google.common.math.BigIntegerMath; class GFG { // Driver code public static void main(String args[]) { try { int n1 = -5; // Using factorial(int n) method of // Guava's BigIntegerMath class // This should throw \"IllegalArgumentException\" // as n < 0 BigInteger ans1 = BigIntegerMath.factorial(n1); System.out.println(\"Factorial of \" + n1 + \" is: \" + ans1); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 26474, "s": 25765, "text": null }, { "code": null, "e": 26541, "s": 26474, "text": "Exception: java.lang.IllegalArgumentException: n (-5) must be >= 0" }, { "code": null, "e": 26667, "s": 26543, "text": "Reference: https://google.github.io/guava/releases/21.0/api/docs/com/google/common/math/BigIntegerMath.html#factorial-int- " }, { "code": null, "e": 26681, "s": 26667, "text": "manikarora059" }, { "code": null, "e": 26697, "s": 26681, "text": "Java-BigInteger" }, { "code": null, "e": 26708, "s": 26697, "text": "java-guava" }, { "code": null, "e": 26713, "s": 26708, "text": "Java" }, { "code": null, "e": 26729, "s": 26713, "text": "Java-BigInteger" }, { "code": null, "e": 26734, "s": 26729, "text": "Java" }, { "code": null, "e": 26832, "s": 26734, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26841, "s": 26832, "text": "Comments" }, { "code": null, "e": 26854, "s": 26841, "text": "Old Comments" }, { "code": null, "e": 26905, "s": 26854, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26935, "s": 26905, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26966, "s": 26935, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26998, "s": 26966, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27017, "s": 26998, "text": "Interfaces in Java" }, { "code": null, "e": 27035, "s": 27017, "text": "ArrayList in Java" }, { "code": null, "e": 27067, "s": 27035, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27087, "s": 27067, "text": "Stack Class in Java" }, { "code": null, "e": 27111, "s": 27087, "text": "Singleton Class in Java" } ]
Why you should be analyzing your marketing campaigns with Python | by Limor Goldhaber | Towards Data Science
Like most young kids one of my favorite birthday games was the piñata. I would eagerly await my turn, crack the biggest smile as I was blindfolded, step up with bat in hand, and swing wildly to break open a side and set free all of the beautiful candy stored within. Obviously trying to hit your target while blindfolded proves to be an almost impossible task, which is incredibly frustrating given the fact that you know for certain there’s something hidden in that piñata. Trying to build a successful marketing campaign without data is the equivalent of hoping to hit a piñata when you’re blindfolded. Unfortunately, working in marketing can often feel this way. Many marketing teams struggle to secure sufficient analyst resources to successfully employ a data-driven approach in developing growth marketing campaigns: identifying user segments, uncovering growth opportunities, developing churn and retention prediction models, and eventually designing and analyzing the performance & impact. Without data almost any impact derived from the campaigns will be pure luck. I don’t like to operate blindfolded. I trust data, and so should you. So I invested the time and energy to learn how to explore and analyze marketing data myself. As a growth marketer who can conduct deep, meaningful data analysis I’m able to identify marketing and growth opportunities, design rapid experimentation, analyze results in a timely manner and respond with additional campaign ideas based on experiments results, without needing to rely on a data scientist or analyst. It hasn’t been easy. It took me almost 2 years to become proficient with SQL, Python and Statistics at a level that allows me to properly analyze and interpret data for growth marketing. As a marketer, reaching this level of analytical proficiency has been eye opening, and now that I’ve reached this level I would like to help other marketers take the blindfolds off too. The truth is you don’t have to be a data scientist to effectively analyze marketing campaigns, but you do need to be proficient in Statistics (especially frequentist) in order to design and interpret experiments. If you’re just starting I suggest you first take introductory courses in Statistics. If you’re already proficient in foundational Statistics, invest in learning basic Python functions that will help you analyze marketing campaigns more efficiently and with greater depth. The most common form of experimentation of marketing campaigns is A/B testing, aka ‘hypothesis testing’. While programs such as Mixpanel or Amplitude offer a handful of ‘off the shelf’ solutions for analyzing campaign performance, using Python at even the most basic level allows you to explore more complex relationships among different segments in your data, identify possible bugs or issues and actually save time through automation. Let’s take a more granular look at how to start deploying Python for marketing analysis: Every analysis starts with getting to know your data. This includes (but is not limited to): understanding the way the data is structured, removing unneeded columns, addressing nulls, running summary statistics and exploring possible relationships by creating segments or groups, and finally conducting visual exploration by plotting the data. As most of the functions you will utilize are included in every EDA you conduct, you can create a template, or use the one I created here, to make exploring your data simple and fast. Every marketing campaign has specific goals, and majority of campaigns will focus on a conversion metric. Let’s say you’re sending an email blast letting users know about a time limited discount for your product. To properly analyze the impact of your campaign you’ll need to define conversion metrics, such as the conversion rate of users who redeemed the discount of those targeted with the email, as well as the conversion rate of users who continued to use the product after redeeming the discount. Your campaign will likely convert some segments of users more than others, so you’ll want to repeat the analysis on diverse segments of the population to identify differences in impact. Using Python you can define a loop that runs the through the different segments of your population and calculates the conversion rate for each. Your segments can be anything from age groups, engagement level, or any other segment of interest. Python allows you to quickly explore conversion on a more granular level, something every successful marketing campaign needs. Without Python you will find yourself spending a significant amount of time repeating similar analyses. Now let’s put these principles into practice. Conversion rate is calculated by the total number of users converted divided by the total number of users targeted. In this example we’ll assume that the data is already cleaned for nulls, and organized such that each user is flagged if they were targeted in the campaign, if they converted following the campaign, and / or if they were retained post campaign. Running these formulas on your data will give you the overall conversion and retention rates. You should compare your results to a control if you’re conducting this analysis as part of an experiment, or compare the results to other benchmarks defined in the campaign design. Once you have an overall understanding of your campaign performance you’ll want to dive deeper and uncover differences in performance amongst subgroups of your population throughout the campaign duration, as well as compare certain features of your population. This is where using Python can really expedite your analysis. Using custom functions you can analyze conversion and retention rate for any desired subgroup in your population, such as different languages, dates served or any other relevant feature of your targeted population. First, create custom functions that take on any dataset and column and return the conversion and retention rates for each segment. You do this by utilizing a “group by” function. You can then calculate the conversion and retention rates similar to the way you calculated it on step 1, and return the outcome as a new dataframe. Note that you may need to unstack the results first. Your functions should look similar to the following: While you can merge these two functions into a single function, I generally prefer to keep them separate- you may want to explore different features affecting the specific performance of each. For example, in some instances you may find that conversion rates of certain groups are lower, but their retention rates are higher, and you’ll need to further explore the features that may have impacted each rate separately. Using a table format to explore the impact of different features and segments can start to feel overwhelming. It is often time easier to use plotting functions to visually (and quickly) detect fluctuations and potential relationships impacting the overall results. You can define custom plotting functions to save you time and allow for easier debugging. There may be several reasons for fluctuations in your data. In some cases you may find that users convert differently on certain days of the week or time of day. In other cases you may notice differences in performance of certain languages, which could be indicative of issues related to translation of the campaign, and whether or not the campaign was served in the correct languages to users. You may even identify the need to use different types of visuals, colors or triggers to better localize the campaign in different markets. Diving deeper into the data and resolving inconsistencies may require more advanced coding, which is out of scope for this post. I’ll explore how to handle these issues in a separate post in the future. In the meantime, if you identify any possible inconsistencies in your data I recommend consulting with the analysts within your organization. As I was building out my analytical skill set I found input from my Analyst peers to be absolutely invaluable. As you begin to uncover relationships and conversion rates of subgroups in your target population you’ll need to calculate the lift- this will allow you to understand the rate in which your campaign actually increased conversion. If you designed your campaign in the form of a hypothesis test (aka an A/B test) you’ll first need to split the data into the relevant control and treatment groups, and then calculate the conversion rate of each group separately. From there you will calculate the difference between the treatment group conversion rate and the control conversion rate, divided by the control conversion rate. Using Python, we can define a function for that: Finally, the conversion & retention rates and lift you uncover will be meaningless without understanding their statistical significance. To do that you will need to conduct a T-test. There are several types of T-tests, depending on the design of your experiment & campaign. In this case, we’ll look at a two sample T-test calculation. The T-test will provide us with a T statistic and a P-value that will determine the likelihood of getting a result at least as extreme as the result you ended up with. That is, was the outcome of this campaign the result of a random chance, or was the campaign indeed impactful? In general, a T-statistics of at least 1.96 is considered statistically significant at 95% significance level. Our P-value will need to be less than 0.05 to consider our results statistically significant. Running a T-test in Python is actually very simple when using the SciPy library. It should look similar to the following: # t-tetst for two independent samplesfrom scipy.stats import ttest_indt= ttest_ind(control,treatment)print (t) In order to get the most accurate picture of the groups for whom your campaign was successful It is important to estimate the lift and whether or not the results were statistically significant among subgroups and demographics of your target population. Failing to uncover the lift and statistical significance of the subgroups that account for the targeted population may lead to a false conclusion about the overall impact of your campaign. If you’d like to learn more about conducting hypothesis testing with Python, as well as analyzing lift and significance levels, you can read more about it in my post “A growth marketer guide to designing A/B tests using python”. While many marketing teams may lack sufficient analyst resources, every team can still take a more data-driven approach to marketing. Marketers, and specifically those who focus on growth marketing, can greatly benefit by increasing their proficiency in Statistics and coding languages such as Python to develop more meaningful campaigns and properly analyze their impact. In this post we covered how using Python can help you: (1) quickly uncover the relationships in the data that affect the usage of your product, (2) expedite the analysis of every campaign, which will allow you to experiment even more, and (3) optimize your campaigns to increase conversion and retention rates. Invest the time in learning the tools you need to be the best possible growth marketer. You’ll find the reward is even better than that old piñata candy.
[ { "code": null, "e": 648, "s": 171, "text": "Like most young kids one of my favorite birthday games was the piñata. I would eagerly await my turn, crack the biggest smile as I was blindfolded, step up with bat in hand, and swing wildly to break open a side and set free all of the beautiful candy stored within. Obviously trying to hit your target while blindfolded proves to be an almost impossible task, which is incredibly frustrating given the fact that you know for certain there’s something hidden in that piñata." }, { "code": null, "e": 1249, "s": 648, "text": "Trying to build a successful marketing campaign without data is the equivalent of hoping to hit a piñata when you’re blindfolded. Unfortunately, working in marketing can often feel this way. Many marketing teams struggle to secure sufficient analyst resources to successfully employ a data-driven approach in developing growth marketing campaigns: identifying user segments, uncovering growth opportunities, developing churn and retention prediction models, and eventually designing and analyzing the performance & impact. Without data almost any impact derived from the campaigns will be pure luck." }, { "code": null, "e": 1319, "s": 1249, "text": "I don’t like to operate blindfolded. I trust data, and so should you." }, { "code": null, "e": 1731, "s": 1319, "text": "So I invested the time and energy to learn how to explore and analyze marketing data myself. As a growth marketer who can conduct deep, meaningful data analysis I’m able to identify marketing and growth opportunities, design rapid experimentation, analyze results in a timely manner and respond with additional campaign ideas based on experiments results, without needing to rely on a data scientist or analyst." }, { "code": null, "e": 2104, "s": 1731, "text": "It hasn’t been easy. It took me almost 2 years to become proficient with SQL, Python and Statistics at a level that allows me to properly analyze and interpret data for growth marketing. As a marketer, reaching this level of analytical proficiency has been eye opening, and now that I’ve reached this level I would like to help other marketers take the blindfolds off too." }, { "code": null, "e": 2589, "s": 2104, "text": "The truth is you don’t have to be a data scientist to effectively analyze marketing campaigns, but you do need to be proficient in Statistics (especially frequentist) in order to design and interpret experiments. If you’re just starting I suggest you first take introductory courses in Statistics. If you’re already proficient in foundational Statistics, invest in learning basic Python functions that will help you analyze marketing campaigns more efficiently and with greater depth." }, { "code": null, "e": 3026, "s": 2589, "text": "The most common form of experimentation of marketing campaigns is A/B testing, aka ‘hypothesis testing’. While programs such as Mixpanel or Amplitude offer a handful of ‘off the shelf’ solutions for analyzing campaign performance, using Python at even the most basic level allows you to explore more complex relationships among different segments in your data, identify possible bugs or issues and actually save time through automation." }, { "code": null, "e": 3115, "s": 3026, "text": "Let’s take a more granular look at how to start deploying Python for marketing analysis:" }, { "code": null, "e": 3459, "s": 3115, "text": "Every analysis starts with getting to know your data. This includes (but is not limited to): understanding the way the data is structured, removing unneeded columns, addressing nulls, running summary statistics and exploring possible relationships by creating segments or groups, and finally conducting visual exploration by plotting the data." }, { "code": null, "e": 3643, "s": 3459, "text": "As most of the functions you will utilize are included in every EDA you conduct, you can create a template, or use the one I created here, to make exploring your data simple and fast." }, { "code": null, "e": 4146, "s": 3643, "text": "Every marketing campaign has specific goals, and majority of campaigns will focus on a conversion metric. Let’s say you’re sending an email blast letting users know about a time limited discount for your product. To properly analyze the impact of your campaign you’ll need to define conversion metrics, such as the conversion rate of users who redeemed the discount of those targeted with the email, as well as the conversion rate of users who continued to use the product after redeeming the discount." }, { "code": null, "e": 4332, "s": 4146, "text": "Your campaign will likely convert some segments of users more than others, so you’ll want to repeat the analysis on diverse segments of the population to identify differences in impact." }, { "code": null, "e": 4806, "s": 4332, "text": "Using Python you can define a loop that runs the through the different segments of your population and calculates the conversion rate for each. Your segments can be anything from age groups, engagement level, or any other segment of interest. Python allows you to quickly explore conversion on a more granular level, something every successful marketing campaign needs. Without Python you will find yourself spending a significant amount of time repeating similar analyses." }, { "code": null, "e": 4852, "s": 4806, "text": "Now let’s put these principles into practice." }, { "code": null, "e": 5213, "s": 4852, "text": "Conversion rate is calculated by the total number of users converted divided by the total number of users targeted. In this example we’ll assume that the data is already cleaned for nulls, and organized such that each user is flagged if they were targeted in the campaign, if they converted following the campaign, and / or if they were retained post campaign." }, { "code": null, "e": 5488, "s": 5213, "text": "Running these formulas on your data will give you the overall conversion and retention rates. You should compare your results to a control if you’re conducting this analysis as part of an experiment, or compare the results to other benchmarks defined in the campaign design." }, { "code": null, "e": 5749, "s": 5488, "text": "Once you have an overall understanding of your campaign performance you’ll want to dive deeper and uncover differences in performance amongst subgroups of your population throughout the campaign duration, as well as compare certain features of your population." }, { "code": null, "e": 6026, "s": 5749, "text": "This is where using Python can really expedite your analysis. Using custom functions you can analyze conversion and retention rate for any desired subgroup in your population, such as different languages, dates served or any other relevant feature of your targeted population." }, { "code": null, "e": 6460, "s": 6026, "text": "First, create custom functions that take on any dataset and column and return the conversion and retention rates for each segment. You do this by utilizing a “group by” function. You can then calculate the conversion and retention rates similar to the way you calculated it on step 1, and return the outcome as a new dataframe. Note that you may need to unstack the results first. Your functions should look similar to the following:" }, { "code": null, "e": 6879, "s": 6460, "text": "While you can merge these two functions into a single function, I generally prefer to keep them separate- you may want to explore different features affecting the specific performance of each. For example, in some instances you may find that conversion rates of certain groups are lower, but their retention rates are higher, and you’ll need to further explore the features that may have impacted each rate separately." }, { "code": null, "e": 7234, "s": 6879, "text": "Using a table format to explore the impact of different features and segments can start to feel overwhelming. It is often time easier to use plotting functions to visually (and quickly) detect fluctuations and potential relationships impacting the overall results. You can define custom plotting functions to save you time and allow for easier debugging." }, { "code": null, "e": 7768, "s": 7234, "text": "There may be several reasons for fluctuations in your data. In some cases you may find that users convert differently on certain days of the week or time of day. In other cases you may notice differences in performance of certain languages, which could be indicative of issues related to translation of the campaign, and whether or not the campaign was served in the correct languages to users. You may even identify the need to use different types of visuals, colors or triggers to better localize the campaign in different markets." }, { "code": null, "e": 8224, "s": 7768, "text": "Diving deeper into the data and resolving inconsistencies may require more advanced coding, which is out of scope for this post. I’ll explore how to handle these issues in a separate post in the future. In the meantime, if you identify any possible inconsistencies in your data I recommend consulting with the analysts within your organization. As I was building out my analytical skill set I found input from my Analyst peers to be absolutely invaluable." }, { "code": null, "e": 8846, "s": 8224, "text": "As you begin to uncover relationships and conversion rates of subgroups in your target population you’ll need to calculate the lift- this will allow you to understand the rate in which your campaign actually increased conversion. If you designed your campaign in the form of a hypothesis test (aka an A/B test) you’ll first need to split the data into the relevant control and treatment groups, and then calculate the conversion rate of each group separately. From there you will calculate the difference between the treatment group conversion rate and the control conversion rate, divided by the control conversion rate." }, { "code": null, "e": 8895, "s": 8846, "text": "Using Python, we can define a function for that:" }, { "code": null, "e": 9509, "s": 8895, "text": "Finally, the conversion & retention rates and lift you uncover will be meaningless without understanding their statistical significance. To do that you will need to conduct a T-test. There are several types of T-tests, depending on the design of your experiment & campaign. In this case, we’ll look at a two sample T-test calculation. The T-test will provide us with a T statistic and a P-value that will determine the likelihood of getting a result at least as extreme as the result you ended up with. That is, was the outcome of this campaign the result of a random chance, or was the campaign indeed impactful?" }, { "code": null, "e": 9714, "s": 9509, "text": "In general, a T-statistics of at least 1.96 is considered statistically significant at 95% significance level. Our P-value will need to be less than 0.05 to consider our results statistically significant." }, { "code": null, "e": 9836, "s": 9714, "text": "Running a T-test in Python is actually very simple when using the SciPy library. It should look similar to the following:" }, { "code": null, "e": 9947, "s": 9836, "text": "# t-tetst for two independent samplesfrom scipy.stats import ttest_indt= ttest_ind(control,treatment)print (t)" }, { "code": null, "e": 10389, "s": 9947, "text": "In order to get the most accurate picture of the groups for whom your campaign was successful It is important to estimate the lift and whether or not the results were statistically significant among subgroups and demographics of your target population. Failing to uncover the lift and statistical significance of the subgroups that account for the targeted population may lead to a false conclusion about the overall impact of your campaign." }, { "code": null, "e": 10618, "s": 10389, "text": "If you’d like to learn more about conducting hypothesis testing with Python, as well as analyzing lift and significance levels, you can read more about it in my post “A growth marketer guide to designing A/B tests using python”." }, { "code": null, "e": 10991, "s": 10618, "text": "While many marketing teams may lack sufficient analyst resources, every team can still take a more data-driven approach to marketing. Marketers, and specifically those who focus on growth marketing, can greatly benefit by increasing their proficiency in Statistics and coding languages such as Python to develop more meaningful campaigns and properly analyze their impact." }, { "code": null, "e": 11302, "s": 10991, "text": "In this post we covered how using Python can help you: (1) quickly uncover the relationships in the data that affect the usage of your product, (2) expedite the analysis of every campaign, which will allow you to experiment even more, and (3) optimize your campaigns to increase conversion and retention rates." } ]
Flutter - Updating Data on the Internet - GeeksforGeeks
14 Aug, 2021 In today’s world, most applications heavily rely on fetching and updating information from the servers through the internet. In Flutter, such services are provided by the http package. In this article, we will explore the same. To update the data on the Internet follow the below steps: Import the http packageUpdate data t using the http packageConvert the response into custom Dart objectGet the data from the internet.Update and display the response on screen Import the http package Update data t using the http package Convert the response into custom Dart object Get the data from the internet. Update and display the response on screen To install the http package use the below command in your command prompt: pub get Or, if you’re using the flutter cmd use the below command: flutter pub get After the installation add the dependency to the pubsec.yml file as shown below: import 'package:http/http.dart' as http; Use the http.put() method to update the title of the Album in JSONPlaceholder as shown below: Dart Future<http.Response> updateAlbum(String title) { return http.put( 'https://jsonplaceholder.typicode.com/albums/1', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), );} Though making a network request is no big deal, working with the raw response data can be inconvenient. To make your life easier, converting the raw data (ie, http.response) into dart object. Here we will create an Album class that contains the JSON data as shown below: Dart class Album { final int id; final String title; Album({this.id, this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( id: json['id'], title: json['title'], ); }} Now, follow the below steps to update the fetchAlbum() function to return a Future<Album>: Use the dart: convert package to convert the response body into a JSON Map.Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200.Throw an exception if the server doesn’t return an OK response with a status code of 200. Use the dart: convert package to convert the response body into a JSON Map. Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200. Throw an exception if the server doesn’t return an OK response with a status code of 200. Dart Future<Album> updateAlbum(String title) async { final http.Response response = await http.put( 'https://jsonplaceholder.typicode.com/albums', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); // Dispatch action depending upon // the server response if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); }} Now use the fetch() method to fetch the data as shown below: Dart Future<Album> fetchAlbum() async { final response = await http.get('https://jsonplaceholder.typicode.com/albums/1'); if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); }} Now create a TextField for the user to enter a title and a RaisedButton to send data to the server. Also, define a TextEditingController to read the user input from a TextField as shown below: Dart Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: TextField( controller: _controller, decoration: InputDecoration(hintText: 'Enter Title'), ), ), RaisedButton( child: Text('Update Data'), onPressed: () { setState(() { _futureAlbum = updateAlbum(_controller.text); }); }, ), ],) Use the FlutterBuilder widget to display the data on the screen as shown below: Dart FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.hasData) { return Text(snapshot.data.title); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } return CircularProgressIndicator(); },) Complete Source Code: Dart import 'dart:async';import 'dart:convert'; import 'package:flutter/material.dart';import 'package:http/http.dart' as http; Future<Album> fetchAlbum() async { final response = await http.get('https://jsonplaceholder.typicode.com/albums/1'); // Dispatch action depending upon //the server response if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); }} Future<Album> updateAlbum(String title) async { final http.Response response = await http.put( 'https://jsonplaceholder.typicode.com/albums/1', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); // parsing JSOn or throwing an exception if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to update album.'); }} class Album { final int id; final String title; Album({this.id, this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( id: json['id'], title: json['title'], ); }} void main() { runApp(MyApp());} class MyApp extends StatefulWidget { MyApp({Key key}) : super(key: key); @override _MyAppState createState() { return _MyAppState(); }} class _MyAppState extends State<MyApp> { final TextEditingController _controller = TextEditingController(); Future<Album> _futureAlbum; @override void initState() { super.initState(); _futureAlbum = fetchAlbum(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Update Data Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Container( alignment: Alignment.center, padding: const EdgeInsets.all(8.0), child: FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasData) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(snapshot.data.title), TextField( controller: _controller, decoration: InputDecoration(hintText: 'Enter Title'), ), RaisedButton( child: Text('Update Data'), onPressed: () { setState(() { _futureAlbum = updateAlbum(_controller.text); }); }, ), ], ); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } } return CircularProgressIndicator(); }, ), ), ), ); }} Output: sumitgumber28 android Flutter Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Listview.builder in Flutter Flutter - DropDownButton Widget Flutter - Asset Image Flutter - Custom Bottom Navigation Bar Splash Screen in Flutter Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - BoxShadow Widget Flutter - Flexible Widget
[ { "code": null, "e": 25914, "s": 25886, "text": "\n14 Aug, 2021" }, { "code": null, "e": 26142, "s": 25914, "text": "In today’s world, most applications heavily rely on fetching and updating information from the servers through the internet. In Flutter, such services are provided by the http package. In this article, we will explore the same." }, { "code": null, "e": 26201, "s": 26142, "text": "To update the data on the Internet follow the below steps:" }, { "code": null, "e": 26377, "s": 26201, "text": "Import the http packageUpdate data t using the http packageConvert the response into custom Dart objectGet the data from the internet.Update and display the response on screen" }, { "code": null, "e": 26401, "s": 26377, "text": "Import the http package" }, { "code": null, "e": 26438, "s": 26401, "text": "Update data t using the http package" }, { "code": null, "e": 26483, "s": 26438, "text": "Convert the response into custom Dart object" }, { "code": null, "e": 26515, "s": 26483, "text": "Get the data from the internet." }, { "code": null, "e": 26557, "s": 26515, "text": "Update and display the response on screen" }, { "code": null, "e": 26631, "s": 26557, "text": "To install the http package use the below command in your command prompt:" }, { "code": null, "e": 26639, "s": 26631, "text": "pub get" }, { "code": null, "e": 26698, "s": 26639, "text": "Or, if you’re using the flutter cmd use the below command:" }, { "code": null, "e": 26714, "s": 26698, "text": "flutter pub get" }, { "code": null, "e": 26795, "s": 26714, "text": "After the installation add the dependency to the pubsec.yml file as shown below:" }, { "code": null, "e": 26836, "s": 26795, "text": "import 'package:http/http.dart' as http;" }, { "code": null, "e": 26930, "s": 26836, "text": "Use the http.put() method to update the title of the Album in JSONPlaceholder as shown below:" }, { "code": null, "e": 26935, "s": 26930, "text": "Dart" }, { "code": "Future<http.Response> updateAlbum(String title) { return http.put( 'https://jsonplaceholder.typicode.com/albums/1', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), );}", "e": 27218, "s": 26935, "text": null }, { "code": null, "e": 27489, "s": 27218, "text": "Though making a network request is no big deal, working with the raw response data can be inconvenient. To make your life easier, converting the raw data (ie, http.response) into dart object. Here we will create an Album class that contains the JSON data as shown below:" }, { "code": null, "e": 27494, "s": 27489, "text": "Dart" }, { "code": "class Album { final int id; final String title; Album({this.id, this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( id: json['id'], title: json['title'], ); }}", "e": 27705, "s": 27494, "text": null }, { "code": null, "e": 27796, "s": 27705, "text": "Now, follow the below steps to update the fetchAlbum() function to return a Future<Album>:" }, { "code": null, "e": 28089, "s": 27796, "text": "Use the dart: convert package to convert the response body into a JSON Map.Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200.Throw an exception if the server doesn’t return an OK response with a status code of 200." }, { "code": null, "e": 28165, "s": 28089, "text": "Use the dart: convert package to convert the response body into a JSON Map." }, { "code": null, "e": 28294, "s": 28165, "text": "Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200." }, { "code": null, "e": 28384, "s": 28294, "text": "Throw an exception if the server doesn’t return an OK response with a status code of 200." }, { "code": null, "e": 28389, "s": 28384, "text": "Dart" }, { "code": "Future<Album> updateAlbum(String title) async { final http.Response response = await http.put( 'https://jsonplaceholder.typicode.com/albums', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); // Dispatch action depending upon // the server response if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); }}", "e": 28903, "s": 28389, "text": null }, { "code": null, "e": 28964, "s": 28903, "text": "Now use the fetch() method to fetch the data as shown below:" }, { "code": null, "e": 28969, "s": 28964, "text": "Dart" }, { "code": "Future<Album> fetchAlbum() async { final response = await http.get('https://jsonplaceholder.typicode.com/albums/1'); if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); }}", "e": 29240, "s": 28969, "text": null }, { "code": null, "e": 29433, "s": 29240, "text": "Now create a TextField for the user to enter a title and a RaisedButton to send data to the server. Also, define a TextEditingController to read the user input from a TextField as shown below:" }, { "code": null, "e": 29438, "s": 29433, "text": "Dart" }, { "code": "Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: TextField( controller: _controller, decoration: InputDecoration(hintText: 'Enter Title'), ), ), RaisedButton( child: Text('Update Data'), onPressed: () { setState(() { _futureAlbum = updateAlbum(_controller.text); }); }, ), ],)", "e": 29873, "s": 29438, "text": null }, { "code": null, "e": 29953, "s": 29873, "text": "Use the FlutterBuilder widget to display the data on the screen as shown below:" }, { "code": null, "e": 29958, "s": 29953, "text": "Dart" }, { "code": "FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.hasData) { return Text(snapshot.data.title); } else if (snapshot.hasError) { return Text(\"${snapshot.error}\"); } return CircularProgressIndicator(); },)", "e": 30225, "s": 29958, "text": null }, { "code": null, "e": 30247, "s": 30225, "text": "Complete Source Code:" }, { "code": null, "e": 30252, "s": 30247, "text": "Dart" }, { "code": "import 'dart:async';import 'dart:convert'; import 'package:flutter/material.dart';import 'package:http/http.dart' as http; Future<Album> fetchAlbum() async { final response = await http.get('https://jsonplaceholder.typicode.com/albums/1'); // Dispatch action depending upon //the server response if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); }} Future<Album> updateAlbum(String title) async { final http.Response response = await http.put( 'https://jsonplaceholder.typicode.com/albums/1', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); // parsing JSOn or throwing an exception if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to update album.'); }} class Album { final int id; final String title; Album({this.id, this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( id: json['id'], title: json['title'], ); }} void main() { runApp(MyApp());} class MyApp extends StatefulWidget { MyApp({Key key}) : super(key: key); @override _MyAppState createState() { return _MyAppState(); }} class _MyAppState extends State<MyApp> { final TextEditingController _controller = TextEditingController(); Future<Album> _futureAlbum; @override void initState() { super.initState(); _futureAlbum = fetchAlbum(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Update Data Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Container( alignment: Alignment.center, padding: const EdgeInsets.all(8.0), child: FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasData) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(snapshot.data.title), TextField( controller: _controller, decoration: InputDecoration(hintText: 'Enter Title'), ), RaisedButton( child: Text('Update Data'), onPressed: () { setState(() { _futureAlbum = updateAlbum(_controller.text); }); }, ), ], ); } else if (snapshot.hasError) { return Text(\"${snapshot.error}\"); } } return CircularProgressIndicator(); }, ), ), ), ); }}", "e": 33407, "s": 30252, "text": null }, { "code": null, "e": 33415, "s": 33407, "text": "Output:" }, { "code": null, "e": 33429, "s": 33415, "text": "sumitgumber28" }, { "code": null, "e": 33437, "s": 33429, "text": "android" }, { "code": null, "e": 33445, "s": 33437, "text": "Flutter" }, { "code": null, "e": 33450, "s": 33445, "text": "Dart" }, { "code": null, "e": 33458, "s": 33450, "text": "Flutter" }, { "code": null, "e": 33556, "s": 33458, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33584, "s": 33556, "text": "Listview.builder in Flutter" }, { "code": null, "e": 33616, "s": 33584, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 33638, "s": 33616, "text": "Flutter - Asset Image" }, { "code": null, "e": 33677, "s": 33638, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 33702, "s": 33677, "text": "Splash Screen in Flutter" }, { "code": null, "e": 33734, "s": 33702, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 33773, "s": 33734, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 33799, "s": 33773, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 33826, "s": 33799, "text": "Flutter - BoxShadow Widget" } ]
Puppet - Configuration
Once we have Puppet installed on the system, the next step is to configure it to perform certain initial operations. To make the Puppet server manage the client’s server centrally, one needs to open a specified port on all the machines, i.e. 8140 can be used if it is not in use in any of the machines which we are trying to configure. We need to enable both TCP and UDP communication on all the machines. The main configuration file for Puppet is etc/puppet/puppet.conf. All the configuration files get created in a package-based configuration of Puppet. Most of the configuration which is required to configure Puppet is kept in these files and once the Puppet run takes place, it picks up those configurations automatically. However, for some specific tasks such as configuring a web server or an external Certificate Authority (CA), Puppet has separate configuration for files and settings. Server configuration files are located in conf.d directory which is also known as the Puppet master. These files are by default located under /etc/puppetlabs/puppetserver/conf.d path. These config files are in HOCON format, which keeps the basic structure of JSON but it is more readable. When the Puppet startup takes place it picks up all .cong files from conf.d directory and uses them for making any configurational changes. Any changes in these files only takes place when the server is restarted. global.conf webserver.conf web-routes.conf puppetserver.conf auth.conf master.conf (deprecated) ca.conf (deprecated) There are different configuration files in Puppet which are specific to each component in Puppet. Puppet.conf file is Puppet’s main configuration file. Puppet uses the same configuration file to configure all the required Puppet command and services. All Puppet related settings such as the definition of Puppet master, Puppet agent, Puppet apply and certificates are defined in this file. Puppet can refer them as per requirement. The config file resembles a standard ini file wherein the settings can go into the specific application section of the main section. [main] certname = Test1.vipin.com server = TestingSrv environment = production runinterval = 1h [main] certname = puppetmaster.vipin.com server = MasterSrv environment = production runinterval = 1h strict_variables = true [master] dns_alt_names = MasterSrv,brcleprod01.vipin.com,puppet,puppet.test.com reports = puppetdb storeconfigs_backend = puppetdb storeconfigs = true environment_timeout = unlimited In Puppet configuration, the file which is going to be used has multiple configuration sections wherein each section has different kinds of multiple number of settings. Puppet configuration file mainly consists of the following config sections. Main − This is known as the global section which is used by all the commands and services in Puppet. One defines the default values in the main section which can be overridden by any section present in puppet.conf file. Main − This is known as the global section which is used by all the commands and services in Puppet. One defines the default values in the main section which can be overridden by any section present in puppet.conf file. Master − This section is referred by Puppet master service and Puppet cert command. Master − This section is referred by Puppet master service and Puppet cert command. Agent − This section is referred by Puppet agent service. Agent − This section is referred by Puppet agent service. User − It is mostly used by Puppet apply command as well as many of the less common commands. User − It is mostly used by Puppet apply command as well as many of the less common commands. [main] certname = PuppetTestmaster1.example.com Following are the key components of Config file. In Puppet, any comment line starts with (#) sign. This may intend with any amount of space. We can have a partial comment as well within the same line. # This is a comment. Testing = true #this is also a comment in same line Settings line must consist of − Any amount of leading space (optional) Name of the settings An equals = to sign, which may be surrounded by any number of space A value for the setting In most of the cases, the value of settings will be a single word but in some special cases, there are few special values. In configuration file settings, take a list of directories. While defining these directories, one should keep in mind that they should be separated by the system path separator character, which is (:) in *nix platforms and semicolons (;) on Windows. # *nix version: environmentpath = $codedir/special_environments:$codedir/environments # Windows version: environmentpath = $codedir/environments;C:\ProgramData\PuppetLabs\code\environment In the definition, the file directory which is listed first is scanned and then later moves to the other directory in the list, if it doesn’t find one. All the settings that take a single file or directory can accept an optional hash of permissions. When the server is starting up, Puppet will enforce those files or directories in the list. ssldir = $vardir/ssl {owner = service, mode = 0771} In the above code, the allowed hash are owner, group, and mode. There are only two valid values of the owner and group keys. Print Add Notes Bookmark this page
[ { "code": null, "e": 2291, "s": 2173, "text": "Once we have Puppet installed on the system, the next step is to configure it to perform certain initial operations." }, { "code": null, "e": 2580, "s": 2291, "text": "To make the Puppet server manage the client’s server centrally, one needs to open a specified port on all the machines, i.e. 8140 can be used if it is not in use in any of the machines which we are trying to configure. We need to enable both TCP and UDP communication on all the machines." }, { "code": null, "e": 3069, "s": 2580, "text": "The main configuration file for Puppet is etc/puppet/puppet.conf. All the configuration files get created in a package-based configuration of Puppet. Most of the configuration which is required to configure Puppet is kept in these files and once the Puppet run takes place, it picks up those configurations automatically. However, for some specific tasks such as configuring a web server or an external Certificate Authority (CA), Puppet has separate configuration for files and settings." }, { "code": null, "e": 3572, "s": 3069, "text": "Server configuration files are located in conf.d directory which is also known as the Puppet master. These files are by default located under /etc/puppetlabs/puppetserver/conf.d path. These config files are in HOCON format, which keeps the basic structure of JSON but it is more readable. When the Puppet startup takes place it picks up all .cong files from conf.d directory and uses them for making any configurational changes. Any changes in these files only takes place when the server is restarted." }, { "code": null, "e": 3584, "s": 3572, "text": "global.conf" }, { "code": null, "e": 3599, "s": 3584, "text": "webserver.conf" }, { "code": null, "e": 3615, "s": 3599, "text": "web-routes.conf" }, { "code": null, "e": 3633, "s": 3615, "text": "puppetserver.conf" }, { "code": null, "e": 3643, "s": 3633, "text": "auth.conf" }, { "code": null, "e": 3668, "s": 3643, "text": "master.conf (deprecated)" }, { "code": null, "e": 3689, "s": 3668, "text": "ca.conf (deprecated)" }, { "code": null, "e": 3787, "s": 3689, "text": "There are different configuration files in Puppet which are specific to each component in Puppet." }, { "code": null, "e": 4121, "s": 3787, "text": "Puppet.conf file is Puppet’s main configuration file. Puppet uses the same configuration file to configure all the required Puppet command and services. All Puppet related settings such as the definition of Puppet master, Puppet agent, Puppet apply and certificates are defined in this file. Puppet can refer them as per requirement." }, { "code": null, "e": 4254, "s": 4121, "text": "The config file resembles a standard ini file wherein the settings can go into the specific application section of the main section." }, { "code": null, "e": 4356, "s": 4254, "text": "[main] \ncertname = Test1.vipin.com \nserver = TestingSrv \nenvironment = production \nruninterval = 1h \n" }, { "code": null, "e": 4680, "s": 4356, "text": "[main] \ncertname = puppetmaster.vipin.com \nserver = MasterSrv \nenvironment = production \nruninterval = 1h \nstrict_variables = true \n[master] \n\ndns_alt_names = MasterSrv,brcleprod01.vipin.com,puppet,puppet.test.com \nreports = puppetdb \nstoreconfigs_backend = puppetdb \nstoreconfigs = true \nenvironment_timeout = unlimited \n" }, { "code": null, "e": 4849, "s": 4680, "text": "In Puppet configuration, the file which is going to be used has multiple configuration sections wherein each section has different kinds of multiple number of settings." }, { "code": null, "e": 4925, "s": 4849, "text": "Puppet configuration file mainly consists of the following config sections." }, { "code": null, "e": 5145, "s": 4925, "text": "Main − This is known as the global section which is used by all the commands and services in Puppet. One defines the default values in the main section which can be overridden by any section present in puppet.conf file." }, { "code": null, "e": 5365, "s": 5145, "text": "Main − This is known as the global section which is used by all the commands and services in Puppet. One defines the default values in the main section which can be overridden by any section present in puppet.conf file." }, { "code": null, "e": 5449, "s": 5365, "text": "Master − This section is referred by Puppet master service and Puppet cert command." }, { "code": null, "e": 5533, "s": 5449, "text": "Master − This section is referred by Puppet master service and Puppet cert command." }, { "code": null, "e": 5591, "s": 5533, "text": "Agent − This section is referred by Puppet agent service." }, { "code": null, "e": 5649, "s": 5591, "text": "Agent − This section is referred by Puppet agent service." }, { "code": null, "e": 5743, "s": 5649, "text": "User − It is mostly used by Puppet apply command as well as many of the less common commands." }, { "code": null, "e": 5837, "s": 5743, "text": "User − It is mostly used by Puppet apply command as well as many of the less common commands." }, { "code": null, "e": 5888, "s": 5837, "text": "[main] \ncertname = PuppetTestmaster1.example.com \n" }, { "code": null, "e": 5937, "s": 5888, "text": "Following are the key components of Config file." }, { "code": null, "e": 6089, "s": 5937, "text": "In Puppet, any comment line starts with (#) sign. This may intend with any amount of space. We can have a partial comment as well within the same line." }, { "code": null, "e": 6165, "s": 6089, "text": "# This is a comment. \nTesting = true #this is also a comment in same line \n" }, { "code": null, "e": 6197, "s": 6165, "text": "Settings line must consist of −" }, { "code": null, "e": 6236, "s": 6197, "text": "Any amount of leading space (optional)" }, { "code": null, "e": 6257, "s": 6236, "text": "Name of the settings" }, { "code": null, "e": 6325, "s": 6257, "text": "An equals = to sign, which may be surrounded by any number of space" }, { "code": null, "e": 6349, "s": 6325, "text": "A value for the setting" }, { "code": null, "e": 6472, "s": 6349, "text": "In most of the cases, the value of settings will be a single word but in some special cases, there are few special values." }, { "code": null, "e": 6722, "s": 6472, "text": "In configuration file settings, take a list of directories. While defining these directories, one should keep in mind that they should be separated by the system path separator character, which is (:) in *nix platforms and semicolons (;) on Windows." }, { "code": null, "e": 6915, "s": 6722, "text": "# *nix version: \nenvironmentpath = $codedir/special_environments:$codedir/environments \n# Windows version: \nenvironmentpath = $codedir/environments;C:\\ProgramData\\PuppetLabs\\code\\environment \n" }, { "code": null, "e": 7067, "s": 6915, "text": "In the definition, the file directory which is listed first is scanned and then later moves to the other directory in the list, if it doesn’t find one." }, { "code": null, "e": 7257, "s": 7067, "text": "All the settings that take a single file or directory can accept an optional hash of permissions. When the server is starting up, Puppet will enforce those files or directories in the list." }, { "code": null, "e": 7311, "s": 7257, "text": "ssldir = $vardir/ssl {owner = service, mode = 0771} \n" }, { "code": null, "e": 7436, "s": 7311, "text": "In the above code, the allowed hash are owner, group, and mode. There are only two valid values of the owner and group keys." }, { "code": null, "e": 7443, "s": 7436, "text": " Print" }, { "code": null, "e": 7454, "s": 7443, "text": " Add Notes" } ]
Extract all the URLs that are nested within <li> tags using BeautifulSoup - GeeksforGeeks
16 Mar, 2021 Beautiful Soup is a python library used for extracting html and xml files. In this article we will understand how we can extract all the URLSs from a web page that are nested within <li> tags. BeautifulSoup: Our primary module contains a method to access a webpage over HTTP. pip install bs4 Requests: used to perform GET request to the webpage and get their content. Note: You do not need to install it separately as it downloads automatically with bs4, but in case of any problem you can download it manually. pip install requests We will first import our required libraries.We will perform a get request to the desired web page from which we want all the URLs from.We will pass the text to the BeautifulSoup function and convert it to a soup object.Using a for loop we will look for all the <li> tags in the webpage.If a <li> tag has an anchor tag in it we will look for the href attribute and store its parameter in a list. It is the url we were looking for.The print the list that contains all the urls. We will first import our required libraries. We will perform a get request to the desired web page from which we want all the URLs from. We will pass the text to the BeautifulSoup function and convert it to a soup object. Using a for loop we will look for all the <li> tags in the webpage. If a <li> tag has an anchor tag in it we will look for the href attribute and store its parameter in a list. It is the url we were looking for. The print the list that contains all the urls. Step 1: Initialize the Python program by importing all the required libraries and setting up the URL of the web page from which you want all the URLs contained in an anchor tag. In the following example, we will take another geek for geeks article on implementing web scraping using BeautifulSoup and extract all the URLs stored in anchor tags nested within <li> tag. LInk of the article is : https://www.geeksforgeeks.org/implementing-web-scraping-python-beautiful-soup/ Python3 # Importing librariesimport requestsfrom bs4 import BeautifulSoup # setting up the URLURL = 'https://www.geeksforgeeks.org/implementing-web-scraping-python-beautiful-soup/' Step 2: We will perform a get request to the desired URL and pass all the text from it into BeautifuLSoup and convert it into a soup object. We will set the parser as html.parser. You can set it different depending on the webpage you are scraping. Python3 # perform get request to the urlreqs = requests.get(URL) # extract all the text that you received # from the GET request content = reqs.text # convert the text to a beautiful soup objectsoup = BeautifulSoup(content, 'html.parser') Step 3: Create an empty list to store all the URLs that you will receive as your desired output. Run a for loop that iterates over all the <li> tags in the web page. Then for each <li> tag check if it has an anchor tag in it. If that anchor tag has an href attribute then store the parameter of that href in the list that you created. Python3 # Empty list to store the outputurls = [] # For loop that iterates over all the <li> tagsfor h in soup.findAll('li'): # looking for anchor tag inside the <li>tag a = h.find('a') try: # looking for href inside anchor tag if 'href' in a.attrs: # storing the value of href in a separate # variable url = a.get('href') # appending the url to the output list urls.append(url) # if the list does not has a anchor tag or an anchor # tag does not has a href params we pass except: pass Step 4: We print the output by iterating over the list of the url. Python3 # print all the urls stored in the urls listfor url in urls: print(url) Complete code: Python3 # Importing librariesimport requestsfrom bs4 import BeautifulSoup # setting up the URLURL = 'https://www.geeksforgeeks.org/implementing-web-scraping-python-beautiful-soup/' # perform get request to the urlreqs = requests.get(URL) # extract all the text that you received from# the GET requestcontent = reqs.text # convert the text to a beautiful soup objectsoup = BeautifulSoup(content, 'html.parser') # Empty list to store the outputurls = [] # For loop that iterates over all the <li> tagsfor h in soup.findAll('li'): # looking for anchor tag inside the <li>tag a = h.find('a') try: # looking for href inside anchor tag if 'href' in a.attrs: # storing the value of href in a separate variable url = a.get('href') # appending the url to the output list urls.append(url) # if the list does not has a anchor tag or an anchor tag # does not has a href params we pass except: pass # print all the urls stored in the urls listfor url in urls: print(url) Output: Picked Python BeautifulSoup 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": 24318, "s": 24290, "text": "\n16 Mar, 2021" }, { "code": null, "e": 24511, "s": 24318, "text": "Beautiful Soup is a python library used for extracting html and xml files. In this article we will understand how we can extract all the URLSs from a web page that are nested within <li> tags." }, { "code": null, "e": 24594, "s": 24511, "text": "BeautifulSoup: Our primary module contains a method to access a webpage over HTTP." }, { "code": null, "e": 24610, "s": 24594, "text": "pip install bs4" }, { "code": null, "e": 24686, "s": 24610, "text": "Requests: used to perform GET request to the webpage and get their content." }, { "code": null, "e": 24830, "s": 24686, "text": "Note: You do not need to install it separately as it downloads automatically with bs4, but in case of any problem you can download it manually." }, { "code": null, "e": 24851, "s": 24830, "text": "pip install requests" }, { "code": null, "e": 25327, "s": 24851, "text": "We will first import our required libraries.We will perform a get request to the desired web page from which we want all the URLs from.We will pass the text to the BeautifulSoup function and convert it to a soup object.Using a for loop we will look for all the <li> tags in the webpage.If a <li> tag has an anchor tag in it we will look for the href attribute and store its parameter in a list. It is the url we were looking for.The print the list that contains all the urls." }, { "code": null, "e": 25372, "s": 25327, "text": "We will first import our required libraries." }, { "code": null, "e": 25464, "s": 25372, "text": "We will perform a get request to the desired web page from which we want all the URLs from." }, { "code": null, "e": 25549, "s": 25464, "text": "We will pass the text to the BeautifulSoup function and convert it to a soup object." }, { "code": null, "e": 25617, "s": 25549, "text": "Using a for loop we will look for all the <li> tags in the webpage." }, { "code": null, "e": 25761, "s": 25617, "text": "If a <li> tag has an anchor tag in it we will look for the href attribute and store its parameter in a list. It is the url we were looking for." }, { "code": null, "e": 25808, "s": 25761, "text": "The print the list that contains all the urls." }, { "code": null, "e": 25986, "s": 25808, "text": "Step 1: Initialize the Python program by importing all the required libraries and setting up the URL of the web page from which you want all the URLs contained in an anchor tag." }, { "code": null, "e": 26176, "s": 25986, "text": "In the following example, we will take another geek for geeks article on implementing web scraping using BeautifulSoup and extract all the URLs stored in anchor tags nested within <li> tag." }, { "code": null, "e": 26280, "s": 26176, "text": "LInk of the article is : https://www.geeksforgeeks.org/implementing-web-scraping-python-beautiful-soup/" }, { "code": null, "e": 26288, "s": 26280, "text": "Python3" }, { "code": "# Importing librariesimport requestsfrom bs4 import BeautifulSoup # setting up the URLURL = 'https://www.geeksforgeeks.org/implementing-web-scraping-python-beautiful-soup/'", "e": 26462, "s": 26288, "text": null }, { "code": null, "e": 26710, "s": 26462, "text": "Step 2: We will perform a get request to the desired URL and pass all the text from it into BeautifuLSoup and convert it into a soup object. We will set the parser as html.parser. You can set it different depending on the webpage you are scraping." }, { "code": null, "e": 26718, "s": 26710, "text": "Python3" }, { "code": "# perform get request to the urlreqs = requests.get(URL) # extract all the text that you received # from the GET request content = reqs.text # convert the text to a beautiful soup objectsoup = BeautifulSoup(content, 'html.parser')", "e": 26952, "s": 26718, "text": null }, { "code": null, "e": 27288, "s": 26952, "text": "Step 3: Create an empty list to store all the URLs that you will receive as your desired output. Run a for loop that iterates over all the <li> tags in the web page. Then for each <li> tag check if it has an anchor tag in it. If that anchor tag has an href attribute then store the parameter of that href in the list that you created." }, { "code": null, "e": 27296, "s": 27288, "text": "Python3" }, { "code": "# Empty list to store the outputurls = [] # For loop that iterates over all the <li> tagsfor h in soup.findAll('li'): # looking for anchor tag inside the <li>tag a = h.find('a') try: # looking for href inside anchor tag if 'href' in a.attrs: # storing the value of href in a separate # variable url = a.get('href') # appending the url to the output list urls.append(url) # if the list does not has a anchor tag or an anchor # tag does not has a href params we pass except: pass", "e": 27919, "s": 27296, "text": null }, { "code": null, "e": 27986, "s": 27919, "text": "Step 4: We print the output by iterating over the list of the url." }, { "code": null, "e": 27994, "s": 27986, "text": "Python3" }, { "code": "# print all the urls stored in the urls listfor url in urls: print(url)", "e": 28069, "s": 27994, "text": null }, { "code": null, "e": 28084, "s": 28069, "text": "Complete code:" }, { "code": null, "e": 28092, "s": 28084, "text": "Python3" }, { "code": "# Importing librariesimport requestsfrom bs4 import BeautifulSoup # setting up the URLURL = 'https://www.geeksforgeeks.org/implementing-web-scraping-python-beautiful-soup/' # perform get request to the urlreqs = requests.get(URL) # extract all the text that you received from# the GET requestcontent = reqs.text # convert the text to a beautiful soup objectsoup = BeautifulSoup(content, 'html.parser') # Empty list to store the outputurls = [] # For loop that iterates over all the <li> tagsfor h in soup.findAll('li'): # looking for anchor tag inside the <li>tag a = h.find('a') try: # looking for href inside anchor tag if 'href' in a.attrs: # storing the value of href in a separate variable url = a.get('href') # appending the url to the output list urls.append(url) # if the list does not has a anchor tag or an anchor tag # does not has a href params we pass except: pass # print all the urls stored in the urls listfor url in urls: print(url)", "e": 29187, "s": 28092, "text": null }, { "code": null, "e": 29195, "s": 29187, "text": "Output:" }, { "code": null, "e": 29202, "s": 29195, "text": "Picked" }, { "code": null, "e": 29223, "s": 29202, "text": "Python BeautifulSoup" }, { "code": null, "e": 29230, "s": 29223, "text": "Python" }, { "code": null, "e": 29328, "s": 29230, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29360, "s": 29328, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29402, "s": 29360, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29458, "s": 29402, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29500, "s": 29458, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29531, "s": 29500, "text": "Python | os.path.join() method" }, { "code": null, "e": 29586, "s": 29531, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 29608, "s": 29586, "text": "Defaultdict in Python" }, { "code": null, "e": 29647, "s": 29608, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29676, "s": 29647, "text": "Create a directory in Python" } ]
Simulating Multi-Agent Swarming Events in Python | by Juan Nathaniel | Towards Data Science
Swarming occurs frequently in nature: from a group of migratory birds to a collection of drones performing a particular mission. Thus, being able to simulate how swarming works will enable you to build your own multi-agent reinforcement learning algorithm that closely mimics real-world scenarios. To give you a glimpse of what we are building today, the GIF below will be the output of our swarming simulation model using an example of migratory birds. Without further ado, let’s begin! Note: You can find the full code at the end of the post. Why is simulation important in multi-agent Reinforcement Learning (RL) problems? It is primarily because simulation is one of the Exploratory Data Analysis (EDA) methods in RL that allows us to visualize the interrelatedness of different agents within a system. In this post, we are going to discuss swarming events because they are some of the many examples of multi-agent reinforcement learning, and I have compiled below how they act in real life! Swarming of birdsDrone swarmsFish schoolAnd many others! Swarming of birds Drone swarms Fish school And many others! We will be implementing the Viscek model (1995) as our multi-agent swarming baseline algorithm where many more advanced implementations have since been built on top. Imagine you are trying to simulate the swarming of 300 birds (N=300), where each bird is indexed i=0...(N-1). A bird will only change its direction and velocity vectors when it interacts with another one within a circle of radius, R. Let’s start by importing the required Python libraries and initializing the above constants. import matplotlib.pyplot as pltimport numpy as npN = 300 # number of birdsR = 0.5 # radius of effect# Preparing the drawingL = 5 # size of drawing boxfig = plt.figure(figsize=(6,6), dpi=96)ax = plt.gca() For each time step, n, the position of each bird along the x- and y-axes (r) is updated as follows: And this is implemented in Python below. Nt = 200 # number of time stepsdt = 0.1 # time step# bird positions (initial)x = np.random.rand(N,1)*Ly = np.random.rand(N,1)*L v is the velocity vector with a constant speed, v0, and an angle Θi (read: theta). We will also introduce an angle perturbation (read: eta) to mimic the natural stochasticity of birds’ movement. The velocity vector is initialized in Python below. v0 = 0.5 # constant speedeta = 0.6 # random fluctuation in angle (in radians)theta = 2 * np.pi * np.random.rand(N,1)# bird velocities (initial)vx = v0 * np.cos(theta)vy = v0 * np.sin(theta) Now we will come to the main for loop. For each timestep, the position, r, is updated as: # Update positionx += vx*dty += vy*dt And the v is updated by finding the (1) mean angle within R, (2) adding random perturbation to generate a new theta, and (3) updating the new velocity vector, v: (1) Mean angle within R mean_theta = theta# Mean angle within Rfor b in range(N): neighbors = (x-x[b])**2+(y-y[b])**2 < R**2 sx = np.sum(np.cos(theta[neighbors])) sy = np.sum(np.sin(theta[neighbors])) mean_theta[b] = np.arctan2(sy, sx) (2) Adding a random perturbation to the velocity angle. The random term is generated by sampling from a normal distribution within [-0.5, 0.5], multiplying it by a pre-defined eta, and adding this perturbation term with the calculated mean theta. # Adding a random angle perturbationtheta = mean_theta + eta*(np.random.rand(N,1)-0.5) (3) Updating the velocity vector with a new theta: # Updating velocityvx = v0 * np.cos(theta)vy = v0 * np.sin(theta) Overall, the updates for r and v will be done across dt * Nt time steps. Finally, now that everything is in order, let’s finish up by plotting how the updates will look like! plt.cla()plt.quiver(x,y,vx,vy,color='r')ax.set(xlim=(0, L), ylim=(0, L))ax.set_aspect('equal')plt.pause(0.001) If everything works out, you will be greeted with this on your screen. Congratulations! You can experiment around and change some of the parameters to see how your simulation model varies. Well done if you have reached the end. You can find the full code here: Simulation is one of the Exploratory Data Analysis (EDA) steps in Reinforcement Learning (RL). Once you have a clearer idea of how your real-world scenario behaves mathematically, you will be able to design more robust RL algorithms. If you enjoy this post, I will make many more real-world simulations as part of my multi-agent RL EDA series. So stay tuned! Do subscribe to my Email newsletter: https://tinyurl.com/2npw2fnz where I regularly summarize AI research papers in plain English and beautiful visualization. Lastly, you can find more resources surrounding the topic of RL and simulation here:
[ { "code": null, "e": 660, "s": 172, "text": "Swarming occurs frequently in nature: from a group of migratory birds to a collection of drones performing a particular mission. Thus, being able to simulate how swarming works will enable you to build your own multi-agent reinforcement learning algorithm that closely mimics real-world scenarios. To give you a glimpse of what we are building today, the GIF below will be the output of our swarming simulation model using an example of migratory birds. Without further ado, let’s begin!" }, { "code": null, "e": 717, "s": 660, "text": "Note: You can find the full code at the end of the post." }, { "code": null, "e": 1168, "s": 717, "text": "Why is simulation important in multi-agent Reinforcement Learning (RL) problems? It is primarily because simulation is one of the Exploratory Data Analysis (EDA) methods in RL that allows us to visualize the interrelatedness of different agents within a system. In this post, we are going to discuss swarming events because they are some of the many examples of multi-agent reinforcement learning, and I have compiled below how they act in real life!" }, { "code": null, "e": 1225, "s": 1168, "text": "Swarming of birdsDrone swarmsFish schoolAnd many others!" }, { "code": null, "e": 1243, "s": 1225, "text": "Swarming of birds" }, { "code": null, "e": 1256, "s": 1243, "text": "Drone swarms" }, { "code": null, "e": 1268, "s": 1256, "text": "Fish school" }, { "code": null, "e": 1285, "s": 1268, "text": "And many others!" }, { "code": null, "e": 1451, "s": 1285, "text": "We will be implementing the Viscek model (1995) as our multi-agent swarming baseline algorithm where many more advanced implementations have since been built on top." }, { "code": null, "e": 1685, "s": 1451, "text": "Imagine you are trying to simulate the swarming of 300 birds (N=300), where each bird is indexed i=0...(N-1). A bird will only change its direction and velocity vectors when it interacts with another one within a circle of radius, R." }, { "code": null, "e": 1778, "s": 1685, "text": "Let’s start by importing the required Python libraries and initializing the above constants." }, { "code": null, "e": 1984, "s": 1778, "text": "import matplotlib.pyplot as pltimport numpy as npN = 300 # number of birdsR = 0.5 # radius of effect# Preparing the drawingL = 5 # size of drawing boxfig = plt.figure(figsize=(6,6), dpi=96)ax = plt.gca()" }, { "code": null, "e": 2084, "s": 1984, "text": "For each time step, n, the position of each bird along the x- and y-axes (r) is updated as follows:" }, { "code": null, "e": 2125, "s": 2084, "text": "And this is implemented in Python below." }, { "code": null, "e": 2253, "s": 2125, "text": "Nt = 200 # number of time stepsdt = 0.1 # time step# bird positions (initial)x = np.random.rand(N,1)*Ly = np.random.rand(N,1)*L" }, { "code": null, "e": 2448, "s": 2253, "text": "v is the velocity vector with a constant speed, v0, and an angle Θi (read: theta). We will also introduce an angle perturbation (read: eta) to mimic the natural stochasticity of birds’ movement." }, { "code": null, "e": 2500, "s": 2448, "text": "The velocity vector is initialized in Python below." }, { "code": null, "e": 2690, "s": 2500, "text": "v0 = 0.5 # constant speedeta = 0.6 # random fluctuation in angle (in radians)theta = 2 * np.pi * np.random.rand(N,1)# bird velocities (initial)vx = v0 * np.cos(theta)vy = v0 * np.sin(theta)" }, { "code": null, "e": 2780, "s": 2690, "text": "Now we will come to the main for loop. For each timestep, the position, r, is updated as:" }, { "code": null, "e": 2818, "s": 2780, "text": "# Update positionx += vx*dty += vy*dt" }, { "code": null, "e": 2980, "s": 2818, "text": "And the v is updated by finding the (1) mean angle within R, (2) adding random perturbation to generate a new theta, and (3) updating the new velocity vector, v:" }, { "code": null, "e": 3004, "s": 2980, "text": "(1) Mean angle within R" }, { "code": null, "e": 3228, "s": 3004, "text": "mean_theta = theta# Mean angle within Rfor b in range(N): neighbors = (x-x[b])**2+(y-y[b])**2 < R**2 sx = np.sum(np.cos(theta[neighbors])) sy = np.sum(np.sin(theta[neighbors])) mean_theta[b] = np.arctan2(sy, sx)" }, { "code": null, "e": 3475, "s": 3228, "text": "(2) Adding a random perturbation to the velocity angle. The random term is generated by sampling from a normal distribution within [-0.5, 0.5], multiplying it by a pre-defined eta, and adding this perturbation term with the calculated mean theta." }, { "code": null, "e": 3562, "s": 3475, "text": "# Adding a random angle perturbationtheta = mean_theta + eta*(np.random.rand(N,1)-0.5)" }, { "code": null, "e": 3613, "s": 3562, "text": "(3) Updating the velocity vector with a new theta:" }, { "code": null, "e": 3679, "s": 3613, "text": "# Updating velocityvx = v0 * np.cos(theta)vy = v0 * np.sin(theta)" }, { "code": null, "e": 3752, "s": 3679, "text": "Overall, the updates for r and v will be done across dt * Nt time steps." }, { "code": null, "e": 3854, "s": 3752, "text": "Finally, now that everything is in order, let’s finish up by plotting how the updates will look like!" }, { "code": null, "e": 3965, "s": 3854, "text": "plt.cla()plt.quiver(x,y,vx,vy,color='r')ax.set(xlim=(0, L), ylim=(0, L))ax.set_aspect('equal')plt.pause(0.001)" }, { "code": null, "e": 4154, "s": 3965, "text": "If everything works out, you will be greeted with this on your screen. Congratulations! You can experiment around and change some of the parameters to see how your simulation model varies." }, { "code": null, "e": 4226, "s": 4154, "text": "Well done if you have reached the end. You can find the full code here:" }, { "code": null, "e": 4585, "s": 4226, "text": "Simulation is one of the Exploratory Data Analysis (EDA) steps in Reinforcement Learning (RL). Once you have a clearer idea of how your real-world scenario behaves mathematically, you will be able to design more robust RL algorithms. If you enjoy this post, I will make many more real-world simulations as part of my multi-agent RL EDA series. So stay tuned!" }, { "code": null, "e": 4744, "s": 4585, "text": "Do subscribe to my Email newsletter: https://tinyurl.com/2npw2fnz where I regularly summarize AI research papers in plain English and beautiful visualization." } ]
How to create boxplot with multiple factor levels using ggplot2 in R?
To create a boxplot, we have one factor and one numerical column and the boxplot is created for each category or levels in that factor. Now if we have two factors then the boxplot can be created for both factor levels by passing fill argument in geom_boxplot. This will help us to differentiate between the boxplots for the two factors. Check out the below examples to understand how it works. Consider the below data frame − Live Demo > x<-sample(c("Male","Female"),30,replace=TRUE) > y<-rnorm(30) > grp<-sample(letters[1:3],30,replace=TRUE) > df<-data.frame(x,y,grp) > df x y grp 1 Female 0.790349405 b 2 Male 0.868186299 b 3 Female -2.108607808 b 4 Female 0.284872060 c 5 Male -1.128470452 b 6 Male 0.001181183 b 7 Female -2.915847134 c 8 Male -1.416607857 c 9 Female -1.784574028 a 10 Male 0.685830764 a 11 Female 0.581216168 c 12 Male 0.387109500 c 13 Female 0.611448059 c 14 Female 0.603614728 c 15 Male 0.207989975 c 16 Male 0.357018523 b 17 Female -0.196608618 c 18 Male 1.165436068 c 19 Male 0.466733550 c 20 Female -1.293515169 b 21 Male -1.046339186 b 22 Female 1.692938740 c 23 Female 1.360998968 a 24 Female -0.141122217 c 25 Male -0.946920446 a 26 Female 1.091516275 c 27 Male 0.216101163 a 28 Female 0.935390544 a 29 Male -0.636606941 a 30 Female 0.266238867 b Loading ggplot2 and creating the boxplot − > library(ggplot2) > ggplot(df,aes(x,y))+geom_boxplot(aes(fill=grp))
[ { "code": null, "e": 1456, "s": 1062, "text": "To create a boxplot, we have one factor and one numerical column and the boxplot is created for each category or levels in that factor. Now if we have two factors then the boxplot can be created for both factor levels by passing fill argument in geom_boxplot. This will help us to differentiate between the boxplots for the two factors. Check out the below examples to understand how it works." }, { "code": null, "e": 1488, "s": 1456, "text": "Consider the below data frame −" }, { "code": null, "e": 1498, "s": 1488, "text": "Live Demo" }, { "code": null, "e": 1636, "s": 1498, "text": "> x<-sample(c(\"Male\",\"Female\"),30,replace=TRUE)\n> y<-rnorm(30)\n> grp<-sample(letters[1:3],30,replace=TRUE)\n> df<-data.frame(x,y,grp)\n> df" }, { "code": null, "e": 2535, "s": 1636, "text": " x y grp\n1 Female 0.790349405 b\n2 Male 0.868186299 b\n3 Female -2.108607808 b\n4 Female 0.284872060 c\n5 Male -1.128470452 b\n6 Male 0.001181183 b\n7 Female -2.915847134 c\n8 Male -1.416607857 c\n9 Female -1.784574028 a\n10 Male 0.685830764 a\n11 Female 0.581216168 c\n12 Male 0.387109500 c\n13 Female 0.611448059 c\n14 Female 0.603614728 c\n15 Male 0.207989975 c\n16 Male 0.357018523 b\n17 Female -0.196608618 c\n18 Male 1.165436068 c\n19 Male 0.466733550 c\n20 Female -1.293515169 b\n21 Male -1.046339186 b\n22 Female 1.692938740 c\n23 Female 1.360998968 a\n24 Female -0.141122217 c\n25 Male -0.946920446 a\n26 Female 1.091516275 c\n27 Male 0.216101163 a\n28 Female 0.935390544 a\n29 Male -0.636606941 a\n30 Female 0.266238867 b" }, { "code": null, "e": 2578, "s": 2535, "text": "Loading ggplot2 and creating the boxplot −" }, { "code": null, "e": 2647, "s": 2578, "text": "> library(ggplot2)\n> ggplot(df,aes(x,y))+geom_boxplot(aes(fill=grp))" } ]
VLOOKUP in 5 languages (VBA/SQL/PYTHON/M query/DAX powerBI) | Towards Data Science
Excel is a powerful spreadsheet used by most people working in data analysis. The increase of volume of data and development user-friendly tools is an opportunity of improvement of Excel reports by mixing them with another tool or language. As working for a financial reporting department I faced the need to boost our reporting tools. A simple way to start working with a new language is to translate what we use to do in excel, in another language. “How can I pivot this?”, “How can I vlookup that ?”. In this article I will share with you how you can make VLOOKUP in 5 different languages: VBA, python, SQL, DAX (Power BI), M (Power query). it will simple tips but if you want to get more detailed article don’t forget to follow me! VLOOKUP is a function used in Excel to look up data in a table or range organised vertically. We will use a simple example with a tab with items and their relative prices. In cell E2 we can put an item and with the VLOOKUP formula in F2 we get its relative price. F2=VLOOKUP(What you want to look up so here the item written in E2, where you want to look for it so the range from A1 to B4, the column number in the range containing the value to return so the price in column 2, return an Approximate or Exact match – indicated as 1/TRUE, or 0/FALSE). Visual Basic for Application (VBA) is an implementation of Microsoft Visual Basic integrated into Microsoft Office applications. On your code, you can set up a variable to store the result of the VLOOKUP result using the statement “WorksheetFunction.vlookup”. It works exactly as the function itself. Then you can set the value of the cell F2 as the variable. VLookupResult = WorksheetFunction.vlookup(Range("E2"), RANGE("A1:B4"), 2 , False) RANGE("F2")=VLookupResult Additional tip: This case is really simple as we want to get the result of the VLOOKUP into a single cell. But what if we want to loop through all the lines of a table? For example, if we want to put in cells E3 and E4 other items and get in cells F3 and F4 the price using VLOOKUP? If we loop the same formula we will get the as result the same price as the VLOOKUP will always be done on the same item (always the cell “E2”). In this case, I suggest using the statement “FormulaR1C1”, where R and C stand for Row and Column. In this statement instead of putting the exact cell where is the value we are looking for, we will say “The cell where is the value we look for is situated at X rows and Y columns from here”. Range("F2").FormulaR1C1="=VLOOKUP(RC(-1),RANGE("$A$1:$B$4),2,FALSE) Then we can loop like this: Sub VLOOKUP()On Error Resume NextDim Cell_Row As LongDim Cell_Clm As LongTable1 = Sheet1.Range("F2:F4") 'Table where we loopTable2= Sheet1.Range("A1:B4") 'Table with items and pricesCell_Row = Sheet1.Range("F2").Row 'variable to get the rows of the loopCell_Clm = Sheet1.Range("F2").Column 'variable to get the column of the loopFor each cl in Table1 'loopSheet1.Cells(Dept_Row, Dept_Clm).FormulaR1C1="=VLOOKUP(RC(-1),Table2,2,FALSE)Cell_Row = Cell_Row + 1Next clEnd Sub SQL ( Structured Query Language) or sequel, is a standard language for storing, manipulating and retrieving data in databases. It is one of the common upgrade done by companies that face limits with Excel. Usually the first reaction is to negotiate some budget in order to store the data into a database and use SQL to “speak” with this database and organise, manipulate the data. The language is also highly appreciable. Close to a natural language, you don’t feel coding when typing simple SQL request. Let’s build a table1 that will match with the RANGE(“A1:B4) of our Excel. In table2 we will mention just the item for which we are looking for the price. CREATE TABLE table1 ( Item varchar(255), Price int );INSERT INTO table1VALUES ('Item1', 4);INSERT INTO table1VALUES ('Item2', 12);INSERT INTO table1VALUES ('Item3', 56);CREATE TABLE table2 ( Item varchar(255), Price int ); INSERT INTO table2VALUES ('Item2',0); Then we will use a “Right.Join” request to show the item of table 2 with its relative price of table 1. select t1.Item, t1.Pricefrom table1 as t1right join table2 as t2 on t2.Item = t1.Item This request means that we select the item and its price in table1 if the item is present in table 2. Additional tip: Right join return all rows from the right table and the matched rows from the left table. based on your database you can switch with Left join (in the opposite way), inner join if the match is done in both table, full join if we want all rows that match in one table. Python is an interpreted, high level language with a generic purpose. It is used in a large range of application, including data analysis. We can present python by saying “For all application its libraries”. And for data, without surprise, we will use the famous Pandas. The logic used by pandas to do a VLOOKUP is close to the one of SQL. We will create two data frames, one (df1) for the items and their relative prices (cells A1 to B4), one (df2) for the items we want to look up the price. And then we will create a third data frame (Resultdf) that will join the item of df1 with prices of df2. import pandas as pditems = {'Item': ['Item1','Item2','Item3'], 'Price': [4, 12,56]}lookup = {'Item': ['Item2']}df1 = pd.DataFrame(data=items)df2 = pd.DataFrame(data=lookup)Resultdf = pd.merge(df1, df2, on ='Item', how ='right') Resultdf Additional tip: There are tones of way to interact directly with Excel in python. If you are interested into that; you can check another article specially for this topic that you can check here: https://medium.com/analytics-vidhya/spice-up-your-excel-with-python-621c9693c027 M is the powerful language behind the tool power query. Even if you are working on the query editor, every single step will be written in M. M stands for Data Mashup or Data Modeling. I highly recommend to have a look at this language, we can do so much more than just using the graphical interface. The request behind VLOOKUP in M is a join method between the table where we have the items and the prices, and the table where we have the item we look for the price. To create both tables you just have to select the range of cells and use short cut ctrl+T (or command T in mac). Table.NestedJoin(table1 as table, key1 as any, table2 as any, key2 as any, newColumnName as text, optional joinKind as nullable number) as table In our sample “Table 1” is my table with items and prices, “Table2” is the one with the lookup. The method Table.NestedJoin will join the rows of table 1 (with the prices) with the row of table 2; based on the equality of the key element of each table. The final result will be on the new Table 2 with additional column. We add an optional argument to specify that we do a right join. = Table.NestedJoin(Table1, {"Item"}, Table2, {"Insert one item"}, Table2, JoinKind.RightOuter) Additional tip: This join method can be done directly in the query editor. Even if I recommend to learn M as a all features available these last month in the query editor were already possible with M since years, I will share here how do to it using the query editor: First we have 2 tables: Then in “Data” we select from Table/Range after selecting Table 1. Automatically the query editor will appear with Table1 and the M query of the creation of this table. Then we can load the result and do the same with Table2. Once done, in Excel we have a query panel with both table. Just select one of them with a click right and click on Merge. A merge editor will appear, where you will put Table 1vas the first table, table 2 as second table and select both column with items. Then click on OK. And here is the result. DAX stands for Data Analysis Expressions. More than a language, it is a library of functions and operators that can be used to build formulas in Power BI and Power Pivot. Some functions are already built by default, and thankfully LOOKUP is one of them! LOOKUPVALUE(<result_columnName>,<search_columnName>, <search_value>[, <search2_columnName>, <search2_value>]...[) The logical is close the VLOOKUP excel formula but with argument set in a different order. result_columnName: is the name of the column where is the result we are looking for;search_columnName: is the name of the column where is the value on with we do the lookup;search_value: value on which we do the lookup. In our case the function would be: LOOKUPVALUE(Table1[Prices],Table1[Item],Table2[Insert an item]) Additional tip: Power BI two tables can have a relationship. If there is already a relationship between both table you can use functions “RELATED” and “FILTERED”. I hope that you found here something that might help you on your report. This article is a part of a full set of articles where I want to share some Excel features in different famous language used in data analysis. If you enjoyed it, follow me on my different social network if you want to get notified for the next one.
[ { "code": null, "e": 412, "s": 171, "text": "Excel is a powerful spreadsheet used by most people working in data analysis. The increase of volume of data and development user-friendly tools is an opportunity of improvement of Excel reports by mixing them with another tool or language." }, { "code": null, "e": 675, "s": 412, "text": "As working for a financial reporting department I faced the need to boost our reporting tools. A simple way to start working with a new language is to translate what we use to do in excel, in another language. “How can I pivot this?”, “How can I vlookup that ?”." }, { "code": null, "e": 907, "s": 675, "text": "In this article I will share with you how you can make VLOOKUP in 5 different languages: VBA, python, SQL, DAX (Power BI), M (Power query). it will simple tips but if you want to get more detailed article don’t forget to follow me!" }, { "code": null, "e": 1001, "s": 907, "text": "VLOOKUP is a function used in Excel to look up data in a table or range organised vertically." }, { "code": null, "e": 1171, "s": 1001, "text": "We will use a simple example with a tab with items and their relative prices. In cell E2 we can put an item and with the VLOOKUP formula in F2 we get its relative price." }, { "code": null, "e": 1458, "s": 1171, "text": "F2=VLOOKUP(What you want to look up so here the item written in E2, where you want to look for it so the range from A1 to B4, the column number in the range containing the value to return so the price in column 2, return an Approximate or Exact match – indicated as 1/TRUE, or 0/FALSE)." }, { "code": null, "e": 1587, "s": 1458, "text": "Visual Basic for Application (VBA) is an implementation of Microsoft Visual Basic integrated into Microsoft Office applications." }, { "code": null, "e": 1818, "s": 1587, "text": "On your code, you can set up a variable to store the result of the VLOOKUP result using the statement “WorksheetFunction.vlookup”. It works exactly as the function itself. Then you can set the value of the cell F2 as the variable." }, { "code": null, "e": 1926, "s": 1818, "text": "VLookupResult = WorksheetFunction.vlookup(Range(\"E2\"), RANGE(\"A1:B4\"), 2 , False) RANGE(\"F2\")=VLookupResult" }, { "code": null, "e": 2209, "s": 1926, "text": "Additional tip: This case is really simple as we want to get the result of the VLOOKUP into a single cell. But what if we want to loop through all the lines of a table? For example, if we want to put in cells E3 and E4 other items and get in cells F3 and F4 the price using VLOOKUP?" }, { "code": null, "e": 2645, "s": 2209, "text": "If we loop the same formula we will get the as result the same price as the VLOOKUP will always be done on the same item (always the cell “E2”). In this case, I suggest using the statement “FormulaR1C1”, where R and C stand for Row and Column. In this statement instead of putting the exact cell where is the value we are looking for, we will say “The cell where is the value we look for is situated at X rows and Y columns from here”." }, { "code": null, "e": 2713, "s": 2645, "text": "Range(\"F2\").FormulaR1C1=\"=VLOOKUP(RC(-1),RANGE(\"$A$1:$B$4),2,FALSE)" }, { "code": null, "e": 2741, "s": 2713, "text": "Then we can loop like this:" }, { "code": null, "e": 3212, "s": 2741, "text": "Sub VLOOKUP()On Error Resume NextDim Cell_Row As LongDim Cell_Clm As LongTable1 = Sheet1.Range(\"F2:F4\") 'Table where we loopTable2= Sheet1.Range(\"A1:B4\") 'Table with items and pricesCell_Row = Sheet1.Range(\"F2\").Row 'variable to get the rows of the loopCell_Clm = Sheet1.Range(\"F2\").Column 'variable to get the column of the loopFor each cl in Table1 'loopSheet1.Cells(Dept_Row, Dept_Clm).FormulaR1C1=\"=VLOOKUP(RC(-1),Table2,2,FALSE)Cell_Row = Cell_Row + 1Next clEnd Sub" }, { "code": null, "e": 3717, "s": 3212, "text": "SQL ( Structured Query Language) or sequel, is a standard language for storing, manipulating and retrieving data in databases. It is one of the common upgrade done by companies that face limits with Excel. Usually the first reaction is to negotiate some budget in order to store the data into a database and use SQL to “speak” with this database and organise, manipulate the data. The language is also highly appreciable. Close to a natural language, you don’t feel coding when typing simple SQL request." }, { "code": null, "e": 3871, "s": 3717, "text": "Let’s build a table1 that will match with the RANGE(“A1:B4) of our Excel. In table2 we will mention just the item for which we are looking for the price." }, { "code": null, "e": 4151, "s": 3871, "text": "CREATE TABLE table1 ( Item varchar(255), Price int );INSERT INTO table1VALUES ('Item1', 4);INSERT INTO table1VALUES ('Item2', 12);INSERT INTO table1VALUES ('Item3', 56);CREATE TABLE table2 ( Item varchar(255), Price int ); INSERT INTO table2VALUES ('Item2',0);" }, { "code": null, "e": 4255, "s": 4151, "text": "Then we will use a “Right.Join” request to show the item of table 2 with its relative price of table 1." }, { "code": null, "e": 4344, "s": 4255, "text": "select t1.Item, t1.Pricefrom table1 as t1right join table2 as t2 on t2.Item = t1.Item" }, { "code": null, "e": 4446, "s": 4344, "text": "This request means that we select the item and its price in table1 if the item is present in table 2." }, { "code": null, "e": 4730, "s": 4446, "text": "Additional tip: Right join return all rows from the right table and the matched rows from the left table. based on your database you can switch with Left join (in the opposite way), inner join if the match is done in both table, full join if we want all rows that match in one table." }, { "code": null, "e": 5001, "s": 4730, "text": "Python is an interpreted, high level language with a generic purpose. It is used in a large range of application, including data analysis. We can present python by saying “For all application its libraries”. And for data, without surprise, we will use the famous Pandas." }, { "code": null, "e": 5329, "s": 5001, "text": "The logic used by pandas to do a VLOOKUP is close to the one of SQL. We will create two data frames, one (df1) for the items and their relative prices (cells A1 to B4), one (df2) for the items we want to look up the price. And then we will create a third data frame (Resultdf) that will join the item of df1 with prices of df2." }, { "code": null, "e": 5632, "s": 5329, "text": "import pandas as pditems = {'Item': ['Item1','Item2','Item3'], 'Price': [4, 12,56]}lookup = {'Item': ['Item2']}df1 = pd.DataFrame(data=items)df2 = pd.DataFrame(data=lookup)Resultdf = pd.merge(df1, df2, on ='Item', how ='right') Resultdf" }, { "code": null, "e": 5908, "s": 5632, "text": "Additional tip: There are tones of way to interact directly with Excel in python. If you are interested into that; you can check another article specially for this topic that you can check here: https://medium.com/analytics-vidhya/spice-up-your-excel-with-python-621c9693c027" }, { "code": null, "e": 6208, "s": 5908, "text": "M is the powerful language behind the tool power query. Even if you are working on the query editor, every single step will be written in M. M stands for Data Mashup or Data Modeling. I highly recommend to have a look at this language, we can do so much more than just using the graphical interface." }, { "code": null, "e": 6375, "s": 6208, "text": "The request behind VLOOKUP in M is a join method between the table where we have the items and the prices, and the table where we have the item we look for the price." }, { "code": null, "e": 6488, "s": 6375, "text": "To create both tables you just have to select the range of cells and use short cut ctrl+T (or command T in mac)." }, { "code": null, "e": 6633, "s": 6488, "text": "Table.NestedJoin(table1 as table, key1 as any, table2 as any, key2 as any, newColumnName as text, optional joinKind as nullable number) as table" }, { "code": null, "e": 6729, "s": 6633, "text": "In our sample “Table 1” is my table with items and prices, “Table2” is the one with the lookup." }, { "code": null, "e": 7018, "s": 6729, "text": "The method Table.NestedJoin will join the rows of table 1 (with the prices) with the row of table 2; based on the equality of the key element of each table. The final result will be on the new Table 2 with additional column. We add an optional argument to specify that we do a right join." }, { "code": null, "e": 7113, "s": 7018, "text": "= Table.NestedJoin(Table1, {\"Item\"}, Table2, {\"Insert one item\"}, Table2, JoinKind.RightOuter)" }, { "code": null, "e": 7381, "s": 7113, "text": "Additional tip: This join method can be done directly in the query editor. Even if I recommend to learn M as a all features available these last month in the query editor were already possible with M since years, I will share here how do to it using the query editor:" }, { "code": null, "e": 7405, "s": 7381, "text": "First we have 2 tables:" }, { "code": null, "e": 7472, "s": 7405, "text": "Then in “Data” we select from Table/Range after selecting Table 1." }, { "code": null, "e": 7574, "s": 7472, "text": "Automatically the query editor will appear with Table1 and the M query of the creation of this table." }, { "code": null, "e": 7753, "s": 7574, "text": "Then we can load the result and do the same with Table2. Once done, in Excel we have a query panel with both table. Just select one of them with a click right and click on Merge." }, { "code": null, "e": 7905, "s": 7753, "text": "A merge editor will appear, where you will put Table 1vas the first table, table 2 as second table and select both column with items. Then click on OK." }, { "code": null, "e": 7929, "s": 7905, "text": "And here is the result." }, { "code": null, "e": 8100, "s": 7929, "text": "DAX stands for Data Analysis Expressions. More than a language, it is a library of functions and operators that can be used to build formulas in Power BI and Power Pivot." }, { "code": null, "e": 8183, "s": 8100, "text": "Some functions are already built by default, and thankfully LOOKUP is one of them!" }, { "code": null, "e": 8301, "s": 8183, "text": "LOOKUPVALUE(<result_columnName>,<search_columnName>, <search_value>[, <search2_columnName>, <search2_value>]...[)" }, { "code": null, "e": 8392, "s": 8301, "text": "The logical is close the VLOOKUP excel formula but with argument set in a different order." }, { "code": null, "e": 8612, "s": 8392, "text": "result_columnName: is the name of the column where is the result we are looking for;search_columnName: is the name of the column where is the value on with we do the lookup;search_value: value on which we do the lookup." }, { "code": null, "e": 8647, "s": 8612, "text": "In our case the function would be:" }, { "code": null, "e": 8711, "s": 8647, "text": "LOOKUPVALUE(Table1[Prices],Table1[Item],Table2[Insert an item])" }, { "code": null, "e": 8874, "s": 8711, "text": "Additional tip: Power BI two tables can have a relationship. If there is already a relationship between both table you can use functions “RELATED” and “FILTERED”." } ]
Design Patterns - Iterator Pattern
Iterator pattern is very commonly used design pattern in Java and .Net programming environment. This pattern is used to get a way to access the elements of a collection object in sequential manner without any need to know its underlying representation. Iterator pattern falls under behavioral pattern category. We're going to create a Iterator interface which narrates navigation method and a Container interface which retruns the iterator . Concrete classes implementing the Container interface will be responsible to implement Iterator interface and use it IteratorPatternDemo, our demo class will use NamesRepository, a concrete class implementation to print a Names stored as a collection in NamesRepository. Create interfaces. Iterator.java public interface Iterator { public boolean hasNext(); public Object next(); } Container.java public interface Container { public Iterator getIterator(); } Create concrete class implementing the Container interface. This class has inner class NameIterator implementing the Iterator interface. NameRepository.java public class NameRepository implements Container { public String names[] = {"Robert" , "John" ,"Julie" , "Lora"}; @Override public Iterator getIterator() { return new NameIterator(); } private class NameIterator implements Iterator { int index; @Override public boolean hasNext() { if(index < names.length){ return true; } return false; } @Override public Object next() { if(this.hasNext()){ return names[index++]; } return null; } } } Use the NameRepository to get iterator and print names. IteratorPatternDemo.java public class IteratorPatternDemo { public static void main(String[] args) { NameRepository namesRepository = new NameRepository(); for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){ String name = (String)iter.next(); System.out.println("Name : " + name); } } } Verify the output. Name : Robert Name : John Name : Julie Name : Lora 102 Lectures 10 hours Arnab Chakraborty 30 Lectures 3 hours Arnab Chakraborty 31 Lectures 4 hours Arnab Chakraborty 43 Lectures 1.5 hours Manoj Kumar 7 Lectures 1 hours Zach Miller 54 Lectures 4 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 3005, "s": 2751, "text": "Iterator pattern is very commonly used design pattern in Java and .Net programming environment. This pattern is used to get a way to access the elements of a collection object in sequential manner without any need to know its underlying representation. " }, { "code": null, "e": 3063, "s": 3005, "text": "Iterator pattern falls under behavioral pattern category." }, { "code": null, "e": 3312, "s": 3063, "text": "We're going to create a Iterator interface which narrates navigation method and a Container interface which retruns the iterator . Concrete classes implementing the Container interface will be responsible to implement Iterator interface and use it " }, { "code": null, "e": 3466, "s": 3312, "text": "IteratorPatternDemo, our demo class will use NamesRepository, a concrete class implementation to print a Names stored as a collection in NamesRepository." }, { "code": null, "e": 3485, "s": 3466, "text": "Create interfaces." }, { "code": null, "e": 3499, "s": 3485, "text": "Iterator.java" }, { "code": null, "e": 3583, "s": 3499, "text": "public interface Iterator {\n public boolean hasNext();\n public Object next();\n}" }, { "code": null, "e": 3598, "s": 3583, "text": "Container.java" }, { "code": null, "e": 3663, "s": 3598, "text": "public interface Container {\n public Iterator getIterator();\n}" }, { "code": null, "e": 3800, "s": 3663, "text": "Create concrete class implementing the Container interface. This class has inner class NameIterator implementing the Iterator interface." }, { "code": null, "e": 3820, "s": 3800, "text": "NameRepository.java" }, { "code": null, "e": 4421, "s": 3820, "text": "public class NameRepository implements Container {\n public String names[] = {\"Robert\" , \"John\" ,\"Julie\" , \"Lora\"};\n\n @Override\n public Iterator getIterator() {\n return new NameIterator();\n }\n\n private class NameIterator implements Iterator {\n\n int index;\n\n @Override\n public boolean hasNext() {\n \n if(index < names.length){\n return true;\n }\n return false;\n }\n\n @Override\n public Object next() {\n \n if(this.hasNext()){\n return names[index++];\n }\n return null;\n }\t\t\n }\n}" }, { "code": null, "e": 4477, "s": 4421, "text": "Use the NameRepository to get iterator and print names." }, { "code": null, "e": 4502, "s": 4477, "text": "IteratorPatternDemo.java" }, { "code": null, "e": 4828, "s": 4502, "text": "public class IteratorPatternDemo {\n\t\n public static void main(String[] args) {\n NameRepository namesRepository = new NameRepository();\n\n for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){\n String name = (String)iter.next();\n System.out.println(\"Name : \" + name);\n } \t\n }\n}" }, { "code": null, "e": 4847, "s": 4828, "text": "Verify the output." }, { "code": null, "e": 4899, "s": 4847, "text": "Name : Robert\nName : John\nName : Julie\nName : Lora\n" }, { "code": null, "e": 4934, "s": 4899, "text": "\n 102 Lectures \n 10 hours \n" }, { "code": null, "e": 4953, "s": 4934, "text": " Arnab Chakraborty" }, { "code": null, "e": 4986, "s": 4953, "text": "\n 30 Lectures \n 3 hours \n" }, { "code": null, "e": 5005, "s": 4986, "text": " Arnab Chakraborty" }, { "code": null, "e": 5038, "s": 5005, "text": "\n 31 Lectures \n 4 hours \n" }, { "code": null, "e": 5057, "s": 5038, "text": " Arnab Chakraborty" }, { "code": null, "e": 5092, "s": 5057, "text": "\n 43 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5105, "s": 5092, "text": " Manoj Kumar" }, { "code": null, "e": 5137, "s": 5105, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 5150, "s": 5137, "text": " Zach Miller" }, { "code": null, "e": 5183, "s": 5150, "text": "\n 54 Lectures \n 4 hours \n" }, { "code": null, "e": 5197, "s": 5183, "text": " Sasha Miller" }, { "code": null, "e": 5204, "s": 5197, "text": " Print" }, { "code": null, "e": 5215, "s": 5204, "text": " Add Notes" } ]
Ackermann's function using Dynamic programming - GeeksforGeeks
12 Nov, 2021 Given two non-zero integers M and N, the problem is to compute the result of the Ackermann function based on some particular equations. Ackermann function is defined as: Examples: Input: M = 2, N = 2Output: 7 Input: M = 2, N = 7Output: 6141004759 The approach for Ackermann function described in this article, takes a very huge amount of time to compute the value for even small values of (M, N) or in most cases doesn’t result in anything. Dynamic Programming approach: Here are the following Ackermann equations that would be used to come up with efficient solution. A(m, n) = A(m-1, A(m, n-1)) —– (Eq 1) A(0, n) = n+1 —– (Eq 2) A(m, 0) = A(m-1, 1) —– (Eq 3) Let’s assume the value of m = 2 and n = 2 A 2d DP table of size ( (m+1) x (n+1) ) is created for storing the result of each sub-problem. Following are the steps demonstrated to fill up the table. Empty Table – Initial StepFilled using A ( 0, n ) = n + 1The very next method is to fill all the base values, by taking the help of equation-2.In the next step the whole 1st row would be filled,A ( 1, 0 ) = A ( 0, 1 ) —– (refer Eq (3))Since A ( 0, 1 ) = 2Therefore, A ( 1, 0 ) = 2 —–(Eq 4)A ( 1, 1 ) = A ( 0, A ( 1, 0 ) ) —– refer Eq (1)= A ( 0, 2 ) —– refer Eq (4)= 3 —– refer Eq (2)So, A ( 1, 1 ) = 3 —–(Eq 5)A ( 1, 2 ) = A ( 0, A ( 1, 1 ) ) —– refer equation (1)= A ( 0, 3 ) —– refer equation (5)= 4 —– refer equation (2)So, A ( 1, 2 ) = 4 —–(Eq 6)Fill the table using equations and stored valuesLet’s just fill the first column of the last row i.e (2, 0) in the same manner as above, because for the other two columns there are some unsolved values.A ( 2, 0 ) = A ( 1, 1 ) —– refer equation (3)A ( 1, 1 ) = 3So, A ( 2, 0 ) = 3 —– (Eq. 7)Solving for A ( 2, 1 ) and A ( 2, 2 ).For simplicity the process for solving above functions is divided into two steps,In the first one, the problem is identified.A ( 2, 1 ) = A ( 1, A ( 2, 0 ) ) —– refer equation (1)A ( 2, 0 ) = 3A ( 2, 1 ) = A ( 1, 3 )So to compute this value, again use equation (1)A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4A ( 1, 3 ) = A ( 0, 4 ) —– refer equation(2)= 5Therefore A ( 2, 1 ) = A ( 1, 3 ) = 5 — (Eq 7)In the next one, methodology is described in detail and a generic formula is obtained to be logical while being used in programLet’s solve A ( 2, 2 ) , with a theory upfrontA ( 2, 2 ) = A ( 1, A ( 2, 1 ) ) —– refer equation (1)A ( 2, 1) = 5A ( 2, 2 ) = A ( 1, 5 )To compute A(1, 5) in a generic manner, observe how it reduces itself!A ( 1, 5 ) = A ( 0, A ( 1, 4 ) )A ( 1, 4 ) = A( 0, A ( 1, 3 ) )A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4Returning back from the function we get,A ( 1, 3 ) = A ( 0, 4 ) = 5 —– refer equation (2)A ( 1, 4 ) = A ( 0, A (1, 3 ) ) = A ( 0, 5 ) = 6 —–Since A ( 1, 3 ) = 5A ( 1, 5 ) = A ( 0, A ( 1, 4 ) ) = A ( 0, 6 ) = 7So, A ( 2, 2 ) = 7 ——- (Eq 9)Important Points:(n = column number, c: ( any number > n), r: row number]1 . A ( 1, c ) = A ( 1, n ) + ( c – n ) From the Above Observation2 . A ( r, c ) = A ( r, n ) + ( c – n )*r Based on hand tracingFinal Table with result of each sub-problem Empty Table – Initial Step Filled using A ( 0, n ) = n + 1The very next method is to fill all the base values, by taking the help of equation-2. Filled using A ( 0, n ) = n + 1The very next method is to fill all the base values, by taking the help of equation-2. In the next step the whole 1st row would be filled,A ( 1, 0 ) = A ( 0, 1 ) —– (refer Eq (3))Since A ( 0, 1 ) = 2Therefore, A ( 1, 0 ) = 2 —–(Eq 4)A ( 1, 1 ) = A ( 0, A ( 1, 0 ) ) —– refer Eq (1)= A ( 0, 2 ) —– refer Eq (4)= 3 —– refer Eq (2)So, A ( 1, 1 ) = 3 —–(Eq 5)A ( 1, 2 ) = A ( 0, A ( 1, 1 ) ) —– refer equation (1)= A ( 0, 3 ) —– refer equation (5)= 4 —– refer equation (2)So, A ( 1, 2 ) = 4 —–(Eq 6) In the next step the whole 1st row would be filled, A ( 1, 0 ) = A ( 0, 1 ) —– (refer Eq (3))Since A ( 0, 1 ) = 2Therefore, A ( 1, 0 ) = 2 —–(Eq 4) A ( 1, 0 ) = A ( 0, 1 ) —– (refer Eq (3))Since A ( 0, 1 ) = 2Therefore, A ( 1, 0 ) = 2 —–(Eq 4) A ( 1, 1 ) = A ( 0, A ( 1, 0 ) ) —– refer Eq (1)= A ( 0, 2 ) —– refer Eq (4)= 3 —– refer Eq (2)So, A ( 1, 1 ) = 3 —–(Eq 5) A ( 1, 1 ) = A ( 0, A ( 1, 0 ) ) —– refer Eq (1)= A ( 0, 2 ) —– refer Eq (4)= 3 —– refer Eq (2)So, A ( 1, 1 ) = 3 —–(Eq 5) A ( 1, 2 ) = A ( 0, A ( 1, 1 ) ) —– refer equation (1)= A ( 0, 3 ) —– refer equation (5)= 4 —– refer equation (2)So, A ( 1, 2 ) = 4 —–(Eq 6) A ( 1, 2 ) = A ( 0, A ( 1, 1 ) ) —– refer equation (1)= A ( 0, 3 ) —– refer equation (5)= 4 —– refer equation (2)So, A ( 1, 2 ) = 4 —–(Eq 6) Fill the table using equations and stored valuesLet’s just fill the first column of the last row i.e (2, 0) in the same manner as above, because for the other two columns there are some unsolved values.A ( 2, 0 ) = A ( 1, 1 ) —– refer equation (3)A ( 1, 1 ) = 3So, A ( 2, 0 ) = 3 —– (Eq. 7) Let’s just fill the first column of the last row i.e (2, 0) in the same manner as above, because for the other two columns there are some unsolved values. A ( 2, 0 ) = A ( 1, 1 ) —– refer equation (3)A ( 1, 1 ) = 3So, A ( 2, 0 ) = 3 —– (Eq. 7) Solving for A ( 2, 1 ) and A ( 2, 2 ).For simplicity the process for solving above functions is divided into two steps,In the first one, the problem is identified.A ( 2, 1 ) = A ( 1, A ( 2, 0 ) ) —– refer equation (1)A ( 2, 0 ) = 3A ( 2, 1 ) = A ( 1, 3 )So to compute this value, again use equation (1)A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4A ( 1, 3 ) = A ( 0, 4 ) —– refer equation(2)= 5Therefore A ( 2, 1 ) = A ( 1, 3 ) = 5 — (Eq 7)In the next one, methodology is described in detail and a generic formula is obtained to be logical while being used in programLet’s solve A ( 2, 2 ) , with a theory upfrontA ( 2, 2 ) = A ( 1, A ( 2, 1 ) ) —– refer equation (1)A ( 2, 1) = 5A ( 2, 2 ) = A ( 1, 5 )To compute A(1, 5) in a generic manner, observe how it reduces itself!A ( 1, 5 ) = A ( 0, A ( 1, 4 ) )A ( 1, 4 ) = A( 0, A ( 1, 3 ) )A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4Returning back from the function we get,A ( 1, 3 ) = A ( 0, 4 ) = 5 —– refer equation (2)A ( 1, 4 ) = A ( 0, A (1, 3 ) ) = A ( 0, 5 ) = 6 —–Since A ( 1, 3 ) = 5A ( 1, 5 ) = A ( 0, A ( 1, 4 ) ) = A ( 0, 6 ) = 7So, A ( 2, 2 ) = 7 ——- (Eq 9)Important Points:(n = column number, c: ( any number > n), r: row number]1 . A ( 1, c ) = A ( 1, n ) + ( c – n ) From the Above Observation2 . A ( r, c ) = A ( r, n ) + ( c – n )*r Based on hand tracing Solving for A ( 2, 1 ) and A ( 2, 2 ). For simplicity the process for solving above functions is divided into two steps, In the first one, the problem is identified.A ( 2, 1 ) = A ( 1, A ( 2, 0 ) ) —– refer equation (1)A ( 2, 0 ) = 3A ( 2, 1 ) = A ( 1, 3 )So to compute this value, again use equation (1)A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4A ( 1, 3 ) = A ( 0, 4 ) —– refer equation(2)= 5Therefore A ( 2, 1 ) = A ( 1, 3 ) = 5 — (Eq 7) A ( 2, 1 ) = A ( 1, A ( 2, 0 ) ) —– refer equation (1)A ( 2, 0 ) = 3A ( 2, 1 ) = A ( 1, 3 ) So to compute this value, again use equation (1)A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4A ( 1, 3 ) = A ( 0, 4 ) —– refer equation(2)= 5 Therefore A ( 2, 1 ) = A ( 1, 3 ) = 5 — (Eq 7) In the next one, methodology is described in detail and a generic formula is obtained to be logical while being used in programLet’s solve A ( 2, 2 ) , with a theory upfrontA ( 2, 2 ) = A ( 1, A ( 2, 1 ) ) —– refer equation (1)A ( 2, 1) = 5A ( 2, 2 ) = A ( 1, 5 )To compute A(1, 5) in a generic manner, observe how it reduces itself!A ( 1, 5 ) = A ( 0, A ( 1, 4 ) )A ( 1, 4 ) = A( 0, A ( 1, 3 ) )A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4Returning back from the function we get,A ( 1, 3 ) = A ( 0, 4 ) = 5 —– refer equation (2)A ( 1, 4 ) = A ( 0, A (1, 3 ) ) = A ( 0, 5 ) = 6 —–Since A ( 1, 3 ) = 5A ( 1, 5 ) = A ( 0, A ( 1, 4 ) ) = A ( 0, 6 ) = 7So, A ( 2, 2 ) = 7 ——- (Eq 9) Let’s solve A ( 2, 2 ) , with a theory upfront A ( 2, 2 ) = A ( 1, A ( 2, 1 ) ) —– refer equation (1)A ( 2, 1) = 5A ( 2, 2 ) = A ( 1, 5 ) To compute A(1, 5) in a generic manner, observe how it reduces itself! A ( 1, 5 ) = A ( 0, A ( 1, 4 ) )A ( 1, 4 ) = A( 0, A ( 1, 3 ) )A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4 Returning back from the function we get,A ( 1, 3 ) = A ( 0, 4 ) = 5 —– refer equation (2)A ( 1, 4 ) = A ( 0, A (1, 3 ) ) = A ( 0, 5 ) = 6 —–Since A ( 1, 3 ) = 5A ( 1, 5 ) = A ( 0, A ( 1, 4 ) ) = A ( 0, 6 ) = 7So, A ( 2, 2 ) = 7 ——- (Eq 9) Important Points: (n = column number, c: ( any number > n), r: row number] 1 . A ( 1, c ) = A ( 1, n ) + ( c – n ) From the Above Observation 2 . A ( r, c ) = A ( r, n ) + ( c – n )*r Based on hand tracing Final Table with result of each sub-problem Below is the implementation of the above approach: Python3 # Python code for the above approach # Bottom Up Approachdef Ackermann(m, n): # creating 2D LIST cache = [[0 for i in range(n + 1)] for j in range(m + 1)] for rows in range(m + 1): for cols in range(n + 1): # base case A ( 0, n ) = n + 1 if rows == 0: cache[rows][cols] = cols + 1 # base case A ( m, 0 ) = # A ( m-1, 1) [Computed already] elif cols == 0: cache[rows][cols] = cache[rows-1][1] else: # if rows and cols > 0 # then applying A ( m, n ) = # A ( m-1, A ( m, n-1 ) ) r = rows - 1 c = cache[rows][cols-1] # applying equation (2) # here A ( 0, n ) = n + 1 if r == 0: ans = c + 1 elif c <= n: # using stored value in cache ans = cache[rows-1][cache[rows][cols-1]] else: # Using the Derived Formula # to compute mystery values in O(1) time ans = (c-n)*(r) + cache[r][n] cache[rows][cols] = ans return cache[m][n] # very small valuesm = 2 n = 2 # a bit higher valuem1 = 5 n1 = 7 print("Ackermann value for m = ", m, " and n = ", n, "is -> ", Ackermann(m, n)) print("Ackermann value for m = ", m1, " and n = ", n1, "is -> ", Ackermann(m1, n1)) Ackermann value for m = 2 and n = 2 is -> 7Ackermann value for m = 5 and n = 7 is -> 6141004759 Time complexity: O( M * N )Auxiliary Space complexity: O( M * N ) kapoorsagar226 Dynamic Programming Mathematical Recursion Dynamic Programming Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimal Substructure Property in Dynamic Programming | DP-2 Optimal Binary Search Tree | DP-24 Min Cost Path | DP-6 Greedy approach vs Dynamic programming Maximum Subarray Sum using Divide and Conquer algorithm Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 25941, "s": 25913, "text": "\n12 Nov, 2021" }, { "code": null, "e": 26077, "s": 25941, "text": "Given two non-zero integers M and N, the problem is to compute the result of the Ackermann function based on some particular equations." }, { "code": null, "e": 26111, "s": 26077, "text": "Ackermann function is defined as:" }, { "code": null, "e": 26121, "s": 26111, "text": "Examples:" }, { "code": null, "e": 26150, "s": 26121, "text": "Input: M = 2, N = 2Output: 7" }, { "code": null, "e": 26188, "s": 26150, "text": "Input: M = 2, N = 7Output: 6141004759" }, { "code": null, "e": 26382, "s": 26188, "text": "The approach for Ackermann function described in this article, takes a very huge amount of time to compute the value for even small values of (M, N) or in most cases doesn’t result in anything." }, { "code": null, "e": 26412, "s": 26382, "text": "Dynamic Programming approach:" }, { "code": null, "e": 26510, "s": 26412, "text": "Here are the following Ackermann equations that would be used to come up with efficient solution." }, { "code": null, "e": 26548, "s": 26510, "text": "A(m, n) = A(m-1, A(m, n-1)) —– (Eq 1)" }, { "code": null, "e": 26572, "s": 26548, "text": "A(0, n) = n+1 —– (Eq 2)" }, { "code": null, "e": 26602, "s": 26572, "text": "A(m, 0) = A(m-1, 1) —– (Eq 3)" }, { "code": null, "e": 26644, "s": 26602, "text": "Let’s assume the value of m = 2 and n = 2" }, { "code": null, "e": 26739, "s": 26644, "text": "A 2d DP table of size ( (m+1) x (n+1) ) is created for storing the result of each sub-problem." }, { "code": null, "e": 26798, "s": 26739, "text": "Following are the steps demonstrated to fill up the table." }, { "code": null, "e": 29006, "s": 26798, "text": "Empty Table – Initial StepFilled using A ( 0, n ) = n + 1The very next method is to fill all the base values, by taking the help of equation-2.In the next step the whole 1st row would be filled,A ( 1, 0 ) = A ( 0, 1 ) —– (refer Eq (3))Since A ( 0, 1 ) = 2Therefore, A ( 1, 0 ) = 2 —–(Eq 4)A ( 1, 1 ) = A ( 0, A ( 1, 0 ) ) —– refer Eq (1)= A ( 0, 2 ) —– refer Eq (4)= 3 —– refer Eq (2)So, A ( 1, 1 ) = 3 —–(Eq 5)A ( 1, 2 ) = A ( 0, A ( 1, 1 ) ) —– refer equation (1)= A ( 0, 3 ) —– refer equation (5)= 4 —– refer equation (2)So, A ( 1, 2 ) = 4 —–(Eq 6)Fill the table using equations and stored valuesLet’s just fill the first column of the last row i.e (2, 0) in the same manner as above, because for the other two columns there are some unsolved values.A ( 2, 0 ) = A ( 1, 1 ) —– refer equation (3)A ( 1, 1 ) = 3So, A ( 2, 0 ) = 3 —– (Eq. 7)Solving for A ( 2, 1 ) and A ( 2, 2 ).For simplicity the process for solving above functions is divided into two steps,In the first one, the problem is identified.A ( 2, 1 ) = A ( 1, A ( 2, 0 ) ) —– refer equation (1)A ( 2, 0 ) = 3A ( 2, 1 ) = A ( 1, 3 )So to compute this value, again use equation (1)A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4A ( 1, 3 ) = A ( 0, 4 ) —– refer equation(2)= 5Therefore A ( 2, 1 ) = A ( 1, 3 ) = 5 — (Eq 7)In the next one, methodology is described in detail and a generic formula is obtained to be logical while being used in programLet’s solve A ( 2, 2 ) , with a theory upfrontA ( 2, 2 ) = A ( 1, A ( 2, 1 ) ) —– refer equation (1)A ( 2, 1) = 5A ( 2, 2 ) = A ( 1, 5 )To compute A(1, 5) in a generic manner, observe how it reduces itself!A ( 1, 5 ) = A ( 0, A ( 1, 4 ) )A ( 1, 4 ) = A( 0, A ( 1, 3 ) )A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4Returning back from the function we get,A ( 1, 3 ) = A ( 0, 4 ) = 5 —– refer equation (2)A ( 1, 4 ) = A ( 0, A (1, 3 ) ) = A ( 0, 5 ) = 6 —–Since A ( 1, 3 ) = 5A ( 1, 5 ) = A ( 0, A ( 1, 4 ) ) = A ( 0, 6 ) = 7So, A ( 2, 2 ) = 7 ——- (Eq 9)Important Points:(n = column number, c: ( any number > n), r: row number]1 . A ( 1, c ) = A ( 1, n ) + ( c – n ) From the Above Observation2 . A ( r, c ) = A ( r, n ) + ( c – n )*r Based on hand tracingFinal Table with result of each sub-problem" }, { "code": null, "e": 29033, "s": 29006, "text": "Empty Table – Initial Step" }, { "code": null, "e": 29151, "s": 29033, "text": "Filled using A ( 0, n ) = n + 1The very next method is to fill all the base values, by taking the help of equation-2." }, { "code": null, "e": 29269, "s": 29151, "text": "Filled using A ( 0, n ) = n + 1The very next method is to fill all the base values, by taking the help of equation-2." }, { "code": null, "e": 29678, "s": 29269, "text": "In the next step the whole 1st row would be filled,A ( 1, 0 ) = A ( 0, 1 ) —– (refer Eq (3))Since A ( 0, 1 ) = 2Therefore, A ( 1, 0 ) = 2 —–(Eq 4)A ( 1, 1 ) = A ( 0, A ( 1, 0 ) ) —– refer Eq (1)= A ( 0, 2 ) —– refer Eq (4)= 3 —– refer Eq (2)So, A ( 1, 1 ) = 3 —–(Eq 5)A ( 1, 2 ) = A ( 0, A ( 1, 1 ) ) —– refer equation (1)= A ( 0, 3 ) —– refer equation (5)= 4 —– refer equation (2)So, A ( 1, 2 ) = 4 —–(Eq 6)" }, { "code": null, "e": 29730, "s": 29678, "text": "In the next step the whole 1st row would be filled," }, { "code": null, "e": 29826, "s": 29730, "text": "A ( 1, 0 ) = A ( 0, 1 ) —– (refer Eq (3))Since A ( 0, 1 ) = 2Therefore, A ( 1, 0 ) = 2 —–(Eq 4)" }, { "code": null, "e": 29922, "s": 29826, "text": "A ( 1, 0 ) = A ( 0, 1 ) —– (refer Eq (3))Since A ( 0, 1 ) = 2Therefore, A ( 1, 0 ) = 2 —–(Eq 4)" }, { "code": null, "e": 30045, "s": 29922, "text": "A ( 1, 1 ) = A ( 0, A ( 1, 0 ) ) —– refer Eq (1)= A ( 0, 2 ) —– refer Eq (4)= 3 —– refer Eq (2)So, A ( 1, 1 ) = 3 —–(Eq 5)" }, { "code": null, "e": 30168, "s": 30045, "text": "A ( 1, 1 ) = A ( 0, A ( 1, 0 ) ) —– refer Eq (1)= A ( 0, 2 ) —– refer Eq (4)= 3 —– refer Eq (2)So, A ( 1, 1 ) = 3 —–(Eq 5)" }, { "code": null, "e": 30309, "s": 30168, "text": "A ( 1, 2 ) = A ( 0, A ( 1, 1 ) ) —– refer equation (1)= A ( 0, 3 ) —– refer equation (5)= 4 —– refer equation (2)So, A ( 1, 2 ) = 4 —–(Eq 6)" }, { "code": null, "e": 30450, "s": 30309, "text": "A ( 1, 2 ) = A ( 0, A ( 1, 1 ) ) —– refer equation (1)= A ( 0, 3 ) —– refer equation (5)= 4 —– refer equation (2)So, A ( 1, 2 ) = 4 —–(Eq 6)" }, { "code": null, "e": 30741, "s": 30450, "text": "Fill the table using equations and stored valuesLet’s just fill the first column of the last row i.e (2, 0) in the same manner as above, because for the other two columns there are some unsolved values.A ( 2, 0 ) = A ( 1, 1 ) —– refer equation (3)A ( 1, 1 ) = 3So, A ( 2, 0 ) = 3 —– (Eq. 7)" }, { "code": null, "e": 30896, "s": 30741, "text": "Let’s just fill the first column of the last row i.e (2, 0) in the same manner as above, because for the other two columns there are some unsolved values." }, { "code": null, "e": 30985, "s": 30896, "text": "A ( 2, 0 ) = A ( 1, 1 ) —– refer equation (3)A ( 1, 1 ) = 3So, A ( 2, 0 ) = 3 —– (Eq. 7)" }, { "code": null, "e": 32309, "s": 30985, "text": "Solving for A ( 2, 1 ) and A ( 2, 2 ).For simplicity the process for solving above functions is divided into two steps,In the first one, the problem is identified.A ( 2, 1 ) = A ( 1, A ( 2, 0 ) ) —– refer equation (1)A ( 2, 0 ) = 3A ( 2, 1 ) = A ( 1, 3 )So to compute this value, again use equation (1)A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4A ( 1, 3 ) = A ( 0, 4 ) —– refer equation(2)= 5Therefore A ( 2, 1 ) = A ( 1, 3 ) = 5 — (Eq 7)In the next one, methodology is described in detail and a generic formula is obtained to be logical while being used in programLet’s solve A ( 2, 2 ) , with a theory upfrontA ( 2, 2 ) = A ( 1, A ( 2, 1 ) ) —– refer equation (1)A ( 2, 1) = 5A ( 2, 2 ) = A ( 1, 5 )To compute A(1, 5) in a generic manner, observe how it reduces itself!A ( 1, 5 ) = A ( 0, A ( 1, 4 ) )A ( 1, 4 ) = A( 0, A ( 1, 3 ) )A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4Returning back from the function we get,A ( 1, 3 ) = A ( 0, 4 ) = 5 —– refer equation (2)A ( 1, 4 ) = A ( 0, A (1, 3 ) ) = A ( 0, 5 ) = 6 —–Since A ( 1, 3 ) = 5A ( 1, 5 ) = A ( 0, A ( 1, 4 ) ) = A ( 0, 6 ) = 7So, A ( 2, 2 ) = 7 ——- (Eq 9)Important Points:(n = column number, c: ( any number > n), r: row number]1 . A ( 1, c ) = A ( 1, n ) + ( c – n ) From the Above Observation2 . A ( r, c ) = A ( r, n ) + ( c – n )*r Based on hand tracing" }, { "code": null, "e": 32348, "s": 32309, "text": "Solving for A ( 2, 1 ) and A ( 2, 2 )." }, { "code": null, "e": 32430, "s": 32348, "text": "For simplicity the process for solving above functions is divided into two steps," }, { "code": null, "e": 32753, "s": 32430, "text": "In the first one, the problem is identified.A ( 2, 1 ) = A ( 1, A ( 2, 0 ) ) —– refer equation (1)A ( 2, 0 ) = 3A ( 2, 1 ) = A ( 1, 3 )So to compute this value, again use equation (1)A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4A ( 1, 3 ) = A ( 0, 4 ) —– refer equation(2)= 5Therefore A ( 2, 1 ) = A ( 1, 3 ) = 5 — (Eq 7)" }, { "code": null, "e": 32845, "s": 32753, "text": "A ( 2, 1 ) = A ( 1, A ( 2, 0 ) ) —– refer equation (1)A ( 2, 0 ) = 3A ( 2, 1 ) = A ( 1, 3 )" }, { "code": null, "e": 32987, "s": 32845, "text": "So to compute this value, again use equation (1)A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4A ( 1, 3 ) = A ( 0, 4 ) —– refer equation(2)= 5" }, { "code": null, "e": 33034, "s": 32987, "text": "Therefore A ( 2, 1 ) = A ( 1, 3 ) = 5 — (Eq 7)" }, { "code": null, "e": 33715, "s": 33034, "text": "In the next one, methodology is described in detail and a generic formula is obtained to be logical while being used in programLet’s solve A ( 2, 2 ) , with a theory upfrontA ( 2, 2 ) = A ( 1, A ( 2, 1 ) ) —– refer equation (1)A ( 2, 1) = 5A ( 2, 2 ) = A ( 1, 5 )To compute A(1, 5) in a generic manner, observe how it reduces itself!A ( 1, 5 ) = A ( 0, A ( 1, 4 ) )A ( 1, 4 ) = A( 0, A ( 1, 3 ) )A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4Returning back from the function we get,A ( 1, 3 ) = A ( 0, 4 ) = 5 —– refer equation (2)A ( 1, 4 ) = A ( 0, A (1, 3 ) ) = A ( 0, 5 ) = 6 —–Since A ( 1, 3 ) = 5A ( 1, 5 ) = A ( 0, A ( 1, 4 ) ) = A ( 0, 6 ) = 7So, A ( 2, 2 ) = 7 ——- (Eq 9)" }, { "code": null, "e": 33762, "s": 33715, "text": "Let’s solve A ( 2, 2 ) , with a theory upfront" }, { "code": null, "e": 33853, "s": 33762, "text": "A ( 2, 2 ) = A ( 1, A ( 2, 1 ) ) —– refer equation (1)A ( 2, 1) = 5A ( 2, 2 ) = A ( 1, 5 )" }, { "code": null, "e": 33924, "s": 33853, "text": "To compute A(1, 5) in a generic manner, observe how it reduces itself!" }, { "code": null, "e": 34034, "s": 33924, "text": "A ( 1, 5 ) = A ( 0, A ( 1, 4 ) )A ( 1, 4 ) = A( 0, A ( 1, 3 ) )A ( 1, 3 ) = A ( 0, A ( 1, 2 ) )A ( 1, 2 ) = 4" }, { "code": null, "e": 34273, "s": 34034, "text": "Returning back from the function we get,A ( 1, 3 ) = A ( 0, 4 ) = 5 —– refer equation (2)A ( 1, 4 ) = A ( 0, A (1, 3 ) ) = A ( 0, 5 ) = 6 —–Since A ( 1, 3 ) = 5A ( 1, 5 ) = A ( 0, A ( 1, 4 ) ) = A ( 0, 6 ) = 7So, A ( 2, 2 ) = 7 ——- (Eq 9)" }, { "code": null, "e": 34291, "s": 34273, "text": "Important Points:" }, { "code": null, "e": 34348, "s": 34291, "text": "(n = column number, c: ( any number > n), r: row number]" }, { "code": null, "e": 34415, "s": 34348, "text": "1 . A ( 1, c ) = A ( 1, n ) + ( c – n ) From the Above Observation" }, { "code": null, "e": 34479, "s": 34415, "text": "2 . A ( r, c ) = A ( r, n ) + ( c – n )*r Based on hand tracing" }, { "code": null, "e": 34523, "s": 34479, "text": "Final Table with result of each sub-problem" }, { "code": null, "e": 34574, "s": 34523, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 34582, "s": 34574, "text": "Python3" }, { "code": "# Python code for the above approach # Bottom Up Approachdef Ackermann(m, n): # creating 2D LIST cache = [[0 for i in range(n + 1)] for j in range(m + 1)] for rows in range(m + 1): for cols in range(n + 1): # base case A ( 0, n ) = n + 1 if rows == 0: cache[rows][cols] = cols + 1 # base case A ( m, 0 ) = # A ( m-1, 1) [Computed already] elif cols == 0: cache[rows][cols] = cache[rows-1][1] else: # if rows and cols > 0 # then applying A ( m, n ) = # A ( m-1, A ( m, n-1 ) ) r = rows - 1 c = cache[rows][cols-1] # applying equation (2) # here A ( 0, n ) = n + 1 if r == 0: ans = c + 1 elif c <= n: # using stored value in cache ans = cache[rows-1][cache[rows][cols-1]] else: # Using the Derived Formula # to compute mystery values in O(1) time ans = (c-n)*(r) + cache[r][n] cache[rows][cols] = ans return cache[m][n] # very small valuesm = 2 n = 2 # a bit higher valuem1 = 5 n1 = 7 print(\"Ackermann value for m = \", m, \" and n = \", n, \"is -> \", Ackermann(m, n)) print(\"Ackermann value for m = \", m1, \" and n = \", n1, \"is -> \", Ackermann(m1, n1))", "e": 36085, "s": 34582, "text": null }, { "code": null, "e": 36181, "s": 36085, "text": "Ackermann value for m = 2 and n = 2 is -> 7Ackermann value for m = 5 and n = 7 is -> 6141004759" }, { "code": null, "e": 36247, "s": 36181, "text": "Time complexity: O( M * N )Auxiliary Space complexity: O( M * N )" }, { "code": null, "e": 36262, "s": 36247, "text": "kapoorsagar226" }, { "code": null, "e": 36282, "s": 36262, "text": "Dynamic Programming" }, { "code": null, "e": 36295, "s": 36282, "text": "Mathematical" }, { "code": null, "e": 36305, "s": 36295, "text": "Recursion" }, { "code": null, "e": 36325, "s": 36305, "text": "Dynamic Programming" }, { "code": null, "e": 36338, "s": 36325, "text": "Mathematical" }, { "code": null, "e": 36348, "s": 36338, "text": "Recursion" }, { "code": null, "e": 36446, "s": 36348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36506, "s": 36446, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 36541, "s": 36506, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 36562, "s": 36541, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 36601, "s": 36562, "text": "Greedy approach vs Dynamic programming" }, { "code": null, "e": 36657, "s": 36601, "text": "Maximum Subarray Sum using Divide and Conquer algorithm" }, { "code": null, "e": 36717, "s": 36657, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 36732, "s": 36717, "text": "C++ Data Types" }, { "code": null, "e": 36775, "s": 36732, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 36799, "s": 36775, "text": "Merge two sorted arrays" } ]
Python | Minimum element in tuple list - GeeksforGeeks
11 Nov, 2019 Sometimes, while working with data in form of records, we can have a problem in which we need to find the minimum element of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using min() + generator expression This is the most basic method to achieve solution to this task. In this, we iterate over whole nested lists using generator expression and get the minimum element using min(). # Python3 code to demonstrate working of# Minimum element in tuple list# using min() + generator expression # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] # printing original list print("The original list : " + str(test_list)) # Minimum element in tuple list# using min() + generator expressionres = min(int(j) for i in test_list for j in i) # printing resultprint("The Minimum element of list is : " + str(res)) The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] The Minimum element of list is : 1 Method #2 : Using min() + map() + chain.from_iterable() The combination of above methods can also be used to perform this task. In this, the extension of finding minimum is done by combination of map() and from_iterable(). # Python3 code to demonstrate working of# Minimum element in tuple list# using min() + map() + chain.from_iterable()from itertools import chain # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] # printing original list print("The original list : " + str(test_list)) # Minimum element in tuple list# using min() + map() + chain.from_iterable()res = min(map(int, chain.from_iterable(test_list))) # printing resultprint("The Minimum element of list is : " + str(res)) The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] The Minimum element of list is : 1 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25963, "s": 25935, "text": "\n11 Nov, 2019" }, { "code": null, "e": 26251, "s": 25963, "text": "Sometimes, while working with data in form of records, we can have a problem in which we need to find the minimum element of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26298, "s": 26251, "text": "Method #1 : Using min() + generator expression" }, { "code": null, "e": 26474, "s": 26298, "text": "This is the most basic method to achieve solution to this task. In this, we iterate over whole nested lists using generator expression and get the minimum element using min()." }, { "code": "# Python3 code to demonstrate working of# Minimum element in tuple list# using min() + generator expression # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] # printing original list print(\"The original list : \" + str(test_list)) # Minimum element in tuple list# using min() + generator expressionres = min(int(j) for i in test_list for j in i) # printing resultprint(\"The Minimum element of list is : \" + str(res))", "e": 26916, "s": 26474, "text": null }, { "code": null, "e": 27014, "s": 26916, "text": "The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]\nThe Minimum element of list is : 1\n" }, { "code": null, "e": 27072, "s": 27016, "text": "Method #2 : Using min() + map() + chain.from_iterable()" }, { "code": null, "e": 27239, "s": 27072, "text": "The combination of above methods can also be used to perform this task. In this, the extension of finding minimum is done by combination of map() and from_iterable()." }, { "code": "# Python3 code to demonstrate working of# Minimum element in tuple list# using min() + map() + chain.from_iterable()from itertools import chain # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)] # printing original list print(\"The original list : \" + str(test_list)) # Minimum element in tuple list# using min() + map() + chain.from_iterable()res = min(map(int, chain.from_iterable(test_list))) # printing resultprint(\"The Minimum element of list is : \" + str(res))", "e": 27730, "s": 27239, "text": null }, { "code": null, "e": 27828, "s": 27730, "text": "The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]\nThe Minimum element of list is : 1\n" }, { "code": null, "e": 27849, "s": 27828, "text": "Python list-programs" }, { "code": null, "e": 27856, "s": 27849, "text": "Python" }, { "code": null, "e": 27872, "s": 27856, "text": "Python Programs" }, { "code": null, "e": 27970, "s": 27872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27988, "s": 27970, "text": "Python Dictionary" }, { "code": null, "e": 28023, "s": 27988, "text": "Read a file line by line in Python" }, { "code": null, "e": 28055, "s": 28023, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28097, "s": 28055, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28123, "s": 28097, "text": "Python String | replace()" }, { "code": null, "e": 28166, "s": 28123, "text": "Python program to convert a list to string" }, { "code": null, "e": 28188, "s": 28166, "text": "Defaultdict in Python" }, { "code": null, "e": 28227, "s": 28188, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28273, "s": 28227, "text": "Python | Split string into list of characters" } ]
SaltStack - Python API
Salt provides programmatic access to all of its commands. Salt provides different modules for every section of the Salt system. Let us learn the basics of the python API and about how to run the basic salt commands in this chapter. The salt.config module is used to access Salt configuration details. import salt.config opts = salt.config.client_config('/etc/salt/master') Here, the client_config reads the salt configuration file and returns the configuration details as dictionary. The salt.loader module is used to load each modules in Salt such as grains, minions, etc. import salt.loader opts = salt.config.minion_config('/etc/salt/minion') grains = salt.loader.grains(opts) Here, grains reads the details of the grains in the Salt system and returns it. The salt.client module is used to execute salt, salt-call and the salt-SSH commands programmatically. The most important python classes are as follows − salt.client.LocalClient salt.client.Caller salt.client.ssh.client.SSHClient The main function provided by most of the client module is cmd. This function wraps the CLI options and executes it, which is similar to the command line and returns the results as python data structures. The LocalClient is used to send commands from the master to the salt minions and return the results to the master. import salt.client local = salt.client.LocalClient() local.cmd('*', 'test.ping') It will produce the following output − {'minion1': True, 'minion2': True } The Caller is used to run salt-call programmatically and return the results. import salt.client caller = salt.client.Caller() caller.cmd('test.ping') It will produce the following output − True The SSHCient is used to run the salt-ssh programmatically and return the results. import salt.client.ssh.client ssh = salt.client.ssh.client.SSHClient() ssh.cmd('*', 'test.ping') It will produce the following output − {'minion1': True, 'minion2': True } The salt.cloud module is used to execute the salt-cloud commands programmatically. client = salt.cloud.CloudClient(path = '/etc/salt/cloud') Cloud module provides functions to create VMs (create), to destroy VMs (destroy), list images provided by a cloud provider (list_images), list locations of a cloud provider (list_locations), list machine sizes of a cloud provider (list_sizes), etc. Print Add Notes Bookmark this page
[ { "code": null, "e": 2439, "s": 2207, "text": "Salt provides programmatic access to all of its commands. Salt provides different modules for every section of the Salt system. Let us learn the basics of the python API and about how to run the basic salt commands in this chapter." }, { "code": null, "e": 2508, "s": 2439, "text": "The salt.config module is used to access Salt configuration details." }, { "code": null, "e": 2581, "s": 2508, "text": "import salt.config\nopts = salt.config.client_config('/etc/salt/master')\n" }, { "code": null, "e": 2692, "s": 2581, "text": "Here, the client_config reads the salt configuration file and returns the configuration details as dictionary." }, { "code": null, "e": 2782, "s": 2692, "text": "The salt.loader module is used to load each modules in Salt such as grains, minions, etc." }, { "code": null, "e": 2889, "s": 2782, "text": "import salt.loader\nopts = salt.config.minion_config('/etc/salt/minion')\ngrains = salt.loader.grains(opts)\n" }, { "code": null, "e": 2969, "s": 2889, "text": "Here, grains reads the details of the grains in the Salt system and returns it." }, { "code": null, "e": 3071, "s": 2969, "text": "The salt.client module is used to execute salt, salt-call and the salt-SSH commands programmatically." }, { "code": null, "e": 3122, "s": 3071, "text": "The most important python classes are as follows −" }, { "code": null, "e": 3146, "s": 3122, "text": "salt.client.LocalClient" }, { "code": null, "e": 3165, "s": 3146, "text": "salt.client.Caller" }, { "code": null, "e": 3198, "s": 3165, "text": "salt.client.ssh.client.SSHClient" }, { "code": null, "e": 3403, "s": 3198, "text": "The main function provided by most of the client module is cmd. This function wraps the CLI options and executes it, which is similar to the command line and returns the results as python data structures." }, { "code": null, "e": 3518, "s": 3403, "text": "The LocalClient is used to send commands from the master to the salt minions and return the results to the master." }, { "code": null, "e": 3600, "s": 3518, "text": "import salt.client\n\nlocal = salt.client.LocalClient()\nlocal.cmd('*', 'test.ping')" }, { "code": null, "e": 3639, "s": 3600, "text": "It will produce the following output −" }, { "code": null, "e": 3676, "s": 3639, "text": "{'minion1': True, 'minion2': True }\n" }, { "code": null, "e": 3753, "s": 3676, "text": "The Caller is used to run salt-call programmatically and return the results." }, { "code": null, "e": 3826, "s": 3753, "text": "import salt.client\ncaller = salt.client.Caller()\ncaller.cmd('test.ping')" }, { "code": null, "e": 3865, "s": 3826, "text": "It will produce the following output −" }, { "code": null, "e": 3871, "s": 3865, "text": "True\n" }, { "code": null, "e": 3953, "s": 3871, "text": "The SSHCient is used to run the salt-ssh programmatically and return the results." }, { "code": null, "e": 4051, "s": 3953, "text": "import salt.client.ssh.client\nssh = salt.client.ssh.client.SSHClient()\nssh.cmd('*', 'test.ping')\n" }, { "code": null, "e": 4090, "s": 4051, "text": "It will produce the following output −" }, { "code": null, "e": 4127, "s": 4090, "text": "{'minion1': True, 'minion2': True }\n" }, { "code": null, "e": 4210, "s": 4127, "text": "The salt.cloud module is used to execute the salt-cloud commands programmatically." }, { "code": null, "e": 4269, "s": 4210, "text": "client = salt.cloud.CloudClient(path = '/etc/salt/cloud')\n" }, { "code": null, "e": 4518, "s": 4269, "text": "Cloud module provides functions to create VMs (create), to destroy VMs (destroy), list images provided by a cloud provider (list_images), list locations of a cloud provider (list_locations), list machine sizes of a cloud provider (list_sizes), etc." }, { "code": null, "e": 4525, "s": 4518, "text": " Print" }, { "code": null, "e": 4536, "s": 4525, "text": " Add Notes" } ]
Bulma - Image
This chapter covers the Bulma support for images. The Bulma uses .image class to display the images in the page. Bulma provides 7 types of dimensions to display the images − is-16x16 is-16x16 is-24x24 is-24x24 is-32x32 is-32x32 is-48x48 is-48x48 is-64x64 is-64x64 is-96x96 is-96x96 is-128x128 is-128x128 Bulma provides .is-rounded class to make the rounded images. The below example describes usage of above 7 dimensions and displaying of rounded image − <!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <title>Bulma Elements Example</title> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css"> <link href = "https://unpkg.com/[email protected]/dist/css/ionicons.min.css" rel = "stylesheet"> <script src = "https://use.fontawesome.com/releases/v5.1.0/js/all.js"></script> <script src = "https://unpkg.com/[email protected]/dist/ionicons.js"></script> <link rel = "stylesheet" href = "https://cdn.materialdesignicons.com/2.1.19/css/materialdesignicons.min.css"> </head> <body> <section class = "section"> <div class = "container"> <span class = "is-size-5"> Fixed Square Images </span> <br> <br> <figure class = "image is-16x16"> <img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"> </figure> <span class = "is-size-6"> 16x16 </span> <br> <br> <figure class = "image is-24x24"> <img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"> </figure> <span class = "is-size-6"> 24x24 </span> <br> <br> <figure class = "image is-32x32"> <img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"> </figure> <span class = "is-size-6"> 32x32 </span> <br> <br> <figure class = "image is-48x48"> <img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"> </figure> <span class = "is-size-6"> 48x48 </span> <br> <br> <figure class = "image is-64x64"> <img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"> </figure> <span class = "is-size-6"> 64x64 </span> <br> <br> <figure class = "image is-96x96"> <img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"> </figure> <span class = "is-size-6"> 96x96 </span> <br> <br> <figure class = "image is-128x128"> <img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"> </figure> <span class = "is-size-6"> 128x128 </span> <br> <br> <span class = "is-size-5"> Rounded Image </span> <br> <br> <figure class = "image is-128x128"> <img class = "is-rounded" src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"> </figure> </div> </section> </body> </html> Execute the above code and it will display the below output − Bulma provides below 16 ratio modifiers for the images. is-square is-square is-1by1 is-1by1 is-5by4 is-5by4 is-4by3 is-4by3 is-3by2 is-3by2 is-5by3 is-5by3 is-16by9 is-16by9 is-2by1 is-2by1 is-3by1 is-3by1 is-4by5 is-4by5 is-3by4 is-3by4 is-2by3 is-2by3 is-3by5 is-3by5 is-9by16 is-9by16 is-1by2 is-1by2 is-1by3 is-1by3 The below example specifies displaying of an image with ratio modifier (here, we are using is-2by1 ratio modifier in the figure tag) − <!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <title>Bulma Elements Example</title> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css"> <link href = "https://unpkg.com/[email protected]/dist/css/ionicons.min.css" rel = "stylesheet"> <script src = "https://use.fontawesome.com/releases/v5.1.0/js/all.js"></script> <script src = "https://unpkg.com/[email protected]/dist/ionicons.js"></script> <link rel = "stylesheet" href = "https://cdn.materialdesignicons.com/2.1.19/css/materialdesignicons.min.css"> </head> <body> <section class = "section"> <div class = "container"> <span class = "is-size-5"> Images with Ratio </span> <br> <br> <figure class = "image is-2by1"> <img src = "https://www.tutorialspoint.com/bootstrap/images/64.jpg"> </figure> </div> </section> </body> </html> It displays the below output − To make use of remaining ratio modifiers, replace the above modifier with your ratio modifier in the figure tag. Print Add Notes Bookmark this page
[ { "code": null, "e": 1811, "s": 1698, "text": "This chapter covers the Bulma support for images. The Bulma uses .image class to display the images in the page." }, { "code": null, "e": 1872, "s": 1811, "text": "Bulma provides 7 types of dimensions to display the images −" }, { "code": null, "e": 1881, "s": 1872, "text": "is-16x16" }, { "code": null, "e": 1890, "s": 1881, "text": "is-16x16" }, { "code": null, "e": 1899, "s": 1890, "text": "is-24x24" }, { "code": null, "e": 1908, "s": 1899, "text": "is-24x24" }, { "code": null, "e": 1917, "s": 1908, "text": "is-32x32" }, { "code": null, "e": 1926, "s": 1917, "text": "is-32x32" }, { "code": null, "e": 1935, "s": 1926, "text": "is-48x48" }, { "code": null, "e": 1944, "s": 1935, "text": "is-48x48" }, { "code": null, "e": 1953, "s": 1944, "text": "is-64x64" }, { "code": null, "e": 1962, "s": 1953, "text": "is-64x64" }, { "code": null, "e": 1971, "s": 1962, "text": "is-96x96" }, { "code": null, "e": 1980, "s": 1971, "text": "is-96x96" }, { "code": null, "e": 1991, "s": 1980, "text": "is-128x128" }, { "code": null, "e": 2002, "s": 1991, "text": "is-128x128" }, { "code": null, "e": 2063, "s": 2002, "text": "Bulma provides .is-rounded class to make the rounded images." }, { "code": null, "e": 2153, "s": 2063, "text": "The below example describes usage of above 7 dimensions and displaying of rounded image −" }, { "code": null, "e": 5503, "s": 2153, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <title>Bulma Elements Example</title>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css\">\n <link href = \"https://unpkg.com/[email protected]/dist/css/ionicons.min.css\" rel = \"stylesheet\">\n <script src = \"https://use.fontawesome.com/releases/v5.1.0/js/all.js\"></script>\n <script src = \"https://unpkg.com/[email protected]/dist/ionicons.js\"></script>\n <link rel = \"stylesheet\" href = \"https://cdn.materialdesignicons.com/2.1.19/css/materialdesignicons.min.css\">\n </head>\n \n <body>\n <section class = \"section\">\n <div class = \"container\">\n <span class = \"is-size-5\">\n Fixed Square Images\n </span>\n <br>\n <br>\n \n <figure class = \"image is-16x16\">\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\">\n </figure>\n \n <span class = \"is-size-6\">\n 16x16\n </span>\n <br>\n <br>\n \n <figure class = \"image is-24x24\">\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\">\n </figure>\n \n <span class = \"is-size-6\">\n 24x24\n </span>\n <br>\n <br>\n \n <figure class = \"image is-32x32\">\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\">\n </figure>\n \n <span class = \"is-size-6\">\n 32x32\n </span>\n <br>\n <br>\n \n <figure class = \"image is-48x48\">\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\">\n </figure>\n \n <span class = \"is-size-6\">\n 48x48\n </span>\n <br>\n <br>\n \n <figure class = \"image is-64x64\">\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\">\n </figure>\n \n <span class = \"is-size-6\">\n 64x64\n </span>\n <br>\n <br>\n \n <figure class = \"image is-96x96\">\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\">\n </figure>\n \n <span class = \"is-size-6\">\n 96x96\n </span>\n <br>\n <br>\n \n <figure class = \"image is-128x128\">\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\">\n </figure>\n \n <span class = \"is-size-6\">\n 128x128\n </span>\n <br>\n <br>\n \n <span class = \"is-size-5\">\n Rounded Image\n </span>\n <br>\n <br>\n \n <figure class = \"image is-128x128\">\n <img class = \"is-rounded\" src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\">\n </figure>\n \n </div>\n </section>\n \n </body>\n</html>" }, { "code": null, "e": 5565, "s": 5503, "text": "Execute the above code and it will display the below output −" }, { "code": null, "e": 5621, "s": 5565, "text": "Bulma provides below 16 ratio modifiers for the images." }, { "code": null, "e": 5631, "s": 5621, "text": "is-square" }, { "code": null, "e": 5641, "s": 5631, "text": "is-square" }, { "code": null, "e": 5649, "s": 5641, "text": "is-1by1" }, { "code": null, "e": 5657, "s": 5649, "text": "is-1by1" }, { "code": null, "e": 5665, "s": 5657, "text": "is-5by4" }, { "code": null, "e": 5673, "s": 5665, "text": "is-5by4" }, { "code": null, "e": 5681, "s": 5673, "text": "is-4by3" }, { "code": null, "e": 5689, "s": 5681, "text": "is-4by3" }, { "code": null, "e": 5697, "s": 5689, "text": "is-3by2" }, { "code": null, "e": 5705, "s": 5697, "text": "is-3by2" }, { "code": null, "e": 5713, "s": 5705, "text": "is-5by3" }, { "code": null, "e": 5721, "s": 5713, "text": "is-5by3" }, { "code": null, "e": 5730, "s": 5721, "text": "is-16by9" }, { "code": null, "e": 5739, "s": 5730, "text": "is-16by9" }, { "code": null, "e": 5747, "s": 5739, "text": "is-2by1" }, { "code": null, "e": 5755, "s": 5747, "text": "is-2by1" }, { "code": null, "e": 5763, "s": 5755, "text": "is-3by1" }, { "code": null, "e": 5771, "s": 5763, "text": "is-3by1" }, { "code": null, "e": 5779, "s": 5771, "text": "is-4by5" }, { "code": null, "e": 5787, "s": 5779, "text": "is-4by5" }, { "code": null, "e": 5795, "s": 5787, "text": "is-3by4" }, { "code": null, "e": 5803, "s": 5795, "text": "is-3by4" }, { "code": null, "e": 5811, "s": 5803, "text": "is-2by3" }, { "code": null, "e": 5819, "s": 5811, "text": "is-2by3" }, { "code": null, "e": 5827, "s": 5819, "text": "is-3by5" }, { "code": null, "e": 5835, "s": 5827, "text": "is-3by5" }, { "code": null, "e": 5844, "s": 5835, "text": "is-9by16" }, { "code": null, "e": 5853, "s": 5844, "text": "is-9by16" }, { "code": null, "e": 5861, "s": 5853, "text": "is-1by2" }, { "code": null, "e": 5869, "s": 5861, "text": "is-1by2" }, { "code": null, "e": 5877, "s": 5869, "text": "is-1by3" }, { "code": null, "e": 5885, "s": 5877, "text": "is-1by3" }, { "code": null, "e": 6020, "s": 5885, "text": "The below example specifies displaying of an image with ratio modifier (here, we are using is-2by1 ratio modifier in the figure tag) −" }, { "code": null, "e": 7149, "s": 6020, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <title>Bulma Elements Example</title>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css\">\n <link href = \"https://unpkg.com/[email protected]/dist/css/ionicons.min.css\" rel = \"stylesheet\">\n <script src = \"https://use.fontawesome.com/releases/v5.1.0/js/all.js\"></script>\n <script src = \"https://unpkg.com/[email protected]/dist/ionicons.js\"></script>\n <link rel = \"stylesheet\" href = \"https://cdn.materialdesignicons.com/2.1.19/css/materialdesignicons.min.css\">\n </head>\n \n <body>\n <section class = \"section\">\n <div class = \"container\">\n <span class = \"is-size-5\">\n Images with Ratio\n </span>\n <br>\n <br>\n \n <figure class = \"image is-2by1\">\n <img src = \"https://www.tutorialspoint.com/bootstrap/images/64.jpg\">\n </figure> \n </div>\n </section>\n </body>\n \n</html>" }, { "code": null, "e": 7180, "s": 7149, "text": "It displays the below output −" }, { "code": null, "e": 7293, "s": 7180, "text": "To make use of remaining ratio modifiers, replace the above modifier with your ratio modifier in the figure tag." }, { "code": null, "e": 7300, "s": 7293, "text": " Print" }, { "code": null, "e": 7311, "s": 7300, "text": " Add Notes" } ]
Check whether a Stack is empty or not in Java
The method java.util.Stack.empty() is used to check if a stack is empty or not. This method requires no parameters. It returns true if the stack is empty and false if the stack is not empty. A program that demonstrates this is given as follows − Live Demo import java.util.Stack; public class Demo { public static void main (String args[]) { Stack stack = new Stack(); stack.push("Amy"); stack.push("John"); stack.push("Mary"); System.out.println("The stack elements are: " + stack); System.out.println("The stack is empty? " + stack.empty()); System.out.println("\nThe element that was popped is: " + stack.pop()); System.out.println("The element that was popped is: " + stack.pop()); System.out.println("The element that was popped is: " + stack.pop()); System.out.println("\nThe stack elements are: " + stack); System.out.println("The stack is empty? " + stack.empty()); } } The stack elements are: [Amy, John, Mary] The stack is empty? false The element that was popped is: Mary The element that was popped is: John The element that was popped is: Amy The stack elements are: [] The stack is empty? true Now let us understand the above program. The Stack is created. Then Stack.push() method is used to add the elements to the stack. The stack is displayed and then the Stack.empty() method is used to check if a stack is empty or not. A code snippet which demonstrates this is as follows − Stack stack = new Stack(); stack.push("Amy"); stack.push("John"); stack.push("Mary"); System.out.println("The stack elements are: " + stack); System.out.println("The stack is empty? " + stack.empty()); The Stack.pop() method is used to pop the three stack elements. The stack is displayed and then the Stack.empty() method is used to check if a stack is empty or not. A code snippet which demonstrates this is as follows − System.out.println("\nThe element that was popped is: " + stack.pop()); System.out.println("The element that was popped is: " + stack.pop()); System.out.println("The element that was popped is: " + stack.pop()); System.out.println("\nThe stack elements are: " + stack); System.out.println("The stack is empty? " + stack.empty());
[ { "code": null, "e": 1253, "s": 1062, "text": "The method java.util.Stack.empty() is used to check if a stack is empty or not. This method requires no parameters. It returns true if the stack is empty and false if the stack is not empty." }, { "code": null, "e": 1308, "s": 1253, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1319, "s": 1308, "text": " Live Demo" }, { "code": null, "e": 2013, "s": 1319, "text": "import java.util.Stack;\npublic class Demo {\n public static void main (String args[]) {\n Stack stack = new Stack();\n stack.push(\"Amy\");\n stack.push(\"John\");\n stack.push(\"Mary\");\n System.out.println(\"The stack elements are: \" + stack);\n System.out.println(\"The stack is empty? \" + stack.empty());\n System.out.println(\"\\nThe element that was popped is: \" + stack.pop());\n System.out.println(\"The element that was popped is: \" + stack.pop());\n System.out.println(\"The element that was popped is: \" + stack.pop());\n System.out.println(\"\\nThe stack elements are: \" + stack);\n System.out.println(\"The stack is empty? \" + stack.empty());\n }\n}" }, { "code": null, "e": 2243, "s": 2013, "text": "The stack elements are: [Amy, John, Mary]\nThe stack is empty? false\nThe element that was popped is: Mary\nThe element that was popped is: John\nThe element that was popped is: Amy\nThe stack elements are: []\nThe stack is empty? true" }, { "code": null, "e": 2284, "s": 2243, "text": "Now let us understand the above program." }, { "code": null, "e": 2530, "s": 2284, "text": "The Stack is created. Then Stack.push() method is used to add the elements to the stack. The stack is displayed and then the Stack.empty() method is used to check if a stack is empty or not. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2732, "s": 2530, "text": "Stack stack = new Stack();\nstack.push(\"Amy\");\nstack.push(\"John\");\nstack.push(\"Mary\");\nSystem.out.println(\"The stack elements are: \" + stack);\nSystem.out.println(\"The stack is empty? \" + stack.empty());" }, { "code": null, "e": 2953, "s": 2732, "text": "The Stack.pop() method is used to pop the three stack elements. The stack is displayed and then the Stack.empty() method is used to check if a stack is empty or not. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 3283, "s": 2953, "text": "System.out.println(\"\\nThe element that was popped is: \" + stack.pop());\nSystem.out.println(\"The element that was popped is: \" + stack.pop());\nSystem.out.println(\"The element that was popped is: \" + stack.pop());\nSystem.out.println(\"\\nThe stack elements are: \" + stack);\nSystem.out.println(\"The stack is empty? \" + stack.empty());" } ]
Create a Boolean object from Boolean value in Java
To create a Boolean object from Boolean value is quite easy. Create an object with Boolean and set the Boolean value “true” or “false”, which are the Boolean literals. Let us now see how “true” value is added. Boolean bool = new Boolean("true"); In the same way, “False” value is added. Boolean bool = new Boolean("false"); The following is an example displaying how to create a Boolean object from Boolean value. Live Demo public class Demo { public static void main(String[] args) { Boolean bool = new Boolean("true"); System.out.println(bool); bool = new Boolean("false"); System.out.println(bool); } } True False
[ { "code": null, "e": 1230, "s": 1062, "text": "To create a Boolean object from Boolean value is quite easy. Create an object with Boolean and set the Boolean value “true” or “false”, which are the Boolean literals." }, { "code": null, "e": 1272, "s": 1230, "text": "Let us now see how “true” value is added." }, { "code": null, "e": 1308, "s": 1272, "text": "Boolean bool = new Boolean(\"true\");" }, { "code": null, "e": 1349, "s": 1308, "text": "In the same way, “False” value is added." }, { "code": null, "e": 1386, "s": 1349, "text": "Boolean bool = new Boolean(\"false\");" }, { "code": null, "e": 1476, "s": 1386, "text": "The following is an example displaying how to create a Boolean object from Boolean value." }, { "code": null, "e": 1487, "s": 1476, "text": " Live Demo" }, { "code": null, "e": 1699, "s": 1487, "text": "public class Demo {\n public static void main(String[] args) {\n Boolean bool = new Boolean(\"true\");\n System.out.println(bool);\n bool = new Boolean(\"false\");\n System.out.println(bool);\n }\n}" }, { "code": null, "e": 1710, "s": 1699, "text": "True\nFalse" } ]
Building a react boilerplate from scratch without using create-react-app - GeeksforGeeks
24 Sep, 2021 In this article, we are going to build a basic boilerplate for a React project from scratch without using the create-react-app or any other predefined boilerplate. This is a great experience for any react developer to look into what is happening behind the scenes. The file structure for our project will be looking like the following. You will understand how this project structure is created while going through the below steps. Below is the step-by-step procedure that we will be going to follow. Step 1: Create an empty new directory and name it according to your choice. Open up the terminal inside that directory and initialize the package.json file by writing the following command: npm init -y Here, -y is a flag that creates a new package.json file with default configurations. You can change these default configurations anytime in the package.json file. Package.json contains all dependencies and devDependencies. A package.json file is created with default configurations Also, initialize git in your project if you want. Run the following command on the terminal: git init Add a .gitignore file in the root directory and add node_modules in it because node_modules contains all dependency folders and files so the folder becomes too big. Hence, it is not recommended to add it in git. Step 2: Make two directories named “public” and “src” inside the root directory ( “/”). “public” folder contains all static assets like images, svgs, etc. and an index.html file where the react will render our app while “src” folder contains the whole source code. Inside the public folder, make a file named index.html. Filename: index.html HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Basic Boilerplate of React</title></head><body> <!-- This is the div where React will render our app --> <div id="root"></div> <noscript> Please enable javascript to view this site. </noscript> <script src="../dist/bundle.js"></script></body></html> Step 3: We will write our code in modern ES6 syntax but many browsers do not support it. So, we install Babel that performs the following things: Converts new ES6 syntaxes into browser compatible syntaxes so that old versions of browsers can also support our code.Converts JSX (JavaScript XML) into vanilla javascript. Converts new ES6 syntaxes into browser compatible syntaxes so that old versions of browsers can also support our code. Converts JSX (JavaScript XML) into vanilla javascript. To install Babel, run the following command on the terminal: npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/preset-react Here, –save-dev means save all above installed modules in devDependencies in package.json file, @babel/core is a module that contains the main functionality of Babel, @babel/cli is a module that allows us to use babel from the terminal, @babel/preset-env is preset that handles the transformation of ES6 syntax into common javascript, @babel/preset-react is preset which deals with JSX and converts it into vanilla javascript. Now, create a file “.babelrc” in the root directory. This file will tell babel transpiler what presets and plugins to use to transpile the code. Add the following JSON code: { "presets": ["@babel/preset-env","@babel/preset-react"] } Step 4: Install React and React DOM by running the following command on the terminal: npm i react react-dom present inside package.json file. Step 5: Now, create three files inside “src” directory named as ‘App.js’, ‘index.js’, ‘App.css’. These files contain the actual code. App.js: A component of React. Javascript import React from "react";import "./App.css";const App = () => { return ( <div> <h1 className="heading">GeeksForGeeks</h1> <h4 className="sub-heading"> A computer science portal for geeks </h4> </div> );}; export default App; App.css: Provides stylings for App component. CSS /* stylings for App component */.heading,.sub-heading{ color:green; text-align: center;} index.js: Renders the components on the browser. Javascript import React from "react";import ReactDOM from "react-dom";import App from "./App";ReactDOM.render(<App/>,document.getElementById("root")); Note: You can make as many components as you want in your react project inside the src folder. Step 6: Install the webpack. The webpack is a static module bundler. It works well with babel. It creates a local development server for our project. The webpack collects all the modules (either custom that we created or installed through NPM ) and bundles them up together in a single file or more files (static assets). To install webpack, run the following command on the terminal: npm install --save-dev webpack webpack-cli webpack-dev-server Here, –save-dev is the same as discussed above, webpack is a modular bundler, webpack-cli allows us to use webpack from the terminal by running a set of commands, webpack-dev-server provides a development server with live reloading i.e. you do not need to refresh the page manually. The webpack takes code from the src directory and perform required operations like bundling of code, conversion of ES6 syntax and JSX syntax into common javascript etc. and host the public directory so that we can view our app in the browser. Step 7: Webpack can understand JavaScript and JSON files only. So, to use webpack functionality in other files like .css, babel files, etc., we have to install some loaders in the project by writing the following command on the terminal: npm i --save-dev style-loader css-loader babel-loader Here, css-loader collects CSS from all the CSS files in the app and bundle it into one file, style-loader puts all stylings inside <style> tag in index.html file present in the public folder, babel-loader is a package that allows the transpiling of javascript files using babel and webpack. Step 8: Create a webpack.config.js file in the root directory that helps us to define what exactly the webpack should do with our source code. We will specify the entry point from where the webpack should start bundling, the output point that is where it should output the bundles and assets, plugins, etc. webpack.config.js Javascript const path = require("path"); module.exports = { // Entry point that indicates where // should the webpack starts bundling entry: "./src/index.js", mode: "development", module: { rules: [ { test: /\.(js|jsx)$/, // checks for .js or .jsx files exclude: /(node_modules)/, loader: "babel-loader", options: { presets: ["@babel/env"] }, }, { test: /\.css$/, //checks for .css files use: ["style-loader", "css-loader"], }, ], }, // Options for resolving module requests // extensions that are used resolve: { extensions: ["*", ".js", ".jsx"] }, // Output point is where webpack should // output the bundles and assets output: { path: path.resolve(__dirname, "dist/"), publicPath: "/dist/", filename: "bundle.js", },}; Step 9: Now, add some scripts in the package.json file to run and build the project. "scripts": { "start":"npx webpack-dev-server --mode development --open --hot", "build":"npx webpack --mode production", } Here, –open flag tells the webpack-dev-server to open the browser instantly after the server had been started. –hot flag enables webpack’s Hot Module Replacement feature. It only updates what’s changed in the code, so does not update the whole code, again and again, that’s why it saves precious development time. Step to run the application: Run the command following on the terminal to run the project in development mode. npm start Output: Run command “npm run build” to run the project in production mode. Note: When we are running our webpack server, there isn’t a dist folder. This is because what webpack server does is holds this dist folder in the memory and serves it, and deletes it when we stop the server. If you actually want to build the react app so that we can see that dist folder, run the command “npm run build”. Now, you can see the dist folder in the root directory. That’s all! We are equipped with our own react boilerplate and ready to make some amazing and cool projects. simranarora5sos Blogathon-2021 React-Questions Blogathon ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? How to Install Tkinter in Windows? SQL Query to Convert Datetime to Date How to pass data into table from a form using React Components SQL Query to Create Table With a Primary Key How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? Create a Responsive Navbar using ReactJS How to pass data from one component to other component in ReactJS ?
[ { "code": null, "e": 24850, "s": 24822, "text": "\n24 Sep, 2021" }, { "code": null, "e": 25115, "s": 24850, "text": "In this article, we are going to build a basic boilerplate for a React project from scratch without using the create-react-app or any other predefined boilerplate. This is a great experience for any react developer to look into what is happening behind the scenes." }, { "code": null, "e": 25281, "s": 25115, "text": "The file structure for our project will be looking like the following. You will understand how this project structure is created while going through the below steps." }, { "code": null, "e": 25350, "s": 25281, "text": "Below is the step-by-step procedure that we will be going to follow." }, { "code": null, "e": 25540, "s": 25350, "text": "Step 1: Create an empty new directory and name it according to your choice. Open up the terminal inside that directory and initialize the package.json file by writing the following command:" }, { "code": null, "e": 25552, "s": 25540, "text": "npm init -y" }, { "code": null, "e": 25775, "s": 25552, "text": "Here, -y is a flag that creates a new package.json file with default configurations. You can change these default configurations anytime in the package.json file. Package.json contains all dependencies and devDependencies." }, { "code": null, "e": 25834, "s": 25775, "text": "A package.json file is created with default configurations" }, { "code": null, "e": 25927, "s": 25834, "text": "Also, initialize git in your project if you want. Run the following command on the terminal:" }, { "code": null, "e": 25936, "s": 25927, "text": "git init" }, { "code": null, "e": 26148, "s": 25936, "text": "Add a .gitignore file in the root directory and add node_modules in it because node_modules contains all dependency folders and files so the folder becomes too big. Hence, it is not recommended to add it in git." }, { "code": null, "e": 26414, "s": 26148, "text": "Step 2: Make two directories named “public” and “src” inside the root directory ( “/”). “public” folder contains all static assets like images, svgs, etc. and an index.html file where the react will render our app while “src” folder contains the whole source code." }, { "code": null, "e": 26470, "s": 26414, "text": "Inside the public folder, make a file named index.html." }, { "code": null, "e": 26491, "s": 26470, "text": "Filename: index.html" }, { "code": null, "e": 26496, "s": 26491, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Basic Boilerplate of React</title></head><body> <!-- This is the div where React will render our app --> <div id=\"root\"></div> <noscript> Please enable javascript to view this site. </noscript> <script src=\"../dist/bundle.js\"></script></body></html>", "e": 26989, "s": 26496, "text": null }, { "code": null, "e": 27135, "s": 26989, "text": "Step 3: We will write our code in modern ES6 syntax but many browsers do not support it. So, we install Babel that performs the following things:" }, { "code": null, "e": 27308, "s": 27135, "text": "Converts new ES6 syntaxes into browser compatible syntaxes so that old versions of browsers can also support our code.Converts JSX (JavaScript XML) into vanilla javascript." }, { "code": null, "e": 27427, "s": 27308, "text": "Converts new ES6 syntaxes into browser compatible syntaxes so that old versions of browsers can also support our code." }, { "code": null, "e": 27482, "s": 27427, "text": "Converts JSX (JavaScript XML) into vanilla javascript." }, { "code": null, "e": 27543, "s": 27482, "text": "To install Babel, run the following command on the terminal:" }, { "code": null, "e": 27627, "s": 27543, "text": "npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/preset-react" }, { "code": null, "e": 27634, "s": 27627, "text": "Here, " }, { "code": null, "e": 27724, "s": 27634, "text": "–save-dev means save all above installed modules in devDependencies in package.json file," }, { "code": null, "e": 27795, "s": 27724, "text": "@babel/core is a module that contains the main functionality of Babel," }, { "code": null, "e": 27865, "s": 27795, "text": "@babel/cli is a module that allows us to use babel from the terminal," }, { "code": null, "e": 27963, "s": 27865, "text": "@babel/preset-env is preset that handles the transformation of ES6 syntax into common javascript," }, { "code": null, "e": 28055, "s": 27963, "text": "@babel/preset-react is preset which deals with JSX and converts it into vanilla javascript." }, { "code": null, "e": 28229, "s": 28055, "text": "Now, create a file “.babelrc” in the root directory. This file will tell babel transpiler what presets and plugins to use to transpile the code. Add the following JSON code:" }, { "code": null, "e": 28292, "s": 28229, "text": "{\n \"presets\": [\"@babel/preset-env\",\"@babel/preset-react\"]\n}" }, { "code": null, "e": 28379, "s": 28292, "text": "Step 4: Install React and React DOM by running the following command on the terminal:" }, { "code": null, "e": 28401, "s": 28379, "text": "npm i react react-dom" }, { "code": null, "e": 28435, "s": 28401, "text": "present inside package.json file." }, { "code": null, "e": 28570, "s": 28435, "text": "Step 5: Now, create three files inside “src” directory named as ‘App.js’, ‘index.js’, ‘App.css’. These files contain the actual code." }, { "code": null, "e": 28600, "s": 28570, "text": "App.js: A component of React." }, { "code": null, "e": 28611, "s": 28600, "text": "Javascript" }, { "code": "import React from \"react\";import \"./App.css\";const App = () => { return ( <div> <h1 className=\"heading\">GeeksForGeeks</h1> <h4 className=\"sub-heading\"> A computer science portal for geeks </h4> </div> );}; export default App;", "e": 28867, "s": 28611, "text": null }, { "code": null, "e": 28913, "s": 28867, "text": "App.css: Provides stylings for App component." }, { "code": null, "e": 28917, "s": 28913, "text": "CSS" }, { "code": "/* stylings for App component */.heading,.sub-heading{ color:green; text-align: center;}", "e": 29012, "s": 28917, "text": null }, { "code": null, "e": 29061, "s": 29012, "text": "index.js: Renders the components on the browser." }, { "code": null, "e": 29072, "s": 29061, "text": "Javascript" }, { "code": "import React from \"react\";import ReactDOM from \"react-dom\";import App from \"./App\";ReactDOM.render(<App/>,document.getElementById(\"root\"));", "e": 29213, "s": 29072, "text": null }, { "code": null, "e": 29308, "s": 29213, "text": "Note: You can make as many components as you want in your react project inside the src folder." }, { "code": null, "e": 29694, "s": 29308, "text": "Step 6: Install the webpack. The webpack is a static module bundler. It works well with babel. It creates a local development server for our project. The webpack collects all the modules (either custom that we created or installed through NPM ) and bundles them up together in a single file or more files (static assets). To install webpack, run the following command on the terminal:" }, { "code": null, "e": 29756, "s": 29694, "text": "npm install --save-dev webpack webpack-cli webpack-dev-server" }, { "code": null, "e": 29762, "s": 29756, "text": "Here," }, { "code": null, "e": 29804, "s": 29762, "text": "–save-dev is the same as discussed above," }, { "code": null, "e": 29834, "s": 29804, "text": "webpack is a modular bundler," }, { "code": null, "e": 29919, "s": 29834, "text": "webpack-cli allows us to use webpack from the terminal by running a set of commands," }, { "code": null, "e": 30039, "s": 29919, "text": "webpack-dev-server provides a development server with live reloading i.e. you do not need to refresh the page manually." }, { "code": null, "e": 30282, "s": 30039, "text": "The webpack takes code from the src directory and perform required operations like bundling of code, conversion of ES6 syntax and JSX syntax into common javascript etc. and host the public directory so that we can view our app in the browser." }, { "code": null, "e": 30521, "s": 30282, "text": "Step 7: Webpack can understand JavaScript and JSON files only. So, to use webpack functionality in other files like .css, babel files, etc., we have to install some loaders in the project by writing the following command on the terminal:" }, { "code": null, "e": 30575, "s": 30521, "text": "npm i --save-dev style-loader css-loader babel-loader" }, { "code": null, "e": 30581, "s": 30575, "text": "Here," }, { "code": null, "e": 30668, "s": 30581, "text": "css-loader collects CSS from all the CSS files in the app and bundle it into one file," }, { "code": null, "e": 30767, "s": 30668, "text": "style-loader puts all stylings inside <style> tag in index.html file present in the public folder," }, { "code": null, "e": 30866, "s": 30767, "text": "babel-loader is a package that allows the transpiling of javascript files using babel and webpack." }, { "code": null, "e": 31174, "s": 30866, "text": "Step 8: Create a webpack.config.js file in the root directory that helps us to define what exactly the webpack should do with our source code. We will specify the entry point from where the webpack should start bundling, the output point that is where it should output the bundles and assets, plugins, etc." }, { "code": null, "e": 31192, "s": 31174, "text": "webpack.config.js" }, { "code": null, "e": 31203, "s": 31192, "text": "Javascript" }, { "code": "const path = require(\"path\"); module.exports = { // Entry point that indicates where // should the webpack starts bundling entry: \"./src/index.js\", mode: \"development\", module: { rules: [ { test: /\\.(js|jsx)$/, // checks for .js or .jsx files exclude: /(node_modules)/, loader: \"babel-loader\", options: { presets: [\"@babel/env\"] }, }, { test: /\\.css$/, //checks for .css files use: [\"style-loader\", \"css-loader\"], }, ], }, // Options for resolving module requests // extensions that are used resolve: { extensions: [\"*\", \".js\", \".jsx\"] }, // Output point is where webpack should // output the bundles and assets output: { path: path.resolve(__dirname, \"dist/\"), publicPath: \"/dist/\", filename: \"bundle.js\", },};", "e": 32007, "s": 31203, "text": null }, { "code": null, "e": 32093, "s": 32007, "text": "Step 9: Now, add some scripts in the package.json file to run and build the project." }, { "code": null, "e": 32226, "s": 32093, "text": "\"scripts\": {\n \"start\":\"npx webpack-dev-server --mode development --open --hot\",\n \"build\":\"npx webpack --mode production\",\n\n }" }, { "code": null, "e": 32233, "s": 32226, "text": "Here, " }, { "code": null, "e": 32338, "s": 32233, "text": "–open flag tells the webpack-dev-server to open the browser instantly after the server had been started." }, { "code": null, "e": 32541, "s": 32338, "text": "–hot flag enables webpack’s Hot Module Replacement feature. It only updates what’s changed in the code, so does not update the whole code, again and again, that’s why it saves precious development time." }, { "code": null, "e": 32652, "s": 32541, "text": "Step to run the application: Run the command following on the terminal to run the project in development mode." }, { "code": null, "e": 32662, "s": 32652, "text": "npm start" }, { "code": null, "e": 32670, "s": 32662, "text": "Output:" }, { "code": null, "e": 32738, "s": 32670, "text": "Run command “npm run build” to run the project in production mode. " }, { "code": null, "e": 33118, "s": 32738, "text": "Note: When we are running our webpack server, there isn’t a dist folder. This is because what webpack server does is holds this dist folder in the memory and serves it, and deletes it when we stop the server. If you actually want to build the react app so that we can see that dist folder, run the command “npm run build”. Now, you can see the dist folder in the root directory." }, { "code": null, "e": 33227, "s": 33118, "text": "That’s all! We are equipped with our own react boilerplate and ready to make some amazing and cool projects." }, { "code": null, "e": 33243, "s": 33227, "text": "simranarora5sos" }, { "code": null, "e": 33258, "s": 33243, "text": "Blogathon-2021" }, { "code": null, "e": 33274, "s": 33258, "text": "React-Questions" }, { "code": null, "e": 33284, "s": 33274, "text": "Blogathon" }, { "code": null, "e": 33292, "s": 33284, "text": "ReactJS" }, { "code": null, "e": 33309, "s": 33292, "text": "Web Technologies" }, { "code": null, "e": 33407, "s": 33309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33448, "s": 33407, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 33483, "s": 33448, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 33521, "s": 33483, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 33584, "s": 33521, "text": "How to pass data into table from a form using React Components" }, { "code": null, "e": 33629, "s": 33584, "text": "SQL Query to Create Table With a Primary Key" }, { "code": null, "e": 33672, "s": 33629, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 33717, "s": 33672, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 33782, "s": 33717, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 33823, "s": 33782, "text": "Create a Responsive Navbar using ReactJS" } ]
Python OpenCV - imdecode() Function - GeeksforGeeks
05 Nov, 2021 Python cv2.imdecode() function is used to read image data from a memory cache and convert it into image format. This is generally used for loading the image efficiently from the internet. Syntax: cv2.imdecode(buf,flags) Parameters: buf – It is the image data received in bytes flags – It specifies the way in which image should be read. It’s default value is cv2.IMREAD_COLOR Return: Image array Note: If buf given is not image data then NULL will be returned. Example 1: Python3 #import modulesimport numpy as npimport urllib.requestimport cv2 # read the image urlurl = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png' with urllib.request.urlopen(url) as resp: # read image as an numpy array image = np.asarray(bytearray(resp.read()), dtype="uint8") # use imdecode function image = cv2.imdecode(image, cv2.IMREAD_COLOR) # display image cv2.imwrite("result.jpg", image) Output: Example 2: If grayscale is required, then 0 can be used as flag. Python3 # import necessary modulesimport numpy as npimport urllib.requestimport cv2 # read image urlurl = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png' with urllib.request.urlopen(url) as resp: # convert to numpy array image = np.asarray(bytearray(resp.read()), dtype="uint8") # 0 is used for grayscale image image = cv2.imdecode(image, 0) # display image cv2.imwrite("result.jpg", image) Output: Example 3: Reading image from a file Input Image: Python3 # import necessayr modulesimport numpy as npimport urllib.requestimport cv2 # read th imagewith open("image.jpg", "rb") as image: f = image.read() # convert to numpy array image = np.asarray(bytearray(f)) # RGB to Grayscale image = cv2.imdecode(image, 0) # display image cv2.imshow("output", image) Output: Picked Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n05 Nov, 2021" }, { "code": null, "e": 24481, "s": 24292, "text": "Python cv2.imdecode() function is used to read image data from a memory cache and convert it into image format. This is generally used for loading the image efficiently from the internet. " }, { "code": null, "e": 24513, "s": 24481, "text": "Syntax: cv2.imdecode(buf,flags)" }, { "code": null, "e": 24525, "s": 24513, "text": "Parameters:" }, { "code": null, "e": 24571, "s": 24525, "text": "buf – It is the image data received in bytes" }, { "code": null, "e": 24670, "s": 24571, "text": "flags – It specifies the way in which image should be read. It’s default value is cv2.IMREAD_COLOR" }, { "code": null, "e": 24690, "s": 24670, "text": "Return: Image array" }, { "code": null, "e": 24755, "s": 24690, "text": "Note: If buf given is not image data then NULL will be returned." }, { "code": null, "e": 24766, "s": 24755, "text": "Example 1:" }, { "code": null, "e": 24774, "s": 24766, "text": "Python3" }, { "code": "#import modulesimport numpy as npimport urllib.requestimport cv2 # read the image urlurl = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png' with urllib.request.urlopen(url) as resp: # read image as an numpy array image = np.asarray(bytearray(resp.read()), dtype=\"uint8\") # use imdecode function image = cv2.imdecode(image, cv2.IMREAD_COLOR) # display image cv2.imwrite(\"result.jpg\", image)", "e": 25229, "s": 24774, "text": null }, { "code": null, "e": 25237, "s": 25229, "text": "Output:" }, { "code": null, "e": 25302, "s": 25237, "text": "Example 2: If grayscale is required, then 0 can be used as flag." }, { "code": null, "e": 25310, "s": 25302, "text": "Python3" }, { "code": "# import necessary modulesimport numpy as npimport urllib.requestimport cv2 # read image urlurl = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png' with urllib.request.urlopen(url) as resp: # convert to numpy array image = np.asarray(bytearray(resp.read()), dtype=\"uint8\") # 0 is used for grayscale image image = cv2.imdecode(image, 0) # display image cv2.imwrite(\"result.jpg\", image)", "e": 25759, "s": 25310, "text": null }, { "code": null, "e": 25767, "s": 25759, "text": "Output:" }, { "code": null, "e": 25804, "s": 25767, "text": "Example 3: Reading image from a file" }, { "code": null, "e": 25817, "s": 25804, "text": "Input Image:" }, { "code": null, "e": 25825, "s": 25817, "text": "Python3" }, { "code": "# import necessayr modulesimport numpy as npimport urllib.requestimport cv2 # read th imagewith open(\"image.jpg\", \"rb\") as image: f = image.read() # convert to numpy array image = np.asarray(bytearray(f)) # RGB to Grayscale image = cv2.imdecode(image, 0) # display image cv2.imshow(\"output\", image)", "e": 26168, "s": 25825, "text": null }, { "code": null, "e": 26176, "s": 26168, "text": "Output:" }, { "code": null, "e": 26183, "s": 26176, "text": "Picked" }, { "code": null, "e": 26197, "s": 26183, "text": "Python-OpenCV" }, { "code": null, "e": 26204, "s": 26197, "text": "Python" }, { "code": null, "e": 26302, "s": 26204, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26311, "s": 26302, "text": "Comments" }, { "code": null, "e": 26324, "s": 26311, "text": "Old Comments" }, { "code": null, "e": 26356, "s": 26324, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26412, "s": 26356, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26467, "s": 26412, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26509, "s": 26467, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26551, "s": 26509, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26582, "s": 26551, "text": "Python | os.path.join() method" }, { "code": null, "e": 26621, "s": 26582, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26650, "s": 26621, "text": "Create a directory in Python" }, { "code": null, "e": 26672, "s": 26650, "text": "Defaultdict in Python" } ]
How to Implement One to Many Mapping in Spring Boot? - GeeksforGeeks
20 Dec, 2021 Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence API) is like an interface and the hibernate is the implementation of the methods of the interface Like how insertion will be down is already defined with the help of hibernate. In this article, we will discuss how to insert the values in the MySQL table using Spring JPA. Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer. Step 1: Go to this link. Fill in the details as per the requirements. For this application: Project: Maven Language: Java Spring Boot: 2.5.6 Packaging: JAR Java: 11 Dependencies: Spring Web,Spring Data JPA, MySql Driver Click on Generate which will download the starter project. Step 2: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows: Project Structure: Step 3: Adding the necessary properties in the application.properties file. (mapping is the database name) spring.datasource.username=root spring.datasource.password=Aayush spring.datasource.url=jdbc:mysql://localhost:3306/mapping spring.jpa.hibernate.ddl-auto=update Step 4: Go to src->main->java->com->example->Mapping and create two files in the Models folder i.e Address.java and Student Information.java. Project structure: Address.java(Mapped table) Java package com.example.Mapping.Models; import javax.persistence.*; @Entity// Adding the table name@Table(name = "Address")public class Address { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String cityname; // Mapping the column of this table @ManyToOne //Adding the name @JoinColumn(name = "Student_id") StudentInformation ob; Address() {} public Address(int id, String cityname, StudentInformation ob1) { this.id = id; this.cityname = cityname; this.ob = ob1; }} StudentInformation.java(Mapped by table) Java @Entity// Adding the table name@Table(name = "Student")public class StudentInformation { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int rollno; private String name; // Mapping to the other table @OneToMany(cascade = CascadeType.ALL) private Set<Address> ob; public int getRollno() { return rollno; } public StudentInformation() {} public StudentInformation(int rollno, String name) { this.rollno = rollno; this.name = name; } public void setRollno(int rollno) { this.rollno = rollno; } public String getName() { return name; } public void setName(String name) { this.name = name; }} Step 5: Adding the JPA repository of both classes in the project structure: Project Structure: AddressRepo: Java package com.example.Mapping.Repositery; import com.example.Mapping.Models.Address;import org.springframework.data.jpa.repository.JpaRepository; public interface AddressRepo extends JpaRepository<Address, Integer> { } StudentRepo: Java package com.example.Mapping.Repositery; import com.example.Mapping.Models.StudentInformation;import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepo extends JpaRepository<StudentInformation, Integer> {} Step 6: Executing the information in these tables MappingApplication: Java @SpringBootApplicationpublic class MappingApplication implements CommandLineRunner { @Autowired StudentRepo ob; @Autowired AddressRepo ob1; public static void main(String[] args) { SpringApplication.run(MappingApplication.class, args); } @Override public void run(String... args) throws Exception { StudentInformation student = new StudentInformation(1, "Aayush"); ob.save(student); Address address = new Address(1, "Sonipat", student); ob1.save(address); }} Now run the main application Terminal Output: StudentTable: Address.java Java-Spring-Boot Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways of Reading a text file in Java Constructors in Java Stream In Java Generics in Java Exceptions in Java Functional Interfaces in Java Comparator Interface in Java with Examples HashMap get() Method in Java Strings in Java StringBuilder Class in Java with Examples
[ { "code": null, "e": 23948, "s": 23920, "text": "\n20 Dec, 2021" }, { "code": null, "e": 24868, "s": 23948, "text": "Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence API) is like an interface and the hibernate is the implementation of the methods of the interface Like how insertion will be down is already defined with the help of hibernate. In this article, we will discuss how to insert the values in the MySQL table using Spring JPA. Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer." }, { "code": null, "e": 24960, "s": 24868, "text": "Step 1: Go to this link. Fill in the details as per the requirements. For this application:" }, { "code": null, "e": 25088, "s": 24960, "text": "Project: Maven\nLanguage: Java\nSpring Boot: 2.5.6\nPackaging: JAR\nJava: 11\nDependencies: Spring Web,Spring Data JPA, MySql Driver" }, { "code": null, "e": 25147, "s": 25088, "text": "Click on Generate which will download the starter project." }, { "code": null, "e": 25406, "s": 25147, "text": "Step 2: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows:" }, { "code": null, "e": 25425, "s": 25406, "text": "Project Structure:" }, { "code": null, "e": 25532, "s": 25425, "text": "Step 3: Adding the necessary properties in the application.properties file. (mapping is the database name)" }, { "code": null, "e": 25693, "s": 25532, "text": "spring.datasource.username=root\nspring.datasource.password=Aayush\nspring.datasource.url=jdbc:mysql://localhost:3306/mapping\nspring.jpa.hibernate.ddl-auto=update" }, { "code": null, "e": 25835, "s": 25693, "text": "Step 4: Go to src->main->java->com->example->Mapping and create two files in the Models folder i.e Address.java and Student Information.java." }, { "code": null, "e": 25854, "s": 25835, "text": "Project structure:" }, { "code": null, "e": 25881, "s": 25854, "text": "Address.java(Mapped table)" }, { "code": null, "e": 25886, "s": 25881, "text": "Java" }, { "code": "package com.example.Mapping.Models; import javax.persistence.*; @Entity// Adding the table name@Table(name = \"Address\")public class Address { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String cityname; // Mapping the column of this table @ManyToOne //Adding the name @JoinColumn(name = \"Student_id\") StudentInformation ob; Address() {} public Address(int id, String cityname, StudentInformation ob1) { this.id = id; this.cityname = cityname; this.ob = ob1; }}", "e": 26454, "s": 25886, "text": null }, { "code": null, "e": 26495, "s": 26454, "text": "StudentInformation.java(Mapped by table)" }, { "code": null, "e": 26500, "s": 26495, "text": "Java" }, { "code": "@Entity// Adding the table name@Table(name = \"Student\")public class StudentInformation { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int rollno; private String name; // Mapping to the other table @OneToMany(cascade = CascadeType.ALL) private Set<Address> ob; public int getRollno() { return rollno; } public StudentInformation() {} public StudentInformation(int rollno, String name) { this.rollno = rollno; this.name = name; } public void setRollno(int rollno) { this.rollno = rollno; } public String getName() { return name; } public void setName(String name) { this.name = name; }}", "e": 27192, "s": 26500, "text": null }, { "code": null, "e": 27268, "s": 27192, "text": "Step 5: Adding the JPA repository of both classes in the project structure:" }, { "code": null, "e": 27287, "s": 27268, "text": "Project Structure:" }, { "code": null, "e": 27300, "s": 27287, "text": "AddressRepo:" }, { "code": null, "e": 27305, "s": 27300, "text": "Java" }, { "code": "package com.example.Mapping.Repositery; import com.example.Mapping.Models.Address;import org.springframework.data.jpa.repository.JpaRepository; public interface AddressRepo extends JpaRepository<Address, Integer> { }", "e": 27525, "s": 27305, "text": null }, { "code": null, "e": 27538, "s": 27525, "text": "StudentRepo:" }, { "code": null, "e": 27543, "s": 27538, "text": "Java" }, { "code": "package com.example.Mapping.Repositery; import com.example.Mapping.Models.StudentInformation;import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepo extends JpaRepository<StudentInformation, Integer> {}", "e": 27783, "s": 27543, "text": null }, { "code": null, "e": 27833, "s": 27783, "text": "Step 6: Executing the information in these tables" }, { "code": null, "e": 27853, "s": 27833, "text": "MappingApplication:" }, { "code": null, "e": 27858, "s": 27853, "text": "Java" }, { "code": "@SpringBootApplicationpublic class MappingApplication implements CommandLineRunner { @Autowired StudentRepo ob; @Autowired AddressRepo ob1; public static void main(String[] args) { SpringApplication.run(MappingApplication.class, args); } @Override public void run(String... args) throws Exception { StudentInformation student = new StudentInformation(1, \"Aayush\"); ob.save(student); Address address = new Address(1, \"Sonipat\", student); ob1.save(address); }}", "e": 28383, "s": 27858, "text": null }, { "code": null, "e": 28412, "s": 28383, "text": "Now run the main application" }, { "code": null, "e": 28429, "s": 28412, "text": "Terminal Output:" }, { "code": null, "e": 28443, "s": 28429, "text": "StudentTable:" }, { "code": null, "e": 28456, "s": 28443, "text": "Address.java" }, { "code": null, "e": 28473, "s": 28456, "text": "Java-Spring-Boot" }, { "code": null, "e": 28478, "s": 28473, "text": "Java" }, { "code": null, "e": 28483, "s": 28478, "text": "Java" }, { "code": null, "e": 28581, "s": 28483, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28590, "s": 28581, "text": "Comments" }, { "code": null, "e": 28603, "s": 28590, "text": "Old Comments" }, { "code": null, "e": 28649, "s": 28603, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28670, "s": 28649, "text": "Constructors in Java" }, { "code": null, "e": 28685, "s": 28670, "text": "Stream In Java" }, { "code": null, "e": 28702, "s": 28685, "text": "Generics in Java" }, { "code": null, "e": 28721, "s": 28702, "text": "Exceptions in Java" }, { "code": null, "e": 28751, "s": 28721, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28794, "s": 28751, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28823, "s": 28794, "text": "HashMap get() Method in Java" }, { "code": null, "e": 28839, "s": 28823, "text": "Strings in Java" } ]
Tryit Editor v3.6 - Show Python
mydb = mysql.connector.connect( host="localhost", user="myusername", password="mypassword", database="mydatabase" ) ​ mycursor = mydb.cursor()
[ { "code": null, "e": 57, "s": 25, "text": "mydb = mysql.connector.connect(" }, { "code": null, "e": 77, "s": 57, "text": " host=\"localhost\"," }, { "code": null, "e": 98, "s": 77, "text": " user=\"myusername\"," }, { "code": null, "e": 123, "s": 98, "text": " password=\"mypassword\"," }, { "code": null, "e": 147, "s": 123, "text": " database=\"mydatabase\"" }, { "code": null, "e": 149, "s": 147, "text": ")" }, { "code": null, "e": 151, "s": 149, "text": "​" } ]
Python Library API for Docker
You can access, manage and manipulate docker objects such as containers, images, clusters, swarms, etc. using a python library API. You can do pretty much anything that docker commands let you do. This comes very handy when you are using a python app such as django or flask and you want to maintain your docker container using the same python script that you use for the application. To use the python library API for docker, you need to install a package called docker−py. You can do so using the following pip command. If you have python 2 installed, replace pip3 with pip. pip3 install docker−py Now, we will look at different features of the python client library API for docker one by one. In order to run docker commands inside the python script using the API, you first need to connect to the docker daemon. You can do so using the following commands − #import client from docker import client #create a client object to connect to the daemon myClient = client.Client(base_url='unix://var/run/docker.sock') After you have connected to the docker daemon, you can get a list of all the containers using the following command. Please note that you are logged in as the root user before running any of the commands in order to avoid permission errors. myClient.containers() It will give you a list of all the containers that exist in your local machine along with their Id, associated image and image Id, labels, ports, status, etc. To create a new container, you can use the create_container method from the client object. myContainer=myClient.create_container(image='ubuntu:latest',command='/bin/bash') Using the above commands, you can create a container from the ubuntu image and provide the command to open the bash or any other command as you want. You can check that the container has been created by printing the container’s Id using the following command − print(myContainer['Id']) To inspect a particular container, you can use the inspect_container method on the client object. myClient.inspect_container('a74688e3cf61ac11fd19bcbca1003465b03b117537adfc826db52c6430c46ba5') You need to provide the container Id of the container you want to inspect inside as the argument. You can also inspect only specific fields such as the path or the name or the date of creation. myClient.inspect_container('a74688e3cf61ac11fd19bcbca1003465b03b117537adfc826db52c6430c46ba5')['Name'] myClient.inspect_container('a74688e3cf61ac11fd19bcbca1003465b03b117537adfc826db52c6430c46ba5')['Created'] myClient.inspect_container('a74688e3cf61ac11fd19bcbca1003465b03b117537adfc826db52c6430c46ba5')['Path'] To commit a container, you can use the commit method on the container object. You can also provide a tag to the container. myClient.commit('a74688e3cf61ac11fd19bcbca1003465b03b117537adfc826db52c6430c46ba5', tag='container1') The above command will return the Id of the container. In order to restart a container, you need to make sure the container still exists. To avoid this, what we can do is to wrap the command inside a try−catch block. try: myClient.restart('a74688e3cf61ac11fd19bcbca1003465b03b117537adfc826db52c6430c46ba5') except Exception as e: print(e) To get a list of all the images, you can use the images method on the client object. images = myClient.images() It will return a list of all the images. To print the details of the first image, use − print(images[0]) To inspect the image − myClient.inspect_image('9140108b62dc87d9b278bb0d4fd6a3e44c2959646eb966b86531306faa81b09b') You need to provide the image Id as the argument. We will now see some useful commands to work with volumes. To get a list of all the volumes, you can use the volumes method on the client object. volumes = myClient.volumes() It will return a list of all the volumes. To print the details of the first volume, you can use − print(volumes['Volumes'][0]) In order to create a volume, you need to specify the volume name, driver name and optionally, you can also specify other options as well. volume=myClient.create_volume(name='myVolume1', driver='local', driver_opts={}) To check whether the volume has been created or not, try printing it. print(volume) To inspect a volume, use the inspect_volume method on the client object. myClient.inspect_volume('myVolume1') To create a container with a volume mounted on it, you can use the following example − mounted_container = myClient.create_container( 'ubuntu', 'ls', volumes=['/var/lib/docker/volumes/myVolume1'], host_config=myClient.create_host_config(binds=[ '/var/lib/docker/volumes/myVolume1:/usr/src/app/myVolume1' , ]) ) The above command creates a container from ubuntu image and specifies the entrypoint as ls and mounts a volume located at /var/lib/docker/volumes/myVolume1 in you local machine to /usr/src/app/myVolume1 in your docker container. To conclude, in this article, we have discussed how to create, inspect and manage docker objects such as docker containers, images, volumes using a python script. This is very useful when you are building an application using python tools such as a web application using django or flask or a GUI application using tkinter or using any other python script. If you are willing to manage the application from a docker container, it is strongly advised to use python scripts to write docker commands instead of executing commands separately through the command line interface.
[ { "code": null, "e": 1447, "s": 1062, "text": "You can access, manage and manipulate docker objects such as containers, images, clusters, swarms, etc. using a python library API. You can do pretty much anything that docker commands let you do. This comes very handy when you are using a python app such as django or flask and you want to maintain your docker container using the same python script that you use for the application." }, { "code": null, "e": 1639, "s": 1447, "text": "To use the python library API for docker, you need to install a package called docker−py. You can do so using the following pip command. If you have python 2 installed, replace pip3 with pip." }, { "code": null, "e": 1662, "s": 1639, "text": "pip3 install docker−py" }, { "code": null, "e": 1758, "s": 1662, "text": "Now, we will look at different features of the python client library API for docker one by one." }, { "code": null, "e": 1923, "s": 1758, "text": "In order to run docker commands inside the python script using the API, you first need to connect to the docker daemon. You can do so using the following commands −" }, { "code": null, "e": 2078, "s": 1923, "text": "#import client\nfrom docker import client\n\n#create a client object to connect to the daemon\nmyClient = client.Client(base_url='unix://var/run/docker.sock')" }, { "code": null, "e": 2319, "s": 2078, "text": "After you have connected to the docker daemon, you can get a list of all the containers using the following command. Please note that you are logged in as the root user before running any of the commands in order to avoid permission errors." }, { "code": null, "e": 2341, "s": 2319, "text": "myClient.containers()" }, { "code": null, "e": 2500, "s": 2341, "text": "It will give you a list of all the containers that exist in your local machine along with their Id, associated image and image Id, labels, ports, status, etc." }, { "code": null, "e": 2591, "s": 2500, "text": "To create a new container, you can use the create_container method from the client object." }, { "code": null, "e": 2672, "s": 2591, "text": "myContainer=myClient.create_container(image='ubuntu:latest',command='/bin/bash')" }, { "code": null, "e": 2822, "s": 2672, "text": "Using the above commands, you can create a container from the ubuntu image and provide the command to open the bash or any other command as you want." }, { "code": null, "e": 2933, "s": 2822, "text": "You can check that the container has been created by printing the container’s Id using the following command −" }, { "code": null, "e": 2959, "s": 2933, "text": "print(myContainer['Id'])\n" }, { "code": null, "e": 3057, "s": 2959, "text": "To inspect a particular container, you can use the inspect_container method on the client object." }, { "code": null, "e": 3152, "s": 3057, "text": "myClient.inspect_container('a74688e3cf61ac11fd19bcbca1003465b03b117537adfc826db52c6430c46ba5')" }, { "code": null, "e": 3346, "s": 3152, "text": "You need to provide the container Id of the container you want to inspect inside as the argument. You can also inspect only specific fields such as the path or the name or the date of creation." }, { "code": null, "e": 3660, "s": 3346, "text": "myClient.inspect_container('a74688e3cf61ac11fd19bcbca1003465b03b117537adfc826db52c6430c46ba5')['Name']\n\nmyClient.inspect_container('a74688e3cf61ac11fd19bcbca1003465b03b117537adfc826db52c6430c46ba5')['Created']\n\nmyClient.inspect_container('a74688e3cf61ac11fd19bcbca1003465b03b117537adfc826db52c6430c46ba5')['Path']" }, { "code": null, "e": 3783, "s": 3660, "text": "To commit a container, you can use the commit method on the container object. You can also provide a tag to the container." }, { "code": null, "e": 3885, "s": 3783, "text": "myClient.commit('a74688e3cf61ac11fd19bcbca1003465b03b117537adfc826db52c6430c46ba5', tag='container1')" }, { "code": null, "e": 4102, "s": 3885, "text": "The above command will return the Id of the container. In order to restart a container, you need to make sure the container still exists. To avoid this, what we can do is to wrap the command inside a try−catch block." }, { "code": null, "e": 4224, "s": 4102, "text": "try:\nmyClient.restart('a74688e3cf61ac11fd19bcbca1003465b03b117537adfc826db52c6430c46ba5')\nexcept Exception as e:\nprint(e)" }, { "code": null, "e": 4309, "s": 4224, "text": "To get a list of all the images, you can use the images method on the client object." }, { "code": null, "e": 4336, "s": 4309, "text": "images = myClient.images()" }, { "code": null, "e": 4424, "s": 4336, "text": "It will return a list of all the images. To print the details of the first image, use −" }, { "code": null, "e": 4441, "s": 4424, "text": "print(images[0])" }, { "code": null, "e": 4464, "s": 4441, "text": "To inspect the image −" }, { "code": null, "e": 4556, "s": 4464, "text": "myClient.inspect_image('9140108b62dc87d9b278bb0d4fd6a3e44c2959646eb966b86531306faa81b09b')\n" }, { "code": null, "e": 4606, "s": 4556, "text": "You need to provide the image Id as the argument." }, { "code": null, "e": 4752, "s": 4606, "text": "We will now see some useful commands to work with volumes. To get a list of all the volumes, you can use the volumes method on the client object." }, { "code": null, "e": 4781, "s": 4752, "text": "volumes = myClient.volumes()" }, { "code": null, "e": 4879, "s": 4781, "text": "It will return a list of all the volumes. To print the details of the first volume, you can use −" }, { "code": null, "e": 4908, "s": 4879, "text": "print(volumes['Volumes'][0])" }, { "code": null, "e": 5046, "s": 4908, "text": "In order to create a volume, you need to specify the volume name, driver name and optionally, you can also specify other options as well." }, { "code": null, "e": 5126, "s": 5046, "text": "volume=myClient.create_volume(name='myVolume1', driver='local', driver_opts={})" }, { "code": null, "e": 5196, "s": 5126, "text": "To check whether the volume has been created or not, try printing it." }, { "code": null, "e": 5211, "s": 5196, "text": "print(volume)\n" }, { "code": null, "e": 5284, "s": 5211, "text": "To inspect a volume, use the inspect_volume method on the client object." }, { "code": null, "e": 5321, "s": 5284, "text": "myClient.inspect_volume('myVolume1')" }, { "code": null, "e": 5408, "s": 5321, "text": "To create a container with a volume mounted on it, you can use the following example −" }, { "code": null, "e": 5642, "s": 5408, "text": "mounted_container = myClient.create_container(\n 'ubuntu', 'ls', volumes=['/var/lib/docker/volumes/myVolume1'],\n host_config=myClient.create_host_config(binds=[\n '/var/lib/docker/volumes/myVolume1:/usr/src/app/myVolume1'\n , ])\n)" }, { "code": null, "e": 5871, "s": 5642, "text": "The above command creates a container from ubuntu image and specifies the entrypoint as ls and mounts a volume located at /var/lib/docker/volumes/myVolume1 in you local machine to /usr/src/app/myVolume1 in your docker container." }, { "code": null, "e": 6444, "s": 5871, "text": "To conclude, in this article, we have discussed how to create, inspect and manage docker objects such as docker containers, images, volumes using a python script. This is very useful when you are building an application using python tools such as a web application using django or flask or a GUI application using tkinter or using any other python script. If you are willing to manage the application from a docker container, it is strongly advised to use python scripts to write docker commands instead of executing commands separately through the command line interface." } ]
C++ Program to Generate Multiplication Table
The multiplication table is used to define a multiplication operation for any number. It is normally used to lay the foundation of elementary arithmetic operations with base ten numbers. The multiplication table of any number is written till 10. In each row, the product of the number with 1 to 10 is displayed. An example of the multiplication table of 4 is as follows − 4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16 4 * 5 = 20 4 * 6 = 24 4 * 7 = 28 4 * 8 = 32 4 * 9 = 36 4 * 10 = 40 A program that generates the multiplication table of the given number is as follows. Live Demo #include <iostream> using namespace std; int main() { int n = 7, i; cout<<"The multiplication table for "<< n <<" is as follows:"<< endl; for (i = 1; i <= 10; i++) cout << n << " * " << i << " = " << n * i << endl; return 0; } The multiplication table for 7 is as follows: 7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 7 * 8 = 56 7 * 9 = 63 7 * 10 = 70 In the above program, a for loop is used from 1 to 10. In each iteration of the for loop, the number is multiplied with i and the product is displayed. This is demonstrated by the following code snippet. for (i = 1; i <= 10; i++) cout << n << " * " << i << " = " << n * i <<endl;
[ { "code": null, "e": 1249, "s": 1062, "text": "The multiplication table is used to define a multiplication operation for any number. It is normally used to lay the foundation of elementary arithmetic operations with base ten numbers." }, { "code": null, "e": 1434, "s": 1249, "text": "The multiplication table of any number is written till 10. In each row, the product of the number with 1 to 10 is displayed. An example of the multiplication table of 4 is as follows −" }, { "code": null, "e": 1543, "s": 1434, "text": "4 * 1 = 4\n4 * 2 = 8\n4 * 3 = 12\n4 * 4 = 16\n4 * 5 = 20\n4 * 6 = 24\n4 * 7 = 28\n4 * 8 = 32\n4 * 9 = 36\n4 * 10 = 40" }, { "code": null, "e": 1628, "s": 1543, "text": "A program that generates the multiplication table of the given number is as follows." }, { "code": null, "e": 1639, "s": 1628, "text": " Live Demo" }, { "code": null, "e": 1881, "s": 1639, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int n = 7, i;\n cout<<\"The multiplication table for \"<< n <<\" is as follows:\"<< endl;\n for (i = 1; i <= 10; i++)\n cout << n << \" * \" << i << \" = \" << n * i << endl;\n return 0;\n}" }, { "code": null, "e": 2037, "s": 1881, "text": "The multiplication table for 7 is as follows:\n7 * 1 = 7\n7 * 2 = 14\n7 * 3 = 21\n7 * 4 = 28\n7 * 5 = 35\n7 * 6 = 42\n7 * 7 = 49\n7 * 8 = 56\n7 * 9 = 63\n7 * 10 = 70" }, { "code": null, "e": 2241, "s": 2037, "text": "In the above program, a for loop is used from 1 to 10. In each iteration of the for loop, the number is multiplied with i and the product is displayed. This is demonstrated by the following code snippet." }, { "code": null, "e": 2317, "s": 2241, "text": "for (i = 1; i <= 10; i++)\ncout << n << \" * \" << i << \" = \" << n * i <<endl;" } ]
Absolute and Relative Frequency in R Programming - GeeksforGeeks
04 May, 2020 In statistics, frequency or absolute frequency indicates the number of occurrences of a data value or the number of times a data value occurs. These frequencies are often plotted on bar graphs or histograms to compare the data values. For example, to find out the number of kids, adults, and senior citizens in a particular area, to create a poll on some criteria, etc.In R language, frequencies can be depicted as absolute frequency and relative frequency. Absolute frequency shows the number of times the value is repeated in the data vector. Formula: where, is represented as absolute frequency of each valueN represents total number of data values In R, frequency table of a data vector can be created using table() function.Syntax: table(x) where,x is data vector Example:Assume, “M” represents males and “F” represents females in the data vector below. # Defining vectorx <- c("M", "M", "F", "M", "M", "M", "F", "F", "F", "M") # Absolute frequency tableaf <- table(x) # Printing frequency tableprint(af) # Check the classclass(af) Output: x F M 4 6 [1] "table" Relative frequency is the absolute frequency of that event divided by the total number of events. It represents the proportion of a particular data category present in the data vector. Mathematically, where, represents the relative frequency of event is represented as absolute frequency of each valueN represents total number of data values In R language, table() function and length of data vector is used together to find relative frequency of data vector.Syntax: table(x)/length(x) Example: # Defining vectorx <- c("M", "M", "F", "M", "M", "M", "F", "F", "F", "M") # Relative frequency tablerf <- table(x)/length(x) # Printing frequency tableprint(rf) # Check the classclass(rf) Output: x F M 0.4 0.6 [1] "table" R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Loops in R (for, while, repeat) Filter data by multiple conditions in R using Dplyr How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Remove rows with NA in one column of R DataFrame How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming R Programming Language - Introduction
[ { "code": null, "e": 24936, "s": 24908, "text": "\n04 May, 2020" }, { "code": null, "e": 25394, "s": 24936, "text": "In statistics, frequency or absolute frequency indicates the number of occurrences of a data value or the number of times a data value occurs. These frequencies are often plotted on bar graphs or histograms to compare the data values. For example, to find out the number of kids, adults, and senior citizens in a particular area, to create a poll on some criteria, etc.In R language, frequencies can be depicted as absolute frequency and relative frequency." }, { "code": null, "e": 25481, "s": 25394, "text": "Absolute frequency shows the number of times the value is repeated in the data vector." }, { "code": null, "e": 25490, "s": 25481, "text": "Formula:" }, { "code": null, "e": 25497, "s": 25490, "text": "where," }, { "code": null, "e": 25589, "s": 25497, "text": " is represented as absolute frequency of each valueN represents total number of data values" }, { "code": null, "e": 25674, "s": 25589, "text": "In R, frequency table of a data vector can be created using table() function.Syntax:" }, { "code": null, "e": 25684, "s": 25674, "text": "table(x)\n" }, { "code": null, "e": 25707, "s": 25684, "text": "where,x is data vector" }, { "code": null, "e": 25797, "s": 25707, "text": "Example:Assume, “M” represents males and “F” represents females in the data vector below." }, { "code": "# Defining vectorx <- c(\"M\", \"M\", \"F\", \"M\", \"M\", \"M\", \"F\", \"F\", \"F\", \"M\") # Absolute frequency tableaf <- table(x) # Printing frequency tableprint(af) # Check the classclass(af)", "e": 25978, "s": 25797, "text": null }, { "code": null, "e": 25986, "s": 25978, "text": "Output:" }, { "code": null, "e": 26011, "s": 25986, "text": "x\nF M \n4 6 \n[1] \"table\"\n" }, { "code": null, "e": 26212, "s": 26011, "text": "Relative frequency is the absolute frequency of that event divided by the total number of events. It represents the proportion of a particular data category present in the data vector. Mathematically," }, { "code": null, "e": 26219, "s": 26212, "text": "where," }, { "code": null, "e": 26355, "s": 26219, "text": " represents the relative frequency of event is represented as absolute frequency of each valueN represents total number of data values" }, { "code": null, "e": 26480, "s": 26355, "text": "In R language, table() function and length of data vector is used together to find relative frequency of data vector.Syntax:" }, { "code": null, "e": 26500, "s": 26480, "text": "table(x)/length(x)\n" }, { "code": null, "e": 26509, "s": 26500, "text": "Example:" }, { "code": "# Defining vectorx <- c(\"M\", \"M\", \"F\", \"M\", \"M\", \"M\", \"F\", \"F\", \"F\", \"M\") # Relative frequency tablerf <- table(x)/length(x) # Printing frequency tableprint(rf) # Check the classclass(rf)", "e": 26700, "s": 26509, "text": null }, { "code": null, "e": 26708, "s": 26700, "text": "Output:" }, { "code": null, "e": 26740, "s": 26708, "text": "x\n F M \n0.4 0.6\n[1] \"table\"\n" }, { "code": null, "e": 26751, "s": 26740, "text": "R Language" }, { "code": null, "e": 26849, "s": 26751, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26858, "s": 26849, "text": "Comments" }, { "code": null, "e": 26871, "s": 26858, "text": "Old Comments" }, { "code": null, "e": 26903, "s": 26871, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 26955, "s": 26903, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 26999, "s": 26955, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 27051, "s": 26999, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27100, "s": 27051, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 27138, "s": 27100, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27173, "s": 27138, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27231, "s": 27173, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27267, "s": 27231, "text": "K-Means Clustering in R Programming" } ]
Process Object in ElectronJS - GeeksforGeeks
24 Jul, 2020 ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. As mentioned above, Electron combines the Chromium engine and NodeJS into a single runtime. Electron extends the features of NodeJS and provides access to several APIs which otherwise would not be accessible in a sandbox browser environment. One such crucial feature is the NodeJS process object. The NodeJS process object is a global object that provides an extensive set of information and defines the behavior of the NodeJS application. Since it is a global object, it can be accessed within any module of the NodeJS application. It provides us with an extensive set of Instance Properties, Methods, and Events that can be used. For a detailed explanation on the Process object, refer to the article: Global, Process and buffer in Node.js. Electron also supports the global process object. It is an extension of the NodeJS process object and adds its own set of Instance Properties, Methods, and Events which are exclusive to Electron. In this tutorial, we will look at some features of the Electron’s process object. We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. Project Structure: Example: Follow the Steps given in Drag and Drop Files in ElectronJS to set up the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also, perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to set up the Electron application remain the same. package.json: { "name": "electron-properties", "version": "1.0.0", "description": "Process Object in Electron", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.3.0" } } Output: Process Object in Electron: A process object is a global object which can be accessed in the Main Process as well as in the Renderer Processes. As discussed above, the process object in the Electron provides its own set of features apart from the already pre-existing features of the NodeJS process object. In a Sandbox environment, the process object contains only a subset of the APIs. Note: The process object in Electron can interact with the System APIs as well and hence has access to detailed System properties such as CPU Information, Memory Information, etc which can be leveraged in a Desktop Application. index.html: Add the following snippet in that file. html <h3>System Properties in Electron</h3> <button id="print"> Print all System Properties in Console </button> index.js: The Print all System Properties in Console button does not have any functionality associated with it yet. To change this, add the following code in the index.js file. javascript const electron = require('electron') // Instance Properties process.noDeprecation = false;process.throwDeprecation = false;process.traceDeprecation = true;process.traceProcessWarnings = true; // Instance Event process.once('loaded', () => { console.log('Pre-Initialization Complete'); }); function properties(label, value) { this.label = label; this.value = value;} var props = {}; var print = document.getElementById('print');// Instance Properties, continued ...print.addEventListener('click', (event) => { props.defaultApp = new properties('Default App', process.defaultApp); props.mainFrame = new properties('Main Frame', process.isMainFrame); props.resourcePath = new properties('Resource Path', process.resourcesPath); props.sandbox = new properties('Sandbox Environment', process.sandboxed); props.processType = new properties('Type of Process', process.type); props.chrome = new properties('Chrome Version', process.versions.chrome); props.electron = new properties('Electron Version', process.versions.electron); props.windowsStore = new properties('Window Store', process.windowsStore); props.CreationTime = new properties('Window Store', process.getCreationTime()); console.table(props); // Instance Methods console.log('-------------------'); console.log('Application Creation Time'); console.log(process.getCreationTime()); console.log('-------------------'); console.log('CPU Usage Information') console.log(process.getCPUUsage()); console.log('-------------------'); console.log('IOCounters Information') console.log(process.getIOCounters()); console.log('-------------------'); console.log('Heap Statistics Information') console.log(process.getHeapStatistics()); console.log('-------------------'); console.log('Blink Memory Information') console.log(process.getBlinkMemoryInfo()); console.log('-------------------'); console.log('System Memory Information') console.log(process.getSystemMemoryInfo()); console.log('-------------------'); console.log('System Versions Information') console.log(process.getSystemVersion()); console.log('-------------------'); console.log('Process Memory Information') process.getProcessMemoryInfo().then(processMemoryInfo => { console.log(processMemoryInfo); }).catch(err => { console.log(err); })}); loaded: Event This Instance event is emitted when Electron has loaded its internal initialization script and libraries and is beginning to load the web page or the main script i.e. the main.js file. One important use-case of this Event is that it can be used by the preloaded script to add the Node global symbols which are removed, back to the global scope when node integration is turned off for the electron application such as when defining the BrowserWindow webPreferences property. process.defaultApp: This Instance property is a ReadOnly property. It returns a Boolean value. This property is set during application startup and is passed to the Main Process. If the default app, the value returned is true, else undefined. process.isMainFrame: This Instance property is a ReadOnly property. It returns a Boolean value. It returns true when the current renderer context is the main renderer frame. Refer to the output below for a better understanding. If we want the ID of the current frame we should use the webFrame.routingId Instance property. process.mas: This Instance property is a ReadOnly property. It returns a Boolean value. For Mac App Store build, this property is set as true. For other operating systems builds it is returned as undefined. process.noAsar: This Instance property takes in a Boolean value. This property controls ASAR support inside your application. Setting this to true will disable the support for asar archives in NodeJS built-in modules. Asar is a simple extensive archive format, it works like .tar that concatenates all files together without compression, while having random access support. With this Property is enabled, Electron can read arbitrary files from it without unpacking the whole file. For a detailed Explanation and leveraging ASAR Support, refer https://www.npmjs.com/package/asar. process.noDeprecation: This Instance property takes in a Boolean value. This property controls whether or not deprecation warnings are printed to stderr/console. Setting this to true will silence deprecation warnings. This property is used instead of the –no-deprecation command line flag. For a detailed Explanation on command line arguments and switches, Refer Command Line Arguments in ElectronJS process.resourcesPath: This Instance property is a ReadOnly property. It returns a String value. It represents the path to the resources’ directory in Electron. process.sandboxed: This Instance property is a ReadOnly property. It returns a Boolean value. This property returns true when the Renderer Process is a sandbox, otherwise returns undefined. process.throwDeprecation: This Instance property takes in a Boolean value. This Instance Property controls whether or not deprecation warnings will be thrown as exceptions. Setting this to true will throw errors for deprecations and interrupt the execution of the application. This property is used instead of the –throw-deprecation command line flag. For a detailed Explanation on command line arguments and switches, Refer Command Line Arguments in ElectronJS process.traceDeprecation: This Instance property takes in a Boolean value. This Instance property controls whether or not deprecation warnings are printed to stderr/console with their stack trace. Setting this to true will print stack traces. This property is used instead of the –trace-deprecation command line flag. For a detailed Explanation on command line arguments and switches, Refer Command Line Arguments in ElectronJS process.traceProcessWarnings: This Instance property takes in a Boolean value. This Instance property controls whether or not process warnings are printed to stderr/console with their stack trace. Setting this to true will print stack traces. This property is used instead of the –trace-warnings command line flag. For a detailed Explanation on command line arguments and switches, Refer Command Line Arguments in ElectronJS Note – Setting this Instance Property to true will override the behavior of the process.traceDeprecation since it will print the stack traces of deprecations as well to stderr. process.type: This Instance property is a ReadOnly property. It returns a String value representing the current process’s type. It can return the following values:browser: For the Main Process.renderer: For the Renderer Process.worker: For the Web Worker. browser: For the Main Process. renderer: For the Renderer Process. worker: For the Web Worker. process.versions.chrome: This Instance property is a ReadOnly property. It returns a String value representing the Chrome’s current version being used. process.versions.electron: This Instance property is a ReadOnly property. It returns a String value representing the Electron’s current version being used. process.windowsStore: This Instance property is a ReadOnly property. It returns a Boolean value. If the application is running as a Windows Store app (appx) build, this property is set as true. For other operating systems builds it is returned as undefined. process.crash(): This Instance method causes the main thread of the current process to crash. This Instance method is extremely useful when testing the application for the production environment to determine how the application behaves in different operating systems in case it crashes. This method does not have a return type. process.hang() This Instance method causes the main thread of the current process to hang. This Instance method is extremely useful when testing the application for the production environment to determine how the application behaves in different operating systems in case it crashes. This method does not have a return type. process.getCreationTime(): This Instance method returns an integer value which represents the number of milliseconds since epoch. This indicates the creation time of the application. It returns null if it is unable to get the process creation time. process.getCPUUsage(): This Instance method returns a CPUUsage object. This object consists of the following parameters. percentCPUUsage: Integer This parameter represents the percentage of CPU used since the last call to this Instance Method. First call always returns 0 and sets up the measurement task.idleWakeupsPerSecond: Integer This Parameter is not Supported in Windows and will always return 0. This parameter returns the number of average idle CPU wakeups per second since the last call to this Instance Method. First call always returns 0 and sets up the measurement task. percentCPUUsage: Integer This parameter represents the percentage of CPU used since the last call to this Instance Method. First call always returns 0 and sets up the measurement task. idleWakeupsPerSecond: Integer This Parameter is not Supported in Windows and will always return 0. This parameter returns the number of average idle CPU wakeups per second since the last call to this Instance Method. First call always returns 0 and sets up the measurement task. process.getIOCounters(): This Instance Method is supported in Windows and Linux only. It returns an IOCounters object. This object consists of the following parameters.readOperationCount: Integer The number of read I/O operations.writeOperationCount: Integer The number of write I/O operations.otherOperationCount: Integer The number of I/O other operations.readTransferCount: Integer The number of I/O read transfers.writeTransferCount: Integer The number of I/O write transfers.otherTransferCount: Integer The number of I/O other transfers. readOperationCount: Integer The number of read I/O operations. writeOperationCount: Integer The number of write I/O operations. otherOperationCount: Integer The number of I/O other operations. readTransferCount: Integer The number of I/O read transfers. writeTransferCount: Integer The number of I/O write transfers. otherTransferCount: Integer The number of I/O other transfers. process.getHeapStatistics(): This Instance method returns an object with V8 Heap Statistics, the same which are generated by the .snapshot file when uploaded to the Chrome Dev Tools. This Instance method is important in analyzing code statistics and Memory Leaks within the application. All statistics are reported in Kilobytes. For a detailed Explanation of the V8 Heap Snapshot, refer to the article: Create a V8 Heap Snapshot in ElectronJS. The object consists of the following parameters.totalHeapSize: IntegertotalHeapSizeExecutable: IntegertotalPhysicalSize: IntegertotalAvailableSize: IntegerheapSizeLimit: IntegerusedHeapSize: IntegermallocedMemory: IntegerpeakMallocedMemory: IntegerdoesZapGarbage: Boolean totalHeapSize: Integer totalHeapSizeExecutable: Integer totalPhysicalSize: Integer totalAvailableSize: Integer heapSizeLimit: Integer usedHeapSize: Integer mallocedMemory: Integer peakMallocedMemory: Integer doesZapGarbage: Boolean process.takeHeapSnapshot(filePath): This Instance Method takes a V8 Heap snapshot of the application and saves it to provided filePath String parameter. It behaves exactly in the same way as the webContents.takeHeapSnapshot(filepath) Instance method of the webContents Property of the BrowserWindow object. For a detailed Explanation and understanding of how V8 Heap Snapshot works in ElectronJS, Refer the article: Create a V8 Heap Snapshot in ElectronJS. process.getBlinkMemoryInfo(): This Instance method returns an object with Blink Memory Information. It can be useful for debugging rendering, DOM related memory issues. All statistics are reported in Kilobytes. The object consists of the following parameters.allocated: Integer Size of all allocated objects.marked: Integer Size of all marked objects.total: Integer The Total allocated space. allocated: Integer Size of all allocated objects. marked: Integer Size of all marked objects. total: Integer The Total allocated space. process.getSystemVersion(): This Instance Method returns a String value representing the current version of the Host OS. Note: This Instance method returns the actual OS version instead of Kernel Version on macOS. process.getSystemMemoryInfo(): This Instance Method returns an object giving general memory usage statistics about the entire system where the application is hosted. All statistics are reported in Kilobytes. This object consists of the following parameters.total: Integer The total amount of physical memory available to the system.free: Integer The total amount of memory not being used by applications or disk cache.swapTotal: Integer This Parameter is supported in Windows and Linux only. The total amount of Swap memory available to the system.swapFree: Integer This Parameter is supported in Windows and Linux only. The free amount of Swap memory available to the system. total: Integer The total amount of physical memory available to the system. free: Integer The total amount of memory not being used by applications or disk cache. swapTotal: Integer This Parameter is supported in Windows and Linux only. The total amount of Swap memory available to the system. swapFree: Integer This Parameter is supported in Windows and Linux only. The free amount of Swap memory available to the system. process.setFdLimit(maxDescriptors): This Instance Method is supported in macOS and Linux only. It sets the file descriptor soft limit or the OS hard limit to the specified maxDescriptors Integer value, whichever is lower for the current process. This method does not have a return type. Output: ElectronJS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript
[ { "code": null, "e": 24362, "s": 24334, "text": "\n24 Jul, 2020" }, { "code": null, "e": 24662, "s": 24362, "text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime." }, { "code": null, "e": 25294, "s": 24662, "text": "As mentioned above, Electron combines the Chromium engine and NodeJS into a single runtime. Electron extends the features of NodeJS and provides access to several APIs which otherwise would not be accessible in a sandbox browser environment. One such crucial feature is the NodeJS process object. The NodeJS process object is a global object that provides an extensive set of information and defines the behavior of the NodeJS application. Since it is a global object, it can be accessed within any module of the NodeJS application. It provides us with an extensive set of Instance Properties, Methods, and Events that can be used." }, { "code": null, "e": 25683, "s": 25294, "text": "For a detailed explanation on the Process object, refer to the article: Global, Process and buffer in Node.js. Electron also supports the global process object. It is an extension of the NodeJS process object and adds its own set of Instance Properties, Methods, and Events which are exclusive to Electron. In this tutorial, we will look at some features of the Electron’s process object." }, { "code": null, "e": 25853, "s": 25683, "text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system." }, { "code": null, "e": 25874, "s": 25853, "text": "Project Structure: " }, { "code": null, "e": 26338, "s": 25874, "text": "Example: Follow the Steps given in Drag and Drop Files in ElectronJS to set up the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also, perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to set up the Electron application remain the same. " }, { "code": null, "e": 26353, "s": 26338, "text": "package.json: " }, { "code": null, "e": 26662, "s": 26353, "text": "{\n \"name\": \"electron-properties\",\n \"version\": \"1.0.0\",\n \"description\": \"Process Object in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}\n" }, { "code": null, "e": 26671, "s": 26662, "text": "Output: " }, { "code": null, "e": 27059, "s": 26671, "text": "Process Object in Electron: A process object is a global object which can be accessed in the Main Process as well as in the Renderer Processes. As discussed above, the process object in the Electron provides its own set of features apart from the already pre-existing features of the NodeJS process object. In a Sandbox environment, the process object contains only a subset of the APIs." }, { "code": null, "e": 27287, "s": 27059, "text": "Note: The process object in Electron can interact with the System APIs as well and hence has access to detailed System properties such as CPU Information, Memory Information, etc which can be leveraged in a Desktop Application." }, { "code": null, "e": 27340, "s": 27287, "text": "index.html: Add the following snippet in that file. " }, { "code": null, "e": 27345, "s": 27340, "text": "html" }, { "code": "<h3>System Properties in Electron</h3> <button id=\"print\"> Print all System Properties in Console </button>", "e": 27458, "s": 27345, "text": null }, { "code": null, "e": 27635, "s": 27458, "text": "index.js: The Print all System Properties in Console button does not have any functionality associated with it yet. To change this, add the following code in the index.js file." }, { "code": null, "e": 27646, "s": 27635, "text": "javascript" }, { "code": "const electron = require('electron') // Instance Properties process.noDeprecation = false;process.throwDeprecation = false;process.traceDeprecation = true;process.traceProcessWarnings = true; // Instance Event process.once('loaded', () => { console.log('Pre-Initialization Complete'); }); function properties(label, value) { this.label = label; this.value = value;} var props = {}; var print = document.getElementById('print');// Instance Properties, continued ...print.addEventListener('click', (event) => { props.defaultApp = new properties('Default App', process.defaultApp); props.mainFrame = new properties('Main Frame', process.isMainFrame); props.resourcePath = new properties('Resource Path', process.resourcesPath); props.sandbox = new properties('Sandbox Environment', process.sandboxed); props.processType = new properties('Type of Process', process.type); props.chrome = new properties('Chrome Version', process.versions.chrome); props.electron = new properties('Electron Version', process.versions.electron); props.windowsStore = new properties('Window Store', process.windowsStore); props.CreationTime = new properties('Window Store', process.getCreationTime()); console.table(props); // Instance Methods console.log('-------------------'); console.log('Application Creation Time'); console.log(process.getCreationTime()); console.log('-------------------'); console.log('CPU Usage Information') console.log(process.getCPUUsage()); console.log('-------------------'); console.log('IOCounters Information') console.log(process.getIOCounters()); console.log('-------------------'); console.log('Heap Statistics Information') console.log(process.getHeapStatistics()); console.log('-------------------'); console.log('Blink Memory Information') console.log(process.getBlinkMemoryInfo()); console.log('-------------------'); console.log('System Memory Information') console.log(process.getSystemMemoryInfo()); console.log('-------------------'); console.log('System Versions Information') console.log(process.getSystemVersion()); console.log('-------------------'); console.log('Process Memory Information') process.getProcessMemoryInfo().then(processMemoryInfo => { console.log(processMemoryInfo); }).catch(err => { console.log(err); })});", "e": 30039, "s": 27646, "text": null }, { "code": null, "e": 30528, "s": 30039, "text": "loaded: Event This Instance event is emitted when Electron has loaded its internal initialization script and libraries and is beginning to load the web page or the main script i.e. the main.js file. One important use-case of this Event is that it can be used by the preloaded script to add the Node global symbols which are removed, back to the global scope when node integration is turned off for the electron application such as when defining the BrowserWindow webPreferences property. " }, { "code": null, "e": 30770, "s": 30528, "text": "process.defaultApp: This Instance property is a ReadOnly property. It returns a Boolean value. This property is set during application startup and is passed to the Main Process. If the default app, the value returned is true, else undefined." }, { "code": null, "e": 31093, "s": 30770, "text": "process.isMainFrame: This Instance property is a ReadOnly property. It returns a Boolean value. It returns true when the current renderer context is the main renderer frame. Refer to the output below for a better understanding. If we want the ID of the current frame we should use the webFrame.routingId Instance property." }, { "code": null, "e": 31300, "s": 31093, "text": "process.mas: This Instance property is a ReadOnly property. It returns a Boolean value. For Mac App Store build, this property is set as true. For other operating systems builds it is returned as undefined." }, { "code": null, "e": 31879, "s": 31300, "text": "process.noAsar: This Instance property takes in a Boolean value. This property controls ASAR support inside your application. Setting this to true will disable the support for asar archives in NodeJS built-in modules. Asar is a simple extensive archive format, it works like .tar that concatenates all files together without compression, while having random access support. With this Property is enabled, Electron can read arbitrary files from it without unpacking the whole file. For a detailed Explanation and leveraging ASAR Support, refer https://www.npmjs.com/package/asar." }, { "code": null, "e": 32279, "s": 31879, "text": "process.noDeprecation: This Instance property takes in a Boolean value. This property controls whether or not deprecation warnings are printed to stderr/console. Setting this to true will silence deprecation warnings. This property is used instead of the –no-deprecation command line flag. For a detailed Explanation on command line arguments and switches, Refer Command Line Arguments in ElectronJS" }, { "code": null, "e": 32440, "s": 32279, "text": "process.resourcesPath: This Instance property is a ReadOnly property. It returns a String value. It represents the path to the resources’ directory in Electron." }, { "code": null, "e": 32630, "s": 32440, "text": "process.sandboxed: This Instance property is a ReadOnly property. It returns a Boolean value. This property returns true when the Renderer Process is a sandbox, otherwise returns undefined." }, { "code": null, "e": 33092, "s": 32630, "text": "process.throwDeprecation: This Instance property takes in a Boolean value. This Instance Property controls whether or not deprecation warnings will be thrown as exceptions. Setting this to true will throw errors for deprecations and interrupt the execution of the application. This property is used instead of the –throw-deprecation command line flag. For a detailed Explanation on command line arguments and switches, Refer Command Line Arguments in ElectronJS" }, { "code": null, "e": 33520, "s": 33092, "text": "process.traceDeprecation: This Instance property takes in a Boolean value. This Instance property controls whether or not deprecation warnings are printed to stderr/console with their stack trace. Setting this to true will print stack traces. This property is used instead of the –trace-deprecation command line flag. For a detailed Explanation on command line arguments and switches, Refer Command Line Arguments in ElectronJS" }, { "code": null, "e": 34122, "s": 33520, "text": "process.traceProcessWarnings: This Instance property takes in a Boolean value. This Instance property controls whether or not process warnings are printed to stderr/console with their stack trace. Setting this to true will print stack traces. This property is used instead of the –trace-warnings command line flag. For a detailed Explanation on command line arguments and switches, Refer Command Line Arguments in ElectronJS Note – Setting this Instance Property to true will override the behavior of the process.traceDeprecation since it will print the stack traces of deprecations as well to stderr." }, { "code": null, "e": 34378, "s": 34122, "text": "process.type: This Instance property is a ReadOnly property. It returns a String value representing the current process’s type. It can return the following values:browser: For the Main Process.renderer: For the Renderer Process.worker: For the Web Worker." }, { "code": null, "e": 34409, "s": 34378, "text": "browser: For the Main Process." }, { "code": null, "e": 34445, "s": 34409, "text": "renderer: For the Renderer Process." }, { "code": null, "e": 34473, "s": 34445, "text": "worker: For the Web Worker." }, { "code": null, "e": 34625, "s": 34473, "text": "process.versions.chrome: This Instance property is a ReadOnly property. It returns a String value representing the Chrome’s current version being used." }, { "code": null, "e": 34781, "s": 34625, "text": "process.versions.electron: This Instance property is a ReadOnly property. It returns a String value representing the Electron’s current version being used." }, { "code": null, "e": 35039, "s": 34781, "text": "process.windowsStore: This Instance property is a ReadOnly property. It returns a Boolean value. If the application is running as a Windows Store app (appx) build, this property is set as true. For other operating systems builds it is returned as undefined." }, { "code": null, "e": 35367, "s": 35039, "text": "process.crash(): This Instance method causes the main thread of the current process to crash. This Instance method is extremely useful when testing the application for the production environment to determine how the application behaves in different operating systems in case it crashes. This method does not have a return type." }, { "code": null, "e": 35692, "s": 35367, "text": "process.hang() This Instance method causes the main thread of the current process to hang. This Instance method is extremely useful when testing the application for the production environment to determine how the application behaves in different operating systems in case it crashes. This method does not have a return type." }, { "code": null, "e": 35941, "s": 35692, "text": "process.getCreationTime(): This Instance method returns an integer value which represents the number of milliseconds since epoch. This indicates the creation time of the application. It returns null if it is unable to get the process creation time." }, { "code": null, "e": 36525, "s": 35941, "text": "process.getCPUUsage(): This Instance method returns a CPUUsage object. This object consists of the following parameters. percentCPUUsage: Integer This parameter represents the percentage of CPU used since the last call to this Instance Method. First call always returns 0 and sets up the measurement task.idleWakeupsPerSecond: Integer This Parameter is not Supported in Windows and will always return 0. This parameter returns the number of average idle CPU wakeups per second since the last call to this Instance Method. First call always returns 0 and sets up the measurement task." }, { "code": null, "e": 36710, "s": 36525, "text": "percentCPUUsage: Integer This parameter represents the percentage of CPU used since the last call to this Instance Method. First call always returns 0 and sets up the measurement task." }, { "code": null, "e": 36989, "s": 36710, "text": "idleWakeupsPerSecond: Integer This Parameter is not Supported in Windows and will always return 0. This parameter returns the number of average idle CPU wakeups per second since the last call to this Instance Method. First call always returns 0 and sets up the measurement task." }, { "code": null, "e": 37532, "s": 36989, "text": "process.getIOCounters(): This Instance Method is supported in Windows and Linux only. It returns an IOCounters object. This object consists of the following parameters.readOperationCount: Integer The number of read I/O operations.writeOperationCount: Integer The number of write I/O operations.otherOperationCount: Integer The number of I/O other operations.readTransferCount: Integer The number of I/O read transfers.writeTransferCount: Integer The number of I/O write transfers.otherTransferCount: Integer The number of I/O other transfers." }, { "code": null, "e": 37595, "s": 37532, "text": "readOperationCount: Integer The number of read I/O operations." }, { "code": null, "e": 37660, "s": 37595, "text": "writeOperationCount: Integer The number of write I/O operations." }, { "code": null, "e": 37725, "s": 37660, "text": "otherOperationCount: Integer The number of I/O other operations." }, { "code": null, "e": 37786, "s": 37725, "text": "readTransferCount: Integer The number of I/O read transfers." }, { "code": null, "e": 37849, "s": 37786, "text": "writeTransferCount: Integer The number of I/O write transfers." }, { "code": null, "e": 37912, "s": 37849, "text": "otherTransferCount: Integer The number of I/O other transfers." }, { "code": null, "e": 38628, "s": 37912, "text": "process.getHeapStatistics(): This Instance method returns an object with V8 Heap Statistics, the same which are generated by the .snapshot file when uploaded to the Chrome Dev Tools. This Instance method is important in analyzing code statistics and Memory Leaks within the application. All statistics are reported in Kilobytes. For a detailed Explanation of the V8 Heap Snapshot, refer to the article: Create a V8 Heap Snapshot in ElectronJS. The object consists of the following parameters.totalHeapSize: IntegertotalHeapSizeExecutable: IntegertotalPhysicalSize: IntegertotalAvailableSize: IntegerheapSizeLimit: IntegerusedHeapSize: IntegermallocedMemory: IntegerpeakMallocedMemory: IntegerdoesZapGarbage: Boolean" }, { "code": null, "e": 38651, "s": 38628, "text": "totalHeapSize: Integer" }, { "code": null, "e": 38684, "s": 38651, "text": "totalHeapSizeExecutable: Integer" }, { "code": null, "e": 38711, "s": 38684, "text": "totalPhysicalSize: Integer" }, { "code": null, "e": 38739, "s": 38711, "text": "totalAvailableSize: Integer" }, { "code": null, "e": 38762, "s": 38739, "text": "heapSizeLimit: Integer" }, { "code": null, "e": 38784, "s": 38762, "text": "usedHeapSize: Integer" }, { "code": null, "e": 38808, "s": 38784, "text": "mallocedMemory: Integer" }, { "code": null, "e": 38836, "s": 38808, "text": "peakMallocedMemory: Integer" }, { "code": null, "e": 38860, "s": 38836, "text": "doesZapGarbage: Boolean" }, { "code": null, "e": 39317, "s": 38860, "text": "process.takeHeapSnapshot(filePath): This Instance Method takes a V8 Heap snapshot of the application and saves it to provided filePath String parameter. It behaves exactly in the same way as the webContents.takeHeapSnapshot(filepath) Instance method of the webContents Property of the BrowserWindow object. For a detailed Explanation and understanding of how V8 Heap Snapshot works in ElectronJS, Refer the article: Create a V8 Heap Snapshot in ElectronJS." }, { "code": null, "e": 39710, "s": 39317, "text": "process.getBlinkMemoryInfo(): This Instance method returns an object with Blink Memory Information. It can be useful for debugging rendering, DOM related memory issues. All statistics are reported in Kilobytes. The object consists of the following parameters.allocated: Integer Size of all allocated objects.marked: Integer Size of all marked objects.total: Integer The Total allocated space." }, { "code": null, "e": 39760, "s": 39710, "text": "allocated: Integer Size of all allocated objects." }, { "code": null, "e": 39804, "s": 39760, "text": "marked: Integer Size of all marked objects." }, { "code": null, "e": 39846, "s": 39804, "text": "total: Integer The Total allocated space." }, { "code": null, "e": 40060, "s": 39846, "text": "process.getSystemVersion(): This Instance Method returns a String value representing the current version of the Host OS. Note: This Instance method returns the actual OS version instead of Kernel Version on macOS." }, { "code": null, "e": 40737, "s": 40060, "text": "process.getSystemMemoryInfo(): This Instance Method returns an object giving general memory usage statistics about the entire system where the application is hosted. All statistics are reported in Kilobytes. This object consists of the following parameters.total: Integer The total amount of physical memory available to the system.free: Integer The total amount of memory not being used by applications or disk cache.swapTotal: Integer This Parameter is supported in Windows and Linux only. The total amount of Swap memory available to the system.swapFree: Integer This Parameter is supported in Windows and Linux only. The free amount of Swap memory available to the system." }, { "code": null, "e": 40813, "s": 40737, "text": "total: Integer The total amount of physical memory available to the system." }, { "code": null, "e": 40900, "s": 40813, "text": "free: Integer The total amount of memory not being used by applications or disk cache." }, { "code": null, "e": 41031, "s": 40900, "text": "swapTotal: Integer This Parameter is supported in Windows and Linux only. The total amount of Swap memory available to the system." }, { "code": null, "e": 41160, "s": 41031, "text": "swapFree: Integer This Parameter is supported in Windows and Linux only. The free amount of Swap memory available to the system." }, { "code": null, "e": 41447, "s": 41160, "text": "process.setFdLimit(maxDescriptors): This Instance Method is supported in macOS and Linux only. It sets the file descriptor soft limit or the OS hard limit to the specified maxDescriptors Integer value, whichever is lower for the current process. This method does not have a return type." }, { "code": null, "e": 41456, "s": 41447, "text": "Output: " }, { "code": null, "e": 41467, "s": 41456, "text": "ElectronJS" }, { "code": null, "e": 41478, "s": 41467, "text": "JavaScript" }, { "code": null, "e": 41495, "s": 41478, "text": "Web Technologies" }, { "code": null, "e": 41593, "s": 41495, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41638, "s": 41593, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 41699, "s": 41638, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 41771, "s": 41699, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 41823, "s": 41771, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 41869, "s": 41823, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 41911, "s": 41869, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 41973, "s": 41911, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 42006, "s": 41973, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 42049, "s": 42006, "text": "How to fetch data from an API in ReactJS ?" } ]
How to set the part of the Android text view as clickable in Kotlin?
This example demonstrates how to set the part of the Android text view as clickable in Kotlin. 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"?> <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"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="Tutorials Point" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="32sp" android:textStyle="bold" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textSize="16sp" android:textStyle="bold|italic" /> </RelativeLayout> Step 3 − Add the following code to MainActivity.kt import android.os.Bundle import android.text.SpannableString import android.text.Spanned import android.text.method.LinkMovementMethod import android.text.style.ClickableSpan import android.view.View import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var textView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView = findViewById(R.id.textView) val text = "I want THIS and THIS to be CLICKED" val spannableString = SpannableString(text) val clickableSpan1: ClickableSpan = object : ClickableSpan() { override fun onClick(widget: View?) { Toast.makeText(this@MainActivity, "THIS", Toast.LENGTH_SHORT).show() } } val clickableSpan2: ClickableSpan = object : ClickableSpan() { override fun onClick(widget: View?) { Toast.makeText(this@MainActivity, "THIS", Toast.LENGTH_SHORT).show() } } val clickableSpan3: ClickableSpan = object : ClickableSpan() { override fun onClick(widget: View?) { Toast.makeText(this@MainActivity, "Clicked", Toast.LENGTH_SHORT).show() } } spannableString.setSpan(clickableSpan1, 7, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) spannableString.setSpan(clickableSpan2, 16, 20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) spannableString.setSpan(clickableSpan3, 27, 34, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) textView.setText(spannableString, TextView.BufferType.SPANNABLE) textView.movementMethod = LinkMovementMethod.getInstance() } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.kotlipapp"> <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 the 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": 1157, "s": 1062, "text": "This example demonstrates how to set the part of the Android text view as clickable in Kotlin." }, { "code": null, "e": 1285, "s": 1157, "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": 1350, "s": 1285, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2266, "s": 1350, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold|italic\" />\n</RelativeLayout>" }, { "code": null, "e": 2317, "s": 2266, "text": "Step 3 − Add the following code to MainActivity.kt" }, { "code": null, "e": 4050, "s": 2317, "text": "import android.os.Bundle\nimport android.text.SpannableString\nimport android.text.Spanned\nimport android.text.method.LinkMovementMethod\nimport android.text.style.ClickableSpan\nimport android.view.View\nimport android.widget.TextView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var textView: TextView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n textView = findViewById(R.id.textView)\n val text = \"I want THIS and THIS to be CLICKED\"\n val spannableString = SpannableString(text)\n val clickableSpan1: ClickableSpan = object : ClickableSpan() {\n override fun onClick(widget: View?) {\n Toast.makeText(this@MainActivity, \"THIS\", Toast.LENGTH_SHORT).show()\n }\n }\n val clickableSpan2: ClickableSpan = object : ClickableSpan() {\n override fun onClick(widget: View?) {\n Toast.makeText(this@MainActivity, \"THIS\", Toast.LENGTH_SHORT).show()\n }\n }\n val clickableSpan3: ClickableSpan = object : ClickableSpan() {\n override fun onClick(widget: View?) {\n Toast.makeText(this@MainActivity, \"Clicked\", Toast.LENGTH_SHORT).show()\n }\n }\n spannableString.setSpan(clickableSpan1, 7, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)\n spannableString.setSpan(clickableSpan2, 16, 20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)\n spannableString.setSpan(clickableSpan3, 27, 34, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)\n textView.setText(spannableString, TextView.BufferType.SPANNABLE)\n textView.movementMethod = LinkMovementMethod.getInstance()\n }\n}" }, { "code": null, "e": 4105, "s": 4050, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4781, "s": 4105, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.kotlipapp\">\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": 5132, "s": 4781, "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 the 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": 5173, "s": 5132, "text": "Click here to download the project code." } ]
How to clone a generic list in C#?
A list is a Generic collection to hold elements of same datatypes. To clone a list, you can use the CopyTo method. Declare a list and add elements − List < string > myList = new List < string > (); myList.Add("Programming"); myList.Add("Web Dev"); myList.Add("Database"); Now create a new array and clone the list into it − string[] arr = new string[10]; myList.CopyTo(arr); Here is the complete code − Live Demo using System; using System.Collections.Generic; public class Demo { public static void Main() { List < string > myList = new List < string > (); myList.Add("Programming"); myList.Add("Web Dev"); myList.Add("Database"); Console.WriteLine("First list..."); foreach(string value in myList) { Console.WriteLine(value); } string[] arr = new string[10]; myList.CopyTo(arr); Console.WriteLine("After cloning..."); foreach(string value in arr) { Console.WriteLine(value); } } } First list... Programming Web Dev Database After cloning... Programming Web Dev Database
[ { "code": null, "e": 1129, "s": 1062, "text": "A list is a Generic collection to hold elements of same datatypes." }, { "code": null, "e": 1177, "s": 1129, "text": "To clone a list, you can use the CopyTo method." }, { "code": null, "e": 1211, "s": 1177, "text": "Declare a list and add elements −" }, { "code": null, "e": 1334, "s": 1211, "text": "List < string > myList = new List < string > ();\nmyList.Add(\"Programming\");\nmyList.Add(\"Web Dev\");\nmyList.Add(\"Database\");" }, { "code": null, "e": 1386, "s": 1334, "text": "Now create a new array and clone the list into it −" }, { "code": null, "e": 1437, "s": 1386, "text": "string[] arr = new string[10];\nmyList.CopyTo(arr);" }, { "code": null, "e": 1465, "s": 1437, "text": "Here is the complete code −" }, { "code": null, "e": 1476, "s": 1465, "text": " Live Demo" }, { "code": null, "e": 2045, "s": 1476, "text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n\n List < string > myList = new List < string > ();\n myList.Add(\"Programming\");\n myList.Add(\"Web Dev\");\n myList.Add(\"Database\");\n Console.WriteLine(\"First list...\");\n\n foreach(string value in myList) {\n Console.WriteLine(value);\n }\n string[] arr = new string[10];\n myList.CopyTo(arr);\n Console.WriteLine(\"After cloning...\");\n\n foreach(string value in arr) {\n Console.WriteLine(value);\n }\n }\n}" }, { "code": null, "e": 2134, "s": 2045, "text": "First list...\nProgramming\nWeb Dev\nDatabase\nAfter cloning...\nProgramming\nWeb Dev\nDatabase" } ]
Flexbox - Flex Containers
To use Flexbox in your application, you need to create/define a flex container using the display property. Usage − display: flex | inline-flex This property accepts two values flex − Generates a block level flex container. flex − Generates a block level flex container. inline-flex − Generates an inline flex container box. inline-flex − Generates an inline flex container box. Now, we will see how to use the display property with examples. On passing this value to the display property, a block level flex container will be created. It occupies the full width of the parent container (browser). The following example demonstrates how to create a block level flex container. Here, we are creating six boxes with different colors and we have used the flex container to hold them. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .container{ display:flex; } .box{ font-size:35px; padding:15px; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − Since we have given the value flex to the display property, the container uses the width of the container (browser). You can observe this by adding a border to the container as shown below. .container { display:inline-flex; border:3px solid black; } It will produce the following result − On passing this value to the display property, an inline level flex container will be created. It just takes the place required for the content. The following example demonstrates how to create an inline flex container. Here, we are creating six boxes with different colors and we have used the inline-flex container to hold them. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .container{ display:inline-flex; border:3px solid black; } .box{ font-size:35px; padding:15px; } </style> <body> <div class = "container"> <div class = "box box1">One</div> <div class = "box box2">two</div> <div class = "box box3">three</div> <div class = "box box4">four</div> <div class = "box box5">five</div> <div class = "box box6">six</div> </div> </body> </html> It will produce the following result − Since we have used an inline flex container, it just took the space that is required to wrap its elements. 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 87 Lectures 11 hours Code And Create 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 1918, "s": 1811, "text": "To use Flexbox in your application, you need to create/define a flex container using the display property." }, { "code": null, "e": 1926, "s": 1918, "text": "Usage −" }, { "code": null, "e": 1955, "s": 1926, "text": "display: flex | inline-flex\n" }, { "code": null, "e": 1988, "s": 1955, "text": "This property accepts two values" }, { "code": null, "e": 2035, "s": 1988, "text": "flex − Generates a block level flex container." }, { "code": null, "e": 2082, "s": 2035, "text": "flex − Generates a block level flex container." }, { "code": null, "e": 2136, "s": 2082, "text": "inline-flex − Generates an inline flex container box." }, { "code": null, "e": 2190, "s": 2136, "text": "inline-flex − Generates an inline flex container box." }, { "code": null, "e": 2254, "s": 2190, "text": "Now, we will see how to use the display property with examples." }, { "code": null, "e": 2409, "s": 2254, "text": "On passing this value to the display property, a block level flex container will be created. It occupies the full width of the parent container (browser)." }, { "code": null, "e": 2592, "s": 2409, "text": "The following example demonstrates how to create a block level flex container. Here, we are creating six boxes with different colors and we have used the flex container to hold them." }, { "code": null, "e": 3299, "s": 2592, "text": "<!doctype html>\n<html lang = \"en\">\n <style>\n .box1{background:green;}\n .box2{background:blue;}\n .box3{background:red;}\n .box4{background:magenta;}\n .box5{background:yellow;}\n .box6{background:pink;}\n \n .container{\n display:flex;\n }\n .box{\n font-size:35px;\n padding:15px;\n }\n </style>\n \n <body>\n <div class = \"container\">\n <div class = \"box box1\">One</div>\n <div class = \"box box2\">two</div>\n <div class = \"box box3\">three</div>\n <div class = \"box box4\">four</div>\n <div class = \"box box5\">five</div>\n <div class = \"box box6\">six</div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 3338, "s": 3299, "text": "It will produce the following result −" }, { "code": null, "e": 3455, "s": 3338, "text": "Since we have given the value flex to the display property, the container uses the width of the container (browser)." }, { "code": null, "e": 3528, "s": 3455, "text": "You can observe this by adding a border to the container as shown below." }, { "code": null, "e": 3595, "s": 3528, "text": ".container {\n display:inline-flex;\n border:3px solid black;\n}\n" }, { "code": null, "e": 3634, "s": 3595, "text": "It will produce the following result −" }, { "code": null, "e": 3779, "s": 3634, "text": "On passing this value to the display property, an inline level flex container will be created. It just takes the place required for the content." }, { "code": null, "e": 3965, "s": 3779, "text": "The following example demonstrates how to create an inline flex container. Here, we are creating six boxes with different colors and we have used the inline-flex container to hold them." }, { "code": null, "e": 4712, "s": 3965, "text": "<!doctype html>\n<html lang = \"en\">\n <style>\n .box1{background:green;}\n .box2{background:blue;}\n .box3{background:red;}\n .box4{background:magenta;}\n .box5{background:yellow;}\n .box6{background:pink;}\n \n .container{\n display:inline-flex;\n border:3px solid black;\n }\n .box{\n font-size:35px;\n padding:15px;\n }\n </style>\n \n <body>\n <div class = \"container\">\n <div class = \"box box1\">One</div>\n <div class = \"box box2\">two</div>\n <div class = \"box box3\">three</div>\n <div class = \"box box4\">four</div>\n <div class = \"box box5\">five</div>\n <div class = \"box box6\">six</div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 4751, "s": 4712, "text": "It will produce the following result −" }, { "code": null, "e": 4858, "s": 4751, "text": "Since we have used an inline flex container, it just took the space that is required to wrap its elements." }, { "code": null, "e": 4893, "s": 4858, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4924, "s": 4893, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4958, "s": 4924, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 4975, "s": 4958, "text": " Code And Create" }, { "code": null, "e": 5012, "s": 4975, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 5028, "s": 5012, "text": " Muslim Helalee" }, { "code": null, "e": 5035, "s": 5028, "text": " Print" }, { "code": null, "e": 5046, "s": 5035, "text": " Add Notes" } ]
Rorschach Tests for Deep Learning Image Classifiers | by Mathieu Lemay | Towards Data Science
What do they see, when there is nothing to see? With a lot of exploration in image classification and labeling, we tend to play with various libraries to quickly assess and label pictures. But other than memory use and ease of retraining layers, how do they behave when presented with unclear, grainy pictures? In order to get a better feel for the nuances and trends of each ConvNet at a practical level, I ran the most popular ones, in series, on all of the cards from the Rorschach Test. The goal was simple: set my expectations and clear up my understanding for each one, so I can use the right tool for the job moving forward. Invented (or more accurately, modified) by Hermann Rorschach, the Rorschach Test is the most famous of the inkblot tests. An inkblot test is a simple conversation starter with your therapist, that goes “What do you see?” after being shown an intentionally abstract (and usually symmetrical) drop of ink squeezed in a sheet of paper. Rorschach took it one step further, and created a standard set. This standard set could now we used between patients and therapists. The goal of this test is to evoke a subconscious reaction to the abstract art, overlaying it with your own biases and deepest thoughts, so that whatever you see first is what you’re thinking about. Although it has fallen out of favor in the last few years (“pseudo-science” has been used to describe it), it’s still a very useful trope to describe the field of psychology. In this case, I’ve used it to force various libraries to classify this innocuous dataset into pre-defined labels. In order to classify the pictures, I looked at the following libraries: ResNet50 VGG16 VGG19 InceptionV3 InceptionResNetV2 Xception MobileNet MobileNetV2 DenseNet NASNet (These are all of the native application libraries available with Keras 2.2.0.) Each one of these classifiers has a particular structure and weights associated with it. Besides for the memory usage and trainable parameters, there is a lot of differences in the details of the implementation of each one. Instead of digging in the particularities of each structure, let’s look at how they view the same confusing data. (If you want to learn more about each structure individually, here are the links if you want to learn more about ResNet, Inception, DenseNet, NASNet, VGG16/19, and MobileNet.) Overall, the goal is to get a quick sense of the prediction and intensity of the belief behind the prediction. In order to do this, I’ve grouped the Top-1 predictions by name, and added their score together. This gives a sense of how much each classifier is ready to gamble on a particular card. Doing this for each label gives us a good proxy for the belief of each classifier, and gives us a sense of their relative prediction confidence for each card. As an example, InceptionResNetV2, NASNetLarge, and DensetNet201 believed that Card 1 was a warplane (with scores of 88.3%, 46.2%, 18.6%, respectively). I’ve then added it up to a dimensionless score of 153.1. Now, I can compare this score in between the classifiers to see which one performs the best. Card 1:warplane 153.05wall_clock 75.41letter_opener 47.29lampshade 33.13buckeye 28.95jigsaw_puzzle 23.19paper_towel 22.51birdhouse 11.50Card 2:cock 72.84 # <--- Rooster. They mean rooster.lampshade 59.99brassiere 59.47velvet 43.84earthstar 41.42mask 29.46candle 21.84tray 19.30wall_clock 18.41hair_slide 17.84vase 11.44Card 3:book_jacket 325.35 # <--- No idea what's going on here.coffee_mug 62.61chocolate_sauce 45.00candle 32.68ant 25.81matchstick 24.02jersey 16.94 Cards 4 through 7 elicit a bit more smoke, spaceship, and bugs for me. Which brings me back to my rural childhood, and playing with the best LEGO sets of all time. (For which I obviously mean M-Tron, the evil BlackTron, and Ice Planet.) Card 4:volcano 101.76fountain 72.11space_shuttle 32.72hen-of-the-woods 29.40pitcher 28.28vase 25.00king_crab 23.99wall_clock 18.25triumphal_arch 11.04Card 5: # <--- Bugs. Definitely bugs.isopod 106.54king_crab 83.67ant 61.58long-horned_beetle 32.23tick 30.05hip 26.32rhinoceros_beetle 14.52Card 6:space_shuttle 174.48warplane 155.58conch 104.73missile 63.71airship 57.73fountain 11.57Card 7:missile 195.66parachute 52.52projectile 42.31space_shuttle 31.18hip 29.89geyser 20.92warplane 17.50 Card 8:fountain 189.59parachute 98.27umbrella 94.61pencil_sharpener 63.27spoonbill 51.08poncho 45.19coral_fungus 12.05shovel 10.12Card 9:missile 238.45fountain 64.82parachute 48.21volcano 44.77paper_towel 41.59lampshade 13.48Card 10:tray 229.22handkerchief 151.63conch 77.94feather_boa 60.34rapeseed 15.95 Of course, we can go a lot deeper to see the average confidence of each one of the predictions. Below is some sample data for Card 1. All of the results are available on the project’s GitHub page. In order to label each picture, we start off by loading Pandas, NumPy, and the Keras image pre-processing libraries: from keras.preprocessing import imagefrom keras.preprocessing.image import load_imgfrom keras.preprocessing.image import img_to_arrayfrom keras.models import Modelimport keras.backend as Kimport numpy as npimport pandas as pdimport json We then create a helper function to return a dataframe containing the score of the top 10 results for each library, in order to quickly assemble each one of the images’ score: def getLabels(model, dims, pi, dp):"""Returns the top 10 labels, given a model, image dimensions, preprocess_input() function, and the labels inside decode_predictions()."""df = pd.DataFrame() for img_path in images:# Resize image array image = load_img(img_path, target_size=(dims, dims)) image = img_to_array(image) image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2])) image = pi(image) # Predict what is in the image yhat = model.predict(image) # return the top 10 labels labels = dp(yhat, top=10)[0]# create empty list and counter labellist = [] counter = 0 # get labels for each image for label in labels: # Display the score of the label print('%s (%.2f%%)' % (label[1], label[2]*100)) # Add image results to list labellist.append( {"labelnumber":counter, "labelname" :label[1], "pct" :'%.2f%%' % (label[2]*100), "image" :img_path}) counter = counter + 1 # Add to dataframe df_row = pd.Series() df_row = pd.read_json(json.dumps(labellist), typ='frame', orient='records') df = df.append(df_row,ignore_index=True) print("------------") return df Now, we have a method for evaluating each library very quickly. # ...# ResNet50 Rorschach assessmentfrom keras.applications.resnet50 import ResNet50from keras.applications.resnet50 import preprocess_inputfrom keras.applications.resnet50 import decode_predictionsmodel = ResNet50()df = getLabels(model, 224, preprocess_input, decode_predictions)df.to_csv('results_resnet50.csv', index=False)# ----------# VGG16 Rorschach assessmentfrom keras.applications.vgg16 import VGG16from keras.applications.vgg16 import preprocess_inputfrom keras.applications.vgg16 import decode_predictionsmodel = VGG16()df = getLabels(model, 224, preprocess_input, decode_predictions)df.to_csv('results_vgg16.csv', index=False)# ... ...and so forth. What’s fun about this approach is that it makes for a very functional notebook when playing with different images sets: This notebook structure allows you to quickly explore the different data sets, and see what’s the best classifiers for your product or project. Are you looking for a reliable top-1 accuracy on a fuzzy picture? What about identifying all of the different contents of a picture? your mileage may vary, but you can now start exploring on your own. You can get the full code here. [email protected] Lemay.ai1 (855) LEMAY-AI Other articles you may enjoy: Hubris, laziness and playing with toys: the winning attitudes of a startup engineer AI Prototypes for Clients as a Marketing Strategy Other articles you may enjoy from Daniel Shapiro, my CTO: Artificial Intelligence and Bad Data Artificial Intelligence: Hyperparameters Artificial Intelligence: Get your users to label your data P.S. It’s pronounced roar-shawk.
[ { "code": null, "e": 220, "s": 172, "text": "What do they see, when there is nothing to see?" }, { "code": null, "e": 483, "s": 220, "text": "With a lot of exploration in image classification and labeling, we tend to play with various libraries to quickly assess and label pictures. But other than memory use and ease of retraining layers, how do they behave when presented with unclear, grainy pictures?" }, { "code": null, "e": 663, "s": 483, "text": "In order to get a better feel for the nuances and trends of each ConvNet at a practical level, I ran the most popular ones, in series, on all of the cards from the Rorschach Test." }, { "code": null, "e": 804, "s": 663, "text": "The goal was simple: set my expectations and clear up my understanding for each one, so I can use the right tool for the job moving forward." }, { "code": null, "e": 1270, "s": 804, "text": "Invented (or more accurately, modified) by Hermann Rorschach, the Rorschach Test is the most famous of the inkblot tests. An inkblot test is a simple conversation starter with your therapist, that goes “What do you see?” after being shown an intentionally abstract (and usually symmetrical) drop of ink squeezed in a sheet of paper. Rorschach took it one step further, and created a standard set. This standard set could now we used between patients and therapists." }, { "code": null, "e": 1643, "s": 1270, "text": "The goal of this test is to evoke a subconscious reaction to the abstract art, overlaying it with your own biases and deepest thoughts, so that whatever you see first is what you’re thinking about. Although it has fallen out of favor in the last few years (“pseudo-science” has been used to describe it), it’s still a very useful trope to describe the field of psychology." }, { "code": null, "e": 1757, "s": 1643, "text": "In this case, I’ve used it to force various libraries to classify this innocuous dataset into pre-defined labels." }, { "code": null, "e": 1829, "s": 1757, "text": "In order to classify the pictures, I looked at the following libraries:" }, { "code": null, "e": 1838, "s": 1829, "text": "ResNet50" }, { "code": null, "e": 1844, "s": 1838, "text": "VGG16" }, { "code": null, "e": 1850, "s": 1844, "text": "VGG19" }, { "code": null, "e": 1862, "s": 1850, "text": "InceptionV3" }, { "code": null, "e": 1880, "s": 1862, "text": "InceptionResNetV2" }, { "code": null, "e": 1889, "s": 1880, "text": "Xception" }, { "code": null, "e": 1899, "s": 1889, "text": "MobileNet" }, { "code": null, "e": 1911, "s": 1899, "text": "MobileNetV2" }, { "code": null, "e": 1920, "s": 1911, "text": "DenseNet" }, { "code": null, "e": 1927, "s": 1920, "text": "NASNet" }, { "code": null, "e": 2007, "s": 1927, "text": "(These are all of the native application libraries available with Keras 2.2.0.)" }, { "code": null, "e": 2096, "s": 2007, "text": "Each one of these classifiers has a particular structure and weights associated with it." }, { "code": null, "e": 2345, "s": 2096, "text": "Besides for the memory usage and trainable parameters, there is a lot of differences in the details of the implementation of each one. Instead of digging in the particularities of each structure, let’s look at how they view the same confusing data." }, { "code": null, "e": 2521, "s": 2345, "text": "(If you want to learn more about each structure individually, here are the links if you want to learn more about ResNet, Inception, DenseNet, NASNet, VGG16/19, and MobileNet.)" }, { "code": null, "e": 2976, "s": 2521, "text": "Overall, the goal is to get a quick sense of the prediction and intensity of the belief behind the prediction. In order to do this, I’ve grouped the Top-1 predictions by name, and added their score together. This gives a sense of how much each classifier is ready to gamble on a particular card. Doing this for each label gives us a good proxy for the belief of each classifier, and gives us a sense of their relative prediction confidence for each card." }, { "code": null, "e": 3278, "s": 2976, "text": "As an example, InceptionResNetV2, NASNetLarge, and DensetNet201 believed that Card 1 was a warplane (with scores of 88.3%, 46.2%, 18.6%, respectively). I’ve then added it up to a dimensionless score of 153.1. Now, I can compare this score in between the classifiers to see which one performs the best." }, { "code": null, "e": 3755, "s": 3278, "text": "Card 1:warplane 153.05wall_clock 75.41letter_opener 47.29lampshade 33.13buckeye 28.95jigsaw_puzzle 23.19paper_towel 22.51birdhouse 11.50Card 2:cock 72.84 # <--- Rooster. They mean rooster.lampshade 59.99brassiere 59.47velvet 43.84earthstar 41.42mask 29.46candle 21.84tray 19.30wall_clock 18.41hair_slide 17.84vase 11.44Card 3:book_jacket 325.35 # <--- No idea what's going on here.coffee_mug 62.61chocolate_sauce 45.00candle 32.68ant 25.81matchstick 24.02jersey 16.94" }, { "code": null, "e": 3992, "s": 3755, "text": "Cards 4 through 7 elicit a bit more smoke, spaceship, and bugs for me. Which brings me back to my rural childhood, and playing with the best LEGO sets of all time. (For which I obviously mean M-Tron, the evil BlackTron, and Ice Planet.)" }, { "code": null, "e": 4494, "s": 3992, "text": "Card 4:volcano 101.76fountain 72.11space_shuttle 32.72hen-of-the-woods 29.40pitcher 28.28vase 25.00king_crab 23.99wall_clock 18.25triumphal_arch 11.04Card 5: # <--- Bugs. Definitely bugs.isopod 106.54king_crab 83.67ant 61.58long-horned_beetle 32.23tick 30.05hip 26.32rhinoceros_beetle 14.52Card 6:space_shuttle 174.48warplane 155.58conch 104.73missile 63.71airship 57.73fountain 11.57Card 7:missile 195.66parachute 52.52projectile 42.31space_shuttle 31.18hip 29.89geyser 20.92warplane 17.50" }, { "code": null, "e": 4800, "s": 4494, "text": "Card 8:fountain 189.59parachute 98.27umbrella 94.61pencil_sharpener 63.27spoonbill 51.08poncho 45.19coral_fungus 12.05shovel 10.12Card 9:missile 238.45fountain 64.82parachute 48.21volcano 44.77paper_towel 41.59lampshade 13.48Card 10:tray 229.22handkerchief 151.63conch 77.94feather_boa 60.34rapeseed 15.95" }, { "code": null, "e": 4997, "s": 4800, "text": "Of course, we can go a lot deeper to see the average confidence of each one of the predictions. Below is some sample data for Card 1. All of the results are available on the project’s GitHub page." }, { "code": null, "e": 5114, "s": 4997, "text": "In order to label each picture, we start off by loading Pandas, NumPy, and the Keras image pre-processing libraries:" }, { "code": null, "e": 5351, "s": 5114, "text": "from keras.preprocessing import imagefrom keras.preprocessing.image import load_imgfrom keras.preprocessing.image import img_to_arrayfrom keras.models import Modelimport keras.backend as Kimport numpy as npimport pandas as pdimport json" }, { "code": null, "e": 5527, "s": 5351, "text": "We then create a helper function to return a dataframe containing the score of the top 10 results for each library, in order to quickly assemble each one of the images’ score:" }, { "code": null, "e": 6914, "s": 5527, "text": "def getLabels(model, dims, pi, dp):\"\"\"Returns the top 10 labels, given a model, image dimensions, preprocess_input() function, and the labels inside decode_predictions().\"\"\"df = pd.DataFrame() for img_path in images:# Resize image array image = load_img(img_path, target_size=(dims, dims)) image = img_to_array(image) image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2])) image = pi(image) # Predict what is in the image yhat = model.predict(image) # return the top 10 labels labels = dp(yhat, top=10)[0]# create empty list and counter labellist = [] counter = 0 # get labels for each image for label in labels: # Display the score of the label print('%s (%.2f%%)' % (label[1], label[2]*100)) # Add image results to list labellist.append( {\"labelnumber\":counter, \"labelname\" :label[1], \"pct\" :'%.2f%%' % (label[2]*100), \"image\" :img_path}) counter = counter + 1 # Add to dataframe df_row = pd.Series() df_row = pd.read_json(json.dumps(labellist), typ='frame', orient='records') df = df.append(df_row,ignore_index=True) print(\"------------\") return df" }, { "code": null, "e": 6978, "s": 6914, "text": "Now, we have a method for evaluating each library very quickly." }, { "code": null, "e": 7622, "s": 6978, "text": "# ...# ResNet50 Rorschach assessmentfrom keras.applications.resnet50 import ResNet50from keras.applications.resnet50 import preprocess_inputfrom keras.applications.resnet50 import decode_predictionsmodel = ResNet50()df = getLabels(model, 224, preprocess_input, decode_predictions)df.to_csv('results_resnet50.csv', index=False)# ----------# VGG16 Rorschach assessmentfrom keras.applications.vgg16 import VGG16from keras.applications.vgg16 import preprocess_inputfrom keras.applications.vgg16 import decode_predictionsmodel = VGG16()df = getLabels(model, 224, preprocess_input, decode_predictions)df.to_csv('results_vgg16.csv', index=False)# ..." }, { "code": null, "e": 7639, "s": 7622, "text": "...and so forth." }, { "code": null, "e": 7759, "s": 7639, "text": "What’s fun about this approach is that it makes for a very functional notebook when playing with different images sets:" }, { "code": null, "e": 8104, "s": 7759, "text": "This notebook structure allows you to quickly explore the different data sets, and see what’s the best classifiers for your product or project. Are you looking for a reliable top-1 accuracy on a fuzzy picture? What about identifying all of the different contents of a picture? your mileage may vary, but you can now start exploring on your own." }, { "code": null, "e": 8136, "s": 8104, "text": "You can get the full code here." }, { "code": null, "e": 8156, "s": 8136, "text": "[email protected]" }, { "code": null, "e": 8181, "s": 8156, "text": "Lemay.ai1 (855) LEMAY-AI" }, { "code": null, "e": 8211, "s": 8181, "text": "Other articles you may enjoy:" }, { "code": null, "e": 8295, "s": 8211, "text": "Hubris, laziness and playing with toys: the winning attitudes of a startup engineer" }, { "code": null, "e": 8345, "s": 8295, "text": "AI Prototypes for Clients as a Marketing Strategy" }, { "code": null, "e": 8403, "s": 8345, "text": "Other articles you may enjoy from Daniel Shapiro, my CTO:" }, { "code": null, "e": 8440, "s": 8403, "text": "Artificial Intelligence and Bad Data" }, { "code": null, "e": 8481, "s": 8440, "text": "Artificial Intelligence: Hyperparameters" }, { "code": null, "e": 8540, "s": 8481, "text": "Artificial Intelligence: Get your users to label your data" } ]
BIRCH Clustering Algorithm Example In Python | by Cory Maklin | Towards Data Science
Existing data clustering methods do not adequately address the problem of processing large datasets with a limited amount of resources (i.e. memory and cpu cycles). In consequence, as the dataset size increases, they scale poorly in terms of running time, and result quality. At a high level, Balanced Iterative Reducing and Clustering using Hierarchies, or BIRCH for short, deals with large datasets by first generating a more compact summary that retains as much distribution information as possible, and then clustering the data summary instead of the original dataset. BIRCH actually complements other clustering algorithms by virtue if the fact that different clustering algorithms can be applied to the summary produced by BIRCH. BIRCH can only deal with metric attributes (similar to the kind of features KMEANS can handle). A metric attribute is one whose values can be represented by explicit coordinates in an Euclidean space (no categorical variables). BIRCH attempts to minimize the memory requirements of large datasets by summarizing the information contained in dense regions as Clustering Feature (CF) entries. As we’re about to see, it’s possible to have CFs composed of other CFs. In this case, the subcluster is equal to the sum of the CFs. The CF-tree is a very compact representation of the dataset because each entry in a leaf node is not a single data point but a subcluster. Each nonleaf node contains at most B entries. In this context, a single entry contains a pointer to a child node and a CF made up of the sum of the CFs in the child (subclusters of subclusters). On the other hand, a leaf node contains at most L entries, and each entry is a CF (subclusters of data points). All entries in a leaf node must satisfy a threshold requirement. That is to say, the diameter of each leaf entry has to be less than Threshold. In addition, every leaf node has two pointers, prev and next, which are used to chain all leaf nodes together for efficient scans. Let’s describe how we’d go about inserting a CF entry (a single data point or subcluster) into a CF-tree. Identify the appropriate leaf: Starting from the root, recursively descend the DF-tree by choosing the closest child node according to the chosen distance metric (i.e. euclidean distance).Modify the leaf: Upon reaching a leaf node, find the closest entry and test whether it can absorb the CF entry without violating the threshold condition. If it can, update the CF entry, otherwise, add a new CF entry to the leaf. If there isn’t enough space on the leaf for this new entry to fit in, then we must split the leaf node. Node splitting is done by choosing the two entries that are farthest apart as seeds and redistributing the remaining entries based on distance.Modify the path to the leaf: Recall how every nonleaf node is itself a CF composed of the CFs of all its children. Therefore, after inserting a CF entry into a leaf, we update the CF information for each nonleaf entry on the path to the leaf. In the event of a split, we must insert a new nonleaf entry into the parent node and have it point to the newly formed leaf. If according to B, the parent doesn’t have enough room, then we must split the parent as well, and so on up to the root. Identify the appropriate leaf: Starting from the root, recursively descend the DF-tree by choosing the closest child node according to the chosen distance metric (i.e. euclidean distance). Modify the leaf: Upon reaching a leaf node, find the closest entry and test whether it can absorb the CF entry without violating the threshold condition. If it can, update the CF entry, otherwise, add a new CF entry to the leaf. If there isn’t enough space on the leaf for this new entry to fit in, then we must split the leaf node. Node splitting is done by choosing the two entries that are farthest apart as seeds and redistributing the remaining entries based on distance. Modify the path to the leaf: Recall how every nonleaf node is itself a CF composed of the CFs of all its children. Therefore, after inserting a CF entry into a leaf, we update the CF information for each nonleaf entry on the path to the leaf. In the event of a split, we must insert a new nonleaf entry into the parent node and have it point to the newly formed leaf. If according to B, the parent doesn’t have enough room, then we must split the parent as well, and so on up to the root. Now that we’ve covered some of the concepts underlying BIRCH, let’s walk through how the algorithm works. The algorithm starts with an initial threshold value, scans the data, and inserts points into the tree. If it runs out of memory before it finishes scanning the data, it increases the threshold value, and rebuilds a new, smaller CF-tree, by re-inserting the leaf entries of the old CF-tree into the new CF-tree. After all the old leaf entries have been re-inserted, the scanning of the data and insertion into the new CF-tree is resumed from the point at which it was interrupted. A good choice of threshold value can greatly reduce the number of rebuilds. However, if the initial threshold is too high, we will obtain a less detailed CF-tree than is feasible with the available memory. Optionally, we can allocate a fixed amount of disk space for handling outliers. Outliers are leaf entries of low density that are judged to be unimportant with respect to the overall clustering pattern. When we rebuild the CF-tree by reinserting the old leaf entries, the size of the new CF-tree is reduced in two ways. First, we increase the threshold value, thereby allowing each leaf entry to absorb more points. Second, we treat some leaf entries as potential outliers and write them out to disk. An old leaf entry is considered a potential outlier if it has far fewer data points than average. An increase in the threshold value or a change in the distribution in response to the new data could well mean that the potential outlier no longer qualifies as an outlier. In consequence, the potential outliers are scanned to check if they can be re-absorbed in the tree without causing the tree to grow in size. Given that certain clustering algorithms perform best when the number of objects is within a certain range, we can group crowded subclusters into larger ones resulting in an overall smaller CF-tree. Almost any clustering algorithm can be adapted to categorize Clustering Features instead of data points. For instance, we could use KMEANS to categorize our data, all the while deriving the benefits from BIRCH (i.e. minimize I/O operations). Up until now, although the tree may have been rebuilt multiple times, the original data has only been scanned once. Phase 4 involves additional passes over the data to correct inaccuracies caused by the fact that the clustering algorithm is applied to a coarse summary of the data. Phase 4 also provides us with the option of discarding outliers. Next, we’ll implement BIRCH in Python. import numpy as npfrom matplotlib import pyplot as pltimport seaborn as snssns.set()from sklearn.datasets.samples_generator import make_blobsfrom sklearn.cluster import Birch We use scikit-learn to generate data with nicely defined clusters. X, clusters = make_blobs(n_samples=450, centers=6, cluster_std=0.70, random_state=0)plt.scatter(X[:,0], X[:,1], alpha=0.7, edgecolors='b') Next, we initialize and train our model, using the following parameters: threshold: The radius of the subcluster obtained by merging a new sample and the closest subcluster should be lesser than the threshold. branching_factor: Maximum number of CF subclusters in each node n_clusters: Number of clusters after the final clustering step, which treats the subclusters from the leaves as new samples. If set to None, the final clustering step is not performed and the subclusters are returned as they are. brc = Birch(branching_factor=50, n_clusters=None, threshold=1.5)brc.fit(X) We use the predict method to obtain a list of points and their respective cluster. labels = brc.predict(X) Finally, we plot the data points using a different color for each cluster. plt.scatter(X[:,0], X[:,1], c=labels, cmap='rainbow', alpha=0.7, edgecolors='b') BIRCH provides a clustering method for very large datasets. It makes a large clustering problem plausible by concentrating on densely occupied regions, and creating a compact summary. BIRCH can work with any given amount of memory, and the I/O complexity is a little more than one scan of data. Other clustering algorithms can be applied to the subclusters produced by BIRCH.
[ { "code": null, "e": 1135, "s": 171, "text": "Existing data clustering methods do not adequately address the problem of processing large datasets with a limited amount of resources (i.e. memory and cpu cycles). In consequence, as the dataset size increases, they scale poorly in terms of running time, and result quality. At a high level, Balanced Iterative Reducing and Clustering using Hierarchies, or BIRCH for short, deals with large datasets by first generating a more compact summary that retains as much distribution information as possible, and then clustering the data summary instead of the original dataset. BIRCH actually complements other clustering algorithms by virtue if the fact that different clustering algorithms can be applied to the summary produced by BIRCH. BIRCH can only deal with metric attributes (similar to the kind of features KMEANS can handle). A metric attribute is one whose values can be represented by explicit coordinates in an Euclidean space (no categorical variables)." }, { "code": null, "e": 1298, "s": 1135, "text": "BIRCH attempts to minimize the memory requirements of large datasets by summarizing the information contained in dense regions as Clustering Feature (CF) entries." }, { "code": null, "e": 1431, "s": 1298, "text": "As we’re about to see, it’s possible to have CFs composed of other CFs. In this case, the subcluster is equal to the sum of the CFs." }, { "code": null, "e": 2152, "s": 1431, "text": "The CF-tree is a very compact representation of the dataset because each entry in a leaf node is not a single data point but a subcluster. Each nonleaf node contains at most B entries. In this context, a single entry contains a pointer to a child node and a CF made up of the sum of the CFs in the child (subclusters of subclusters). On the other hand, a leaf node contains at most L entries, and each entry is a CF (subclusters of data points). All entries in a leaf node must satisfy a threshold requirement. That is to say, the diameter of each leaf entry has to be less than Threshold. In addition, every leaf node has two pointers, prev and next, which are used to chain all leaf nodes together for efficient scans." }, { "code": null, "e": 2258, "s": 2152, "text": "Let’s describe how we’d go about inserting a CF entry (a single data point or subcluster) into a CF-tree." }, { "code": null, "e": 3411, "s": 2258, "text": "Identify the appropriate leaf: Starting from the root, recursively descend the DF-tree by choosing the closest child node according to the chosen distance metric (i.e. euclidean distance).Modify the leaf: Upon reaching a leaf node, find the closest entry and test whether it can absorb the CF entry without violating the threshold condition. If it can, update the CF entry, otherwise, add a new CF entry to the leaf. If there isn’t enough space on the leaf for this new entry to fit in, then we must split the leaf node. Node splitting is done by choosing the two entries that are farthest apart as seeds and redistributing the remaining entries based on distance.Modify the path to the leaf: Recall how every nonleaf node is itself a CF composed of the CFs of all its children. Therefore, after inserting a CF entry into a leaf, we update the CF information for each nonleaf entry on the path to the leaf. In the event of a split, we must insert a new nonleaf entry into the parent node and have it point to the newly formed leaf. If according to B, the parent doesn’t have enough room, then we must split the parent as well, and so on up to the root." }, { "code": null, "e": 3600, "s": 3411, "text": "Identify the appropriate leaf: Starting from the root, recursively descend the DF-tree by choosing the closest child node according to the chosen distance metric (i.e. euclidean distance)." }, { "code": null, "e": 4077, "s": 3600, "text": "Modify the leaf: Upon reaching a leaf node, find the closest entry and test whether it can absorb the CF entry without violating the threshold condition. If it can, update the CF entry, otherwise, add a new CF entry to the leaf. If there isn’t enough space on the leaf for this new entry to fit in, then we must split the leaf node. Node splitting is done by choosing the two entries that are farthest apart as seeds and redistributing the remaining entries based on distance." }, { "code": null, "e": 4566, "s": 4077, "text": "Modify the path to the leaf: Recall how every nonleaf node is itself a CF composed of the CFs of all its children. Therefore, after inserting a CF entry into a leaf, we update the CF information for each nonleaf entry on the path to the leaf. In the event of a split, we must insert a new nonleaf entry into the parent node and have it point to the newly formed leaf. If according to B, the parent doesn’t have enough room, then we must split the parent as well, and so on up to the root." }, { "code": null, "e": 4672, "s": 4566, "text": "Now that we’ve covered some of the concepts underlying BIRCH, let’s walk through how the algorithm works." }, { "code": null, "e": 5153, "s": 4672, "text": "The algorithm starts with an initial threshold value, scans the data, and inserts points into the tree. If it runs out of memory before it finishes scanning the data, it increases the threshold value, and rebuilds a new, smaller CF-tree, by re-inserting the leaf entries of the old CF-tree into the new CF-tree. After all the old leaf entries have been re-inserted, the scanning of the data and insertion into the new CF-tree is resumed from the point at which it was interrupted." }, { "code": null, "e": 5359, "s": 5153, "text": "A good choice of threshold value can greatly reduce the number of rebuilds. However, if the initial threshold is too high, we will obtain a less detailed CF-tree than is feasible with the available memory." }, { "code": null, "e": 6272, "s": 5359, "text": "Optionally, we can allocate a fixed amount of disk space for handling outliers. Outliers are leaf entries of low density that are judged to be unimportant with respect to the overall clustering pattern. When we rebuild the CF-tree by reinserting the old leaf entries, the size of the new CF-tree is reduced in two ways. First, we increase the threshold value, thereby allowing each leaf entry to absorb more points. Second, we treat some leaf entries as potential outliers and write them out to disk. An old leaf entry is considered a potential outlier if it has far fewer data points than average. An increase in the threshold value or a change in the distribution in response to the new data could well mean that the potential outlier no longer qualifies as an outlier. In consequence, the potential outliers are scanned to check if they can be re-absorbed in the tree without causing the tree to grow in size." }, { "code": null, "e": 6471, "s": 6272, "text": "Given that certain clustering algorithms perform best when the number of objects is within a certain range, we can group crowded subclusters into larger ones resulting in an overall smaller CF-tree." }, { "code": null, "e": 6713, "s": 6471, "text": "Almost any clustering algorithm can be adapted to categorize Clustering Features instead of data points. For instance, we could use KMEANS to categorize our data, all the while deriving the benefits from BIRCH (i.e. minimize I/O operations)." }, { "code": null, "e": 7060, "s": 6713, "text": "Up until now, although the tree may have been rebuilt multiple times, the original data has only been scanned once. Phase 4 involves additional passes over the data to correct inaccuracies caused by the fact that the clustering algorithm is applied to a coarse summary of the data. Phase 4 also provides us with the option of discarding outliers." }, { "code": null, "e": 7099, "s": 7060, "text": "Next, we’ll implement BIRCH in Python." }, { "code": null, "e": 7274, "s": 7099, "text": "import numpy as npfrom matplotlib import pyplot as pltimport seaborn as snssns.set()from sklearn.datasets.samples_generator import make_blobsfrom sklearn.cluster import Birch" }, { "code": null, "e": 7341, "s": 7274, "text": "We use scikit-learn to generate data with nicely defined clusters." }, { "code": null, "e": 7480, "s": 7341, "text": "X, clusters = make_blobs(n_samples=450, centers=6, cluster_std=0.70, random_state=0)plt.scatter(X[:,0], X[:,1], alpha=0.7, edgecolors='b')" }, { "code": null, "e": 7553, "s": 7480, "text": "Next, we initialize and train our model, using the following parameters:" }, { "code": null, "e": 7690, "s": 7553, "text": "threshold: The radius of the subcluster obtained by merging a new sample and the closest subcluster should be lesser than the threshold." }, { "code": null, "e": 7754, "s": 7690, "text": "branching_factor: Maximum number of CF subclusters in each node" }, { "code": null, "e": 7984, "s": 7754, "text": "n_clusters: Number of clusters after the final clustering step, which treats the subclusters from the leaves as new samples. If set to None, the final clustering step is not performed and the subclusters are returned as they are." }, { "code": null, "e": 8059, "s": 7984, "text": "brc = Birch(branching_factor=50, n_clusters=None, threshold=1.5)brc.fit(X)" }, { "code": null, "e": 8142, "s": 8059, "text": "We use the predict method to obtain a list of points and their respective cluster." }, { "code": null, "e": 8166, "s": 8142, "text": "labels = brc.predict(X)" }, { "code": null, "e": 8241, "s": 8166, "text": "Finally, we plot the data points using a different color for each cluster." }, { "code": null, "e": 8322, "s": 8241, "text": "plt.scatter(X[:,0], X[:,1], c=labels, cmap='rainbow', alpha=0.7, edgecolors='b')" } ]
Predicting Forest Cover Types with the Machine Learning Workflow | by Ceren Iyim | Towards Data Science
In this article, I will explain how to approach a multi-class classification supervised machine learning (ML) problem (or project) with an end-to-end workflow. Supervised: Features (variables to generate predictions) and target (the variable to be determined) are available in the data set. Multi-class classification: There are seven discrete categories to distinguish the target. Project is based on a famous data set in the machine learning community and known as Forest Cover Type available for download in the UCI Machine Learning Repository. A stratified sample from the original data set to apply the workflow and separate test set to generate final predictions is used as part of a beginner-friendly competition in Kaggle. The goal of the Project (and competition): to predict seven different cover types in four different wilderness areas of the Roosevelt National Forest of Northern Colorado with the best accuracy. Four wilderness areas are: 1: Rawah 2: Neota 3: Comanche Peak 4: Cache la Poudre Seven categories numbered from 1 to 7 in the Cover_Type column, to be classified: 1: Spruce/Fir 2: Lodgepole Pine 3: Ponderosa Pine 4: Cottonwood/Willow 5: Aspen 6: Douglas-fir 7: Krummholz The names of the target (cover type) reminded me of the Fantastic Beasts, so I called them fantastic trees to add some imagination to the project 🙃. End-to-end Machine Learning Workflow Steps: to classify cover types and reply to the initiating question, where to find fantastic trees and how to detect them, the below steps will be followed: Understand, Clean and Format DataExploratory Data AnalysisFeature Engineering & SelectionCompare Several Machine Learning ModelsPerform Hyperparameter Tuning on the Best ModelInterpret Model ResultsEvaluate the Best Model with Test Data (replying the initiating question)Summary & Conclusions Understand, Clean and Format Data Exploratory Data Analysis Feature Engineering & Selection Compare Several Machine Learning Models Perform Hyperparameter Tuning on the Best Model Interpret Model Results Evaluate the Best Model with Test Data (replying the initiating question) Summary & Conclusions I will provide highlights of the project in this article, comprehensive analysis and entire code behind the project is available in the Kaggle notebook and GitHub. For data wrangling and visualization numpy, pandas, matplotlib, seaborn; for building the machine learning models xgboost, light gbm and scikit-learn; to perform preprocessing steps scikit-learn will be used. Let’s load the training data and create trees data frame: trees = pd.read_csv("/kaggle/input/learn-together/train.csv") I always find it useful looking at the first and last rows: The very first observation is, there are some negative values in the Vertical_Distance_To_Hydrology column. I will examine this in more detail in the Check for Anomalies & Outliers section. To understand trees dataframe, let’s look at the data types and descriptive statistics. With pandas info method, we can list the non-null values and data types: Data columns (total 56 columns):Id 15120 non-null int64Elevation 15120 non-null int64Aspect 15120 non-null int64Slope 15120 non-null int64Horizontal_Distance_To_Hydrology 15120 non-null int64Vertical_Distance_To_Hydrology 15120 non-null int64Horizontal_Distance_To_Roadways 15120 non-null int64Hillshade_9am 15120 non-null int64Hillshade_Noon 15120 non-null int64Hillshade_3pm 15120 non-null int64Horizontal_Distance_To_Fire_Points 15120 non-null int64Wilderness_Area1 15120 non-null int64Wilderness_Area2 15120 non-null int64Wilderness_Area3 15120 non-null int64Wilderness_Area4 15120 non-null int64Soil_Type1 15120 non-null int64Soil_Type2 15120 non-null int64Soil_Type3 15120 non-null int64Soil_Type4 15120 non-null int64Soil_Type5 15120 non-null int64Soil_Type6 15120 non-null int64Soil_Type7 15120 non-null int64Soil_Type8 15120 non-null int64Soil_Type9 15120 non-null int64Soil_Type10 15120 non-null int64Soil_Type11 15120 non-null int64Soil_Type12 15120 non-null int64Soil_Type13 15120 non-null int64Soil_Type14 15120 non-null int64Soil_Type15 15120 non-null int64Soil_Type16 15120 non-null int64Soil_Type17 15120 non-null int64Soil_Type18 15120 non-null int64Soil_Type19 15120 non-null int64Soil_Type20 15120 non-null int64Soil_Type21 15120 non-null int64Soil_Type22 15120 non-null int64Soil_Type23 15120 non-null int64Soil_Type24 15120 non-null int64Soil_Type25 15120 non-null int64Soil_Type26 15120 non-null int64Soil_Type27 15120 non-null int64Soil_Type28 15120 non-null int64Soil_Type29 15120 non-null int64Soil_Type30 15120 non-null int64Soil_Type31 15120 non-null int64Soil_Type32 15120 non-null int64Soil_Type33 15120 non-null int64Soil_Type34 15120 non-null int64Soil_Type35 15120 non-null int64Soil_Type36 15120 non-null int64Soil_Type37 15120 non-null int64Soil_Type38 15120 non-null int64Soil_Type39 15120 non-null int64Soil_Type40 15120 non-null int64Cover_Type 15120 non-null int64dtypes: int64(56)memory usage: 6.5 MB With describe method, we can observe the descriptive statistics: info method provided some valuable information: Data is formatted and clean: There aren’t any null values and all features are numeric. There are one-hot-encoded columns (as verified in the original notebook): Soil type and wilderness area. Check for Anomalies & Outliers: The first anomaly was observed with the negative values in the Vertical_Distance_To_Hydrology column. The definition is: Vertical distance to nearest surface water features With some research and using logic, negative values show that the nearest surface water is below that data point or it is below the sea level. Either case makes sense, so I am going to keep negative values. To help future ML model to grasp patterns in the data, I am going to search for outliers and use extreme outliers method to determine them. Data points will be dropped if they lie more than the 3 times the interquartile range below the first quartile or above the third quartile. # loop through all columns to see if there are any outliersfor column in trees.columns: if outlier_function(trees, column)[2] > 0: print("There are {} outliers in {}".format(outlier_function(trees, column)[2], column)) Knowing that the wilderness area and soil type columns are one-hot encoded, we can focus on the rest: There are 53 outliers in Horizontal_Distance_To_HydrologyThere are 49 outliers in Vertical_Distance_To_HydrologyThere are 3 outliers in Horizontal_Distance_To_RoadwaysThere are 7 outliers in Hillshade_9amThere are 20 outliers in Hillshade_NoonThere are 132 outliers in Horizontal_Distance_To_Fire_Points Hillshade columns are the RGB color representation of the shadow at a particular time so the range is already fixed between 0 and 255. Considering the Horizontal_Distance_To_Firepoints having the highest number of outliers and widest data range [0, 6993], I am going to remove outliers only from that column. trees = trees[(trees['Horizontal_Distance_To_Fire_Points'] > outlier_function(trees, 'Horizontal_Distance_To_Fire_Points')[0]) & (trees['Horizontal_Distance_To_Fire_Points'] < outlier_function(trees, 'Horizontal_Distance_To_Fire_Points')[1])] EDA is the first step in this workflow where the decision-making process is initiated for the feature selection. Some valuable insights can be obtained by looking at the distribution of the target, relationship of the features to the target and link between the features. My preference is to start by looking at the target, then examine the features and its relations to the target. Distribution of the Target: Data set have balanced labels, resulting in an almost equal number of cover types for each class. This will be an advantage when we are applying ML algorithms because the model will have a good chance to learn patterns of all classes without needing further balancing strategies. Wilderness Area — Cover Type: To have a look at this relationship, wilderness area columns will be reverse-one-hot-encoded. trees['Wilderness_Area_Type'] = (trees.iloc[:, 11:15] == 1).idxmax(1) Wilderness area is a distinctive feature for determining the Cover_Type . Wilderness Area — Soil Type — Cover Type: Reverse-one-hot-encoding will be applied to soil type columns using the below functions. As a result, one column Soil_Type with discrete numbers between 1 and 40 will be added. Different wilderness areas consist of some specific trees. Interestingly, there is one fantastic tree, Cottonwood/Willow, specifically likes to grow in Cache la Poudre (Wilderness Area 4). While Spruce/Fir, Lodgepole Pine, Aspen and Douglas-fir can grow in any soil type, other cover types grow with specific soil types. Relationships Between Continuous Features : Soil type and wilderness area columns were discrete, and both are the one-hot-encoded version of one categorical feature. Rest of the features are addressed as continuous: Elevation, Aspect, Slope, Horizontal_Distance_To_Hydrology, Vertical_Distance_To_Hydrology, Horizontal_Distance_To_Roadways, Hillshade_9am, Hillshade_Noon, Hillshade_3pm, Horizontal_Distance_To_Fire_Points. To visualize all of them with one function Seaborn’s PairGrid will be plotted to provide the flexibility of adjusting upper and lower diagonal with different plots: The upper half shows the KDE plot with Pearson coefficients and the lower half shows the scatter plot. The diagonal is the histogram of a particular feature. As expected, hillshade features are collinear: Hillshade noon — Hillshade 3 pm Hillshade 3 pm — Hillshade 9 am Those pairs provide the same input to the model, for a better interpretability one of them will be dropped in the Feature Engineering & Selection. Pearson Coefficients of the Features and Target: As a last step of the EDA, when Pearson coefficients of the features and targets are observed, only 1% of the one-hot-encoded soil type columns are effective in determining the Cover_Type (not shown in this article but in the notebook here). So they will be excluded and Pearson coefficients will be revisited with the continuous features, one-hot-encoded wilderness areas, Soil_Type and Cover_Type . continuous_variables = trees.columns[1:11].tolist()wilderness_areas = sorted(trees['Wilderness_Area_Type'].value_counts().index.tolist())all_features_w_label = continuous_variables + wilderness_areas + ["Soil_Type"] + ["Cover_Type"]trees_w_numeric_soil = trees[all_features_w_label] Dark colours represent a strong correlation. Unfortunately, the last column consists of light colours, resulting in weak Pearson coefficients of the features to the target, in the range of [-0.22, 0.12]. With a label-encoded Soil_Type column there is a stronger correlation with the Cover_Type. Hillshade_9am has the least importance in determining Cover_Type. Thus, it will be dropped in the following section. Extracting new features based on the existing ones and eliminating features with some methods and algorithms are called feature engineering & selection. There are horizontal and vertical distance to hydrology features, which blinks for adding the euclidian distance of the two. trees_w_numeric_soil['Euclidian_Distance_To_Hydrology'] = (trees_w_numeric_soil['Horizontal_Distance_To_Hydrology']**2 + trees_w_numeric_soil['Vertical_Distance_To_Hydrology']**2)**0.5 Also, adding linear combinations of the numeric features is a common practice in feature engineering. For some of the numeric features, the mean value of the two variables are added: trees_w_numeric_soil['Mean_Elevation_Vertical_Distance_Hydrology'] = (trees_w_numeric_soil['Elevation'] + trees_w_numeric_soil['Vertical_Distance_To_Hydrology'])/2trees_w_numeric_soil['Mean_Distance_Hydrology_Firepoints'] = (trees_w_numeric_soil['Horizontal_Distance_To_Hydrology'] + trees_w_numeric_soil['Horizontal_Distance_To_Fire_Points'])/2trees_w_numeric_soil['Mean_Distance_Hydrology_Roadways'] = (trees_w_numeric_soil['Horizontal_Distance_To_Hydrology'] + trees_w_numeric_soil['Horizontal_Distance_To_Roadways'])/2trees_w_numeric_soil['Mean_Distance_Firepoints_Roadways'] = (trees_w_numeric_soil['Horizontal_Distance_To_Fire_Points'] + trees_w_numeric_soil['Horizontal_Distance_To_Roadways'])/2 Another common practice is to perform logarithm and square root transformations to the numeric features. After adding 5 more features, square root transformation is applied to the positive features: for col in trees_w_numeric_soil.columns: if trees_w_numeric_soil[col].min() >= 0: if col == 'Cover_Type': next else: trees_w_numeric_soil['sqrt' + col] = np.sqrt(trees_w_numeric_soil[col]) After revisiting the Pearson coefficients, if a newly added feature shows a stronger correlation to the target, it is kept and the originating feature is dropped. Additionally, Hillshade_9am is dropped since it is strongly correlated with Hillshade_3pm. Final features are: # final list of featurestransformed_features = ['sqrtHorizontal_Distance_To_Hydrology', 'sqrtMean_Distance_Hydrology_Roadways', 'sqrtEuclidian_Distance_To_Hydrology', 'Mean_Elevation_Vertical_Distance_Hydrology', 'Mean_Distance_Firepoints_Roadways', 'Mean_Distance_Hydrology_Firepoints']all_features = (['Elevation', 'Aspect', 'Slope', 'Vertical_Distance_To_Hydrology', 'Horizontal_Distance_To_Roadways', 'Hillshade_Noon', 'Hillshade_3pm', 'Horizontal_Distance_To_Fire_Points' ] + wilderness_areas + ['Soil_Type'] + transformed_features)trees_training = trees_w_numeric_soil[all_features]labels_training = trees_w_numeric_soil["Cover_Type"].as_matrix() To compare ML models and establish a baseline, trees_training and labels_training data frames are split into training and validation set. X_train, X_valid, y_train, y_valid = train_test_split(trees_training, labels_training, test_size=0.2, random_state=1) Training set is used as an input, so that machine learning models can catch the patterns in the features and utilize them to distinguish the target. Validation set is used to evaluate the ML model’s performance and quantify its ability to generalize patterns to a new data set. Creating a Baseline Metric: Before diving deep into the ML classification algorithms, I am going to calculate a common-sense baseline. A common-sense baseline can be defined as how a person who knows that field would solve the problem without using any ML tricks. It can be calculated with human intuition as well as a dummy or simple algorithm, consisting few lines of code. I am going to use a dummy algorithm from the scikit-learn library. With that algorithm, I will establish a baseline metric with accuracy which is the percentage of correctly predicted cover types out of all cover types. Accuracy is the evaluation metric for this competition and will be used throughout the project, keeping in mind that it is not the most effective metric for some classification problems. Baseline metrics are important in a way that, if a machine learning model can’t beat the simple and intuitive prediction of a person’s or an algorithm’s guess, the original problem needs reconsideration or training data needs reframing. # Create dummy classiferdummy = DummyClassifier(strategy='stratified', random_state=1)# train the modeldummy.fit(X_train, y_train)# Get accuracy scorebaseline_accuracy = dummy.score(X_valid, y_valid)print("Our dummy algorithm classified {:0.2f} of the of the trees correctly".format(baseline_accuracy))Our dummy algorithm classified 0.14 of the of the trees correctly Now, I expect that following ML models beat the accuracy score of 0.14! Sometimes it is hard to know which machine learning model will work effectively for a given problem. So, I always try several machine learning models. A study shows that tree-based and distance-based algorithms outperform other ML algorithms for the 165 datasets analyzed. I am going to compare one distance-based algorithm and four tree-based algorithms on accuracy metric. Distance-based: K-Nearest Neighbors Classifier (using euclidian distance to cluster labels; normalization is required before and applied here in the original notebook.) Tree-based: Light Gradient Boosting Machine (LightGBM) Classifier from the light gbm library Extra Gradient Boosting (XGBoost) Classifier from the xgboost library Random Forest Classifier from the scikit-learn library Extra Trees (Random Forests) Classifier from the scikit-learn library (The code behind the models is here.) Unlike the study results, extra trees classifier outperformed others. All models beat the baseline-metric showing that machine learning is applicable to the classification of the forest cover types. Our best model, extra trees classifier, is an ensemble tree-based model. The definition from the scikit-learn library is as follows: This class implements a meta estimator that fits a number of randomized decision trees (a.k.a. extra-trees) on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. The major differences from the random forests algorithm are: Rather than looking for a most discriminative split value for a feature in a node, splits are chosen completely randomly as thresholds.Sub-samples are drawn from the entire training set instead of a bootstrap sample of the training set. Rather than looking for a most discriminative split value for a feature in a node, splits are chosen completely randomly as thresholds. Sub-samples are drawn from the entire training set instead of a bootstrap sample of the training set. Thus, the algorithm becomes more robust to over-fitting. Searching for the best combination of model parameters are called hyperparameter tuning which can dramatically improve the model’s performance. I will use the random search algorithm with cross-validation for hyperparameter-tuning: Random Search: Set of ML model’s parameters are defined in a range and inputted to sklearn’s RandomizedSearchCV. This algorithm randomly selects some combination of the parameters and compares the defined score (accuracy, for this problem) with iterations. Random search runtime and iterations can be controlled with the parameter n_iter. K-Fold Cross-validation: A method used to assess the performance of the hyperparameters on the whole dataset. (visual explanation is here). Rather than splitting the dataset set into two static subsets of training and validation set, data set is divided equally for the given K, and with iterations, different K-1 subsets are trained and model is tested with a different subset. With the below set of parameters and 5-fold cross-validation RandomizedSearchCV will look for the best combination: # The number of trees in the forest algorithm, default value is 100.n_estimators = [50, 100, 300, 500, 1000]# The minimum number of samples required to split an internal node, default value is 2.min_samples_split = [2, 3, 5, 7, 9]# The minimum number of samples required to be at a leaf node, default value is 1.min_samples_leaf = [1, 2, 4, 6, 8]# The number of features to consider when looking for the best split, default value is auto.max_features = ['auto', 'sqrt', 'log2', None] # Define the grid of hyperparameters to searchhyperparameter_grid = {'n_estimators': n_estimators, 'min_samples_leaf': min_samples_leaf, 'min_samples_split': min_samples_split, 'max_features': max_features}# create modelbest_model = ExtraTreesClassifier(random_state=42)# create Randomized search objectrandom_cv = RandomizedSearchCV(estimator=best_model, param_distributions=hyperparameter_grid, cv=5, n_iter=20, scoring = 'accuracy', n_jobs = -1, verbose = 1, return_train_score = True, random_state=42)# Fit on the all training data using random search objectrandom_cv.fit(trees_training, labels_training)random_cv.best_estimator_ Here is the best combination of parameters: n_estimators = 300 max_features = None min_samples_leaf= 1 min_samples_split= 2 When I feed them into the extra trees classifier: Accuracy score in the previous extra random forests model: 0.8659106070713809Accuracy score after hyperparameter tuning: 0.885923949299533 results in 2 point increase in the accuracy. Another search method is the GridSearchCV, in contrast to RandomizedSearchCV, the search is performed on every single combination of the given parameters. (applied and discussed here in the original notebook) Confusion Matrix: One of the most common methods for the visualization of a classification model results is the confusion matrix. Fantastic tree confusion matrix will be a 7x7 matrix. I will use the normalized confusion matrix, so the percentage of actual cover types correctly guessed out of all guesses in that particular category will appear in the diagonal of the matrix. Non-diagonal elements will show mislabeled elements by the model. The higher percentages and darker color in the diagonal of the confusion matrix are better, indicating many correct predictions. I am going to use the function in the scikit-learn to plot it: The model did pretty good detecting fantastic trees of type Ponderosa Pine, Cottonwood/Willow, Aspen, Douglas-fir, Krummholz, and it seems a bit confused to detect Spruce/Fir and Lodgepole Pine (Cover Type 1 and 2). Feature Importances: Another method is to look at the feature importances with feature_importances_: A number between 0 and 1, showing each feature’s contribution to the prediction. Higher the number shows a significant contribution. With the current selection of features, extra trees classifier and parameters, top 10 features are: 5 of them are created in the scope of this project. This list has stressed the importance of feature engineering and selection. How to detect fantastic trees (generating final predictions): Kaggle provides separate training and test set for the competitions. Until now, I worked on the training set. Nonetheless, the test set is used for the final predictions, so I aligned the test set and training set here and fed it into the hyperparameter-tuned Extra Trees Classifier and successfully detected fantastic trees with 78% accuracy. Where to find fantastic trees: Spruce/Fir, Lodgepole Pine and Krummholz love to hangout in Rawah, Neota and Comanche Peak Wilderness Area. Cache la Poudre Wilderness Area is the perfect place for Ponderosa Pine and Cottonwood/Willow. If you see an Aspen, suspect that you are at the Rawah or Comanche. Douglas-fir is an easy-going species, that goes along with any wilderness area. In this article, I provided highlights of the end-to-end machine learning workflow application to a supervised multi-class classification problem. I started with understanding and visualizing the data with the EDA and formed insights about the cover type dataset. With the outputs of the EDA, I performed feature engineering where I transformed, added and removed features. Extra trees classifier matched well to this classification problem with the accuracy metric. With the hyperparameter tuning, accuracy score of the model increased by 2 points, by adjusting n_estimators parameter. Interpreting model results showed the most important features and how to improve accuracy further (by distinguishing better between cover type 1 and 2). For comprehensive code behind the project: Github Repo: https://github.com/cereniyim/Tree-Classification-ML-Model Kaggle Notebook: https://www.kaggle.com/cereniyim/fantastic-trees-where-to-find-how-to-detect-them/notebook Thanks for reading, this end-to-end workflow can be applied to any machine learning problem, I encourage you to go ahead and give it a try! For any questions, comments or constructive feedback you can reach out to me on responses, Twitter or Linkedin!
[ { "code": null, "e": 332, "s": 172, "text": "In this article, I will explain how to approach a multi-class classification supervised machine learning (ML) problem (or project) with an end-to-end workflow." }, { "code": null, "e": 463, "s": 332, "text": "Supervised: Features (variables to generate predictions) and target (the variable to be determined) are available in the data set." }, { "code": null, "e": 554, "s": 463, "text": "Multi-class classification: There are seven discrete categories to distinguish the target." }, { "code": null, "e": 720, "s": 554, "text": "Project is based on a famous data set in the machine learning community and known as Forest Cover Type available for download in the UCI Machine Learning Repository." }, { "code": null, "e": 903, "s": 720, "text": "A stratified sample from the original data set to apply the workflow and separate test set to generate final predictions is used as part of a beginner-friendly competition in Kaggle." }, { "code": null, "e": 1098, "s": 903, "text": "The goal of the Project (and competition): to predict seven different cover types in four different wilderness areas of the Roosevelt National Forest of Northern Colorado with the best accuracy." }, { "code": null, "e": 1125, "s": 1098, "text": "Four wilderness areas are:" }, { "code": null, "e": 1134, "s": 1125, "text": "1: Rawah" }, { "code": null, "e": 1143, "s": 1134, "text": "2: Neota" }, { "code": null, "e": 1160, "s": 1143, "text": "3: Comanche Peak" }, { "code": null, "e": 1179, "s": 1160, "text": "4: Cache la Poudre" }, { "code": null, "e": 1261, "s": 1179, "text": "Seven categories numbered from 1 to 7 in the Cover_Type column, to be classified:" }, { "code": null, "e": 1275, "s": 1261, "text": "1: Spruce/Fir" }, { "code": null, "e": 1293, "s": 1275, "text": "2: Lodgepole Pine" }, { "code": null, "e": 1311, "s": 1293, "text": "3: Ponderosa Pine" }, { "code": null, "e": 1332, "s": 1311, "text": "4: Cottonwood/Willow" }, { "code": null, "e": 1341, "s": 1332, "text": "5: Aspen" }, { "code": null, "e": 1356, "s": 1341, "text": "6: Douglas-fir" }, { "code": null, "e": 1369, "s": 1356, "text": "7: Krummholz" }, { "code": null, "e": 1518, "s": 1369, "text": "The names of the target (cover type) reminded me of the Fantastic Beasts, so I called them fantastic trees to add some imagination to the project 🙃." }, { "code": null, "e": 1712, "s": 1518, "text": "End-to-end Machine Learning Workflow Steps: to classify cover types and reply to the initiating question, where to find fantastic trees and how to detect them, the below steps will be followed:" }, { "code": null, "e": 2005, "s": 1712, "text": "Understand, Clean and Format DataExploratory Data AnalysisFeature Engineering & SelectionCompare Several Machine Learning ModelsPerform Hyperparameter Tuning on the Best ModelInterpret Model ResultsEvaluate the Best Model with Test Data (replying the initiating question)Summary & Conclusions" }, { "code": null, "e": 2039, "s": 2005, "text": "Understand, Clean and Format Data" }, { "code": null, "e": 2065, "s": 2039, "text": "Exploratory Data Analysis" }, { "code": null, "e": 2097, "s": 2065, "text": "Feature Engineering & Selection" }, { "code": null, "e": 2137, "s": 2097, "text": "Compare Several Machine Learning Models" }, { "code": null, "e": 2185, "s": 2137, "text": "Perform Hyperparameter Tuning on the Best Model" }, { "code": null, "e": 2209, "s": 2185, "text": "Interpret Model Results" }, { "code": null, "e": 2283, "s": 2209, "text": "Evaluate the Best Model with Test Data (replying the initiating question)" }, { "code": null, "e": 2305, "s": 2283, "text": "Summary & Conclusions" }, { "code": null, "e": 2469, "s": 2305, "text": "I will provide highlights of the project in this article, comprehensive analysis and entire code behind the project is available in the Kaggle notebook and GitHub." }, { "code": null, "e": 2678, "s": 2469, "text": "For data wrangling and visualization numpy, pandas, matplotlib, seaborn; for building the machine learning models xgboost, light gbm and scikit-learn; to perform preprocessing steps scikit-learn will be used." }, { "code": null, "e": 2736, "s": 2678, "text": "Let’s load the training data and create trees data frame:" }, { "code": null, "e": 2798, "s": 2736, "text": "trees = pd.read_csv(\"/kaggle/input/learn-together/train.csv\")" }, { "code": null, "e": 2858, "s": 2798, "text": "I always find it useful looking at the first and last rows:" }, { "code": null, "e": 3048, "s": 2858, "text": "The very first observation is, there are some negative values in the Vertical_Distance_To_Hydrology column. I will examine this in more detail in the Check for Anomalies & Outliers section." }, { "code": null, "e": 3209, "s": 3048, "text": "To understand trees dataframe, let’s look at the data types and descriptive statistics. With pandas info method, we can list the non-null values and data types:" }, { "code": null, "e": 6527, "s": 3209, "text": "Data columns (total 56 columns):Id 15120 non-null int64Elevation 15120 non-null int64Aspect 15120 non-null int64Slope 15120 non-null int64Horizontal_Distance_To_Hydrology 15120 non-null int64Vertical_Distance_To_Hydrology 15120 non-null int64Horizontal_Distance_To_Roadways 15120 non-null int64Hillshade_9am 15120 non-null int64Hillshade_Noon 15120 non-null int64Hillshade_3pm 15120 non-null int64Horizontal_Distance_To_Fire_Points 15120 non-null int64Wilderness_Area1 15120 non-null int64Wilderness_Area2 15120 non-null int64Wilderness_Area3 15120 non-null int64Wilderness_Area4 15120 non-null int64Soil_Type1 15120 non-null int64Soil_Type2 15120 non-null int64Soil_Type3 15120 non-null int64Soil_Type4 15120 non-null int64Soil_Type5 15120 non-null int64Soil_Type6 15120 non-null int64Soil_Type7 15120 non-null int64Soil_Type8 15120 non-null int64Soil_Type9 15120 non-null int64Soil_Type10 15120 non-null int64Soil_Type11 15120 non-null int64Soil_Type12 15120 non-null int64Soil_Type13 15120 non-null int64Soil_Type14 15120 non-null int64Soil_Type15 15120 non-null int64Soil_Type16 15120 non-null int64Soil_Type17 15120 non-null int64Soil_Type18 15120 non-null int64Soil_Type19 15120 non-null int64Soil_Type20 15120 non-null int64Soil_Type21 15120 non-null int64Soil_Type22 15120 non-null int64Soil_Type23 15120 non-null int64Soil_Type24 15120 non-null int64Soil_Type25 15120 non-null int64Soil_Type26 15120 non-null int64Soil_Type27 15120 non-null int64Soil_Type28 15120 non-null int64Soil_Type29 15120 non-null int64Soil_Type30 15120 non-null int64Soil_Type31 15120 non-null int64Soil_Type32 15120 non-null int64Soil_Type33 15120 non-null int64Soil_Type34 15120 non-null int64Soil_Type35 15120 non-null int64Soil_Type36 15120 non-null int64Soil_Type37 15120 non-null int64Soil_Type38 15120 non-null int64Soil_Type39 15120 non-null int64Soil_Type40 15120 non-null int64Cover_Type 15120 non-null int64dtypes: int64(56)memory usage: 6.5 MB" }, { "code": null, "e": 6592, "s": 6527, "text": "With describe method, we can observe the descriptive statistics:" }, { "code": null, "e": 6640, "s": 6592, "text": "info method provided some valuable information:" }, { "code": null, "e": 6728, "s": 6640, "text": "Data is formatted and clean: There aren’t any null values and all features are numeric." }, { "code": null, "e": 6833, "s": 6728, "text": "There are one-hot-encoded columns (as verified in the original notebook): Soil type and wilderness area." }, { "code": null, "e": 6865, "s": 6833, "text": "Check for Anomalies & Outliers:" }, { "code": null, "e": 6986, "s": 6865, "text": "The first anomaly was observed with the negative values in the Vertical_Distance_To_Hydrology column. The definition is:" }, { "code": null, "e": 7038, "s": 6986, "text": "Vertical distance to nearest surface water features" }, { "code": null, "e": 7245, "s": 7038, "text": "With some research and using logic, negative values show that the nearest surface water is below that data point or it is below the sea level. Either case makes sense, so I am going to keep negative values." }, { "code": null, "e": 7385, "s": 7245, "text": "To help future ML model to grasp patterns in the data, I am going to search for outliers and use extreme outliers method to determine them." }, { "code": null, "e": 7525, "s": 7385, "text": "Data points will be dropped if they lie more than the 3 times the interquartile range below the first quartile or above the third quartile." }, { "code": null, "e": 7754, "s": 7525, "text": "# loop through all columns to see if there are any outliersfor column in trees.columns: if outlier_function(trees, column)[2] > 0: print(\"There are {} outliers in {}\".format(outlier_function(trees, column)[2], column))" }, { "code": null, "e": 7856, "s": 7754, "text": "Knowing that the wilderness area and soil type columns are one-hot encoded, we can focus on the rest:" }, { "code": null, "e": 8160, "s": 7856, "text": "There are 53 outliers in Horizontal_Distance_To_HydrologyThere are 49 outliers in Vertical_Distance_To_HydrologyThere are 3 outliers in Horizontal_Distance_To_RoadwaysThere are 7 outliers in Hillshade_9amThere are 20 outliers in Hillshade_NoonThere are 132 outliers in Horizontal_Distance_To_Fire_Points" }, { "code": null, "e": 8295, "s": 8160, "text": "Hillshade columns are the RGB color representation of the shadow at a particular time so the range is already fixed between 0 and 255." }, { "code": null, "e": 8469, "s": 8295, "text": "Considering the Horizontal_Distance_To_Firepoints having the highest number of outliers and widest data range [0, 6993], I am going to remove outliers only from that column." }, { "code": null, "e": 8725, "s": 8469, "text": "trees = trees[(trees['Horizontal_Distance_To_Fire_Points'] > outlier_function(trees, 'Horizontal_Distance_To_Fire_Points')[0]) & (trees['Horizontal_Distance_To_Fire_Points'] < outlier_function(trees, 'Horizontal_Distance_To_Fire_Points')[1])]" }, { "code": null, "e": 8997, "s": 8725, "text": "EDA is the first step in this workflow where the decision-making process is initiated for the feature selection. Some valuable insights can be obtained by looking at the distribution of the target, relationship of the features to the target and link between the features." }, { "code": null, "e": 9108, "s": 8997, "text": "My preference is to start by looking at the target, then examine the features and its relations to the target." }, { "code": null, "e": 9136, "s": 9108, "text": "Distribution of the Target:" }, { "code": null, "e": 9416, "s": 9136, "text": "Data set have balanced labels, resulting in an almost equal number of cover types for each class. This will be an advantage when we are applying ML algorithms because the model will have a good chance to learn patterns of all classes without needing further balancing strategies." }, { "code": null, "e": 9446, "s": 9416, "text": "Wilderness Area — Cover Type:" }, { "code": null, "e": 9540, "s": 9446, "text": "To have a look at this relationship, wilderness area columns will be reverse-one-hot-encoded." }, { "code": null, "e": 9610, "s": 9540, "text": "trees['Wilderness_Area_Type'] = (trees.iloc[:, 11:15] == 1).idxmax(1)" }, { "code": null, "e": 9684, "s": 9610, "text": "Wilderness area is a distinctive feature for determining the Cover_Type ." }, { "code": null, "e": 9726, "s": 9684, "text": "Wilderness Area — Soil Type — Cover Type:" }, { "code": null, "e": 9903, "s": 9726, "text": "Reverse-one-hot-encoding will be applied to soil type columns using the below functions. As a result, one column Soil_Type with discrete numbers between 1 and 40 will be added." }, { "code": null, "e": 10224, "s": 9903, "text": "Different wilderness areas consist of some specific trees. Interestingly, there is one fantastic tree, Cottonwood/Willow, specifically likes to grow in Cache la Poudre (Wilderness Area 4). While Spruce/Fir, Lodgepole Pine, Aspen and Douglas-fir can grow in any soil type, other cover types grow with specific soil types." }, { "code": null, "e": 10268, "s": 10224, "text": "Relationships Between Continuous Features :" }, { "code": null, "e": 10390, "s": 10268, "text": "Soil type and wilderness area columns were discrete, and both are the one-hot-encoded version of one categorical feature." }, { "code": null, "e": 10647, "s": 10390, "text": "Rest of the features are addressed as continuous: Elevation, Aspect, Slope, Horizontal_Distance_To_Hydrology, Vertical_Distance_To_Hydrology, Horizontal_Distance_To_Roadways, Hillshade_9am, Hillshade_Noon, Hillshade_3pm, Horizontal_Distance_To_Fire_Points." }, { "code": null, "e": 10812, "s": 10647, "text": "To visualize all of them with one function Seaborn’s PairGrid will be plotted to provide the flexibility of adjusting upper and lower diagonal with different plots:" }, { "code": null, "e": 11017, "s": 10812, "text": "The upper half shows the KDE plot with Pearson coefficients and the lower half shows the scatter plot. The diagonal is the histogram of a particular feature. As expected, hillshade features are collinear:" }, { "code": null, "e": 11049, "s": 11017, "text": "Hillshade noon — Hillshade 3 pm" }, { "code": null, "e": 11081, "s": 11049, "text": "Hillshade 3 pm — Hillshade 9 am" }, { "code": null, "e": 11228, "s": 11081, "text": "Those pairs provide the same input to the model, for a better interpretability one of them will be dropped in the Feature Engineering & Selection." }, { "code": null, "e": 11277, "s": 11228, "text": "Pearson Coefficients of the Features and Target:" }, { "code": null, "e": 11678, "s": 11277, "text": "As a last step of the EDA, when Pearson coefficients of the features and targets are observed, only 1% of the one-hot-encoded soil type columns are effective in determining the Cover_Type (not shown in this article but in the notebook here). So they will be excluded and Pearson coefficients will be revisited with the continuous features, one-hot-encoded wilderness areas, Soil_Type and Cover_Type ." }, { "code": null, "e": 11961, "s": 11678, "text": "continuous_variables = trees.columns[1:11].tolist()wilderness_areas = sorted(trees['Wilderness_Area_Type'].value_counts().index.tolist())all_features_w_label = continuous_variables + wilderness_areas + [\"Soil_Type\"] + [\"Cover_Type\"]trees_w_numeric_soil = trees[all_features_w_label]" }, { "code": null, "e": 12165, "s": 11961, "text": "Dark colours represent a strong correlation. Unfortunately, the last column consists of light colours, resulting in weak Pearson coefficients of the features to the target, in the range of [-0.22, 0.12]." }, { "code": null, "e": 12256, "s": 12165, "text": "With a label-encoded Soil_Type column there is a stronger correlation with the Cover_Type." }, { "code": null, "e": 12373, "s": 12256, "text": "Hillshade_9am has the least importance in determining Cover_Type. Thus, it will be dropped in the following section." }, { "code": null, "e": 12526, "s": 12373, "text": "Extracting new features based on the existing ones and eliminating features with some methods and algorithms are called feature engineering & selection." }, { "code": null, "e": 12651, "s": 12526, "text": "There are horizontal and vertical distance to hydrology features, which blinks for adding the euclidian distance of the two." }, { "code": null, "e": 12891, "s": 12651, "text": "trees_w_numeric_soil['Euclidian_Distance_To_Hydrology'] = (trees_w_numeric_soil['Horizontal_Distance_To_Hydrology']**2 + trees_w_numeric_soil['Vertical_Distance_To_Hydrology']**2)**0.5" }, { "code": null, "e": 13074, "s": 12891, "text": "Also, adding linear combinations of the numeric features is a common practice in feature engineering. For some of the numeric features, the mean value of the two variables are added:" }, { "code": null, "e": 13936, "s": 13074, "text": "trees_w_numeric_soil['Mean_Elevation_Vertical_Distance_Hydrology'] = (trees_w_numeric_soil['Elevation'] + trees_w_numeric_soil['Vertical_Distance_To_Hydrology'])/2trees_w_numeric_soil['Mean_Distance_Hydrology_Firepoints'] = (trees_w_numeric_soil['Horizontal_Distance_To_Hydrology'] + trees_w_numeric_soil['Horizontal_Distance_To_Fire_Points'])/2trees_w_numeric_soil['Mean_Distance_Hydrology_Roadways'] = (trees_w_numeric_soil['Horizontal_Distance_To_Hydrology'] + trees_w_numeric_soil['Horizontal_Distance_To_Roadways'])/2trees_w_numeric_soil['Mean_Distance_Firepoints_Roadways'] = (trees_w_numeric_soil['Horizontal_Distance_To_Fire_Points'] + trees_w_numeric_soil['Horizontal_Distance_To_Roadways'])/2" }, { "code": null, "e": 14135, "s": 13936, "text": "Another common practice is to perform logarithm and square root transformations to the numeric features. After adding 5 more features, square root transformation is applied to the positive features:" }, { "code": null, "e": 14363, "s": 14135, "text": "for col in trees_w_numeric_soil.columns: if trees_w_numeric_soil[col].min() >= 0: if col == 'Cover_Type': next else: trees_w_numeric_soil['sqrt' + col] = np.sqrt(trees_w_numeric_soil[col])" }, { "code": null, "e": 14617, "s": 14363, "text": "After revisiting the Pearson coefficients, if a newly added feature shows a stronger correlation to the target, it is kept and the originating feature is dropped. Additionally, Hillshade_9am is dropped since it is strongly correlated with Hillshade_3pm." }, { "code": null, "e": 14637, "s": 14617, "text": "Final features are:" }, { "code": null, "e": 15291, "s": 14637, "text": "# final list of featurestransformed_features = ['sqrtHorizontal_Distance_To_Hydrology', 'sqrtMean_Distance_Hydrology_Roadways', 'sqrtEuclidian_Distance_To_Hydrology', 'Mean_Elevation_Vertical_Distance_Hydrology', 'Mean_Distance_Firepoints_Roadways', 'Mean_Distance_Hydrology_Firepoints']all_features = (['Elevation', 'Aspect', 'Slope', 'Vertical_Distance_To_Hydrology', 'Horizontal_Distance_To_Roadways', 'Hillshade_Noon', 'Hillshade_3pm', 'Horizontal_Distance_To_Fire_Points' ] + wilderness_areas + ['Soil_Type'] + transformed_features)trees_training = trees_w_numeric_soil[all_features]labels_training = trees_w_numeric_soil[\"Cover_Type\"].as_matrix()" }, { "code": null, "e": 15429, "s": 15291, "text": "To compare ML models and establish a baseline, trees_training and labels_training data frames are split into training and validation set." }, { "code": null, "e": 15547, "s": 15429, "text": "X_train, X_valid, y_train, y_valid = train_test_split(trees_training, labels_training, test_size=0.2, random_state=1)" }, { "code": null, "e": 15696, "s": 15547, "text": "Training set is used as an input, so that machine learning models can catch the patterns in the features and utilize them to distinguish the target." }, { "code": null, "e": 15825, "s": 15696, "text": "Validation set is used to evaluate the ML model’s performance and quantify its ability to generalize patterns to a new data set." }, { "code": null, "e": 15853, "s": 15825, "text": "Creating a Baseline Metric:" }, { "code": null, "e": 16201, "s": 15853, "text": "Before diving deep into the ML classification algorithms, I am going to calculate a common-sense baseline. A common-sense baseline can be defined as how a person who knows that field would solve the problem without using any ML tricks. It can be calculated with human intuition as well as a dummy or simple algorithm, consisting few lines of code." }, { "code": null, "e": 16608, "s": 16201, "text": "I am going to use a dummy algorithm from the scikit-learn library. With that algorithm, I will establish a baseline metric with accuracy which is the percentage of correctly predicted cover types out of all cover types. Accuracy is the evaluation metric for this competition and will be used throughout the project, keeping in mind that it is not the most effective metric for some classification problems." }, { "code": null, "e": 16845, "s": 16608, "text": "Baseline metrics are important in a way that, if a machine learning model can’t beat the simple and intuitive prediction of a person’s or an algorithm’s guess, the original problem needs reconsideration or training data needs reframing." }, { "code": null, "e": 17213, "s": 16845, "text": "# Create dummy classiferdummy = DummyClassifier(strategy='stratified', random_state=1)# train the modeldummy.fit(X_train, y_train)# Get accuracy scorebaseline_accuracy = dummy.score(X_valid, y_valid)print(\"Our dummy algorithm classified {:0.2f} of the of the trees correctly\".format(baseline_accuracy))Our dummy algorithm classified 0.14 of the of the trees correctly" }, { "code": null, "e": 17285, "s": 17213, "text": "Now, I expect that following ML models beat the accuracy score of 0.14!" }, { "code": null, "e": 17436, "s": 17285, "text": "Sometimes it is hard to know which machine learning model will work effectively for a given problem. So, I always try several machine learning models." }, { "code": null, "e": 17558, "s": 17436, "text": "A study shows that tree-based and distance-based algorithms outperform other ML algorithms for the 165 datasets analyzed." }, { "code": null, "e": 17660, "s": 17558, "text": "I am going to compare one distance-based algorithm and four tree-based algorithms on accuracy metric." }, { "code": null, "e": 17676, "s": 17660, "text": "Distance-based:" }, { "code": null, "e": 17829, "s": 17676, "text": "K-Nearest Neighbors Classifier (using euclidian distance to cluster labels; normalization is required before and applied here in the original notebook.)" }, { "code": null, "e": 17841, "s": 17829, "text": "Tree-based:" }, { "code": null, "e": 17922, "s": 17841, "text": "Light Gradient Boosting Machine (LightGBM) Classifier from the light gbm library" }, { "code": null, "e": 17992, "s": 17922, "text": "Extra Gradient Boosting (XGBoost) Classifier from the xgboost library" }, { "code": null, "e": 18047, "s": 17992, "text": "Random Forest Classifier from the scikit-learn library" }, { "code": null, "e": 18117, "s": 18047, "text": "Extra Trees (Random Forests) Classifier from the scikit-learn library" }, { "code": null, "e": 18155, "s": 18117, "text": "(The code behind the models is here.)" }, { "code": null, "e": 18354, "s": 18155, "text": "Unlike the study results, extra trees classifier outperformed others. All models beat the baseline-metric showing that machine learning is applicable to the classification of the forest cover types." }, { "code": null, "e": 18487, "s": 18354, "text": "Our best model, extra trees classifier, is an ensemble tree-based model. The definition from the scikit-learn library is as follows:" }, { "code": null, "e": 18713, "s": 18487, "text": "This class implements a meta estimator that fits a number of randomized decision trees (a.k.a. extra-trees) on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting." }, { "code": null, "e": 18774, "s": 18713, "text": "The major differences from the random forests algorithm are:" }, { "code": null, "e": 19011, "s": 18774, "text": "Rather than looking for a most discriminative split value for a feature in a node, splits are chosen completely randomly as thresholds.Sub-samples are drawn from the entire training set instead of a bootstrap sample of the training set." }, { "code": null, "e": 19147, "s": 19011, "text": "Rather than looking for a most discriminative split value for a feature in a node, splits are chosen completely randomly as thresholds." }, { "code": null, "e": 19249, "s": 19147, "text": "Sub-samples are drawn from the entire training set instead of a bootstrap sample of the training set." }, { "code": null, "e": 19306, "s": 19249, "text": "Thus, the algorithm becomes more robust to over-fitting." }, { "code": null, "e": 19538, "s": 19306, "text": "Searching for the best combination of model parameters are called hyperparameter tuning which can dramatically improve the model’s performance. I will use the random search algorithm with cross-validation for hyperparameter-tuning:" }, { "code": null, "e": 19877, "s": 19538, "text": "Random Search: Set of ML model’s parameters are defined in a range and inputted to sklearn’s RandomizedSearchCV. This algorithm randomly selects some combination of the parameters and compares the defined score (accuracy, for this problem) with iterations. Random search runtime and iterations can be controlled with the parameter n_iter." }, { "code": null, "e": 20256, "s": 19877, "text": "K-Fold Cross-validation: A method used to assess the performance of the hyperparameters on the whole dataset. (visual explanation is here). Rather than splitting the dataset set into two static subsets of training and validation set, data set is divided equally for the given K, and with iterations, different K-1 subsets are trained and model is tested with a different subset." }, { "code": null, "e": 20372, "s": 20256, "text": "With the below set of parameters and 5-fold cross-validation RandomizedSearchCV will look for the best combination:" }, { "code": null, "e": 21734, "s": 20372, "text": "# The number of trees in the forest algorithm, default value is 100.n_estimators = [50, 100, 300, 500, 1000]# The minimum number of samples required to split an internal node, default value is 2.min_samples_split = [2, 3, 5, 7, 9]# The minimum number of samples required to be at a leaf node, default value is 1.min_samples_leaf = [1, 2, 4, 6, 8]# The number of features to consider when looking for the best split, default value is auto.max_features = ['auto', 'sqrt', 'log2', None] # Define the grid of hyperparameters to searchhyperparameter_grid = {'n_estimators': n_estimators, 'min_samples_leaf': min_samples_leaf, 'min_samples_split': min_samples_split, 'max_features': max_features}# create modelbest_model = ExtraTreesClassifier(random_state=42)# create Randomized search objectrandom_cv = RandomizedSearchCV(estimator=best_model, param_distributions=hyperparameter_grid, cv=5, n_iter=20, scoring = 'accuracy', n_jobs = -1, verbose = 1, return_train_score = True, random_state=42)# Fit on the all training data using random search objectrandom_cv.fit(trees_training, labels_training)random_cv.best_estimator_" }, { "code": null, "e": 21778, "s": 21734, "text": "Here is the best combination of parameters:" }, { "code": null, "e": 21797, "s": 21778, "text": "n_estimators = 300" }, { "code": null, "e": 21817, "s": 21797, "text": "max_features = None" }, { "code": null, "e": 21837, "s": 21817, "text": "min_samples_leaf= 1" }, { "code": null, "e": 21858, "s": 21837, "text": "min_samples_split= 2" }, { "code": null, "e": 21908, "s": 21858, "text": "When I feed them into the extra trees classifier:" }, { "code": null, "e": 22047, "s": 21908, "text": "Accuracy score in the previous extra random forests model: 0.8659106070713809Accuracy score after hyperparameter tuning: 0.885923949299533" }, { "code": null, "e": 22092, "s": 22047, "text": "results in 2 point increase in the accuracy." }, { "code": null, "e": 22301, "s": 22092, "text": "Another search method is the GridSearchCV, in contrast to RandomizedSearchCV, the search is performed on every single combination of the given parameters. (applied and discussed here in the original notebook)" }, { "code": null, "e": 22319, "s": 22301, "text": "Confusion Matrix:" }, { "code": null, "e": 22431, "s": 22319, "text": "One of the most common methods for the visualization of a classification model results is the confusion matrix." }, { "code": null, "e": 22677, "s": 22431, "text": "Fantastic tree confusion matrix will be a 7x7 matrix. I will use the normalized confusion matrix, so the percentage of actual cover types correctly guessed out of all guesses in that particular category will appear in the diagonal of the matrix." }, { "code": null, "e": 22872, "s": 22677, "text": "Non-diagonal elements will show mislabeled elements by the model. The higher percentages and darker color in the diagonal of the confusion matrix are better, indicating many correct predictions." }, { "code": null, "e": 22935, "s": 22872, "text": "I am going to use the function in the scikit-learn to plot it:" }, { "code": null, "e": 23151, "s": 22935, "text": "The model did pretty good detecting fantastic trees of type Ponderosa Pine, Cottonwood/Willow, Aspen, Douglas-fir, Krummholz, and it seems a bit confused to detect Spruce/Fir and Lodgepole Pine (Cover Type 1 and 2)." }, { "code": null, "e": 23172, "s": 23151, "text": "Feature Importances:" }, { "code": null, "e": 23385, "s": 23172, "text": "Another method is to look at the feature importances with feature_importances_: A number between 0 and 1, showing each feature’s contribution to the prediction. Higher the number shows a significant contribution." }, { "code": null, "e": 23485, "s": 23385, "text": "With the current selection of features, extra trees classifier and parameters, top 10 features are:" }, { "code": null, "e": 23613, "s": 23485, "text": "5 of them are created in the scope of this project. This list has stressed the importance of feature engineering and selection." }, { "code": null, "e": 23675, "s": 23613, "text": "How to detect fantastic trees (generating final predictions):" }, { "code": null, "e": 23962, "s": 23675, "text": "Kaggle provides separate training and test set for the competitions. Until now, I worked on the training set. Nonetheless, the test set is used for the final predictions, so I aligned the test set and training set here and fed it into the hyperparameter-tuned Extra Trees Classifier and" }, { "code": null, "e": 24019, "s": 23962, "text": "successfully detected fantastic trees with 78% accuracy." }, { "code": null, "e": 24050, "s": 24019, "text": "Where to find fantastic trees:" }, { "code": null, "e": 24158, "s": 24050, "text": "Spruce/Fir, Lodgepole Pine and Krummholz love to hangout in Rawah, Neota and Comanche Peak Wilderness Area." }, { "code": null, "e": 24253, "s": 24158, "text": "Cache la Poudre Wilderness Area is the perfect place for Ponderosa Pine and Cottonwood/Willow." }, { "code": null, "e": 24321, "s": 24253, "text": "If you see an Aspen, suspect that you are at the Rawah or Comanche." }, { "code": null, "e": 24401, "s": 24321, "text": "Douglas-fir is an easy-going species, that goes along with any wilderness area." }, { "code": null, "e": 24775, "s": 24401, "text": "In this article, I provided highlights of the end-to-end machine learning workflow application to a supervised multi-class classification problem. I started with understanding and visualizing the data with the EDA and formed insights about the cover type dataset. With the outputs of the EDA, I performed feature engineering where I transformed, added and removed features." }, { "code": null, "e": 25141, "s": 24775, "text": "Extra trees classifier matched well to this classification problem with the accuracy metric. With the hyperparameter tuning, accuracy score of the model increased by 2 points, by adjusting n_estimators parameter. Interpreting model results showed the most important features and how to improve accuracy further (by distinguishing better between cover type 1 and 2)." }, { "code": null, "e": 25184, "s": 25141, "text": "For comprehensive code behind the project:" }, { "code": null, "e": 25255, "s": 25184, "text": "Github Repo: https://github.com/cereniyim/Tree-Classification-ML-Model" }, { "code": null, "e": 25363, "s": 25255, "text": "Kaggle Notebook: https://www.kaggle.com/cereniyim/fantastic-trees-where-to-find-how-to-detect-them/notebook" }, { "code": null, "e": 25503, "s": 25363, "text": "Thanks for reading, this end-to-end workflow can be applied to any machine learning problem, I encourage you to go ahead and give it a try!" } ]
JUnit - Writing a Test
Here we will see one complete example of JUnit testing using POJO class, Business logic class, and a test class, which will be run by the test runner. Create EmployeeDetails.java in C:\>JUNIT_WORKSPACE, which is a POJO class. public class EmployeeDetails { private String name; private double monthlySalary; private int age; /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the monthlySalary */ public double getMonthlySalary() { return monthlySalary; } /** * @param monthlySalary the monthlySalary to set */ public void setMonthlySalary(double monthlySalary) { this.monthlySalary = monthlySalary; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } } EmployeeDetails class is used to − get/set the value of employee's name. get/set the value of employee's monthly salary. get/set the value of employee's age. Create a file called EmpBusinessLogic.java in C:\>JUNIT_WORKSPACE, which contains the business logic. public class EmpBusinessLogic { // Calculate the yearly salary of employee public double calculateYearlySalary(EmployeeDetails employeeDetails) { double yearlySalary = 0; yearlySalary = employeeDetails.getMonthlySalary() * 12; return yearlySalary; } // Calculate the appraisal amount of employee public double calculateAppraisal(EmployeeDetails employeeDetails) { double appraisal = 0; if(employeeDetails.getMonthlySalary() < 10000){ appraisal = 500; }else{ appraisal = 1000; } return appraisal; } } EmpBusinessLogic class is used for calculating − the yearly salary of an employee. the appraisal amount of an employee. Create a file called TestEmployeeDetails.java in C:\>JUNIT_WORKSPACE, which contains the test cases to be tested. import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestEmployeeDetails { EmpBusinessLogic empBusinessLogic = new EmpBusinessLogic(); EmployeeDetails employee = new EmployeeDetails(); //test to check appraisal @Test public void testCalculateAppriasal() { employee.setName("Rajeev"); employee.setAge(25); employee.setMonthlySalary(8000); double appraisal = empBusinessLogic.calculateAppraisal(employee); assertEquals(500, appraisal, 0.0); } // test to check yearly salary @Test public void testCalculateYearlySalary() { employee.setName("Rajeev"); employee.setAge(25); employee.setMonthlySalary(8000); double salary = empBusinessLogic.calculateYearlySalary(employee); assertEquals(96000, salary, 0.0); } } TestEmployeeDetails class is used for testing the methods of EmpBusinessLogic class. It tests the yearly salary of the employee. tests the appraisal amount of the employee. Next, create a java class filed named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestEmployeeDetails.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the test case and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac EmployeeDetails.java EmpBusinessLogic.java TestEmployeeDetails.java TestRunner.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. true 24 Lectures 2.5 hours Nishita Bhatt 56 Lectures 7.5 hours Dinesh Varyani Print Add Notes Bookmark this page
[ { "code": null, "e": 2123, "s": 1972, "text": "Here we will see one complete example of JUnit testing using POJO class, Business logic class, and a test class, which will be run by the test runner." }, { "code": null, "e": 2198, "s": 2123, "text": "Create EmployeeDetails.java in C:\\>JUNIT_WORKSPACE, which is a POJO class." }, { "code": null, "e": 3000, "s": 2198, "text": "public class EmployeeDetails {\n\n private String name;\n private double monthlySalary;\n private int age;\n \n /**\n * @return the name\n */\n\t\n public String getName() {\n return name;\n }\n\t\n /**\n * @param name the name to set\n */\n\t\n public void setName(String name) {\n this.name = name;\n }\n\t\n /**\n * @return the monthlySalary\n */\n\t\n public double getMonthlySalary() {\n return monthlySalary;\n }\n\t\n /**\n * @param monthlySalary the monthlySalary to set\n */\n\t\n public void setMonthlySalary(double monthlySalary) {\n this.monthlySalary = monthlySalary;\n }\n\t\n /**\n * @return the age\n */\n public int getAge() {\n return age;\n }\n\t\n /**\n * @param age the age to set\n */\n public void setAge(int age) {\n this.age = age;\n }\n}" }, { "code": null, "e": 3035, "s": 3000, "text": "EmployeeDetails class is used to −" }, { "code": null, "e": 3073, "s": 3035, "text": "get/set the value of employee's name." }, { "code": null, "e": 3121, "s": 3073, "text": "get/set the value of employee's monthly salary." }, { "code": null, "e": 3158, "s": 3121, "text": "get/set the value of employee's age." }, { "code": null, "e": 3260, "s": 3158, "text": "Create a file called EmpBusinessLogic.java in C:\\>JUNIT_WORKSPACE, which contains the business logic." }, { "code": null, "e": 3852, "s": 3260, "text": "public class EmpBusinessLogic {\n // Calculate the yearly salary of employee\n public double calculateYearlySalary(EmployeeDetails employeeDetails) {\n double yearlySalary = 0;\n yearlySalary = employeeDetails.getMonthlySalary() * 12;\n return yearlySalary;\n }\n\t\n // Calculate the appraisal amount of employee\n public double calculateAppraisal(EmployeeDetails employeeDetails) {\n double appraisal = 0;\n\t\t\n if(employeeDetails.getMonthlySalary() < 10000){\n appraisal = 500;\n }else{\n appraisal = 1000;\n }\n\t\t\n return appraisal;\n }\n}" }, { "code": null, "e": 3901, "s": 3852, "text": "EmpBusinessLogic class is used for calculating −" }, { "code": null, "e": 3935, "s": 3901, "text": "the yearly salary of an employee." }, { "code": null, "e": 3972, "s": 3935, "text": "the appraisal amount of an employee." }, { "code": null, "e": 4086, "s": 3972, "text": "Create a file called TestEmployeeDetails.java in C:\\>JUNIT_WORKSPACE, which contains the test cases to be tested." }, { "code": null, "e": 4919, "s": 4086, "text": "import org.junit.Test;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestEmployeeDetails {\n EmpBusinessLogic empBusinessLogic = new EmpBusinessLogic();\n EmployeeDetails employee = new EmployeeDetails();\n\n //test to check appraisal\n @Test\n public void testCalculateAppriasal() {\n employee.setName(\"Rajeev\");\n employee.setAge(25);\n employee.setMonthlySalary(8000);\n\t\t\n double appraisal = empBusinessLogic.calculateAppraisal(employee);\n assertEquals(500, appraisal, 0.0);\n }\n\n // test to check yearly salary\n @Test\n public void testCalculateYearlySalary() {\n employee.setName(\"Rajeev\");\n employee.setAge(25);\n employee.setMonthlySalary(8000);\n\t\t\n double salary = empBusinessLogic.calculateYearlySalary(employee);\n assertEquals(96000, salary, 0.0);\n }\n}" }, { "code": null, "e": 5007, "s": 4919, "text": "TestEmployeeDetails class is used for testing the methods of EmpBusinessLogic class. It" }, { "code": null, "e": 5048, "s": 5007, "text": "tests the yearly salary of the employee." }, { "code": null, "e": 5092, "s": 5048, "text": "tests the appraisal amount of the employee." }, { "code": null, "e": 5194, "s": 5092, "text": "Next, create a java class filed named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 5623, "s": 5194, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestEmployeeDetails.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} " }, { "code": null, "e": 5682, "s": 5623, "text": "Compile the test case and Test Runner classes using javac." }, { "code": null, "e": 5793, "s": 5682, "text": "C:\\JUNIT_WORKSPACE>javac EmployeeDetails.java \nEmpBusinessLogic.java TestEmployeeDetails.java TestRunner.java\n" }, { "code": null, "e": 5888, "s": 5793, "text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class." }, { "code": null, "e": 5924, "s": 5888, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 5943, "s": 5924, "text": "Verify the output." }, { "code": null, "e": 5949, "s": 5943, "text": "true\n" }, { "code": null, "e": 5984, "s": 5949, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5999, "s": 5984, "text": " Nishita Bhatt" }, { "code": null, "e": 6034, "s": 5999, "text": "\n 56 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6050, "s": 6034, "text": " Dinesh Varyani" }, { "code": null, "e": 6057, "s": 6050, "text": " Print" }, { "code": null, "e": 6068, "s": 6057, "text": " Add Notes" } ]
Angular PrimeNG FileUpload Component - GeeksforGeeks
07 Oct, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the FileUpload component in Angular PrimeNG. We will also learn about the properties, events, methods & styling along with their syntaxes that will be used in the code. FileUpload component: It is used to make an element that provides users to upload file content. Properties: name: It is the name of the request parameter. It is of string data type, the default value is null. url: It is the url to upload the files. It is of string data type, the default value is null. method: It specifies the HTTP method which is used to send. It is of string data type, the default value is post. multiple: It is used to select multiple files at once. It is of boolean data type, the default value is false. accept: It is the pattern to restrict the allowed file types. It is of string data type, the default value is false. disabled: It is used to disable the upload functionality. It is of boolean data type, the default value is false. auto: It specifies whether the upload begins automatically after selection is completed. It is of boolean data type, the default value is false. maxFileSize: It is the maximum file size allowed in bytes. It is of number data type, the default value is null. fileLimit: It is the maximum number of files that can be uploaded. It is of number data type, the default value is null. invalidFileSizeMessageSummary: It is the summary message of the invalid file size. It is of string data type, the default value is {0}: Invalid file size. invalidFileSizeMessageDetail: It is the detailed message of the invalid file size. It is of string data type, the default value is “maximum upload size is {0}.” invalidFileTypeMessageSummary: It is the summary message of the invalid file type. It is of string data type, the default value is “{0}: Invalid file type, “. invalidFileLimitMessageDetail: It is the detailed message of the invalid file type. It is of string data type, the default value is “limit is {0} at most”. invalidFileLimitMessageSummary: It is the summary message of the invalid file type. It is of string data type, the default value is “Maximum number of files exceeded”. invalidFileTypeMessageDetail: It is the detailed message of the invalid file type. It is of string data type, the default value is “allowed file types: {0}”. style: It is used to specify the inline style of the component. It is of string data type, the default value is null. styleClass: It is used to specify the style class of the component. It is of string data type, the default value is null. previewWidth: It is the width of the image thumbnail in pixels. It is of number data type, the default value is 50. chooseLabel: It is the label of the choose button. It is of string data type, the default value is null. uploadLabel: It is the label of the upload button. It is of string data type, the default value is null. cancelLabel: It is the label of the cancel button. It is of string data type, the default value is null. chooseIcon: It is the icon of the choose button. It is of string data type, the default value is pi pi-plus. uploadIcon: It is the icon of the upload button. It is of string data type, the default value is pi pi-upload. cancelIcon: It is the icon of the cancel button. It is of string data type, the default value is pi pi-times. mode: It is used to define the UI of the component. It is of string data type, the default value is advanced. customUpload: It is used to define whether to use the default upload or a manual implementation-defined in uploadHandler callback. It is of boolean data type, the default value is false. showUploadButton: It is used to define the visibility of the upload button. It is of boolean data type, the default value is true. showCancelButton: It is used to define the visibility of the cancel button. It is of boolean data type, the default value is true. files: It is the list of files to be provided to the FileUpload externally. It is of array data type, the default value is null. headers: It is the HttpHeaders class represents the header configuration options. It is of HttpHeader data type, the default value is null. Events: onBeforeUpload: It is a callback that is fired before file upload is initialized. onSend: It is a callback that is fired when the request was sent to the server. onUpload: It is a callback that is fired when file upload is complete. onError: It is a callback that is fired if file upload fails. onClear: It is a callback that is fired when files in the queue are removed without uploading using the clear all button. onRemove: It is a callback that is fired when a file is removed without uploading using a clear button of a file. onSelect: It is a callback that is fired when files are selected. onProgress: It is a callback that is fired when files are being uploaded. uploadHandler: It is a callback that is fired in custom upload mode to upload the files manually. Methods: upload: It is used to uploads the selected files. clear: It is used to clears the files list. Styling: p-fileupload: It is the container element. p-fileupload-buttonbar: It is the header containing the buttons. p-fileupload-content: It is the content section. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that illustrates how to use the FileUpload component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG FileUpload Component</h5><p-fileUpload name="myfile[]"></p-fileUpload> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { FileUploadModule } from "primeng/fileupload";import { HttpClientModule } from "@angular/common/http"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, FileUploadModule, HttpClientModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 2: In this example, we will be making an upload element that accepts multiple files and images only by using the multiple property. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG FileUpload Component</h5><p-fileUpload name="myfile[]" multiple="multiple" accept="image/*"></p-fileUpload> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { FileUploadModule } from "primeng/fileupload";import { HttpClientModule } from "@angular/common/http"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, FileUploadModule, HttpClientModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/fileupload Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Angular PrimeNG Dropdown Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event How to setup 404 page in angular routing ? How to create module with Routing in Angular 9 ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24718, "s": 24690, "text": "\n07 Oct, 2021" }, { "code": null, "e": 25129, "s": 24718, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the FileUpload component in Angular PrimeNG. We will also learn about the properties, events, methods & styling along with their syntaxes that will be used in the code. " }, { "code": null, "e": 25225, "s": 25129, "text": "FileUpload component: It is used to make an element that provides users to upload file content." }, { "code": null, "e": 25237, "s": 25225, "text": "Properties:" }, { "code": null, "e": 25338, "s": 25237, "text": "name: It is the name of the request parameter. It is of string data type, the default value is null." }, { "code": null, "e": 25432, "s": 25338, "text": "url: It is the url to upload the files. It is of string data type, the default value is null." }, { "code": null, "e": 25546, "s": 25432, "text": "method: It specifies the HTTP method which is used to send. It is of string data type, the default value is post." }, { "code": null, "e": 25657, "s": 25546, "text": "multiple: It is used to select multiple files at once. It is of boolean data type, the default value is false." }, { "code": null, "e": 25774, "s": 25657, "text": "accept: It is the pattern to restrict the allowed file types. It is of string data type, the default value is false." }, { "code": null, "e": 25888, "s": 25774, "text": "disabled: It is used to disable the upload functionality. It is of boolean data type, the default value is false." }, { "code": null, "e": 26033, "s": 25888, "text": "auto: It specifies whether the upload begins automatically after selection is completed. It is of boolean data type, the default value is false." }, { "code": null, "e": 26146, "s": 26033, "text": "maxFileSize: It is the maximum file size allowed in bytes. It is of number data type, the default value is null." }, { "code": null, "e": 26267, "s": 26146, "text": "fileLimit: It is the maximum number of files that can be uploaded. It is of number data type, the default value is null." }, { "code": null, "e": 26422, "s": 26267, "text": "invalidFileSizeMessageSummary: It is the summary message of the invalid file size. It is of string data type, the default value is {0}: Invalid file size." }, { "code": null, "e": 26583, "s": 26422, "text": "invalidFileSizeMessageDetail: It is the detailed message of the invalid file size. It is of string data type, the default value is “maximum upload size is {0}.”" }, { "code": null, "e": 26742, "s": 26583, "text": "invalidFileTypeMessageSummary: It is the summary message of the invalid file type. It is of string data type, the default value is “{0}: Invalid file type, “." }, { "code": null, "e": 26898, "s": 26742, "text": "invalidFileLimitMessageDetail: It is the detailed message of the invalid file type. It is of string data type, the default value is “limit is {0} at most”." }, { "code": null, "e": 27066, "s": 26898, "text": "invalidFileLimitMessageSummary: It is the summary message of the invalid file type. It is of string data type, the default value is “Maximum number of files exceeded”." }, { "code": null, "e": 27224, "s": 27066, "text": "invalidFileTypeMessageDetail: It is the detailed message of the invalid file type. It is of string data type, the default value is “allowed file types: {0}”." }, { "code": null, "e": 27342, "s": 27224, "text": "style: It is used to specify the inline style of the component. It is of string data type, the default value is null." }, { "code": null, "e": 27464, "s": 27342, "text": "styleClass: It is used to specify the style class of the component. It is of string data type, the default value is null." }, { "code": null, "e": 27580, "s": 27464, "text": "previewWidth: It is the width of the image thumbnail in pixels. It is of number data type, the default value is 50." }, { "code": null, "e": 27685, "s": 27580, "text": "chooseLabel: It is the label of the choose button. It is of string data type, the default value is null." }, { "code": null, "e": 27790, "s": 27685, "text": "uploadLabel: It is the label of the upload button. It is of string data type, the default value is null." }, { "code": null, "e": 27895, "s": 27790, "text": "cancelLabel: It is the label of the cancel button. It is of string data type, the default value is null." }, { "code": null, "e": 28004, "s": 27895, "text": "chooseIcon: It is the icon of the choose button. It is of string data type, the default value is pi pi-plus." }, { "code": null, "e": 28115, "s": 28004, "text": "uploadIcon: It is the icon of the upload button. It is of string data type, the default value is pi pi-upload." }, { "code": null, "e": 28225, "s": 28115, "text": "cancelIcon: It is the icon of the cancel button. It is of string data type, the default value is pi pi-times." }, { "code": null, "e": 28335, "s": 28225, "text": "mode: It is used to define the UI of the component. It is of string data type, the default value is advanced." }, { "code": null, "e": 28522, "s": 28335, "text": "customUpload: It is used to define whether to use the default upload or a manual implementation-defined in uploadHandler callback. It is of boolean data type, the default value is false." }, { "code": null, "e": 28653, "s": 28522, "text": "showUploadButton: It is used to define the visibility of the upload button. It is of boolean data type, the default value is true." }, { "code": null, "e": 28784, "s": 28653, "text": "showCancelButton: It is used to define the visibility of the cancel button. It is of boolean data type, the default value is true." }, { "code": null, "e": 28913, "s": 28784, "text": "files: It is the list of files to be provided to the FileUpload externally. It is of array data type, the default value is null." }, { "code": null, "e": 29053, "s": 28913, "text": "headers: It is the HttpHeaders class represents the header configuration options. It is of HttpHeader data type, the default value is null." }, { "code": null, "e": 29061, "s": 29053, "text": "Events:" }, { "code": null, "e": 29143, "s": 29061, "text": "onBeforeUpload: It is a callback that is fired before file upload is initialized." }, { "code": null, "e": 29223, "s": 29143, "text": "onSend: It is a callback that is fired when the request was sent to the server." }, { "code": null, "e": 29294, "s": 29223, "text": "onUpload: It is a callback that is fired when file upload is complete." }, { "code": null, "e": 29356, "s": 29294, "text": "onError: It is a callback that is fired if file upload fails." }, { "code": null, "e": 29478, "s": 29356, "text": "onClear: It is a callback that is fired when files in the queue are removed without uploading using the clear all button." }, { "code": null, "e": 29592, "s": 29478, "text": "onRemove: It is a callback that is fired when a file is removed without uploading using a clear button of a file." }, { "code": null, "e": 29658, "s": 29592, "text": "onSelect: It is a callback that is fired when files are selected." }, { "code": null, "e": 29732, "s": 29658, "text": "onProgress: It is a callback that is fired when files are being uploaded." }, { "code": null, "e": 29830, "s": 29732, "text": "uploadHandler: It is a callback that is fired in custom upload mode to upload the files manually." }, { "code": null, "e": 29841, "s": 29832, "text": "Methods:" }, { "code": null, "e": 29891, "s": 29841, "text": "upload: It is used to uploads the selected files." }, { "code": null, "e": 29935, "s": 29891, "text": "clear: It is used to clears the files list." }, { "code": null, "e": 29944, "s": 29935, "text": "Styling:" }, { "code": null, "e": 29987, "s": 29944, "text": "p-fileupload: It is the container element." }, { "code": null, "e": 30052, "s": 29987, "text": "p-fileupload-buttonbar: It is the header containing the buttons." }, { "code": null, "e": 30101, "s": 30052, "text": "p-fileupload-content: It is the content section." }, { "code": null, "e": 30153, "s": 30101, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 30220, "s": 30153, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 30235, "s": 30220, "text": "ng new appname" }, { "code": null, "e": 30332, "s": 30235, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 30343, "s": 30332, "text": "cd appname" }, { "code": null, "e": 30392, "s": 30343, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 30449, "s": 30392, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 30501, "s": 30449, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 30592, "s": 30501, "text": "Example 1: This is the basic example that illustrates how to use the FileUpload component." }, { "code": null, "e": 30611, "s": 30592, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG FileUpload Component</h5><p-fileUpload name=\"myfile[]\"></p-fileUpload>", "e": 30716, "s": 30611, "text": null }, { "code": null, "e": 30735, "s": 30718, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}", "e": 30918, "s": 30735, "text": null }, { "code": null, "e": 30932, "s": 30918, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { FileUploadModule } from \"primeng/fileupload\";import { HttpClientModule } from \"@angular/common/http\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, FileUploadModule, HttpClientModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 31477, "s": 30932, "text": null }, { "code": null, "e": 31485, "s": 31477, "text": "Output:" }, { "code": null, "e": 31625, "s": 31485, "text": "Example 2: In this example, we will be making an upload element that accepts multiple files and images only by using the multiple property." }, { "code": null, "e": 31644, "s": 31625, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG FileUpload Component</h5><p-fileUpload name=\"myfile[]\" multiple=\"multiple\" accept=\"image/*\"></p-fileUpload>", "e": 31789, "s": 31644, "text": null }, { "code": null, "e": 31806, "s": 31789, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}", "e": 31989, "s": 31806, "text": null }, { "code": null, "e": 32003, "s": 31989, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { FileUploadModule } from \"primeng/fileupload\";import { HttpClientModule } from \"@angular/common/http\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, FileUploadModule, HttpClientModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 32548, "s": 32003, "text": null }, { "code": null, "e": 32556, "s": 32548, "text": "Output:" }, { "code": null, "e": 32620, "s": 32556, "text": "Reference: https://primefaces.org/primeng/showcase/#/fileupload" }, { "code": null, "e": 32636, "s": 32620, "text": "Angular-PrimeNG" }, { "code": null, "e": 32646, "s": 32636, "text": "AngularJS" }, { "code": null, "e": 32663, "s": 32646, "text": "Web Technologies" }, { "code": null, "e": 32761, "s": 32663, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32770, "s": 32761, "text": "Comments" }, { "code": null, "e": 32783, "s": 32770, "text": "Old Comments" }, { "code": null, "e": 32818, "s": 32783, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 32871, "s": 32818, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 32895, "s": 32871, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 32938, "s": 32895, "text": "How to setup 404 page in angular routing ?" }, { "code": null, "e": 32987, "s": 32938, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 33043, "s": 32987, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 33076, "s": 33043, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33138, "s": 33076, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33181, "s": 33138, "text": "How to fetch data from an API in ReactJS ?" } ]
Build a Virtual Assistant Using Python - GeeksforGeeks
16 Jul, 2020 Virtual desktop assistant is an awesome thing. If you want your machine to run on your command like Jarvis did for Tony. Yes it is possible. It is possible using Python. Python offers a good major library so that we can use it for making a virtual assistant. Windows has Sapi5 and Linux has Espeak which can help us in having the voice from our machine. It is a weak A.I. pyttsx3: pyttsx is a cross-platform text to speech library which is platform independent. The major advantage of using this library for text-to-speech conversion is that it works offline. To install this module type the below command in the terminal. pip install pyttsx3 SpeechRecognition: It allow us to convert audio into text for further processing. To install this module type the below command in the terminal. pip install SpeechRecognition webbrowser: It provides a high-level interface which allows displaying Web-based documents to users. To install this module type the below command in the terminal. pip install webbrowser Wikipedia: It is used to fetch a variety of information from the Wikipedia website. To install this module type the below command in the terminal. pip install wikipedia Speak Method will help us in taking the voice from the machine. Here is the code explanation of Speak Method Python3 def speak(audio): engine = pyttsx3.init() # getter method(gets the current value # of engine property) voices = engine.getProperty('voices') # setter method .[0]=male voice and # [1]=female voice in set Property. engine.setProperty('voice', voices[0].id) # Method for the speaking of the the assistant engine.say(audio) # Blocks while processing all the currently # queued commands engine.runAndWait() This method will check for the condition. If the condition is true it will return output. We can add any number if conditions for it and if the condition satisfy we will get the desired output. Python3 def Take_query(): # calling the Hello function for # making it more interactive Hello() # This loop is infinite as it will take # our queries continuously until and unless # we do not say bye to exit or terminate # the program while(True): # taking the query and making it into # lower case so that most of the times # query matches and we get the perfect # output query = takeCommand().lower() if "open geeksforgeeks" in query: speak("Opening GeeksforGeeks ") # in the open method we just to give the link # of the website and it automatically open # it in your default browser webbrowser.open("www.geeksforgeeks.com") continue elif "open google" in query: speak("Opening Google ") webbrowser.open("www.google.com") continue elif "which day it is" in query: tellDay() continue elif "tell me the time" in query: tellTime() continue # this will exit and terminate the program elif "bye" in query: speak("Bye. Check Out GFG for more exicting things") exit() elif "from wikipedia" in query: # if any one wants to have a information # from wikipedia speak("Checking the wikipedia ") query = query.replace("wikipedia", "") # it will give the summary of 4 lines from # wikipedia we can increase and decrease # it also. result = wikipedia.summary(query, sentences=4) speak("According to wikipedia") speak(result) elif "tell me your name" in query: speak("I am Jarvis. Your deskstop Assistant") This method is for taking the commands and recognizing the command from the speech_Recognition module Python3 # this method is for taking the commands# and recognizing the command from the# speech_Recognition module we will use# the recongizer method for recognizingdef takeCommand(): r = sr.Recognizer() # from the speech_Recognition module # we will use the Microphone module # for listening the command with sr.Microphone() as source: print('Listening') # seconds of non-speaking audio before # a phrase is considered complete r.pause_threshold = 0.7 audio = r.listen(source) # Now we will be using the try and catch # method so that if sound is recognized # it is good else we will have exception # handling try: print("Recognizing") # for Listening the command in indian # english we can also use 'hi-In' # for hindi recognizing Query = r.recognize_google(audio, language='en-in') print("the command is printed=", Query) except Exception as e: print(e) print("Say that again sir") return "None" return Query Python3 # codedef tellTime(self):# This method will give the time time = str(datetime.datetime.now()) # the time will be displayed like this "2020-06-05 17:50:14.582630" # nd then after slicing we can get time print(time) hour = time[11:13] min = time[14:16] self.Speak(self, "The time is sir" + hour + "Hours and" + min + "Minutes") """ This method will take time and slice it "2020-06-05 17:50:14.582630" from 11 to 12 for hour and 14-15 for min and then speak function will be called and then it will speak the current time """ This is just used to greet the user with a hello message. Python3 def Hello(): # This function is for when the assistant # is called it will say hello and then # take query speak("hello sir I am your desktop assistant. / Tell me how may I help you") Main method is the method where all the files get executed so we will call the Take_query method here so that it can recognize and tell or give us the desired output. Python3 if __name__ == '__main__': # main method for executing # the functions Take_query() Complete Code: Python3 import pyttsx3import speech_recognition as srimport webbrowser import datetime import wikipedia # this method is for taking the commands# and recognizing the command from the# speech_Recognition module we will use# the recongizer method for recognizingdef takeCommand(): r = sr.Recognizer() # from the speech_Recognition module # we will use the Microphone module # for listening the command with sr.Microphone() as source: print('Listening') # seconds of non-speaking audio before # a phrase is considered complete r.pause_threshold = 0.7 audio = r.listen(source) # Now we will be using the try and catch # method so that if sound is recognized # it is good else we will have exception # handling try: print("Recognizing") # for Listening the command in indian # english we can also use 'hi-In' # for hindi recognizing Query = r.recognize_google(audio, language='en-in') print("the command is printed=", Query) except Exception as e: print(e) print("Say that again sir") return "None" return Query def speak(audio): engine = pyttsx3.init() # getter method(gets the current value # of engine property) voices = engine.getProperty('voices') # setter method .[0]=male voice and # [1]=female voice in set Property. engine.setProperty('voice', voices[0].id) # Method for the speaking of the the assistant engine.say(audio) # Blocks while processing all the currently # queued commands engine.runAndWait() def tellDay(): # This function is for telling the # day of the week day = datetime.datetime.today().weekday() + 1 #this line tells us about the number # that will help us in telling the day Day_dict = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', 7: 'Sunday'} if day in Day_dict.keys(): day_of_the_week = Day_dict[day] print(day_of_the_week) speak("The day is " + day_of_the_week) def tellTime(): # This method will give the time time = str(datetime.datetime.now()) # the time will be displayed like # this "2020-06-05 17:50:14.582630" #nd then after slicing we can get time print(time) hour = time[11:13] min = time[14:16] speak(self, "The time is sir" + hour + "Hours and" + min + "Minutes") def Hello(): # This function is for when the assistant # is called it will say hello and then # take query speak("hello sir I am your desktop assistant. / Tell me how may I help you") def Take_query(): # calling the Hello function for # making it more interactive Hello() # This loop is infinite as it will take # our queries continuously until and unless # we do not say bye to exit or terminate # the program while(True): # taking the query and making it into # lower case so that most of the times # query matches and we get the perfect # output query = takeCommand().lower() if "open geeksforgeeks" in query: speak("Opening GeeksforGeeks ") # in the open method we just to give the link # of the website and it automatically open # it in your default browser webbrowser.open("www.geeksforgeeks.com") continue elif "open google" in query: speak("Opening Google ") webbrowser.open("www.google.com") continue elif "which day it is" in query: tellDay() continue elif "tell me the time" in query: tellTime() continue # this will exit and terminate the program elif "bye" in query: speak("Bye. Check Out GFG for more exicting things") exit() elif "from wikipedia" in query: # if any one wants to have a information # from wikipedia speak("Checking the wikipedia ") query = query.replace("wikipedia", "") # it will give the summary of 4 lines from # wikipedia we can increase and decrease # it also. result = wikipedia.summary(query, sentences=4) speak("According to wikipedia") speak(result) elif "tell me your name" in query: speak("I am Jarvis. Your deskstop Assistant") if __name__ == '__main__': # main method for executing # the functions Take_query() Output: Python-projects python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24750, "s": 24722, "text": "\n16 Jul, 2020" }, { "code": null, "e": 25122, "s": 24750, "text": "Virtual desktop assistant is an awesome thing. If you want your machine to run on your command like Jarvis did for Tony. Yes it is possible. It is possible using Python. Python offers a good major library so that we can use it for making a virtual assistant. Windows has Sapi5 and Linux has Espeak which can help us in having the voice from our machine. It is a weak A.I." }, { "code": null, "e": 25373, "s": 25122, "text": "pyttsx3: pyttsx is a cross-platform text to speech library which is platform independent. The major advantage of using this library for text-to-speech conversion is that it works offline. To install this module type the below command in the terminal." }, { "code": null, "e": 25393, "s": 25373, "text": "pip install pyttsx3" }, { "code": null, "e": 25538, "s": 25393, "text": "SpeechRecognition: It allow us to convert audio into text for further processing. To install this module type the below command in the terminal." }, { "code": null, "e": 25568, "s": 25538, "text": "pip install SpeechRecognition" }, { "code": null, "e": 25732, "s": 25568, "text": "webbrowser: It provides a high-level interface which allows displaying Web-based documents to users. To install this module type the below command in the terminal." }, { "code": null, "e": 25755, "s": 25732, "text": "pip install webbrowser" }, { "code": null, "e": 25902, "s": 25755, "text": "Wikipedia: It is used to fetch a variety of information from the Wikipedia website. To install this module type the below command in the terminal." }, { "code": null, "e": 25924, "s": 25902, "text": "pip install wikipedia" }, { "code": null, "e": 26033, "s": 25924, "text": "Speak Method will help us in taking the voice from the machine. Here is the code explanation of Speak Method" }, { "code": null, "e": 26041, "s": 26033, "text": "Python3" }, { "code": "def speak(audio): engine = pyttsx3.init() # getter method(gets the current value # of engine property) voices = engine.getProperty('voices') # setter method .[0]=male voice and # [1]=female voice in set Property. engine.setProperty('voice', voices[0].id) # Method for the speaking of the the assistant engine.say(audio) # Blocks while processing all the currently # queued commands engine.runAndWait()", "e": 26506, "s": 26041, "text": null }, { "code": null, "e": 26700, "s": 26506, "text": "This method will check for the condition. If the condition is true it will return output. We can add any number if conditions for it and if the condition satisfy we will get the desired output." }, { "code": null, "e": 26708, "s": 26700, "text": "Python3" }, { "code": "def Take_query(): # calling the Hello function for # making it more interactive Hello() # This loop is infinite as it will take # our queries continuously until and unless # we do not say bye to exit or terminate # the program while(True): # taking the query and making it into # lower case so that most of the times # query matches and we get the perfect # output query = takeCommand().lower() if \"open geeksforgeeks\" in query: speak(\"Opening GeeksforGeeks \") # in the open method we just to give the link # of the website and it automatically open # it in your default browser webbrowser.open(\"www.geeksforgeeks.com\") continue elif \"open google\" in query: speak(\"Opening Google \") webbrowser.open(\"www.google.com\") continue elif \"which day it is\" in query: tellDay() continue elif \"tell me the time\" in query: tellTime() continue # this will exit and terminate the program elif \"bye\" in query: speak(\"Bye. Check Out GFG for more exicting things\") exit() elif \"from wikipedia\" in query: # if any one wants to have a information # from wikipedia speak(\"Checking the wikipedia \") query = query.replace(\"wikipedia\", \"\") # it will give the summary of 4 lines from # wikipedia we can increase and decrease # it also. result = wikipedia.summary(query, sentences=4) speak(\"According to wikipedia\") speak(result) elif \"tell me your name\" in query: speak(\"I am Jarvis. Your deskstop Assistant\")", "e": 28627, "s": 26708, "text": null }, { "code": null, "e": 28729, "s": 28627, "text": "This method is for taking the commands and recognizing the command from the speech_Recognition module" }, { "code": null, "e": 28737, "s": 28729, "text": "Python3" }, { "code": "# this method is for taking the commands# and recognizing the command from the# speech_Recognition module we will use# the recongizer method for recognizingdef takeCommand(): r = sr.Recognizer() # from the speech_Recognition module # we will use the Microphone module # for listening the command with sr.Microphone() as source: print('Listening') # seconds of non-speaking audio before # a phrase is considered complete r.pause_threshold = 0.7 audio = r.listen(source) # Now we will be using the try and catch # method so that if sound is recognized # it is good else we will have exception # handling try: print(\"Recognizing\") # for Listening the command in indian # english we can also use 'hi-In' # for hindi recognizing Query = r.recognize_google(audio, language='en-in') print(\"the command is printed=\", Query) except Exception as e: print(e) print(\"Say that again sir\") return \"None\" return Query", "e": 29905, "s": 28737, "text": null }, { "code": null, "e": 29913, "s": 29905, "text": "Python3" }, { "code": "# codedef tellTime(self):# This method will give the time time = str(datetime.datetime.now()) # the time will be displayed like this \"2020-06-05 17:50:14.582630\" # nd then after slicing we can get time print(time) hour = time[11:13] min = time[14:16] self.Speak(self, \"The time is sir\" + hour + \"Hours and\" + min + \"Minutes\") \"\"\" This method will take time and slice it \"2020-06-05 17:50:14.582630\" from 11 to 12 for hour and 14-15 for min and then speak function will be called and then it will speak the current time \"\"\"", "e": 30464, "s": 29913, "text": null }, { "code": null, "e": 30522, "s": 30464, "text": "This is just used to greet the user with a hello message." }, { "code": null, "e": 30530, "s": 30522, "text": "Python3" }, { "code": "def Hello(): # This function is for when the assistant # is called it will say hello and then # take query speak(\"hello sir I am your desktop assistant. / Tell me how may I help you\")", "e": 30737, "s": 30530, "text": null }, { "code": null, "e": 30905, "s": 30737, "text": "Main method is the method where all the files get executed so we will call the Take_query method here so that it can recognize and tell or give us the desired output. " }, { "code": null, "e": 30913, "s": 30905, "text": "Python3" }, { "code": "if __name__ == '__main__': # main method for executing # the functions Take_query()", "e": 31012, "s": 30913, "text": null }, { "code": null, "e": 31028, "s": 31012, "text": " Complete Code:" }, { "code": null, "e": 31036, "s": 31028, "text": "Python3" }, { "code": "import pyttsx3import speech_recognition as srimport webbrowser import datetime import wikipedia # this method is for taking the commands# and recognizing the command from the# speech_Recognition module we will use# the recongizer method for recognizingdef takeCommand(): r = sr.Recognizer() # from the speech_Recognition module # we will use the Microphone module # for listening the command with sr.Microphone() as source: print('Listening') # seconds of non-speaking audio before # a phrase is considered complete r.pause_threshold = 0.7 audio = r.listen(source) # Now we will be using the try and catch # method so that if sound is recognized # it is good else we will have exception # handling try: print(\"Recognizing\") # for Listening the command in indian # english we can also use 'hi-In' # for hindi recognizing Query = r.recognize_google(audio, language='en-in') print(\"the command is printed=\", Query) except Exception as e: print(e) print(\"Say that again sir\") return \"None\" return Query def speak(audio): engine = pyttsx3.init() # getter method(gets the current value # of engine property) voices = engine.getProperty('voices') # setter method .[0]=male voice and # [1]=female voice in set Property. engine.setProperty('voice', voices[0].id) # Method for the speaking of the the assistant engine.say(audio) # Blocks while processing all the currently # queued commands engine.runAndWait() def tellDay(): # This function is for telling the # day of the week day = datetime.datetime.today().weekday() + 1 #this line tells us about the number # that will help us in telling the day Day_dict = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', 7: 'Sunday'} if day in Day_dict.keys(): day_of_the_week = Day_dict[day] print(day_of_the_week) speak(\"The day is \" + day_of_the_week) def tellTime(): # This method will give the time time = str(datetime.datetime.now()) # the time will be displayed like # this \"2020-06-05 17:50:14.582630\" #nd then after slicing we can get time print(time) hour = time[11:13] min = time[14:16] speak(self, \"The time is sir\" + hour + \"Hours and\" + min + \"Minutes\") def Hello(): # This function is for when the assistant # is called it will say hello and then # take query speak(\"hello sir I am your desktop assistant. / Tell me how may I help you\") def Take_query(): # calling the Hello function for # making it more interactive Hello() # This loop is infinite as it will take # our queries continuously until and unless # we do not say bye to exit or terminate # the program while(True): # taking the query and making it into # lower case so that most of the times # query matches and we get the perfect # output query = takeCommand().lower() if \"open geeksforgeeks\" in query: speak(\"Opening GeeksforGeeks \") # in the open method we just to give the link # of the website and it automatically open # it in your default browser webbrowser.open(\"www.geeksforgeeks.com\") continue elif \"open google\" in query: speak(\"Opening Google \") webbrowser.open(\"www.google.com\") continue elif \"which day it is\" in query: tellDay() continue elif \"tell me the time\" in query: tellTime() continue # this will exit and terminate the program elif \"bye\" in query: speak(\"Bye. Check Out GFG for more exicting things\") exit() elif \"from wikipedia\" in query: # if any one wants to have a information # from wikipedia speak(\"Checking the wikipedia \") query = query.replace(\"wikipedia\", \"\") # it will give the summary of 4 lines from # wikipedia we can increase and decrease # it also. result = wikipedia.summary(query, sentences=4) speak(\"According to wikipedia\") speak(result) elif \"tell me your name\" in query: speak(\"I am Jarvis. Your deskstop Assistant\") if __name__ == '__main__': # main method for executing # the functions Take_query()", "e": 35899, "s": 31036, "text": null }, { "code": null, "e": 35907, "s": 35899, "text": "Output:" }, { "code": null, "e": 35923, "s": 35907, "text": "Python-projects" }, { "code": null, "e": 35938, "s": 35923, "text": "python-utility" }, { "code": null, "e": 35945, "s": 35938, "text": "Python" }, { "code": null, "e": 36043, "s": 35945, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36061, "s": 36043, "text": "Python Dictionary" }, { "code": null, "e": 36096, "s": 36061, "text": "Read a file line by line in Python" }, { "code": null, "e": 36118, "s": 36096, "text": "Enumerate() in Python" }, { "code": null, "e": 36150, "s": 36118, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 36180, "s": 36150, "text": "Iterate over a list in Python" }, { "code": null, "e": 36222, "s": 36180, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 36248, "s": 36222, "text": "Python String | replace()" }, { "code": null, "e": 36285, "s": 36248, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 36328, "s": 36285, "text": "Python program to convert a list to string" } ]
jQuery - jQuery.ajax( options ) Method
The jQuery.ajax( options ) method loads a remote page using an HTTP request. $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually. Here is the simple syntax to use this method − $.ajax( options ) Here is the description of all the parameters used by this method − options − A set of key/value pairs that configure the Ajax request. All options are optional. options − A set of key/value pairs that configure the Ajax request. All options are optional. A Boolean indicating whether to perform the request asynchronously. The default value is true. A callback function that is executed before the request is sent. A callback function that executes whenever the request finishes. A string containing a MIME content type to set for the request. The default value is application/x-www-form-urlencoded. A map or string that is sent to the server with the request. A function to be used to handle the raw responsed data of XMLHttpRequest. This is a pre-filtering function to sanitize the response. A string defining the type of data expected back from the server (xml, html, json, or script). A callback function that is executed if the request fails. A Boolean indicating whether global AJAX event handlers will be triggered by this request. The default value is true. A Boolean indicating whether the server should check if the page is modified before responding to the request. Override the callback function name in a jsonp request. A password to be used in response to an HTTP access authentication request. A Boolean indicating whether to convert the submitted data from an object form into a query-string form. The default value is true. A callback function that is executed if the request succeeds. Number of milliseconds after which the request will time out in failure. Set a local timeout (in milliseconds) for the request. A string defining the HTTP method to use for the request (GET or POST). The default value is GET. A string containing the URL to which the request is sent. A username to be used in response to an HTTP access authentication request. Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Assuming we have following HTML content in result.html file − <h1>THIS IS RESULT...</h1> Following is a simple example a simple showing the usage of this method. Here we make use of success handler to populate returned HTML − <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){ $.ajax( { url:'result.html', success:function(data) { $('#stage').html(data); } }); }); }); </script> </head> <body> <p>Click on the button to load result.html file:</p> <div id = "stage" style = "background-color:blue;"> STAGE </div> <input type = "button" id = "driver" value = "Load Data" /> </body> </html> This will produce following result − Click on the button to load result.html file − 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": 2399, "s": 2322, "text": "The jQuery.ajax( options ) method loads a remote page using an HTTP request." }, { "code": null, "e": 2580, "s": 2399, "text": "$.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually." }, { "code": null, "e": 2627, "s": 2580, "text": "Here is the simple syntax to use this method −" }, { "code": null, "e": 2646, "s": 2627, "text": "$.ajax( options )\n" }, { "code": null, "e": 2714, "s": 2646, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 2808, "s": 2714, "text": "options − A set of key/value pairs that configure the Ajax request. All options are optional." }, { "code": null, "e": 2902, "s": 2808, "text": "options − A set of key/value pairs that configure the Ajax request. All options are optional." }, { "code": null, "e": 2997, "s": 2902, "text": "A Boolean indicating whether to perform the request asynchronously. The default value is true." }, { "code": null, "e": 3062, "s": 2997, "text": "A callback function that is executed before the request is sent." }, { "code": null, "e": 3127, "s": 3062, "text": "A callback function that executes whenever the request finishes." }, { "code": null, "e": 3247, "s": 3127, "text": "A string containing a MIME content type to set for the request. The default value is application/x-www-form-urlencoded." }, { "code": null, "e": 3308, "s": 3247, "text": "A map or string that is sent to the server with the request." }, { "code": null, "e": 3441, "s": 3308, "text": "A function to be used to handle the raw responsed data of XMLHttpRequest. This is a pre-filtering function to sanitize the response." }, { "code": null, "e": 3536, "s": 3441, "text": "A string defining the type of data expected back from the server (xml, html, json, or script)." }, { "code": null, "e": 3595, "s": 3536, "text": "A callback function that is executed if the request fails." }, { "code": null, "e": 3713, "s": 3595, "text": "A Boolean indicating whether global AJAX event handlers will be triggered by this request. The default value is true." }, { "code": null, "e": 3824, "s": 3713, "text": "A Boolean indicating whether the server should check if the page is modified before responding to the request." }, { "code": null, "e": 3880, "s": 3824, "text": "Override the callback function name in a jsonp request." }, { "code": null, "e": 3956, "s": 3880, "text": "A password to be used in response to an HTTP access authentication request." }, { "code": null, "e": 4088, "s": 3956, "text": "A Boolean indicating whether to convert the submitted data from an object form into a query-string form. The default value is true." }, { "code": null, "e": 4150, "s": 4088, "text": "A callback function that is executed if the request succeeds." }, { "code": null, "e": 4223, "s": 4150, "text": "Number of milliseconds after which the request will time out in failure." }, { "code": null, "e": 4278, "s": 4223, "text": "Set a local timeout (in milliseconds) for the request." }, { "code": null, "e": 4376, "s": 4278, "text": "A string defining the HTTP method to use for the request (GET or POST). The default value is GET." }, { "code": null, "e": 4434, "s": 4376, "text": "A string containing the URL to which the request is sent." }, { "code": null, "e": 4510, "s": 4434, "text": "A username to be used in response to an HTTP access authentication request." }, { "code": null, "e": 4640, "s": 4510, "text": "Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise." }, { "code": null, "e": 4702, "s": 4640, "text": "Assuming we have following HTML content in result.html file −" }, { "code": null, "e": 4730, "s": 4702, "text": "<h1>THIS IS RESULT...</h1>\n" }, { "code": null, "e": 4867, "s": 4730, "text": "Following is a simple example a simple showing the usage of this method. Here we make use of success handler to populate returned HTML −" }, { "code": null, "e": 5711, "s": 4867, "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 $(\"#driver\").click(function(event){\n $.ajax( {\n url:'result.html',\n success:function(data) {\n $('#stage').html(data);\n }\n });\n });\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 = \"stage\" style = \"background-color:blue;\">\n STAGE\n </div>\n\t\t\n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n </body>\n</html>" }, { "code": null, "e": 5748, "s": 5711, "text": "This will produce following result −" }, { "code": null, "e": 5795, "s": 5748, "text": "Click on the button to load result.html file −" }, { "code": null, "e": 5828, "s": 5795, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 5842, "s": 5828, "text": " Mahesh Kumar" }, { "code": null, "e": 5877, "s": 5842, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5891, "s": 5877, "text": " Pratik Singh" }, { "code": null, "e": 5926, "s": 5891, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5943, "s": 5926, "text": " Frahaan Hussain" }, { "code": null, "e": 5976, "s": 5943, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 6004, "s": 5976, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6037, "s": 6004, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 6058, "s": 6037, "text": " Sandip Bhattacharya" }, { "code": null, "e": 6090, "s": 6058, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 6107, "s": 6090, "text": " Laurence Svekis" }, { "code": null, "e": 6114, "s": 6107, "text": " Print" }, { "code": null, "e": 6125, "s": 6114, "text": " Add Notes" } ]
Difference between Antivirus and Internet Security - GeeksforGeeks
24 May, 2020 Antivirus:Antivirus is an application or software which provides security from the malicious software coming from the internet. An antivirus chases the method in which it performs 3 actions which are: 1. Detection 2. Identification 3. Removal Antivirus deals with both external threats and internal threats. It is implemented only software not in hardware also. Internet Security:Internet Security has the antivirus feature as well as some other features. It deals with protection and privacy against viruses, phishing, spyware etc. It also deals with all internet threats and cyber attacks. Internet security includes firewall, features of antivirus, email protection and parent control. Internet security deals with the protection of data, sent over the Internet for example: debit card number, credit card number, email_passwords, bank account details etc. Let’s see the difference between Antivirus and Internet Security: ashushrma378 pp_pankaj Computer Networks Difference Between Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advanced Encryption Standard (AES) Intrusion Detection System (IDS) Multiple Access Protocols in Computer Network GSM in Wireless Communication Cryptography and its Types Difference between BFS and DFS Class method vs Static method in Python Difference between var, let and const keywords in JavaScript Difference Between == and .equals() Method in Java Difference between Process and Thread
[ { "code": null, "e": 24510, "s": 24482, "text": "\n24 May, 2020" }, { "code": null, "e": 24711, "s": 24510, "text": "Antivirus:Antivirus is an application or software which provides security from the malicious software coming from the internet. An antivirus chases the method in which it performs 3 actions which are:" }, { "code": null, "e": 24754, "s": 24711, "text": "1. Detection\n2. Identification\n3. Removal " }, { "code": null, "e": 24873, "s": 24754, "text": "Antivirus deals with both external threats and internal threats. It is implemented only software not in hardware also." }, { "code": null, "e": 25371, "s": 24873, "text": "Internet Security:Internet Security has the antivirus feature as well as some other features. It deals with protection and privacy against viruses, phishing, spyware etc. It also deals with all internet threats and cyber attacks. Internet security includes firewall, features of antivirus, email protection and parent control. Internet security deals with the protection of data, sent over the Internet for example: debit card number, credit card number, email_passwords, bank account details etc." }, { "code": null, "e": 25437, "s": 25371, "text": "Let’s see the difference between Antivirus and Internet Security:" }, { "code": null, "e": 25450, "s": 25437, "text": "ashushrma378" }, { "code": null, "e": 25460, "s": 25450, "text": "pp_pankaj" }, { "code": null, "e": 25478, "s": 25460, "text": "Computer Networks" }, { "code": null, "e": 25497, "s": 25478, "text": "Difference Between" }, { "code": null, "e": 25515, "s": 25497, "text": "Computer Networks" }, { "code": null, "e": 25613, "s": 25515, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25648, "s": 25613, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 25681, "s": 25648, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 25727, "s": 25681, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 25757, "s": 25727, "text": "GSM in Wireless Communication" }, { "code": null, "e": 25784, "s": 25757, "text": "Cryptography and its Types" }, { "code": null, "e": 25815, "s": 25784, "text": "Difference between BFS and DFS" }, { "code": null, "e": 25855, "s": 25815, "text": "Class method vs Static method in Python" }, { "code": null, "e": 25916, "s": 25855, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 25967, "s": 25916, "text": "Difference Between == and .equals() Method in Java" } ]
Conditional wait and signal in multi-threading - GeeksforGeeks
06 Jul, 2021 What are conditional wait and signal in multi-threading? Explanation: When you want to sleep a thread, condition variable can be used. In C under Linux, there is a function pthread_cond_wait() to wait or sleep. On the other hand, there is a function pthread_cond_signal() to wake up sleeping or waiting thread. Threads can wait on a condition variable. Prerequisite : Multithreading Syntax of pthread_cond_wait() : int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex); Parameter : cond : condition variable mutex : is mutex lock Return Value : On success, 0 is returned ; otherwise, an error number shall be returned to indicate the error. The pthread_cond_wait() release a lock specified by mutex and wait on condition cond variable. Syntax of pthread_cond_signal() : int pthread_cond_signal(pthread_cond_t *cond); Parameter : cond : condition variable Return Value : On success, 0 is returned ; otherwise, an error number shall be returned to indicate the error. The pthread_cond_signal() wake up threads waiting for the condition variable. Note : The above two functions works together. Below is the implementation of condition, wait and signal functions. C // C program to implement cond(), signal()// and wait() functions#include <pthread.h>#include <stdio.h>#include <unistd.h> // Declaration of thread condition variablepthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; // declaring mutexpthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; int done = 1; // Thread functionvoid* foo(){ // acquire a lock pthread_mutex_lock(&lock); if (done == 1) { // let's wait on condition variable cond1 done = 2; printf("Waiting on condition variable cond1\n"); pthread_cond_wait(&cond1, &lock); } else { // Let's signal condition variable cond1 printf("Signaling condition variable cond1\n"); pthread_cond_signal(&cond1); } // release lock pthread_mutex_unlock(&lock); printf("Returning thread\n"); return NULL;} // Driver codeint main(){ pthread_t tid1, tid2; // Create thread 1 pthread_create(&tid1, NULL, foo, NULL); // sleep for 1 sec so that thread 1 // would get a chance to run first sleep(1); // Create thread 2 pthread_create(&tid2, NULL, foo, NULL); // wait for the completion of thread 2 pthread_join(tid2, NULL); return 0;} Output: nidhi_biet surinderdawra388 cpp-multithreading mutli-threading system-programming C Programs Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File How to Append a Character to a String in C C program to sort an array in ascending order time() function in C C Program to Swap two Numbers Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 25707, "s": 25679, "text": "\n06 Jul, 2021" }, { "code": null, "e": 26061, "s": 25707, "text": "What are conditional wait and signal in multi-threading? Explanation: When you want to sleep a thread, condition variable can be used. In C under Linux, there is a function pthread_cond_wait() to wait or sleep. On the other hand, there is a function pthread_cond_signal() to wake up sleeping or waiting thread. Threads can wait on a condition variable. " }, { "code": null, "e": 26091, "s": 26061, "text": "Prerequisite : Multithreading" }, { "code": null, "e": 26124, "s": 26091, "text": "Syntax of pthread_cond_wait() : " }, { "code": null, "e": 26231, "s": 26124, "text": "int pthread_cond_wait(pthread_cond_t *restrict cond, \n pthread_mutex_t *restrict mutex);" }, { "code": null, "e": 26245, "s": 26231, "text": "Parameter : " }, { "code": null, "e": 26294, "s": 26245, "text": "cond : condition variable\nmutex : is mutex lock " }, { "code": null, "e": 26311, "s": 26294, "text": "Return Value : " }, { "code": null, "e": 26409, "s": 26311, "text": "On success, 0 is returned ; otherwise, an error \nnumber shall be returned to indicate the error. " }, { "code": null, "e": 26505, "s": 26409, "text": "The pthread_cond_wait() release a lock specified by mutex and wait on condition cond variable. " }, { "code": null, "e": 26541, "s": 26505, "text": "Syntax of pthread_cond_signal() : " }, { "code": null, "e": 26588, "s": 26541, "text": "int pthread_cond_signal(pthread_cond_t *cond);" }, { "code": null, "e": 26601, "s": 26588, "text": "Parameter : " }, { "code": null, "e": 26627, "s": 26601, "text": "cond : condition variable" }, { "code": null, "e": 26644, "s": 26627, "text": "Return Value : " }, { "code": null, "e": 26741, "s": 26644, "text": "On success, 0 is returned ; otherwise, an error number\nshall be returned to indicate the error. " }, { "code": null, "e": 26820, "s": 26741, "text": "The pthread_cond_signal() wake up threads waiting for the condition variable. " }, { "code": null, "e": 26868, "s": 26820, "text": "Note : The above two functions works together. " }, { "code": null, "e": 26939, "s": 26868, "text": "Below is the implementation of condition, wait and signal functions. " }, { "code": null, "e": 26941, "s": 26939, "text": "C" }, { "code": "// C program to implement cond(), signal()// and wait() functions#include <pthread.h>#include <stdio.h>#include <unistd.h> // Declaration of thread condition variablepthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; // declaring mutexpthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; int done = 1; // Thread functionvoid* foo(){ // acquire a lock pthread_mutex_lock(&lock); if (done == 1) { // let's wait on condition variable cond1 done = 2; printf(\"Waiting on condition variable cond1\\n\"); pthread_cond_wait(&cond1, &lock); } else { // Let's signal condition variable cond1 printf(\"Signaling condition variable cond1\\n\"); pthread_cond_signal(&cond1); } // release lock pthread_mutex_unlock(&lock); printf(\"Returning thread\\n\"); return NULL;} // Driver codeint main(){ pthread_t tid1, tid2; // Create thread 1 pthread_create(&tid1, NULL, foo, NULL); // sleep for 1 sec so that thread 1 // would get a chance to run first sleep(1); // Create thread 2 pthread_create(&tid2, NULL, foo, NULL); // wait for the completion of thread 2 pthread_join(tid2, NULL); return 0;}", "e": 28130, "s": 26941, "text": null }, { "code": null, "e": 28140, "s": 28130, "text": "Output: " }, { "code": null, "e": 28151, "s": 28140, "text": "nidhi_biet" }, { "code": null, "e": 28168, "s": 28151, "text": "surinderdawra388" }, { "code": null, "e": 28187, "s": 28168, "text": "cpp-multithreading" }, { "code": null, "e": 28203, "s": 28187, "text": "mutli-threading" }, { "code": null, "e": 28222, "s": 28203, "text": "system-programming" }, { "code": null, "e": 28233, "s": 28222, "text": "C Programs" }, { "code": null, "e": 28244, "s": 28233, "text": "Linux-Unix" }, { "code": null, "e": 28342, "s": 28244, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28383, "s": 28342, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28426, "s": 28383, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 28472, "s": 28426, "text": "C program to sort an array in ascending order" }, { "code": null, "e": 28493, "s": 28472, "text": "time() function in C" }, { "code": null, "e": 28523, "s": 28493, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 28563, "s": 28523, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 28603, "s": 28563, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 28630, "s": 28603, "text": "grep command in Unix/Linux" }, { "code": null, "e": 28665, "s": 28630, "text": "cut command in Linux with examples" } ]
Create Inverted Index for File using Python - GeeksforGeeks
29 Dec, 2020 An inverted index is an index data structure storing a mapping from content, such as words or numbers, to its locations in a document or a set of documents. In simple words, it is a hashmap like data structure that directs you from a word to a document or a web page. We will create a Word level inverted index, that is it will return the list of lines in which the word is present. We will also create a dictionary in which key values represent the words present in the file and the value of a dictionary will be represented by the list containing line numbers in which they are present. To create a file in Jupiter notebook use magic function: %%writefile file.txt This is the first word. This is the second text, Hello! How are you? This is the third, this is it now. This will create a file named file.txt will the following content. Python3 # this will open the filefile = open('file.txt', encoding='utf8')read = file.read()file.seek(0)read # to obtain the# number of lines# in fileline = 1for word in read: if word == '\n': line += 1print("Number of lines in file is: ", line) # create a list to# store each line as# an element of listarray = []for i in range(line): array.append(file.readline()) array Output: Number of lines in file is: 3 ['This is the first word.\n', 'This is the second text, Hello! How are you?\n', 'This is the third, this is it now.'] Functions used: Open: It is used to open the file. read: This function is used to read the content of the file. seek(0): It returns the cursor to the beginning of the file. Python3 punc = '''!()-[]{};:'"\, <>./?@#$%^&*_~'''for ele in read: if ele in punc: read = read.replace(ele, " ") read # to maintain uniformityread=read.lower() read Output: 'this is the first word \n this is the second text hello how are you \n this is the third this is it now ' Stop words are those words that have no emotions associated with it and can safely be ignored without sacrificing the meaning of the sentence. Python3 from nltk.tokenize import word_tokenizeimport nltkfrom nltk.corpus import stopwordsnltk.download('stopwords') for i in range(1): # this will convert # the word into tokens text_tokens = word_tokenize(read) tokens_without_sw = [ word for word in text_tokens if not word in stopwords.words()] print(tokens_without_sw) Output: ['first', 'word', 'second', 'text', 'hello', 'third'] Python3 dict = {} for i in range(line): check = array[i].lower() for item in tokens_without_sw: if item in check: if item not in dict: dict[item] = [] if item in dict: dict[item].append(i+1) dict Output: {'first': [1], 'word': [1], 'second': [2], 'text': [2], 'hello': [2], 'third': [3]} Python file-handling-programs python-file-handling Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python
[ { "code": null, "e": 25985, "s": 25957, "text": "\n29 Dec, 2020" }, { "code": null, "e": 26253, "s": 25985, "text": "An inverted index is an index data structure storing a mapping from content, such as words or numbers, to its locations in a document or a set of documents. In simple words, it is a hashmap like data structure that directs you from a word to a document or a web page." }, { "code": null, "e": 26632, "s": 26253, "text": "We will create a Word level inverted index, that is it will return the list of lines in which the word is present. We will also create a dictionary in which key values represent the words present in the file and the value of a dictionary will be represented by the list containing line numbers in which they are present. To create a file in Jupiter notebook use magic function: " }, { "code": null, "e": 26758, "s": 26632, "text": "%%writefile file.txt\nThis is the first word.\nThis is the second text, Hello! How are you?\nThis is the third, this is it now.\n" }, { "code": null, "e": 26826, "s": 26758, "text": "This will create a file named file.txt will the following content. " }, { "code": null, "e": 26834, "s": 26826, "text": "Python3" }, { "code": "# this will open the filefile = open('file.txt', encoding='utf8')read = file.read()file.seek(0)read # to obtain the# number of lines# in fileline = 1for word in read: if word == '\\n': line += 1print(\"Number of lines in file is: \", line) # create a list to# store each line as# an element of listarray = []for i in range(line): array.append(file.readline()) array", "e": 27213, "s": 26834, "text": null }, { "code": null, "e": 27221, "s": 27213, "text": "Output:" }, { "code": null, "e": 27370, "s": 27221, "text": "Number of lines in file is: 3\n['This is the first word.\\n',\n'This is the second text, Hello! How are you?\\n',\n'This is the third, this is it now.']\n" }, { "code": null, "e": 27386, "s": 27370, "text": "Functions used:" }, { "code": null, "e": 27421, "s": 27386, "text": "Open: It is used to open the file." }, { "code": null, "e": 27482, "s": 27421, "text": "read: This function is used to read the content of the file." }, { "code": null, "e": 27543, "s": 27482, "text": "seek(0): It returns the cursor to the beginning of the file." }, { "code": null, "e": 27551, "s": 27543, "text": "Python3" }, { "code": "punc = '''!()-[]{};:'\"\\, <>./?@#$%^&*_~'''for ele in read: if ele in punc: read = read.replace(ele, \" \") read # to maintain uniformityread=read.lower() read", "e": 27753, "s": 27551, "text": null }, { "code": null, "e": 27761, "s": 27753, "text": "Output:" }, { "code": null, "e": 27869, "s": 27761, "text": "'this is the first word \\n\nthis is the second text hello how are you \\n\nthis is the third this is it now '\n" }, { "code": null, "e": 28013, "s": 27869, "text": "Stop words are those words that have no emotions associated with it and can safely be ignored without sacrificing the meaning of the sentence. " }, { "code": null, "e": 28021, "s": 28013, "text": "Python3" }, { "code": "from nltk.tokenize import word_tokenizeimport nltkfrom nltk.corpus import stopwordsnltk.download('stopwords') for i in range(1): # this will convert # the word into tokens text_tokens = word_tokenize(read) tokens_without_sw = [ word for word in text_tokens if not word in stopwords.words()] print(tokens_without_sw)", "e": 28352, "s": 28021, "text": null }, { "code": null, "e": 28361, "s": 28352, "text": "Output: " }, { "code": null, "e": 28416, "s": 28361, "text": "['first', 'word', 'second', 'text', 'hello', 'third']\n" }, { "code": null, "e": 28424, "s": 28416, "text": "Python3" }, { "code": "dict = {} for i in range(line): check = array[i].lower() for item in tokens_without_sw: if item in check: if item not in dict: dict[item] = [] if item in dict: dict[item].append(i+1) dict", "e": 28683, "s": 28424, "text": null }, { "code": null, "e": 28692, "s": 28683, "text": "Output: " }, { "code": null, "e": 28780, "s": 28692, "text": "{'first': [1],\n'word': [1],\n'second': [2], \n'text': [2], \n'hello': [2], \n'third': [3]}\n" }, { "code": null, "e": 28810, "s": 28780, "text": "Python file-handling-programs" }, { "code": null, "e": 28831, "s": 28810, "text": "python-file-handling" }, { "code": null, "e": 28838, "s": 28831, "text": "Python" }, { "code": null, "e": 28936, "s": 28838, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28954, "s": 28936, "text": "Python Dictionary" }, { "code": null, "e": 28989, "s": 28954, "text": "Read a file line by line in Python" }, { "code": null, "e": 29021, "s": 28989, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29043, "s": 29021, "text": "Enumerate() in Python" }, { "code": null, "e": 29085, "s": 29043, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29115, "s": 29085, "text": "Iterate over a list in Python" }, { "code": null, "e": 29141, "s": 29115, "text": "Python String | replace()" }, { "code": null, "e": 29185, "s": 29141, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29214, "s": 29185, "text": "*args and **kwargs in Python" } ]