title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Table | Guava | Java - GeeksforGeeks
24 May, 2018 Guava’s Table is a collection that represents a table like structure containing rows, columns and the associated cell values. The row and the column act as an ordered pair of keys. The row and column act as an ordered pair of keys. If we have to manage this the traditional way then the structure would be a map of rows where each row contain a map of column and the cell values, for example, Map<rowKey, Map<colKey, cellValue>>. Declaration : Following is the declaration for com.google.common.collect.Table<R, C, V> interface : @GwtCompatible public interface Table<R, C, V> Parameters : R : The type of the table row keys. C : The type of the table column keys. V : The type of the mapped values. Some of methods provided by Table Interface are :Guava provides different variety of implementations for Table interface, which are shown in below table :Important Points : A table may be sparse, with only a small fraction of row key / column key pairs possessing a corresponding value. In some implementations, data access by column key may have fewer supported operations or worse performance than data access by row key. All methods that modify the table are optional, and the views returned by the table may or may not be modifiable. When modification isn’t supported, those methods will throw an UnsupportedOperationException. Below given are some other methods provided by Table Interface :Example : // Java code to show implementation of// Guava's Table interfaceimport java.util.Map;import java.util.Set; import com.google.common.collect.HashBasedTable;import com.google.common.collect.Table; class GFG { // Driver method public static void main(String args[]) { // creating a table to store Student information Table<String, String, String> studentTable = HashBasedTable.create(); // Adding student details in the table // The first field represents the department // of student, second field represents the // Roll no. and third field represents the // student name studentTable.put("CSE", "5", "Dhiman"); studentTable.put("CSE", "7", "Shubham"); studentTable.put("CSE", "9", "Abhishek"); studentTable.put("CSE", "12", "Sahil"); studentTable.put("ECE", "15", "Ram"); studentTable.put("ECE", "18", "Anmol"); studentTable.put("ECE", "20", "Akhil"); studentTable.put("ECE", "25", "Amrit"); // get Map corresponding to ECE department Map<String, String> eceMap = studentTable.row("ECE"); System.out.println("List of ECE students : "); for (Map.Entry<String, String> student : eceMap.entrySet()) { System.out.println("Student Roll No : " + student.getKey() + ", Student Name : " + student.getValue()); } System.out.println(); // get a Map corresponding to Roll no. 12 Map<String, String> stuMap = studentTable.column("12"); for (Map.Entry<String, String> student : stuMap.entrySet()) { System.out.println("Student Roll No : " + student.getKey() + ", Student Name : " + student.getValue()); } }} Output : List of ECE students : Student Roll No : 15, Student Name : Ram Student Roll No : 18, Student Name : Anmol Student Roll No : 20, Student Name : Akhil Student Roll No : 25, Student Name : Amrit Student Roll No : CSE, Student Name : Sahil Reference : Google Guava java-guava Java 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": 24143, "s": 24115, "text": "\n24 May, 2018" }, { "code": null, "e": 24324, "s": 24143, "text": "Guava’s Table is a collection that represents a table like structure containing rows, columns and the associated cell values. The row and the column act as an ordered pair of keys." }, { "code": null, "e": 24573, "s": 24324, "text": "The row and column act as an ordered pair of keys. If we have to manage this the traditional way then the structure would be a map of rows where each row contain a map of column and the cell values, for example, Map<rowKey, Map<colKey, cellValue>>." }, { "code": null, "e": 24673, "s": 24573, "text": "Declaration : Following is the declaration for com.google.common.collect.Table<R, C, V> interface :" }, { "code": null, "e": 24721, "s": 24673, "text": "@GwtCompatible\npublic interface Table<R, C, V>\n" }, { "code": null, "e": 24734, "s": 24721, "text": "Parameters :" }, { "code": null, "e": 24770, "s": 24734, "text": "R : The type of the table row keys." }, { "code": null, "e": 24809, "s": 24770, "text": "C : The type of the table column keys." }, { "code": null, "e": 24844, "s": 24809, "text": "V : The type of the mapped values." }, { "code": null, "e": 25017, "s": 24844, "text": "Some of methods provided by Table Interface are :Guava provides different variety of implementations for Table interface, which are shown in below table :Important Points :" }, { "code": null, "e": 25131, "s": 25017, "text": "A table may be sparse, with only a small fraction of row key / column key pairs possessing a corresponding value." }, { "code": null, "e": 25268, "s": 25131, "text": "In some implementations, data access by column key may have fewer supported operations or worse performance than data access by row key." }, { "code": null, "e": 25476, "s": 25268, "text": "All methods that modify the table are optional, and the views returned by the table may or may not be modifiable. When modification isn’t supported, those methods will throw an UnsupportedOperationException." }, { "code": null, "e": 25550, "s": 25476, "text": "Below given are some other methods provided by Table Interface :Example :" }, { "code": "// Java code to show implementation of// Guava's Table interfaceimport java.util.Map;import java.util.Set; import com.google.common.collect.HashBasedTable;import com.google.common.collect.Table; class GFG { // Driver method public static void main(String args[]) { // creating a table to store Student information Table<String, String, String> studentTable = HashBasedTable.create(); // Adding student details in the table // The first field represents the department // of student, second field represents the // Roll no. and third field represents the // student name studentTable.put(\"CSE\", \"5\", \"Dhiman\"); studentTable.put(\"CSE\", \"7\", \"Shubham\"); studentTable.put(\"CSE\", \"9\", \"Abhishek\"); studentTable.put(\"CSE\", \"12\", \"Sahil\"); studentTable.put(\"ECE\", \"15\", \"Ram\"); studentTable.put(\"ECE\", \"18\", \"Anmol\"); studentTable.put(\"ECE\", \"20\", \"Akhil\"); studentTable.put(\"ECE\", \"25\", \"Amrit\"); // get Map corresponding to ECE department Map<String, String> eceMap = studentTable.row(\"ECE\"); System.out.println(\"List of ECE students : \"); for (Map.Entry<String, String> student : eceMap.entrySet()) { System.out.println(\"Student Roll No : \" + student.getKey() + \", Student Name : \" + student.getValue()); } System.out.println(); // get a Map corresponding to Roll no. 12 Map<String, String> stuMap = studentTable.column(\"12\"); for (Map.Entry<String, String> student : stuMap.entrySet()) { System.out.println(\"Student Roll No : \" + student.getKey() + \", Student Name : \" + student.getValue()); } }}", "e": 27275, "s": 25550, "text": null }, { "code": null, "e": 27284, "s": 27275, "text": "Output :" }, { "code": null, "e": 27524, "s": 27284, "text": "List of ECE students : \nStudent Roll No : 15, Student Name : Ram\nStudent Roll No : 18, Student Name : Anmol\nStudent Roll No : 20, Student Name : Akhil\nStudent Roll No : 25, Student Name : Amrit\n\nStudent Roll No : CSE, Student Name : Sahil\n" }, { "code": null, "e": 27549, "s": 27524, "text": "Reference : Google Guava" }, { "code": null, "e": 27560, "s": 27549, "text": "java-guava" }, { "code": null, "e": 27565, "s": 27560, "text": "Java" }, { "code": null, "e": 27570, "s": 27565, "text": "Java" }, { "code": null, "e": 27668, "s": 27570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27677, "s": 27668, "text": "Comments" }, { "code": null, "e": 27690, "s": 27677, "text": "Old Comments" }, { "code": null, "e": 27741, "s": 27690, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27771, "s": 27741, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27802, "s": 27771, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27834, "s": 27802, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27853, "s": 27834, "text": "Interfaces in Java" }, { "code": null, "e": 27871, "s": 27853, "text": "ArrayList in Java" }, { "code": null, "e": 27903, "s": 27871, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27923, "s": 27903, "text": "Stack Class in Java" }, { "code": null, "e": 27947, "s": 27923, "text": "Singleton Class in Java" } ]
How to apply NOW() to timestamps field in MySQL Workbench?
Let us first create a table − create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, ShippingDate timestamp ); Insert some records in the table using insert command. Here, we have included the current date with NOW() − INSERT INTO DemoTable(ShippingDate) VALUES(now()); Display all records from the table using select statement − SELECT *FROM DemoTable; Following is the screenshot of query in MySQL workbench to set NOW() to timestamp field “ShippingDate”. The query also displays the output below −
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1193, "s": 1092, "text": "create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n ShippingDate timestamp\n);" }, { "code": null, "e": 1301, "s": 1193, "text": "Insert some records in the table using insert command. Here, we have included the current date with NOW() −" }, { "code": null, "e": 1352, "s": 1301, "text": "INSERT INTO DemoTable(ShippingDate) VALUES(now());" }, { "code": null, "e": 1412, "s": 1352, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1436, "s": 1412, "text": "SELECT *FROM DemoTable;" }, { "code": null, "e": 1583, "s": 1436, "text": "Following is the screenshot of query in MySQL workbench to set NOW() to timestamp field “ShippingDate”. The query also displays the output below −" } ]
How to iterate over an Array using for loop in Golang? - GeeksforGeeks
05 May, 2020 An array is a data structure of the collection of items of the similar type stored in contiguous locations. For performing operations on arrays, the need arises to iterate through it. A for loop is used to iterate over data structures in programming languages. It can be used here in the following ways: Example 1: // Golang program to iterate over// an Array using for looppackage main import "fmt" func main() { // taking an array arr := [5]int{1, 2, 3, 4, 5} fmt.Println("The elements of the array are: ") // using for loop for i := 0; i < len(arr); i++ { fmt.Println(arr[i]) }} Output: The elements of the array are: 1 2 3 4 5 Explanation: The variable i is initialized as 0 and is defined to increase at every iteration until it reaches the value of the length of the array. Then the print command is given to print the elements at each index of the array one by one. Example 2: The for loopcan use another keyword return to perform iterations. // Golang program to iterate over// an Array using for looppackage main import "fmt" func main() { // taking an array arr := [5]string{"Ronaldo", "Messi", "Kaka", "James", "Casillas"} fmt.Println("The elements of the array are:") // using for loop for index, element := range arr { fmt.Println("At index", index, "value is", element) }} Output: The elements of the array are: At index 0 value is Ronaldo At index 1 value is Messi At index 2 value is Kaka At index 3 value is James At index 4 value is Casillas Explanation: Keyword range sets the scope of iteration upto the length of arr. The variables index and element store then indexes and values of the array respectively. Example 3: When we don’t need the index, we can ignore it with the blank identifier _. // Golang program to iterate over// an Array using for looppackage main import "fmt" func main() { // taking an array arr := []int{1, 2, 3, 4, 5} fmt.Println("The elements of the array are:") // using for loop for _, value := range arr { fmt.Println(value) }} Output: The elements of the array are: 1 2 3 4 5 Golang-Arrays Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments strings.Replace() Function in Golang With Examples Time Formatting in Golang fmt.Sprintf() Function in Golang With Examples How to Split a String in Golang? Golang Maps How to convert a string in lower case in Golang? Different Ways to Find the Type of Variable in Golang Inheritance in GoLang How to compare times in Golang? Interfaces in Golang
[ { "code": null, "e": 24035, "s": 24007, "text": "\n05 May, 2020" }, { "code": null, "e": 24339, "s": 24035, "text": "An array is a data structure of the collection of items of the similar type stored in contiguous locations. For performing operations on arrays, the need arises to iterate through it. A for loop is used to iterate over data structures in programming languages. It can be used here in the following ways:" }, { "code": null, "e": 24350, "s": 24339, "text": "Example 1:" }, { "code": "// Golang program to iterate over// an Array using for looppackage main import \"fmt\" func main() { // taking an array arr := [5]int{1, 2, 3, 4, 5} fmt.Println(\"The elements of the array are: \") // using for loop for i := 0; i < len(arr); i++ { fmt.Println(arr[i]) }}", "e": 24648, "s": 24350, "text": null }, { "code": null, "e": 24656, "s": 24648, "text": "Output:" }, { "code": null, "e": 24698, "s": 24656, "text": "The elements of the array are:\n1\n2\n3\n4\n5\n" }, { "code": null, "e": 24940, "s": 24698, "text": "Explanation: The variable i is initialized as 0 and is defined to increase at every iteration until it reaches the value of the length of the array. Then the print command is given to print the elements at each index of the array one by one." }, { "code": null, "e": 25017, "s": 24940, "text": "Example 2: The for loopcan use another keyword return to perform iterations." }, { "code": "// Golang program to iterate over// an Array using for looppackage main import \"fmt\" func main() { // taking an array arr := [5]string{\"Ronaldo\", \"Messi\", \"Kaka\", \"James\", \"Casillas\"} fmt.Println(\"The elements of the array are:\") // using for loop for index, element := range arr { fmt.Println(\"At index\", index, \"value is\", element) }}", "e": 25385, "s": 25017, "text": null }, { "code": null, "e": 25393, "s": 25385, "text": "Output:" }, { "code": null, "e": 25559, "s": 25393, "text": "The elements of the array are:\nAt index 0 value is Ronaldo\nAt index 1 value is Messi\nAt index 2 value is Kaka\nAt index 3 value is James\nAt index 4 value is Casillas\n" }, { "code": null, "e": 25727, "s": 25559, "text": "Explanation: Keyword range sets the scope of iteration upto the length of arr. The variables index and element store then indexes and values of the array respectively." }, { "code": null, "e": 25814, "s": 25727, "text": "Example 3: When we don’t need the index, we can ignore it with the blank identifier _." }, { "code": "// Golang program to iterate over// an Array using for looppackage main import \"fmt\" func main() { // taking an array arr := []int{1, 2, 3, 4, 5} fmt.Println(\"The elements of the array are:\") // using for loop for _, value := range arr { fmt.Println(value) }}", "e": 26105, "s": 25814, "text": null }, { "code": null, "e": 26113, "s": 26105, "text": "Output:" }, { "code": null, "e": 26155, "s": 26113, "text": "The elements of the array are:\n1\n2\n3\n4\n5\n" }, { "code": null, "e": 26169, "s": 26155, "text": "Golang-Arrays" }, { "code": null, "e": 26176, "s": 26169, "text": "Picked" }, { "code": null, "e": 26188, "s": 26176, "text": "Go Language" }, { "code": null, "e": 26286, "s": 26188, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26295, "s": 26286, "text": "Comments" }, { "code": null, "e": 26308, "s": 26295, "text": "Old Comments" }, { "code": null, "e": 26359, "s": 26308, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 26385, "s": 26359, "text": "Time Formatting in Golang" }, { "code": null, "e": 26432, "s": 26385, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 26465, "s": 26432, "text": "How to Split a String in Golang?" }, { "code": null, "e": 26477, "s": 26465, "text": "Golang Maps" }, { "code": null, "e": 26526, "s": 26477, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 26580, "s": 26526, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 26602, "s": 26580, "text": "Inheritance in GoLang" }, { "code": null, "e": 26634, "s": 26602, "text": "How to compare times in Golang?" } ]
Bar Chart with negative values
Following is an example of a Bar Chart with negative values. We have already seen the configurations used to draw a chart in Highcharts Configuration Syntax chapter. Now, let us see an example of a basic bar chart with negative values. app.component.ts import { Component } from '@angular/core'; import * as Highcharts from 'highcharts'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { highcharts = Highcharts; chartOptions = { chart: { type: 'bar' }, title: { text: 'Bar chart with negative values' }, xAxis:{ categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas'] }, series: [ { name: 'John', data: [5, 3, 4, 7, 2] }, { name: 'Jane', data: [2, -2, -3, 2, 1] }, { name: 'Joe', data: [3, 4, 4, -2, 5] } ] }; } Verify the result. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2096, "s": 2035, "text": "Following is an example of a Bar Chart with negative values." }, { "code": null, "e": 2272, "s": 2096, "text": "We have already seen the configurations used to draw a chart in Highcharts Configuration Syntax chapter. Now, let us see an example of a basic bar chart with negative values. " }, { "code": null, "e": 2289, "s": 2272, "text": "app.component.ts" }, { "code": null, "e": 3082, "s": 2289, "text": "import { Component } from '@angular/core';\nimport * as Highcharts from 'highcharts';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n highcharts = Highcharts;\n chartOptions = { \n chart: {\n type: 'bar'\n },\n title: {\n text: 'Bar chart with negative values'\n },\n xAxis:{\n categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas'] \n }, \n series: [\n {\n name: 'John',\n data: [5, 3, 4, 7, 2]\n }, \n {\n name: 'Jane',\n data: [2, -2, -3, 2, 1]\n }, \n {\n name: 'Joe',\n data: [3, 4, 4, -2, 5]\n }\n ]\n };\n}" }, { "code": null, "e": 3101, "s": 3082, "text": "Verify the result." }, { "code": null, "e": 3136, "s": 3101, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3150, "s": 3136, "text": " Anadi Sharma" }, { "code": null, "e": 3185, "s": 3150, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3199, "s": 3185, "text": " Anadi Sharma" }, { "code": null, "e": 3234, "s": 3199, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3254, "s": 3234, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 3289, "s": 3254, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3306, "s": 3289, "text": " Frahaan Hussain" }, { "code": null, "e": 3339, "s": 3306, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 3351, "s": 3339, "text": " Senol Atac" }, { "code": null, "e": 3386, "s": 3351, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3398, "s": 3386, "text": " Senol Atac" }, { "code": null, "e": 3405, "s": 3398, "text": " Print" }, { "code": null, "e": 3416, "s": 3405, "text": " Add Notes" } ]
Integer hashCode() Method in Java
05 Dec, 2018 The java.lang.Integer.hashCode() method of Integer class in Java is used to return the hash code for a particular Integer . Syntax: public int hashCode() Parameters : The method does not take any parameters. Return Value: The method returns a hash code integer value for this object, which is equal to the uncomplicated primitive integer value, represented by this Integer object. Below programs illustrate the use of hashCode() of Integer class:Program 1: When integer data type is passed. // Java program to demonstrate working// of Java.lang.Integer.hashCode() Methodimport java.lang.*; public class Geeks { public static void main(String[] args) { // Object s_int created Integer s_int = new Integer("223"); // Returning a hash code value for this object int hashcodevalue = s_int.hashCode(); System.out.println("Hash code Value for object = " + hashcodevalue); }} Hash code Value for object = 223 Program 2: When String data type is passed.Note: This causes RuntimeErrors like NumberFormatException // Java program to demonstrate working// of Java.lang.Integer.hashCode() Methodimport java.lang.*; public class Geeks { public static void main(String[] args) { // object s_int created Integer s_int = new Integer("gfg"); // Returning a hash code value for this object. int hashcodevalue = s_int.hashCode(); System.out.println("Hash code Value for object = " + hashcodevalue); }} Output: Exception in thread "main" java.lang.NumberFormatException: For input string: "gfg" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.(Integer.java:867) at Geeks.main(Geeks.java:9) Java-Functions Java-Integer Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Dec, 2018" }, { "code": null, "e": 178, "s": 54, "text": "The java.lang.Integer.hashCode() method of Integer class in Java is used to return the hash code for a particular Integer ." }, { "code": null, "e": 186, "s": 178, "text": "Syntax:" }, { "code": null, "e": 208, "s": 186, "text": "public int hashCode()" }, { "code": null, "e": 262, "s": 208, "text": "Parameters : The method does not take any parameters." }, { "code": null, "e": 435, "s": 262, "text": "Return Value: The method returns a hash code integer value for this object, which is equal to the uncomplicated primitive integer value, represented by this Integer object." }, { "code": null, "e": 545, "s": 435, "text": "Below programs illustrate the use of hashCode() of Integer class:Program 1: When integer data type is passed." }, { "code": "// Java program to demonstrate working// of Java.lang.Integer.hashCode() Methodimport java.lang.*; public class Geeks { public static void main(String[] args) { // Object s_int created Integer s_int = new Integer(\"223\"); // Returning a hash code value for this object int hashcodevalue = s_int.hashCode(); System.out.println(\"Hash code Value for object = \" + hashcodevalue); }}", "e": 973, "s": 545, "text": null }, { "code": null, "e": 1007, "s": 973, "text": "Hash code Value for object = 223\n" }, { "code": null, "e": 1109, "s": 1007, "text": "Program 2: When String data type is passed.Note: This causes RuntimeErrors like NumberFormatException" }, { "code": "// Java program to demonstrate working// of Java.lang.Integer.hashCode() Methodimport java.lang.*; public class Geeks { public static void main(String[] args) { // object s_int created Integer s_int = new Integer(\"gfg\"); // Returning a hash code value for this object. int hashcodevalue = s_int.hashCode(); System.out.println(\"Hash code Value for object = \" + hashcodevalue); }}", "e": 1537, "s": 1109, "text": null }, { "code": null, "e": 1545, "s": 1537, "text": "Output:" }, { "code": null, "e": 1843, "s": 1545, "text": "Exception in thread \"main\" java.lang.NumberFormatException: For input string: \"gfg\"\n at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)\n at java.lang.Integer.parseInt(Integer.java:580)\n at java.lang.Integer.(Integer.java:867)\n at Geeks.main(Geeks.java:9)\n" }, { "code": null, "e": 1858, "s": 1843, "text": "Java-Functions" }, { "code": null, "e": 1871, "s": 1858, "text": "Java-Integer" }, { "code": null, "e": 1889, "s": 1871, "text": "Java-lang package" }, { "code": null, "e": 1894, "s": 1889, "text": "Java" }, { "code": null, "e": 1899, "s": 1894, "text": "Java" } ]
PHP money_format() Function
14 Jul, 2020 The money_format() function is an inbuilt function in PHP that returns a number formatted as a currency string. In the main string, the formatted number is inserted where there is a percentage sign (%).The function is only defined in systems with strfmon() capacities. For example, money_format() is not defined in windows. It is mostly used with another pre-defined PHP function setlocale() with LC_MONETARY as its category of locale settings. As of version 7.4, money_format() has been deprecated. Instead, NumberFormatter::formatCurrency() is used. Syntax: string money_format( string str, float num ) Example: money_format("you have to pay %i", $num); Return value: It returns the formatted string. It will return the unchanged characters before and after the formatting string. Parameters: str: It specifies the string to be formatted and the way the variables in it will be formatted. The string parameter consists of the next sequence. a % character To insert the formatted number in the main string.optional flags One or more subsequent can be used.=f Numeric fill character. The default fill character is whitespace.^ Disables the utilization of grouping characters.+ or Specifies the formatting style for positive and negative numbers. If + is employed, the locale’s equivalent for + and – will be used. Negative amounts are enclosed in parenthesis. By default the characteristic is + unless the sign of the number is mentioned.(Refer example 2)! Suppresses the currency symbol out of the output string.– If it is present, it makes all the fields left-justified (padded to the right), unlike the default, as per which the fields are right-justified (padded to the left).widthw A decimal digit string that specifies the minimum field width which will be right-justified unless the flag is used. Its default value is 0 (zero).optional left precision#n This is used to define the scale (greatest number of digits (n) to the left of the decimal) of the number. It is used to keep formatted output aligned in the same columns by the use of fill character if the number of digits is less than n. This specification is ignored if the number of digits are greater than n. If ^ flag has not been used, grouping separators will be inserted before the fill characters (if any) are added. If the fill character is a digit, the grouping separators will not be applied to fill characters. Any characters appearing before or after the number in the formatted output are padded as required with the space characters to make sure proper alignment.optional right precision.p A period is followed after the decimal character by the other (p) number of digits. If p is 0, the decimal character and the digits to its right will be omitted. If no right precision is mentioned, the default will be dictated by the current locale in use. Before the process of formatting, the amount being formatted is rounded to the specified number of digits.A required conversion characteri Formats the number according to the locales international currency format.n Formats the number according to the locales national currency format.% Returns % character. a % character To insert the formatted number in the main string. optional flags One or more subsequent can be used.=f Numeric fill character. The default fill character is whitespace.^ Disables the utilization of grouping characters.+ or Specifies the formatting style for positive and negative numbers. If + is employed, the locale’s equivalent for + and – will be used. Negative amounts are enclosed in parenthesis. By default the characteristic is + unless the sign of the number is mentioned.(Refer example 2)! Suppresses the currency symbol out of the output string.– If it is present, it makes all the fields left-justified (padded to the right), unlike the default, as per which the fields are right-justified (padded to the left). =f Numeric fill character. The default fill character is whitespace. ^ Disables the utilization of grouping characters. + or Specifies the formatting style for positive and negative numbers. If + is employed, the locale’s equivalent for + and – will be used. Negative amounts are enclosed in parenthesis. By default the characteristic is + unless the sign of the number is mentioned.(Refer example 2) ! Suppresses the currency symbol out of the output string. – If it is present, it makes all the fields left-justified (padded to the right), unlike the default, as per which the fields are right-justified (padded to the left). widthw A decimal digit string that specifies the minimum field width which will be right-justified unless the flag is used. Its default value is 0 (zero). w A decimal digit string that specifies the minimum field width which will be right-justified unless the flag is used. Its default value is 0 (zero). optional left precision#n This is used to define the scale (greatest number of digits (n) to the left of the decimal) of the number. It is used to keep formatted output aligned in the same columns by the use of fill character if the number of digits is less than n. This specification is ignored if the number of digits are greater than n. If ^ flag has not been used, grouping separators will be inserted before the fill characters (if any) are added. If the fill character is a digit, the grouping separators will not be applied to fill characters. Any characters appearing before or after the number in the formatted output are padded as required with the space characters to make sure proper alignment. #n This is used to define the scale (greatest number of digits (n) to the left of the decimal) of the number. It is used to keep formatted output aligned in the same columns by the use of fill character if the number of digits is less than n. This specification is ignored if the number of digits are greater than n. If ^ flag has not been used, grouping separators will be inserted before the fill characters (if any) are added. If the fill character is a digit, the grouping separators will not be applied to fill characters. Any characters appearing before or after the number in the formatted output are padded as required with the space characters to make sure proper alignment. optional right precision.p A period is followed after the decimal character by the other (p) number of digits. If p is 0, the decimal character and the digits to its right will be omitted. If no right precision is mentioned, the default will be dictated by the current locale in use. Before the process of formatting, the amount being formatted is rounded to the specified number of digits. .p A period is followed after the decimal character by the other (p) number of digits. If p is 0, the decimal character and the digits to its right will be omitted. If no right precision is mentioned, the default will be dictated by the current locale in use. Before the process of formatting, the amount being formatted is rounded to the specified number of digits. A required conversion characteri Formats the number according to the locales international currency format.n Formats the number according to the locales national currency format.% Returns % character. i Formats the number according to the locales international currency format. n Formats the number according to the locales national currency format. % Returns % character. Number: The number to be formatted. Example 1: This example prints a given number in its locale international and national format. <?php $num = 8456.22; setlocale(LC_MONETARY, "en_US"); echo money_format("The output in locales" . " international format is %i", $num);echo "\n"; echo money_format("The output in locales" . " national format is %n", $num);?> Output: The output in locales international format is USD 8, 456.22 The output in locales national format is $8, 456.22 Example 2: Program that takes a negative number and displays it as a currency. <?php $num = -8456.22;setlocale(LC_MONETARY, "en_US");echo money_format("output: %(n", $num);?> Output: Output: ($8, 456.22) PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? Difference between HTTP GET and POST Methods Different ways for passing data to view in Laravel PHP | file_exists( ) Function PHP | Ternary Operator Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jul, 2020" }, { "code": null, "e": 580, "s": 28, "text": "The money_format() function is an inbuilt function in PHP that returns a number formatted as a currency string. In the main string, the formatted number is inserted where there is a percentage sign (%).The function is only defined in systems with strfmon() capacities. For example, money_format() is not defined in windows. It is mostly used with another pre-defined PHP function setlocale() with LC_MONETARY as its category of locale settings. As of version 7.4, money_format() has been deprecated. Instead, NumberFormatter::formatCurrency() is used." }, { "code": null, "e": 588, "s": 580, "text": "Syntax:" }, { "code": null, "e": 633, "s": 588, "text": "string money_format( string str, float num )" }, { "code": null, "e": 642, "s": 633, "text": "Example:" }, { "code": null, "e": 687, "s": 642, "text": " \nmoney_format(\"you have to pay %i\", $num);\n" }, { "code": null, "e": 814, "s": 687, "text": "Return value: It returns the formatted string. It will return the unchanged characters before and after the formatting string." }, { "code": null, "e": 826, "s": 814, "text": "Parameters:" }, { "code": null, "e": 974, "s": 826, "text": "str: It specifies the string to be formatted and the way the variables in it will be formatted. The string parameter consists of the next sequence." }, { "code": null, "e": 3162, "s": 974, "text": "a % character To insert the formatted number in the main string.optional flags One or more subsequent can be used.=f Numeric fill character. The default fill character is whitespace.^ Disables the utilization of grouping characters.+ or Specifies the formatting style for positive and negative numbers. If + is employed, the locale’s equivalent for + and – will be used. Negative amounts are enclosed in parenthesis. By default the characteristic is + unless the sign of the number is mentioned.(Refer example 2)! Suppresses the currency symbol out of the output string.– If it is present, it makes all the fields left-justified (padded to the right), unlike the default, as per which the fields are right-justified (padded to the left).widthw A decimal digit string that specifies the minimum field width which will be right-justified unless the flag is used. Its default value is 0 (zero).optional left precision#n This is used to define the scale (greatest number of digits (n) to the left of the decimal) of the number. It is used to keep formatted output aligned in the same columns by the use of fill character if the number of digits is less than n. This specification is ignored if the number of digits are greater than n. If ^ flag has not been used, grouping separators will be inserted before the fill characters (if any) are added. If the fill character is a digit, the grouping separators will not be applied to fill characters. Any characters appearing before or after the number in the formatted output are padded as required with the space characters to make sure proper alignment.optional right precision.p A period is followed after the decimal character by the other (p) number of digits. If p is 0, the decimal character and the digits to its right will be omitted. If no right precision is mentioned, the default will be dictated by the current locale in use. Before the process of formatting, the amount being formatted is rounded to the specified number of digits.A required conversion characteri Formats the number according to the locales international currency format.n Formats the number according to the locales national currency format.% Returns % character." }, { "code": null, "e": 3227, "s": 3162, "text": "a % character To insert the formatted number in the main string." }, { "code": null, "e": 3901, "s": 3227, "text": "optional flags One or more subsequent can be used.=f Numeric fill character. The default fill character is whitespace.^ Disables the utilization of grouping characters.+ or Specifies the formatting style for positive and negative numbers. If + is employed, the locale’s equivalent for + and – will be used. Negative amounts are enclosed in parenthesis. By default the characteristic is + unless the sign of the number is mentioned.(Refer example 2)! Suppresses the currency symbol out of the output string.– If it is present, it makes all the fields left-justified (padded to the right), unlike the default, as per which the fields are right-justified (padded to the left)." }, { "code": null, "e": 3970, "s": 3901, "text": "=f Numeric fill character. The default fill character is whitespace." }, { "code": null, "e": 4021, "s": 3970, "text": "^ Disables the utilization of grouping characters." }, { "code": null, "e": 4302, "s": 4021, "text": "+ or Specifies the formatting style for positive and negative numbers. If + is employed, the locale’s equivalent for + and – will be used. Negative amounts are enclosed in parenthesis. By default the characteristic is + unless the sign of the number is mentioned.(Refer example 2)" }, { "code": null, "e": 4361, "s": 4302, "text": "! Suppresses the currency symbol out of the output string." }, { "code": null, "e": 4529, "s": 4361, "text": "– If it is present, it makes all the fields left-justified (padded to the right), unlike the default, as per which the fields are right-justified (padded to the left)." }, { "code": null, "e": 4684, "s": 4529, "text": "widthw A decimal digit string that specifies the minimum field width which will be right-justified unless the flag is used. Its default value is 0 (zero)." }, { "code": null, "e": 4834, "s": 4684, "text": "w A decimal digit string that specifies the minimum field width which will be right-justified unless the flag is used. Its default value is 0 (zero)." }, { "code": null, "e": 5541, "s": 4834, "text": "optional left precision#n This is used to define the scale (greatest number of digits (n) to the left of the decimal) of the number. It is used to keep formatted output aligned in the same columns by the use of fill character if the number of digits is less than n. This specification is ignored if the number of digits are greater than n. If ^ flag has not been used, grouping separators will be inserted before the fill characters (if any) are added. If the fill character is a digit, the grouping separators will not be applied to fill characters. Any characters appearing before or after the number in the formatted output are padded as required with the space characters to make sure proper alignment." }, { "code": null, "e": 6225, "s": 5541, "text": "#n This is used to define the scale (greatest number of digits (n) to the left of the decimal) of the number. It is used to keep formatted output aligned in the same columns by the use of fill character if the number of digits is less than n. This specification is ignored if the number of digits are greater than n. If ^ flag has not been used, grouping separators will be inserted before the fill characters (if any) are added. If the fill character is a digit, the grouping separators will not be applied to fill characters. Any characters appearing before or after the number in the formatted output are padded as required with the space characters to make sure proper alignment." }, { "code": null, "e": 6616, "s": 6225, "text": "optional right precision.p A period is followed after the decimal character by the other (p) number of digits. If p is 0, the decimal character and the digits to its right will be omitted. If no right precision is mentioned, the default will be dictated by the current locale in use. Before the process of formatting, the amount being formatted is rounded to the specified number of digits." }, { "code": null, "e": 6983, "s": 6616, "text": ".p A period is followed after the decimal character by the other (p) number of digits. If p is 0, the decimal character and the digits to its right will be omitted. If no right precision is mentioned, the default will be dictated by the current locale in use. Before the process of formatting, the amount being formatted is rounded to the specified number of digits." }, { "code": null, "e": 7184, "s": 6983, "text": "A required conversion characteri Formats the number according to the locales international currency format.n Formats the number according to the locales national currency format.% Returns % character." }, { "code": null, "e": 7261, "s": 7184, "text": "i Formats the number according to the locales international currency format." }, { "code": null, "e": 7333, "s": 7261, "text": "n Formats the number according to the locales national currency format." }, { "code": null, "e": 7356, "s": 7333, "text": "% Returns % character." }, { "code": null, "e": 7392, "s": 7356, "text": "Number: The number to be formatted." }, { "code": null, "e": 7487, "s": 7392, "text": "Example 1: This example prints a given number in its locale international and national format." }, { "code": "<?php $num = 8456.22; setlocale(LC_MONETARY, \"en_US\"); echo money_format(\"The output in locales\" . \" international format is %i\", $num);echo \"\\n\"; echo money_format(\"The output in locales\" . \" national format is %n\", $num);?>", "e": 7723, "s": 7487, "text": null }, { "code": null, "e": 7731, "s": 7723, "text": "Output:" }, { "code": null, "e": 7845, "s": 7731, "text": "The output in locales international format is USD 8, 456.22 \nThe output in locales national format is $8, 456.22\n" }, { "code": null, "e": 7924, "s": 7845, "text": "Example 2: Program that takes a negative number and displays it as a currency." }, { "code": "<?php $num = -8456.22;setlocale(LC_MONETARY, \"en_US\");echo money_format(\"output: %(n\", $num);?>", "e": 8021, "s": 7924, "text": null }, { "code": null, "e": 8029, "s": 8021, "text": "Output:" }, { "code": null, "e": 8050, "s": 8029, "text": "Output: ($8, 456.22)" }, { "code": null, "e": 8063, "s": 8050, "text": "PHP-function" }, { "code": null, "e": 8067, "s": 8063, "text": "PHP" }, { "code": null, "e": 8084, "s": 8067, "text": "Web Technologies" }, { "code": null, "e": 8088, "s": 8084, "text": "PHP" }, { "code": null, "e": 8186, "s": 8088, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8268, "s": 8186, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 8313, "s": 8268, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 8364, "s": 8313, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 8394, "s": 8364, "text": "PHP | file_exists( ) Function" }, { "code": null, "e": 8417, "s": 8394, "text": "PHP | Ternary Operator" }, { "code": null, "e": 8450, "s": 8417, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 8512, "s": 8450, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 8573, "s": 8512, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8623, "s": 8573, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python – Frequencies of Values in a Dictionary
01 Oct, 2020 Sometimes, while working with python dictionaries, we can have a problem in which we need to extract the frequency of values in the dictionary. This is quite a common problem and has applications in many domains including web development and day-day programming. Let’s discuss certain ways in which this task can be performed. Input : test_dict = {‘ide’ : 3, ‘Gfg’ : 3, ‘code’ : 2}Output : {3: 2, 2: 1} Input : test_dict = {10 : 1, 20 : 2, 30 : 1, 40 : 2 }Output : {1 : 2, 2 : 2} Method #1 : Using defaultdict() + loopThe combination of above functions can be used to solve this problem. In this, we use defaultdict() to initialize the counter dictionary with integers and increment counter in brute force manner using loop. # Python3 code to demonstrate working of # Dictionary Values Frequency# Using defaultdict() + loopfrom collections import defaultdict # initializing dictionarytest_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Dictionary Values Frequency# Using defaultdict() + loopres = defaultdict(int)for key, val in test_dict.items(): res[val] += 1 # printing result print("The frequency dictionary : " + str(dict(res))) The original dictionary : {'Gfg': 3, 'code': 2, 'ide': 3} The frequency dictionary : {2: 1, 3: 2} Method #2 : Using Counter() + values()The combination of above functions can be used to solve this problem. In this, we perform the task of extraction of values using values() and frequency counter using Counter(). # Python3 code to demonstrate working of # Dictionary Values Frequency# Using Counter() + values()from collections import Counter # initializing dictionarytest_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Dictionary Values Frequency# Using defaultdict() + loopres = Counter(test_dict.values()) # printing result print("The frequency dictionary : " + str(dict(res))) The original dictionary : {'code': 2, 'Gfg': 3, 'ide': 3} The frequency dictionary : {2: 1, 3: 2} Python dictionary-programs Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2020" }, { "code": null, "e": 355, "s": 28, "text": "Sometimes, while working with python dictionaries, we can have a problem in which we need to extract the frequency of values in the dictionary. This is quite a common problem and has applications in many domains including web development and day-day programming. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 431, "s": 355, "text": "Input : test_dict = {‘ide’ : 3, ‘Gfg’ : 3, ‘code’ : 2}Output : {3: 2, 2: 1}" }, { "code": null, "e": 508, "s": 431, "text": "Input : test_dict = {10 : 1, 20 : 2, 30 : 1, 40 : 2 }Output : {1 : 2, 2 : 2}" }, { "code": null, "e": 753, "s": 508, "text": "Method #1 : Using defaultdict() + loopThe combination of above functions can be used to solve this problem. In this, we use defaultdict() to initialize the counter dictionary with integers and increment counter in brute force manner using loop." }, { "code": "# Python3 code to demonstrate working of # Dictionary Values Frequency# Using defaultdict() + loopfrom collections import defaultdict # initializing dictionarytest_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Dictionary Values Frequency# Using defaultdict() + loopres = defaultdict(int)for key, val in test_dict.items(): res[val] += 1 # printing result print(\"The frequency dictionary : \" + str(dict(res))) ", "e": 1254, "s": 753, "text": null }, { "code": null, "e": 1353, "s": 1254, "text": "The original dictionary : {'Gfg': 3, 'code': 2, 'ide': 3}\nThe frequency dictionary : {2: 1, 3: 2}\n" }, { "code": null, "e": 1568, "s": 1353, "text": "Method #2 : Using Counter() + values()The combination of above functions can be used to solve this problem. In this, we perform the task of extraction of values using values() and frequency counter using Counter()." }, { "code": "# Python3 code to demonstrate working of # Dictionary Values Frequency# Using Counter() + values()from collections import Counter # initializing dictionarytest_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Dictionary Values Frequency# Using defaultdict() + loopres = Counter(test_dict.values()) # printing result print(\"The frequency dictionary : \" + str(dict(res))) ", "e": 2025, "s": 1568, "text": null }, { "code": null, "e": 2124, "s": 2025, "text": "The original dictionary : {'code': 2, 'Gfg': 3, 'ide': 3}\nThe frequency dictionary : {2: 1, 3: 2}\n" }, { "code": null, "e": 2151, "s": 2124, "text": "Python dictionary-programs" }, { "code": null, "e": 2158, "s": 2151, "text": "Python" }, { "code": null, "e": 2256, "s": 2158, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2288, "s": 2256, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2315, "s": 2288, "text": "Python Classes and Objects" }, { "code": null, "e": 2336, "s": 2315, "text": "Python OOPs Concepts" }, { "code": null, "e": 2359, "s": 2336, "text": "Introduction To PYTHON" }, { "code": null, "e": 2415, "s": 2359, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2446, "s": 2415, "text": "Python | os.path.join() method" }, { "code": null, "e": 2488, "s": 2446, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2530, "s": 2488, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2569, "s": 2530, "text": "Python | datetime.timedelta() function" } ]
How to run MongoDB shell using mongos command?
In order to launch the MongoDB shell, you need to use mongo command. Following is the syntax − >mongo First reach the MongoDB bin directory from command prompt as in the below screenshot − Here is the command to launch the mongo shell as in the below screenshot − This will produce the following output −
[ { "code": null, "e": 1282, "s": 1187, "text": "In order to launch the MongoDB shell, you need to use mongo command. Following is the syntax −" }, { "code": null, "e": 1289, "s": 1282, "text": ">mongo" }, { "code": null, "e": 1376, "s": 1289, "text": "First reach the MongoDB bin directory from command prompt as in the below screenshot −" }, { "code": null, "e": 1451, "s": 1376, "text": "Here is the command to launch the mongo shell as in the below screenshot −" }, { "code": null, "e": 1492, "s": 1451, "text": "This will produce the following output −" } ]
Python | Pandas Series.nonzero() to get Index of all non zero values in a series
30 Sep, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.nonzero() is an argument less method. Just like it name says, rather returning non zero values from a series, it returns index of all non zero values. The returned series of indices can be passed to iloc method and return all non zero values. Syntax: Series.nonzero()Return type: Array of indices Example:In this example, a Series is created from a Python List using Pandas Series() method. The series also contains some zero values. After that nonzero() method is called on series and the result is stored in result variable. The result series is then passed to iloc() method to return all non zero values at that indices. # importing pandas module import pandas as pd # importing numpy module import numpy as np # creating listlist =[1, 0, 12, 1, 0, 4, 22, 0, 3, 9] # creating seriesseries = pd.Series(list) # calling .nonzero() methodresult = series.nonzero() # displayprint(result) # retrieving values using iloc methodvalues = series.iloc[result] # displayvalues Output: (array([0, 2, 3, 5, 6, 8, 9]), ) 0 1 2 12 3 1 5 4 6 22 8 3 9 9 dtype: int64 As shown in output, the index position of every non zero elements was returned and the values at that position were returned using iloc method. Akanksha_Rai Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Sep, 2019" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 499, "s": 242, "text": "Pandas Series.nonzero() is an argument less method. Just like it name says, rather returning non zero values from a series, it returns index of all non zero values. The returned series of indices can be passed to iloc method and return all non zero values." }, { "code": null, "e": 553, "s": 499, "text": "Syntax: Series.nonzero()Return type: Array of indices" }, { "code": null, "e": 880, "s": 553, "text": "Example:In this example, a Series is created from a Python List using Pandas Series() method. The series also contains some zero values. After that nonzero() method is called on series and the result is stored in result variable. The result series is then passed to iloc() method to return all non zero values at that indices." }, { "code": "# importing pandas module import pandas as pd # importing numpy module import numpy as np # creating listlist =[1, 0, 12, 1, 0, 4, 22, 0, 3, 9] # creating seriesseries = pd.Series(list) # calling .nonzero() methodresult = series.nonzero() # displayprint(result) # retrieving values using iloc methodvalues = series.iloc[result] # displayvalues", "e": 1237, "s": 880, "text": null }, { "code": null, "e": 1245, "s": 1237, "text": "Output:" }, { "code": null, "e": 1348, "s": 1245, "text": "(array([0, 2, 3, 5, 6, 8, 9]), )\n0 1\n2 12\n3 1\n5 4\n6 22\n8 3\n9 9\ndtype: int64\n" }, { "code": null, "e": 1492, "s": 1348, "text": "As shown in output, the index position of every non zero elements was returned and the values at that position were returned using iloc method." }, { "code": null, "e": 1505, "s": 1492, "text": "Akanksha_Rai" }, { "code": null, "e": 1526, "s": 1505, "text": "Python pandas-series" }, { "code": null, "e": 1555, "s": 1526, "text": "Python pandas-series-methods" }, { "code": null, "e": 1569, "s": 1555, "text": "Python-pandas" }, { "code": null, "e": 1576, "s": 1569, "text": "Python" }, { "code": null, "e": 1674, "s": 1576, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1692, "s": 1674, "text": "Python Dictionary" }, { "code": null, "e": 1734, "s": 1692, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1756, "s": 1734, "text": "Enumerate() in Python" }, { "code": null, "e": 1791, "s": 1756, "text": "Read a file line by line in Python" }, { "code": null, "e": 1817, "s": 1791, "text": "Python String | replace()" }, { "code": null, "e": 1849, "s": 1817, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1878, "s": 1849, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1905, "s": 1878, "text": "Python Classes and Objects" }, { "code": null, "e": 1926, "s": 1905, "text": "Python OOPs Concepts" } ]
What are chrome extensions?
31 Oct, 2019 It is a small program to modify the experience or add functionality to the chrome browser. They are created using web technology like HTML, CSS, JavaScript, etc.The main aim of an extension is to serve a single purpose around which the whole program is built, although it can have multiple components but they should help in accomplishing the main purpose of the program.An extension should have the minimal interface or it can extend to a web page also but main focus is to provide good functionality with less overhead.Extension are zipped into a in .crx package, the user needs to download the package and install it. Chrome extension is published in the Chrome web store. Some example of chrome extension is: Password manager Ads blocker Adding to-do lists or notes to Chrome Making it easier to copy text from a site Let’s create a simple extension just to demonstrate the working procedure: Every extension require a manifest fileFirst, create a manifest.json file { "name": "Hello Extensions", "description" : "Base Level Extension", "version": "1.0", "manifest_version": 2 } { "name": "Hello Extensions", "description" : "Base Level Extension", "version": "1.0", "manifest_version": 2 } Then, for demonstration we will add an icon to the extension which will on being clicked open a web page created by us.Add this inside the file"browser_action": { "default_popup": "hello.html", "default_icon": "icon.png" } "browser_action": { "default_popup": "hello.html", "default_icon": "icon.png" } Then add this to include a shortcut to display the HTML page"commands": { "_execute_browser_action": { "suggested_key": { "default": "Ctrl+Shift+F" }, "description": "Opens hello.html" } } "commands": { "_execute_browser_action": { "suggested_key": { "default": "Ctrl+Shift+F" }, "description": "Opens hello.html" } } Picked GBlog Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge How to Learn Data Science in 10 weeks? What is Data Structure: Types, Classifications and Applications What is Hashing | A Complete Tutorial Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2019" }, { "code": null, "e": 704, "s": 28, "text": "It is a small program to modify the experience or add functionality to the chrome browser. They are created using web technology like HTML, CSS, JavaScript, etc.The main aim of an extension is to serve a single purpose around which the whole program is built, although it can have multiple components but they should help in accomplishing the main purpose of the program.An extension should have the minimal interface or it can extend to a web page also but main focus is to provide good functionality with less overhead.Extension are zipped into a in .crx package, the user needs to download the package and install it. Chrome extension is published in the Chrome web store." }, { "code": null, "e": 741, "s": 704, "text": "Some example of chrome extension is:" }, { "code": null, "e": 758, "s": 741, "text": "Password manager" }, { "code": null, "e": 770, "s": 758, "text": "Ads blocker" }, { "code": null, "e": 808, "s": 770, "text": "Adding to-do lists or notes to Chrome" }, { "code": null, "e": 850, "s": 808, "text": "Making it easier to copy text from a site" }, { "code": null, "e": 925, "s": 850, "text": "Let’s create a simple extension just to demonstrate the working procedure:" }, { "code": null, "e": 1129, "s": 925, "text": "Every extension require a manifest fileFirst, create a manifest.json file {\n \"name\": \"Hello Extensions\",\n \"description\" : \"Base Level Extension\",\n \"version\": \"1.0\",\n \"manifest_version\": 2\n }" }, { "code": null, "e": 1260, "s": 1129, "text": " {\n \"name\": \"Hello Extensions\",\n \"description\" : \"Base Level Extension\",\n \"version\": \"1.0\",\n \"manifest_version\": 2\n }" }, { "code": null, "e": 1503, "s": 1260, "text": "Then, for demonstration we will add an icon to the extension which will on being clicked open a web page created by us.Add this inside the file\"browser_action\": {\n \"default_popup\": \"hello.html\",\n \"default_icon\": \"icon.png\"\n } \n" }, { "code": null, "e": 1603, "s": 1503, "text": "\"browser_action\": {\n \"default_popup\": \"hello.html\",\n \"default_icon\": \"icon.png\"\n } \n" }, { "code": null, "e": 1843, "s": 1603, "text": "Then add this to include a shortcut to display the HTML page\"commands\": {\n \"_execute_browser_action\": {\n \"suggested_key\": {\n \"default\": \"Ctrl+Shift+F\"\n },\n \"description\": \"Opens hello.html\"\n }\n }\n" }, { "code": null, "e": 2023, "s": 1843, "text": "\"commands\": {\n \"_execute_browser_action\": {\n \"suggested_key\": {\n \"default\": \"Ctrl+Shift+F\"\n },\n \"description\": \"Opens hello.html\"\n }\n }\n" }, { "code": null, "e": 2030, "s": 2023, "text": "Picked" }, { "code": null, "e": 2036, "s": 2030, "text": "GBlog" }, { "code": null, "e": 2053, "s": 2036, "text": "Web Technologies" }, { "code": null, "e": 2080, "s": 2053, "text": "Web technologies Questions" }, { "code": null, "e": 2178, "s": 2080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2233, "s": 2178, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 2270, "s": 2233, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 2309, "s": 2270, "text": "How to Learn Data Science in 10 weeks?" }, { "code": null, "e": 2373, "s": 2309, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 2411, "s": 2373, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 2444, "s": 2411, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2505, "s": 2444, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2555, "s": 2505, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2598, "s": 2555, "text": "How to fetch data from an API in ReactJS ?" } ]
Reentrant Lock in Java
04 Feb, 2021 Background The traditional way to achieve thread synchronization in Java is by the use of synchronized keyword. While it provides a certain basic synchronization, the synchronized keyword is quite rigid in its use. For example, a thread can take a lock only once. Synchronized blocks don’t offer any mechanism of a waiting queue and after the exit of one thread, any thread can take the lock. This could lead to starvation of resources for some other thread for a very long period of time. Reentrant Locks are provided in Java to provide synchronization with greater flexibility. What are Reentrant Locks? The ReentrantLock class implements the Lock interface and provides synchronization to methods while accessing shared resources. The code which manipulates the shared resource is surrounded by calls to lock and unlock method. This gives a lock to the current working thread and blocks all other threads which are trying to take a lock on the shared resource. As the name says, ReentrantLock allows threads to enter into the lock on a resource more than once. When the thread first enters into the lock, a hold count is set to one. Before unlocking the thread can re-enter into lock again and every time hold count is incremented by one. For every unlocks request, hold count is decremented by one and when hold count is 0, the resource is unlocked. Reentrant Locks also offer a fairness parameter, by which the lock would abide by the order of the lock request i.e. after a thread unlocks the resource, the lock would go to the thread which has been waiting for the longest time. This fairness mode is set up by passing true to the constructor of the lock. These locks are used in the following way: Java public void some_method(){ reentrantlock.lock(); try { //Do some work } catch(Exception e) { e.printStackTrace(); } finally { reentrantlock.unlock(); } } Unlock statement is always called in the finally block to ensure that the lock is released even if an exception is thrown in the method body(try block). ReentrantLock() Methods lock(): Call to the lock() method increments the hold count by 1 and gives the lock to the thread if the shared resource is initially free. unlock(): Call to the unlock() method decrements the hold count by 1. When this count reaches zero, the resource is released. tryLock(): If the resource is not held by any other thread, then call to tryLock() returns true and the hold count is incremented by one. If the resource is not free, then the method returns false, and the thread is not blocked, but exits. tryLock(long timeout, TimeUnit unit): As per the method, the thread waits for a certain time period as defined by arguments of the method to acquire the lock on the resource before exiting. lockInterruptibly(): This method acquires the lock if the resource is free while allowing for the thread to be interrupted by some other thread while acquiring the resource. It means that if the current thread is waiting for the lock but some other thread requests the lock, then the current thread will be interrupted and return immediately without acquiring the lock. getHoldCount(): This method returns the count of the number of locks held on the resource. isHeldByCurrentThread(): This method returns true if the lock on the resource is held by the current thread. ReentrantLock() Example In the following tutorial, we will look at a basic example of Reentrant Locks. Steps to be followed 1. Create an object of ReentrantLock 2. Create a worker(Runnable Object) to execute and pass the lock to the object 3. Use the lock() method to acquire the lock on shared resource 4. After completing work, call unlock() method to release the lock Below is the implementation of problem statement: Java // Java code to illustrate Reentrant Locksimport java.text.SimpleDateFormat;import java.util.Date;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.locks.ReentrantLock; class worker implements Runnable{ String name; ReentrantLock re; public worker(ReentrantLock rl, String n) { re = rl; name = n; } public void run() { boolean done = false; while (!done) { //Getting Outer Lock boolean ans = re.tryLock(); // Returns True if lock is free if(ans) { try { Date d = new Date(); SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss"); System.out.println("task name - "+ name + " outer lock acquired at " + ft.format(d) + " Doing outer work"); Thread.sleep(1500); // Getting Inner Lock re.lock(); try { d = new Date(); ft = new SimpleDateFormat("hh:mm:ss"); System.out.println("task name - "+ name + " inner lock acquired at " + ft.format(d) + " Doing inner work"); System.out.println("Lock Hold Count - "+ re.getHoldCount()); Thread.sleep(1500); } catch(InterruptedException e) { e.printStackTrace(); } finally { //Inner lock release System.out.println("task name - " + name + " releasing inner lock"); re.unlock(); } System.out.println("Lock Hold Count - " + re.getHoldCount()); System.out.println("task name - " + name + " work done"); done = true; } catch(InterruptedException e) { e.printStackTrace(); } finally { //Outer lock release System.out.println("task name - " + name + " releasing outer lock"); re.unlock(); System.out.println("Lock Hold Count - " + re.getHoldCount()); } } else { System.out.println("task name - " + name + " waiting for lock"); try { Thread.sleep(1000); } catch(InterruptedException e) { e.printStackTrace(); } } } }} public class test{ static final int MAX_T = 2; public static void main(String[] args) { ReentrantLock rel = new ReentrantLock(); ExecutorService pool = Executors.newFixedThreadPool(MAX_T); Runnable w1 = new worker(rel, "Job1"); Runnable w2 = new worker(rel, "Job2"); Runnable w3 = new worker(rel, "Job3"); Runnable w4 = new worker(rel, "Job4"); pool.execute(w1); pool.execute(w2); pool.execute(w3); pool.execute(w4); pool.shutdown(); }} Sample Execution Output: task name - Job2 waiting for lock task name - Job1 outer lock acquired at 09:49:42 Doing outer work task name - Job2 waiting for lock task name - Job1 inner lock acquired at 09:49:44 Doing inner work Lock Hold Count - 2 task name - Job2 waiting for lock task name - Job2 waiting for lock task name - Job1 releasing inner lock Lock Hold Count - 1 task name - Job1 work done task name - Job1 releasing outer lock Lock Hold Count - 0 task name - Job3 outer lock acquired at 09:49:45 Doing outer work task name - Job2 waiting for lock task name - Job3 inner lock acquired at 09:49:47 Doing inner work Lock Hold Count - 2 task name - Job2 waiting for lock task name - Job2 waiting for lock task name - Job3 releasing inner lock Lock Hold Count - 1 task name - Job3 work done task name - Job3 releasing outer lock Lock Hold Count - 0 task name - Job4 outer lock acquired at 09:49:48 Doing outer work task name - Job2 waiting for lock task name - Job4 inner lock acquired at 09:49:50 Doing inner work Lock Hold Count - 2 task name - Job2 waiting for lock task name - Job2 waiting for lock task name - Job4 releasing inner lock Lock Hold Count - 1 task name - Job4 work done task name - Job4 releasing outer lock Lock Hold Count - 0 task name - Job2 outer lock acquired at 09:49:52 Doing outer work task name - Job2 inner lock acquired at 09:49:53 Doing inner work Lock Hold Count - 2 task name - Job2 releasing inner lock Lock Hold Count - 1 task name - Job2 work done task name - Job2 releasing outer lock Lock Hold Count - 0 Important Points One can forget to call the unlock() method in the finally block leading to bugs in the program. Ensure that the lock is released before the thread exits.The fairness parameter used to construct the lock object decreases the throughput of the program. One can forget to call the unlock() method in the finally block leading to bugs in the program. Ensure that the lock is released before the thread exits. The fairness parameter used to construct the lock object decreases the throughput of the program. The ReentrantLock is a better replacement for synchronization, which offers many features not provided by synchronized. However, the existence of these obvious benefits are not a good enough reason to always prefer ReentrantLock to synchronize. Instead, make the decision on the basis of whether you need the flexibility offered by a ReentrantLock. This article is contributed by Abhishek. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. payelsenapatinayan Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Feb, 2021" }, { "code": null, "e": 65, "s": 54, "text": "Background" }, { "code": null, "e": 636, "s": 65, "text": "The traditional way to achieve thread synchronization in Java is by the use of synchronized keyword. While it provides a certain basic synchronization, the synchronized keyword is quite rigid in its use. For example, a thread can take a lock only once. Synchronized blocks don’t offer any mechanism of a waiting queue and after the exit of one thread, any thread can take the lock. This could lead to starvation of resources for some other thread for a very long period of time. Reentrant Locks are provided in Java to provide synchronization with greater flexibility. " }, { "code": null, "e": 662, "s": 636, "text": "What are Reentrant Locks?" }, { "code": null, "e": 1021, "s": 662, "text": "The ReentrantLock class implements the Lock interface and provides synchronization to methods while accessing shared resources. The code which manipulates the shared resource is surrounded by calls to lock and unlock method. This gives a lock to the current working thread and blocks all other threads which are trying to take a lock on the shared resource. " }, { "code": null, "e": 1412, "s": 1021, "text": "As the name says, ReentrantLock allows threads to enter into the lock on a resource more than once. When the thread first enters into the lock, a hold count is set to one. Before unlocking the thread can re-enter into lock again and every time hold count is incremented by one. For every unlocks request, hold count is decremented by one and when hold count is 0, the resource is unlocked. " }, { "code": null, "e": 1765, "s": 1412, "text": "Reentrant Locks also offer a fairness parameter, by which the lock would abide by the order of the lock request i.e. after a thread unlocks the resource, the lock would go to the thread which has been waiting for the longest time. This fairness mode is set up by passing true to the constructor of the lock. These locks are used in the following way: " }, { "code": null, "e": 1770, "s": 1765, "text": "Java" }, { "code": "public void some_method(){ reentrantlock.lock(); try { //Do some work } catch(Exception e) { e.printStackTrace(); } finally { reentrantlock.unlock(); } }", "e": 2035, "s": 1770, "text": null }, { "code": null, "e": 2190, "s": 2037, "text": "Unlock statement is always called in the finally block to ensure that the lock is released even if an exception is thrown in the method body(try block)." }, { "code": null, "e": 2215, "s": 2190, "text": "ReentrantLock() Methods " }, { "code": null, "e": 2355, "s": 2215, "text": "lock(): Call to the lock() method increments the hold count by 1 and gives the lock to the thread if the shared resource is initially free." }, { "code": null, "e": 2481, "s": 2355, "text": "unlock(): Call to the unlock() method decrements the hold count by 1. When this count reaches zero, the resource is released." }, { "code": null, "e": 2721, "s": 2481, "text": "tryLock(): If the resource is not held by any other thread, then call to tryLock() returns true and the hold count is incremented by one. If the resource is not free, then the method returns false, and the thread is not blocked, but exits." }, { "code": null, "e": 2911, "s": 2721, "text": "tryLock(long timeout, TimeUnit unit): As per the method, the thread waits for a certain time period as defined by arguments of the method to acquire the lock on the resource before exiting." }, { "code": null, "e": 3281, "s": 2911, "text": "lockInterruptibly(): This method acquires the lock if the resource is free while allowing for the thread to be interrupted by some other thread while acquiring the resource. It means that if the current thread is waiting for the lock but some other thread requests the lock, then the current thread will be interrupted and return immediately without acquiring the lock." }, { "code": null, "e": 3372, "s": 3281, "text": "getHoldCount(): This method returns the count of the number of locks held on the resource." }, { "code": null, "e": 3481, "s": 3372, "text": "isHeldByCurrentThread(): This method returns true if the lock on the resource is held by the current thread." }, { "code": null, "e": 3505, "s": 3481, "text": "ReentrantLock() Example" }, { "code": null, "e": 3584, "s": 3505, "text": "In the following tutorial, we will look at a basic example of Reentrant Locks." }, { "code": null, "e": 3607, "s": 3584, "text": "Steps to be followed " }, { "code": null, "e": 3855, "s": 3607, "text": "1. Create an object of ReentrantLock\n2. Create a worker(Runnable Object) to execute and pass the lock to the object\n3. Use the lock() method to acquire the lock on shared resource\n4. After completing work, call unlock() method to release the lock " }, { "code": null, "e": 3905, "s": 3855, "text": "Below is the implementation of problem statement:" }, { "code": null, "e": 3910, "s": 3905, "text": "Java" }, { "code": "// Java code to illustrate Reentrant Locksimport java.text.SimpleDateFormat;import java.util.Date;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.locks.ReentrantLock; class worker implements Runnable{ String name; ReentrantLock re; public worker(ReentrantLock rl, String n) { re = rl; name = n; } public void run() { boolean done = false; while (!done) { //Getting Outer Lock boolean ans = re.tryLock(); // Returns True if lock is free if(ans) { try { Date d = new Date(); SimpleDateFormat ft = new SimpleDateFormat(\"hh:mm:ss\"); System.out.println(\"task name - \"+ name + \" outer lock acquired at \" + ft.format(d) + \" Doing outer work\"); Thread.sleep(1500); // Getting Inner Lock re.lock(); try { d = new Date(); ft = new SimpleDateFormat(\"hh:mm:ss\"); System.out.println(\"task name - \"+ name + \" inner lock acquired at \" + ft.format(d) + \" Doing inner work\"); System.out.println(\"Lock Hold Count - \"+ re.getHoldCount()); Thread.sleep(1500); } catch(InterruptedException e) { e.printStackTrace(); } finally { //Inner lock release System.out.println(\"task name - \" + name + \" releasing inner lock\"); re.unlock(); } System.out.println(\"Lock Hold Count - \" + re.getHoldCount()); System.out.println(\"task name - \" + name + \" work done\"); done = true; } catch(InterruptedException e) { e.printStackTrace(); } finally { //Outer lock release System.out.println(\"task name - \" + name + \" releasing outer lock\"); re.unlock(); System.out.println(\"Lock Hold Count - \" + re.getHoldCount()); } } else { System.out.println(\"task name - \" + name + \" waiting for lock\"); try { Thread.sleep(1000); } catch(InterruptedException e) { e.printStackTrace(); } } } }} public class test{ static final int MAX_T = 2; public static void main(String[] args) { ReentrantLock rel = new ReentrantLock(); ExecutorService pool = Executors.newFixedThreadPool(MAX_T); Runnable w1 = new worker(rel, \"Job1\"); Runnable w2 = new worker(rel, \"Job2\"); Runnable w3 = new worker(rel, \"Job3\"); Runnable w4 = new worker(rel, \"Job4\"); pool.execute(w1); pool.execute(w2); pool.execute(w3); pool.execute(w4); pool.shutdown(); }}", "e": 6812, "s": 3910, "text": null }, { "code": null, "e": 6830, "s": 6812, "text": "Sample Execution " }, { "code": null, "e": 8358, "s": 6830, "text": "Output:\ntask name - Job2 waiting for lock\ntask name - Job1 outer lock acquired at 09:49:42 Doing outer work\ntask name - Job2 waiting for lock\ntask name - Job1 inner lock acquired at 09:49:44 Doing inner work\nLock Hold Count - 2\ntask name - Job2 waiting for lock\ntask name - Job2 waiting for lock\ntask name - Job1 releasing inner lock\nLock Hold Count - 1\ntask name - Job1 work done\ntask name - Job1 releasing outer lock\nLock Hold Count - 0\ntask name - Job3 outer lock acquired at 09:49:45 Doing outer work\ntask name - Job2 waiting for lock\ntask name - Job3 inner lock acquired at 09:49:47 Doing inner work\nLock Hold Count - 2\ntask name - Job2 waiting for lock\ntask name - Job2 waiting for lock\ntask name - Job3 releasing inner lock\nLock Hold Count - 1\ntask name - Job3 work done\ntask name - Job3 releasing outer lock\nLock Hold Count - 0\ntask name - Job4 outer lock acquired at 09:49:48 Doing outer work\ntask name - Job2 waiting for lock\ntask name - Job4 inner lock acquired at 09:49:50 Doing inner work\nLock Hold Count - 2\ntask name - Job2 waiting for lock\ntask name - Job2 waiting for lock\ntask name - Job4 releasing inner lock\nLock Hold Count - 1\ntask name - Job4 work done\ntask name - Job4 releasing outer lock\nLock Hold Count - 0\ntask name - Job2 outer lock acquired at 09:49:52 Doing outer work\ntask name - Job2 inner lock acquired at 09:49:53 Doing inner work\nLock Hold Count - 2\ntask name - Job2 releasing inner lock\nLock Hold Count - 1\ntask name - Job2 work done\ntask name - Job2 releasing outer lock\nLock Hold Count - 0" }, { "code": null, "e": 8377, "s": 8358, "text": "Important Points " }, { "code": null, "e": 8628, "s": 8377, "text": "One can forget to call the unlock() method in the finally block leading to bugs in the program. Ensure that the lock is released before the thread exits.The fairness parameter used to construct the lock object decreases the throughput of the program." }, { "code": null, "e": 8782, "s": 8628, "text": "One can forget to call the unlock() method in the finally block leading to bugs in the program. Ensure that the lock is released before the thread exits." }, { "code": null, "e": 8880, "s": 8782, "text": "The fairness parameter used to construct the lock object decreases the throughput of the program." }, { "code": null, "e": 9229, "s": 8880, "text": "The ReentrantLock is a better replacement for synchronization, which offers many features not provided by synchronized. However, the existence of these obvious benefits are not a good enough reason to always prefer ReentrantLock to synchronize. Instead, make the decision on the basis of whether you need the flexibility offered by a ReentrantLock." }, { "code": null, "e": 9650, "s": 9229, "text": "This article is contributed by Abhishek. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9669, "s": 9650, "text": "payelsenapatinayan" }, { "code": null, "e": 9689, "s": 9669, "text": "Java-Multithreading" }, { "code": null, "e": 9694, "s": 9689, "text": "Java" }, { "code": null, "e": 9699, "s": 9694, "text": "Java" } ]
Python – Removing Constant Features From the Dataset
02 Sep, 2020 Those features which contain constant values (i.e. only one value for all the outputs or target values) in the dataset are known as Constant Features. These features don’t provide any information to the target feature. These are redundant data available in the dataset. Presence of this feature has no effect on the target, so it is good to remove these features from the dataset. This process of removing redundant features and keeping only the necessary features in the dataset comes under the filter method of Feature Selection Methods. Now Let’s see how we can remove constant features in Python. Consider the self created dataset for the article: Code: Create DataFrame of the above data # Import pandas to create DataFrameimport pandas as pd # Make DataFrame of the given datadata = pd.DataFrame({"Portal":['GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks'], "Article's_category":['Python', 'Data Science', 'Data Science', 'Data Science', 'Mathematics', 'Python', 'Data Science', 'Mathematics', 'Mathematics'], "Views":[545, 1505, 1157, 2541, 5726, 3125, 3131, 6525, 15000]}) Code: Convert the categorical data to numerical data # import ordinal encoder from sklearnfrom sklearn.preprocessing import OrdinalEncoderord_enc = OrdinalEncoder() # Transform the datadata[["Portal","Article's_category"]] = ord_enc.fit_transform(data[["Portal","Article's_category"]]) Code: Fit the data to VarianceThreshold. # import VarianceThresholdfrom sklearn.feature_selection import VarianceThresholdvar_threshold = VarianceThreshold(threshold=0) # threshold = 0 for constant # fit the datavar_threshold.fit(data) # We can check the variance of different features asprint(var_threshold.variances_) Output: Variance of different features: [0.00000000e+00 6.17283951e-01 1.76746269e+07] Code: Transform the data print(var_threshold.transform(data))print('*' * 10,"Separator",'*' * 10) # shapes of data before transformed and after transformedprint("Earlier shape of data: ", data.shape)print("Shape after transformation: ", var_threshold.transform(data).shape) Output: [[2.000e+00 5.450e+02] [0.000e+00 1.505e+03] [0.000e+00 1.157e+03] [0.000e+00 2.541e+03] [1.000e+00 5.726e+03] [2.000e+00 3.125e+03] [0.000e+00 3.131e+03] [1.000e+00 6.525e+03] [1.000e+00 1.500e+04]] ********** Separator ********** Earlier shape of data: (9, 3) Shape after transformation: (9, 2) As you can observe earlier we had 9 observations with 3 features.After transformation we have 9 observations with 2 features. We can clearly observe that the removed feature is ‘Portal’. data-science Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 568, "s": 28, "text": "Those features which contain constant values (i.e. only one value for all the outputs or target values) in the dataset are known as Constant Features. These features don’t provide any information to the target feature. These are redundant data available in the dataset. Presence of this feature has no effect on the target, so it is good to remove these features from the dataset. This process of removing redundant features and keeping only the necessary features in the dataset comes under the filter method of Feature Selection Methods." }, { "code": null, "e": 629, "s": 568, "text": "Now Let’s see how we can remove constant features in Python." }, { "code": null, "e": 680, "s": 629, "text": "Consider the self created dataset for the article:" }, { "code": null, "e": 721, "s": 680, "text": "Code: Create DataFrame of the above data" }, { "code": "# Import pandas to create DataFrameimport pandas as pd # Make DataFrame of the given datadata = pd.DataFrame({\"Portal\":['GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks'], \"Article's_category\":['Python', 'Data Science', 'Data Science', 'Data Science', 'Mathematics', 'Python', 'Data Science', 'Mathematics', 'Mathematics'], \"Views\":[545, 1505, 1157, 2541, 5726, 3125, 3131, 6525, 15000]})", "e": 1324, "s": 721, "text": null }, { "code": null, "e": 1377, "s": 1324, "text": "Code: Convert the categorical data to numerical data" }, { "code": "# import ordinal encoder from sklearnfrom sklearn.preprocessing import OrdinalEncoderord_enc = OrdinalEncoder() # Transform the datadata[[\"Portal\",\"Article's_category\"]] = ord_enc.fit_transform(data[[\"Portal\",\"Article's_category\"]])", "e": 1611, "s": 1377, "text": null }, { "code": null, "e": 1652, "s": 1611, "text": "Code: Fit the data to VarianceThreshold." }, { "code": "# import VarianceThresholdfrom sklearn.feature_selection import VarianceThresholdvar_threshold = VarianceThreshold(threshold=0) # threshold = 0 for constant # fit the datavar_threshold.fit(data) # We can check the variance of different features asprint(var_threshold.variances_)", "e": 1935, "s": 1652, "text": null }, { "code": null, "e": 1975, "s": 1935, "text": "Output: Variance of different features:" }, { "code": null, "e": 2022, "s": 1975, "text": "[0.00000000e+00 6.17283951e-01 1.76746269e+07]" }, { "code": null, "e": 2047, "s": 2022, "text": "Code: Transform the data" }, { "code": "print(var_threshold.transform(data))print('*' * 10,\"Separator\",'*' * 10) # shapes of data before transformed and after transformedprint(\"Earlier shape of data: \", data.shape)print(\"Shape after transformation: \", var_threshold.transform(data).shape)", "e": 2297, "s": 2047, "text": null }, { "code": null, "e": 2305, "s": 2297, "text": "Output:" }, { "code": null, "e": 2613, "s": 2305, "text": "[[2.000e+00 5.450e+02]\n [0.000e+00 1.505e+03]\n [0.000e+00 1.157e+03]\n [0.000e+00 2.541e+03]\n [1.000e+00 5.726e+03]\n [2.000e+00 3.125e+03]\n [0.000e+00 3.131e+03]\n [1.000e+00 6.525e+03]\n [1.000e+00 1.500e+04]]\n********** Separator **********\nEarlier shape of data: (9, 3)\nShape after transformation: (9, 2)\n" }, { "code": null, "e": 2800, "s": 2613, "text": "As you can observe earlier we had 9 observations with 3 features.After transformation we have 9 observations with 2 features. We can clearly observe that the removed feature is ‘Portal’." }, { "code": null, "e": 2813, "s": 2800, "text": "data-science" }, { "code": null, "e": 2830, "s": 2813, "text": "Machine Learning" }, { "code": null, "e": 2837, "s": 2830, "text": "Python" }, { "code": null, "e": 2854, "s": 2837, "text": "Machine Learning" } ]
How to upload files using HTML to website ?
31 Oct, 2021 Every file that needs to be uploaded to the website, required the basic form which facilitates uploading. This feature is essential when we are filling the form on a specific website. This file upload may support a variety of file formats along with various types of files. The file uploading feature is one of the essential parts of the form in the website. In this article, we will learn to build the file upload feature in the website using HTML. We will use the concept of HTML <input> tag that will allow the user to upload files to a website. <input> tag: It is used to specify an input field where the user can enter the required data. The input tag is used within the <form> element to declare input controls that allow users to input data. An input field can be of various types depending upon the attribute type. The Input tag is an empty element that only contains attributes. Here, we have defined a type attribute whose value is set as “file” Syntax: <input type = "file"... /> This syntax specifies the file-select field that enables the feature to choose one or more files from their device storage then upload it to a server using the form submission button. Example: This example illustrates the use of the <input> tag by specifying the type attribute as a file. HTML <!DOCTYPE html><html><head> <title>How to upload files using HTML to website?</title></head> <body> <center> <h1>Welcome to GFG</h1> <h2>How to upload files using HTML to website?</h2> <input type="file" id="file1" name="upload"> </center></body></html> Output: In the output, you can see that when the file is chosen and then uploaded, its name is also showing right beside the button. HTML-Basics HTML-Questions HTML-Tags Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) HTTP headers | Content-Type Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2021" }, { "code": null, "e": 577, "s": 28, "text": "Every file that needs to be uploaded to the website, required the basic form which facilitates uploading. This feature is essential when we are filling the form on a specific website. This file upload may support a variety of file formats along with various types of files. The file uploading feature is one of the essential parts of the form in the website. In this article, we will learn to build the file upload feature in the website using HTML. We will use the concept of HTML <input> tag that will allow the user to upload files to a website." }, { "code": null, "e": 984, "s": 577, "text": "<input> tag: It is used to specify an input field where the user can enter the required data. The input tag is used within the <form> element to declare input controls that allow users to input data. An input field can be of various types depending upon the attribute type. The Input tag is an empty element that only contains attributes. Here, we have defined a type attribute whose value is set as “file”" }, { "code": null, "e": 992, "s": 984, "text": "Syntax:" }, { "code": null, "e": 1019, "s": 992, "text": "<input type = \"file\"... />" }, { "code": null, "e": 1203, "s": 1019, "text": "This syntax specifies the file-select field that enables the feature to choose one or more files from their device storage then upload it to a server using the form submission button." }, { "code": null, "e": 1308, "s": 1203, "text": "Example: This example illustrates the use of the <input> tag by specifying the type attribute as a file." }, { "code": null, "e": 1313, "s": 1308, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>How to upload files using HTML to website?</title></head> <body> <center> <h1>Welcome to GFG</h1> <h2>How to upload files using HTML to website?</h2> <input type=\"file\" id=\"file1\" name=\"upload\"> </center></body></html>", "e": 1628, "s": 1313, "text": null }, { "code": null, "e": 1761, "s": 1628, "text": "Output: In the output, you can see that when the file is chosen and then uploaded, its name is also showing right beside the button." }, { "code": null, "e": 1773, "s": 1761, "text": "HTML-Basics" }, { "code": null, "e": 1788, "s": 1773, "text": "HTML-Questions" }, { "code": null, "e": 1798, "s": 1788, "text": "HTML-Tags" }, { "code": null, "e": 1805, "s": 1798, "text": "Picked" }, { "code": null, "e": 1810, "s": 1805, "text": "HTML" }, { "code": null, "e": 1827, "s": 1810, "text": "Web Technologies" }, { "code": null, "e": 1832, "s": 1827, "text": "HTML" }, { "code": null, "e": 1930, "s": 1832, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1978, "s": 1930, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2002, "s": 1978, "text": "REST API (Introduction)" }, { "code": null, "e": 2052, "s": 2002, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2089, "s": 2052, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 2117, "s": 2089, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 2150, "s": 2117, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2211, "s": 2150, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2254, "s": 2211, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2326, "s": 2254, "text": "Differences between Functional Components and Class Components in React" } ]
Hierarchically-clustered Heatmap in Python with Seaborn Clustermap
02 Dec, 2020 Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas. Clustering is basically grouping data based on relationships among the variables in the data. Clustering algorithms help in getting structured data in unsupervised learning. The most common types of clustering are shown below. Clustering_types Here we are going to see hierarchical clustering especially Agglomerative(bottom-up) hierarchical clustering. In Agglomerative clustering, we start with considering each data point as a cluster and then repeatedly combine two nearest clusters into larger clusters until we are left with a single cluster. The graph we plot after performing agglomerative clustering on data is called Dendrogram. Coming to the heat map, it is a graphical representation of data where values are represented using colors. Variation in the intensity of color depicts how data is clustered or varies over space. The clustermap() function of seaborn plots a hierarchically-clustered heat map of the given matrix dataset. It returns a clustered grid index. Below are some examples which depict the hierarchically-clustered heat map from a dataset: In the Flights dataset the data(Number of passengers) is clustered based on month and year: Example 1: Python3 # Importing the libraryimport seaborn as snsfrom sunbird.categorical_encoding import frequency_encoding # Load datasetdata = sns.load_dataset('flights') # Categorical encodingfrequency_encoding(data, 'month') # Clustering data row-wise and# changing color of the map.sns.clustermap(data, figsize=(7, 7)) Output : The legend to the left of the cluster map indicates information about the cluster map e.g bright color indicates more passengers and dark color indicates fewer passengers. Example 2: Python3 # Importing the libraryimport seaborn as snsfrom sunbird.categorical_encoding import frequency_encoding # Load datasetdata = sns.load_dataset('flights') # Categorical encodingfrequency_encoding(data, 'month') # Clustering data row-wise and# changing color of the map.sns.clustermap(data, cmap='coolwarm', figsize=(7, 7)) Output: Here we have changed the colors of the cluster map. Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Dec, 2020" }, { "code": null, "e": 328, "s": 28, "text": "Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas. " }, { "code": null, "e": 556, "s": 328, "text": "Clustering is basically grouping data based on relationships among the variables in the data. Clustering algorithms help in getting structured data in unsupervised learning. The most common types of clustering are shown below." }, { "code": null, "e": 573, "s": 556, "text": "Clustering_types" }, { "code": null, "e": 968, "s": 573, "text": "Here we are going to see hierarchical clustering especially Agglomerative(bottom-up) hierarchical clustering. In Agglomerative clustering, we start with considering each data point as a cluster and then repeatedly combine two nearest clusters into larger clusters until we are left with a single cluster. The graph we plot after performing agglomerative clustering on data is called Dendrogram." }, { "code": null, "e": 1164, "s": 968, "text": "Coming to the heat map, it is a graphical representation of data where values are represented using colors. Variation in the intensity of color depicts how data is clustered or varies over space." }, { "code": null, "e": 1308, "s": 1164, "text": "The clustermap() function of seaborn plots a hierarchically-clustered heat map of the given matrix dataset. It returns a clustered grid index. " }, { "code": null, "e": 1399, "s": 1308, "text": "Below are some examples which depict the hierarchically-clustered heat map from a dataset:" }, { "code": null, "e": 1491, "s": 1399, "text": "In the Flights dataset the data(Number of passengers) is clustered based on month and year:" }, { "code": null, "e": 1503, "s": 1491, "text": "Example 1: " }, { "code": null, "e": 1511, "s": 1503, "text": "Python3" }, { "code": "# Importing the libraryimport seaborn as snsfrom sunbird.categorical_encoding import frequency_encoding # Load datasetdata = sns.load_dataset('flights') # Categorical encodingfrequency_encoding(data, 'month') # Clustering data row-wise and# changing color of the map.sns.clustermap(data, figsize=(7, 7))", "e": 1818, "s": 1511, "text": null }, { "code": null, "e": 1827, "s": 1818, "text": "Output :" }, { "code": null, "e": 2004, "s": 1827, "text": "The legend to the left of the cluster map indicates information about the cluster map e.g bright color indicates more passengers and dark color indicates fewer passengers. " }, { "code": null, "e": 2015, "s": 2004, "text": "Example 2:" }, { "code": null, "e": 2023, "s": 2015, "text": "Python3" }, { "code": "# Importing the libraryimport seaborn as snsfrom sunbird.categorical_encoding import frequency_encoding # Load datasetdata = sns.load_dataset('flights') # Categorical encodingfrequency_encoding(data, 'month') # Clustering data row-wise and# changing color of the map.sns.clustermap(data, cmap='coolwarm', figsize=(7, 7))", "e": 2347, "s": 2023, "text": null }, { "code": null, "e": 2355, "s": 2347, "text": "Output:" }, { "code": null, "e": 2407, "s": 2355, "text": "Here we have changed the colors of the cluster map." }, { "code": null, "e": 2422, "s": 2407, "text": "Python-Seaborn" }, { "code": null, "e": 2429, "s": 2422, "text": "Python" }, { "code": null, "e": 2527, "s": 2429, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2559, "s": 2527, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2586, "s": 2559, "text": "Python Classes and Objects" }, { "code": null, "e": 2617, "s": 2586, "text": "Python | os.path.join() method" }, { "code": null, "e": 2640, "s": 2617, "text": "Introduction To PYTHON" }, { "code": null, "e": 2661, "s": 2640, "text": "Python OOPs Concepts" }, { "code": null, "e": 2717, "s": 2661, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2759, "s": 2717, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2801, "s": 2759, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2840, "s": 2801, "text": "Python | Get unique values from a list" } ]
sizeof() Operator in C#
28 May, 2020 The sizeof() operator is used to obtain the size of a data type in bytes in bytes. It will not return the size of the variables or instances. Its return type is always int. Syntax: int sizeof(type); Examples: Input : sizeof(byte); Output : 1 Input : sizeof(int); Output : 4 // C# program to illustrate the // sizeof() operatorusing System;using System.IO;using System.Text; namespace IncludeHelp{ class Test { // Main Method static void Main(string[] args) { Console.WriteLine("sizeof(char) : {0}", sizeof(char)); Console.WriteLine("sizeof(byte) : {0}", sizeof(byte)); Console.WriteLine("sizeof(sbyte) : {0}", sizeof(sbyte)); Console.WriteLine("sizeof(float) : {0}", sizeof(float)); Console.WriteLine("sizeof(ushort) : {0}", sizeof(ushort)); Console.WriteLine("sizeof(double) : {0}", sizeof(double)); Console.WriteLine("sizeof(int) : {0}", sizeof(int)); Console.WriteLine("sizeof(bool) : {0}", sizeof(bool)); Console.WriteLine("sizeof(short) : {0}", sizeof(short)); } }} Output: sizeof(char) : 2 sizeof(byte) : 1 sizeof(sbyte) : 1 sizeof(float) : 4 sizeof(ushort) : 2 sizeof(double) : 8 sizeof(int) : 4 sizeof(bool) : 1 sizeof(short) : 2 CSharp Operators CSharp-keyword C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class HashSet in C# with Examples C# | .NET Framework (Basic Architecture and Component Stack) Switch Statement in C# Lambda Expressions in C# Partial Classes in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n28 May, 2020" }, { "code": null, "e": 201, "s": 28, "text": "The sizeof() operator is used to obtain the size of a data type in bytes in bytes. It will not return the size of the variables or instances. Its return type is always int." }, { "code": null, "e": 209, "s": 201, "text": "Syntax:" }, { "code": null, "e": 227, "s": 209, "text": "int sizeof(type);" }, { "code": null, "e": 237, "s": 227, "text": "Examples:" }, { "code": null, "e": 304, "s": 237, "text": "Input : sizeof(byte);\nOutput : 1\n\nInput : sizeof(int);\nOutput : 4\n" }, { "code": "// C# program to illustrate the // sizeof() operatorusing System;using System.IO;using System.Text; namespace IncludeHelp{ class Test { // Main Method static void Main(string[] args) { Console.WriteLine(\"sizeof(char) : {0}\", sizeof(char)); Console.WriteLine(\"sizeof(byte) : {0}\", sizeof(byte)); Console.WriteLine(\"sizeof(sbyte) : {0}\", sizeof(sbyte)); Console.WriteLine(\"sizeof(float) : {0}\", sizeof(float)); Console.WriteLine(\"sizeof(ushort) : {0}\", sizeof(ushort)); Console.WriteLine(\"sizeof(double) : {0}\", sizeof(double)); Console.WriteLine(\"sizeof(int) : {0}\", sizeof(int)); Console.WriteLine(\"sizeof(bool) : {0}\", sizeof(bool)); Console.WriteLine(\"sizeof(short) : {0}\", sizeof(short)); } }}", "e": 1185, "s": 304, "text": null }, { "code": null, "e": 1193, "s": 1185, "text": "Output:" }, { "code": null, "e": 1383, "s": 1193, "text": "sizeof(char) : 2\nsizeof(byte) : 1\nsizeof(sbyte) : 1\nsizeof(float) : 4\nsizeof(ushort) : 2\nsizeof(double) : 8\nsizeof(int) : 4\nsizeof(bool) : 1\nsizeof(short) : 2\n" }, { "code": null, "e": 1400, "s": 1383, "text": "CSharp Operators" }, { "code": null, "e": 1415, "s": 1400, "text": "CSharp-keyword" }, { "code": null, "e": 1418, "s": 1415, "text": "C#" }, { "code": null, "e": 1516, "s": 1418, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1559, "s": 1516, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 1608, "s": 1559, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 1631, "s": 1608, "text": "Extension Method in C#" }, { "code": null, "e": 1647, "s": 1631, "text": "C# | List Class" }, { "code": null, "e": 1675, "s": 1647, "text": "HashSet in C# with Examples" }, { "code": null, "e": 1736, "s": 1675, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 1759, "s": 1736, "text": "Switch Statement in C#" }, { "code": null, "e": 1784, "s": 1759, "text": "Lambda Expressions in C#" }, { "code": null, "e": 1806, "s": 1784, "text": "Partial Classes in C#" } ]
What is Bridge Protocol Data Unit (BPDU) Frame?
03 Dec, 2021 Bridge Protocol Data Unit is fundamentally a tree traversed convention which portrays each message of the organization with the various sorts of characteristics on the organization like the MAC address or the IP address utilizing distinctive switch ports present on the organization. The Spanning Tree Protocol (STP) can empower and impair every one of the switches in a specific region network like LAN (neighborhood) or PAN (individual) region network so the course of trade of data stays flawless and the crossing tree calculation might turn out appropriately for the system’s administration. There are basically two types of BPDUs: Configuration BPDUs: Configuration BPDUs are mainly used in the presence of the network root bridge where they are responsible for controlling and authenticating the outward flow of data and act as a firewall of protection from outside. Topology Change Notification (TCN) BPDUs: Topology Change Notification (TCN) BPDUs maintain upward data streaming where it continuously regulates which network topologies are being used currently and it notifies with a reminder when the topology changes. Working of BPDU BPDU works in its own way to send a specific information message across the neighborhood for its work for distinguishing the anomalies in the different organization geographies around the framework. It incorporates a switch artist with its need port in it, data of the multitude of different ports and the MAC, IP addresses. BPDU can arrange and change different settings in the crossing geographies of the tree in the organization signal. This data of BDPU assists it with empowering unmistakable pass-through data by the different switches utilized in the organization sign to ascertain the transfer speed of each wave to go BPDUs through them. The primary component behind the Bridge Protocol information unit is that when they are associated with different switches and ports in their environmental factors, they will quite often disregard the transmission of information bundles by then. In another way, they utilize one more strategy for setting up the information prepared for handling until the Bridge Protocol information unit (BPDU) prepares with choosing the right crossing tree geography which can be utilized for information transmission. After the information handling is finished, then, at that point, the information is projected towards other organization ports and switches which is then moved to the primary base of the organization. When the root signal in the BPDU receives the message from the sender, it forwards this message to the original receiver by identifying him with the help of his MAC address. After this, the Bridge Protocol information unit (BPDU) transmits the signal to the Switch Port to enable the message recipient to receive this message by decrypting it with the help of his decryption key. The Bridge Protocol information unit (BPDU) stores all the important information about the PC like its Switch Port ID and its MAC address for all the computers connected to that network. Also, the address of the original Switch Port and of the adjacent ports are used to identify the credentials of each user of the organization on that network. Bridge Data Unit Protocol (BPDU) is mostly used for authenticating the messages sent and received across any organization by using their MAC address. Switch Ports in the BPDU helps to apply Spanning Tree Protocol (STP) in order to manage the layers of communication across an organization. It makes an effective plan for the most efficient way of transfer of messages as it uses the Spanning Tree for finding the nearest Switch Port to divert it from the traffic. It is extremely useful in conditions like Broadcast Storm takes place when the entire server is attacked. Picked Computer Networks Computer Subject Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2021" }, { "code": null, "e": 314, "s": 28, "text": "Bridge Protocol Data Unit is fundamentally a tree traversed convention which portrays each message of the organization with the various sorts of characteristics on the organization like the MAC address or the IP address utilizing distinctive switch ports present on the organization. " }, { "code": null, "e": 627, "s": 314, "text": "The Spanning Tree Protocol (STP) can empower and impair every one of the switches in a specific region network like LAN (neighborhood) or PAN (individual) region network so the course of trade of data stays flawless and the crossing tree calculation might turn out appropriately for the system’s administration. " }, { "code": null, "e": 667, "s": 627, "text": "There are basically two types of BPDUs:" }, { "code": null, "e": 905, "s": 667, "text": "Configuration BPDUs: Configuration BPDUs are mainly used in the presence of the network root bridge where they are responsible for controlling and authenticating the outward flow of data and act as a firewall of protection from outside. " }, { "code": null, "e": 1160, "s": 905, "text": "Topology Change Notification (TCN) BPDUs: Topology Change Notification (TCN) BPDUs maintain upward data streaming where it continuously regulates which network topologies are being used currently and it notifies with a reminder when the topology changes." }, { "code": null, "e": 1176, "s": 1160, "text": "Working of BPDU" }, { "code": null, "e": 1503, "s": 1176, "text": "BPDU works in its own way to send a specific information message across the neighborhood for its work for distinguishing the anomalies in the different organization geographies around the framework. It incorporates a switch artist with its need port in it, data of the multitude of different ports and the MAC, IP addresses. " }, { "code": null, "e": 1825, "s": 1503, "text": "BPDU can arrange and change different settings in the crossing geographies of the tree in the organization signal. This data of BDPU assists it with empowering unmistakable pass-through data by the different switches utilized in the organization sign to ascertain the transfer speed of each wave to go BPDUs through them." }, { "code": null, "e": 2332, "s": 1825, "text": "The primary component behind the Bridge Protocol information unit is that when they are associated with different switches and ports in their environmental factors, they will quite often disregard the transmission of information bundles by then. In another way, they utilize one more strategy for setting up the information prepared for handling until the Bridge Protocol information unit (BPDU) prepares with choosing the right crossing tree geography which can be utilized for information transmission. " }, { "code": null, "e": 2707, "s": 2332, "text": "After the information handling is finished, then, at that point, the information is projected towards other organization ports and switches which is then moved to the primary base of the organization. When the root signal in the BPDU receives the message from the sender, it forwards this message to the original receiver by identifying him with the help of his MAC address." }, { "code": null, "e": 2913, "s": 2707, "text": "After this, the Bridge Protocol information unit (BPDU) transmits the signal to the Switch Port to enable the message recipient to receive this message by decrypting it with the help of his decryption key." }, { "code": null, "e": 3259, "s": 2913, "text": "The Bridge Protocol information unit (BPDU) stores all the important information about the PC like its Switch Port ID and its MAC address for all the computers connected to that network. Also, the address of the original Switch Port and of the adjacent ports are used to identify the credentials of each user of the organization on that network." }, { "code": null, "e": 3829, "s": 3259, "text": "Bridge Data Unit Protocol (BPDU) is mostly used for authenticating the messages sent and received across any organization by using their MAC address. Switch Ports in the BPDU helps to apply Spanning Tree Protocol (STP) in order to manage the layers of communication across an organization. It makes an effective plan for the most efficient way of transfer of messages as it uses the Spanning Tree for finding the nearest Switch Port to divert it from the traffic. It is extremely useful in conditions like Broadcast Storm takes place when the entire server is attacked." }, { "code": null, "e": 3836, "s": 3829, "text": "Picked" }, { "code": null, "e": 3854, "s": 3836, "text": "Computer Networks" }, { "code": null, "e": 3871, "s": 3854, "text": "Computer Subject" }, { "code": null, "e": 3889, "s": 3871, "text": "Computer Networks" } ]
How can we disable the maximize button of a JFrame in Java?
A JFrame is a class from javax. swing package and it can extend java.awt.frame class. It is a top-level window with a border and a title bar. A JFrame class has many methods that can be used to customize it. After setting the size of a JFrame we can still change the size by putting the cursor at the corners and dragging it or if we press resize option next to close at the top right corner, it will maximize to the size of a full screen. This happens because resize is set to true by default for JFrame class. We can make it as false as setResizable(false), now it can appear according to the dimensions we have given in the code and it cannot be resizable. import java.awt.*; import javax.swing.*; public class JFrameDemo extends JFrame { String title; public JFrameDemo(String title) { super(title); add(new JLabel("JFrame with maximize button disabled"), BorderLayout.CENTER); setSize(350, 275); setLocationRelativeTo(null); setResizable(false); // maximize button disable setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String args[]) { new JFrameDemo("JFrame Demo"); } }
[ { "code": null, "e": 1395, "s": 1187, "text": "A JFrame is a class from javax. swing package and it can extend java.awt.frame class. It is a top-level window with a border and a title bar. A JFrame class has many methods that can be used to customize it." }, { "code": null, "e": 1847, "s": 1395, "text": "After setting the size of a JFrame we can still change the size by putting the cursor at the corners and dragging it or if we press resize option next to close at the top right corner, it will maximize to the size of a full screen. This happens because resize is set to true by default for JFrame class. We can make it as false as setResizable(false), now it can appear according to the dimensions we have given in the code and it cannot be resizable." }, { "code": null, "e": 2372, "s": 1847, "text": "import java.awt.*;\nimport javax.swing.*;\npublic class JFrameDemo extends JFrame {\n String title;\n public JFrameDemo(String title) {\n super(title);\n add(new JLabel(\"JFrame with maximize button disabled\"), BorderLayout.CENTER);\n setSize(350, 275);\n setLocationRelativeTo(null);\n setResizable(false); // maximize button disable\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setVisible(true);\n }\n public static void main(String args[]) {\n new JFrameDemo(\"JFrame Demo\");\n }\n}" } ]
PugJS Basics and Installation
25 May, 2021 Pug.js is a template engine for Node.js and browsers to render dynamic reusable content. At compile time, the template engine compiles our Pug template code to HTML. We can use variables in pug just like in JavaScript. At runtime, the template engine injects or replaces variables in a template file with actual values, and transforms the template into an HTML file which is then rendered on client side. Pug has many powerful features like conditions, loops, includes, mixins using which we can render HTML code based on user input or reference data. Pug also support JavaScript natively, hence using JavaScript expressions, we can format HTML code. This approach allows us to reuse static web pages having dynamic data. Pug was formerly called Jade until it’s version 2.0 was released in 2015. Let’s make a basic pug template using express.js: Prerequisite: Basic working knowledge of express is required. Step 1: Make an empty project folder. In command prompt / terminal, run npm init to initialize package.json file: npm init -y -y flag is for default settings in package.json. Step 2: Install express and pug. We will directly install ‘express’ package rather than generating our express app with ‘express-generator’ for simplicity reasons. You can optionally install nodemon for hot reloading. npm install express pug Step 3: Make an empty index.js file. Make a views folder and an empty index.pug file inside it. Optionally, you can also make a public folder for static assets like media files and client side javascript. Our final directory structure will look like this: Final Directory Structure Step 4: Setting up a basic express app. In Index.js: Javascript // Importing node modulesconst express = require("express");const pug = require("pug");const path = require("path"); // Initializing express appconst app = express(); // Setting our view engine to pugapp.set("view engine", "pug"); // Setting our default viewsapp.set("views", __dirname + "/views"); // Serving public assetsapp.use(express.static( path.join(__dirname + "/public"))); // Home page will render "index.pug"// file. ".pug" extension is not// required. Express takes care of// it behind the scenesapp.get("/", (req, res) => { res.render("index");}); // Listening our app on port 3000app.listen(3000); Step 5: In index.pug file: Javascript doctype htmlhtml head title GeeksForGeeks body h1 Welcome to GeeksForGeeks p We successfully made a Sample Pug Template! You can read basics of pug syntax here. Step 6: In terminal start the application. Run nodemon command if we have installed it previously, or just simply use node. node index.js or nodemon index.js In browser on localhost 3000 port, we get the below rendered template: Akanksha_Rai 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": "\n25 May, 2021" }, { "code": null, "e": 433, "s": 28, "text": "Pug.js is a template engine for Node.js and browsers to render dynamic reusable content. At compile time, the template engine compiles our Pug template code to HTML. We can use variables in pug just like in JavaScript. At runtime, the template engine injects or replaces variables in a template file with actual values, and transforms the template into an HTML file which is then rendered on client side." }, { "code": null, "e": 824, "s": 433, "text": "Pug has many powerful features like conditions, loops, includes, mixins using which we can render HTML code based on user input or reference data. Pug also support JavaScript natively, hence using JavaScript expressions, we can format HTML code. This approach allows us to reuse static web pages having dynamic data. Pug was formerly called Jade until it’s version 2.0 was released in 2015." }, { "code": null, "e": 874, "s": 824, "text": "Let’s make a basic pug template using express.js:" }, { "code": null, "e": 936, "s": 874, "text": "Prerequisite: Basic working knowledge of express is required." }, { "code": null, "e": 1050, "s": 936, "text": "Step 1: Make an empty project folder. In command prompt / terminal, run npm init to initialize package.json file:" }, { "code": null, "e": 1062, "s": 1050, "text": "npm init -y" }, { "code": null, "e": 1111, "s": 1062, "text": "-y flag is for default settings in package.json." }, { "code": null, "e": 1329, "s": 1111, "text": "Step 2: Install express and pug. We will directly install ‘express’ package rather than generating our express app with ‘express-generator’ for simplicity reasons. You can optionally install nodemon for hot reloading." }, { "code": null, "e": 1353, "s": 1329, "text": "npm install express pug" }, { "code": null, "e": 1558, "s": 1353, "text": "Step 3: Make an empty index.js file. Make a views folder and an empty index.pug file inside it. Optionally, you can also make a public folder for static assets like media files and client side javascript." }, { "code": null, "e": 1609, "s": 1558, "text": "Our final directory structure will look like this:" }, { "code": null, "e": 1635, "s": 1609, "text": "Final Directory Structure" }, { "code": null, "e": 1688, "s": 1635, "text": "Step 4: Setting up a basic express app. In Index.js:" }, { "code": null, "e": 1699, "s": 1688, "text": "Javascript" }, { "code": "// Importing node modulesconst express = require(\"express\");const pug = require(\"pug\");const path = require(\"path\"); // Initializing express appconst app = express(); // Setting our view engine to pugapp.set(\"view engine\", \"pug\"); // Setting our default viewsapp.set(\"views\", __dirname + \"/views\"); // Serving public assetsapp.use(express.static( path.join(__dirname + \"/public\"))); // Home page will render \"index.pug\"// file. \".pug\" extension is not// required. Express takes care of// it behind the scenesapp.get(\"/\", (req, res) => { res.render(\"index\");}); // Listening our app on port 3000app.listen(3000);", "e": 2317, "s": 1699, "text": null }, { "code": null, "e": 2344, "s": 2317, "text": "Step 5: In index.pug file:" }, { "code": null, "e": 2355, "s": 2344, "text": "Javascript" }, { "code": "doctype htmlhtml head title GeeksForGeeks body h1 Welcome to GeeksForGeeks p We successfully made a Sample Pug Template!", "e": 2503, "s": 2355, "text": null }, { "code": null, "e": 2543, "s": 2503, "text": "You can read basics of pug syntax here." }, { "code": null, "e": 2667, "s": 2543, "text": "Step 6: In terminal start the application. Run nodemon command if we have installed it previously, or just simply use node." }, { "code": null, "e": 2701, "s": 2667, "text": "node index.js or nodemon index.js" }, { "code": null, "e": 2772, "s": 2701, "text": "In browser on localhost 3000 port, we get the below rendered template:" }, { "code": null, "e": 2785, "s": 2772, "text": "Akanksha_Rai" }, { "code": null, "e": 2796, "s": 2785, "text": "JavaScript" }, { "code": null, "e": 2813, "s": 2796, "text": "Web Technologies" } ]
How to Set Axis Ranges in Matplotlib?
28 Nov, 2021 Matplotlib sets the default range of the axis by finding extreme values (i.e. minimum and maximum) on that axis. However, to get a better view of data sometimes pyplot module is used to set axis ranges of the graphs according to the requirements in Matplotlib. Following is the method used to set axis range in Matplotlib: Syntax: For setting range of x-axis: matplotlib.pyplot.xlim(limit_range) For setting range of y-axis: matplotlib.pyplot.ylim(limit_range) Example 1: Let us plot the sine wave function without setting the axis range: Python # import packagesimport matplotlib.pyplot as pltimport numpy as np # return values between 0 and 10 with # even space of 0.1x = np.arange(0, 10, 0.1) # generate value of sine function for # given x valuesy = np.sin(x) # plot graph of sine functionplt.plot(y, color='blue') # display plotplt.show() Output: Now, we will set the x-axis range of the plot as [0, 60]. Following is the code for restricting the range of the x-axis: Example 2: Python # import packagesimport matplotlib.pyplot as pltimport numpy as np # return values between 0 and 10 with # even space of 0.1x = np.arange(0, 10, 0.1) # generate value of sine function for # given x valuesy = np.sin(x) # plot graph of sine functionplt.plot(y, color='blue') # Set the range of x-axisplt.xlim(0, 60) # display plotplt.show() Output: Now, we will set the y axis range of plot as [0, 1]. Following is the code for restricting the range of y-axis: Example 3: Python # import packagesimport matplotlib.pyplot as pltimport numpy as np # return values between 0 and 10 with # even space of 0.1x = np.arange(0, 10, 0.1) # generate value of sine function for # given x valuesy = np.sin(x) # plot graph of sine functionplt.plot(y, color='blue') # Set the range of y-axisplt.ylim(0, 1) # display plotplt.show() Output: We can also set the range for both the axis of the plot at the same time. Now, we will set the x-axis range as [0, 32] and y axis range as [0, 1]. Following is the code for restricting the range of x-axis and y-axis: Example 4: Python # import packagesimport matplotlib.pyplot as pltimport numpy as np # return values between 0 and 10 with # even space of 0.1x = np.arange(0, 10, 0.1) # generate value of sine function for# given x valuesy = np.sin(x) # plot graph of sine functionplt.plot(y, color='blue') # Set the range of x-axisplt.xlim(0, 32)# Set the range of y-axisplt.ylim(0, 1) # display plotplt.show() Output: Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2021" }, { "code": null, "e": 352, "s": 28, "text": "Matplotlib sets the default range of the axis by finding extreme values (i.e. minimum and maximum) on that axis. However, to get a better view of data sometimes pyplot module is used to set axis ranges of the graphs according to the requirements in Matplotlib. Following is the method used to set axis range in Matplotlib:" }, { "code": null, "e": 360, "s": 352, "text": "Syntax:" }, { "code": null, "e": 493, "s": 360, "text": "For setting range of x-axis:\n matplotlib.pyplot.xlim(limit_range)\nFor setting range of y-axis: \n matplotlib.pyplot.ylim(limit_range)" }, { "code": null, "e": 504, "s": 493, "text": "Example 1:" }, { "code": null, "e": 571, "s": 504, "text": "Let us plot the sine wave function without setting the axis range:" }, { "code": null, "e": 578, "s": 571, "text": "Python" }, { "code": "# import packagesimport matplotlib.pyplot as pltimport numpy as np # return values between 0 and 10 with # even space of 0.1x = np.arange(0, 10, 0.1) # generate value of sine function for # given x valuesy = np.sin(x) # plot graph of sine functionplt.plot(y, color='blue') # display plotplt.show()", "e": 880, "s": 578, "text": null }, { "code": null, "e": 889, "s": 880, "text": "Output: " }, { "code": null, "e": 1010, "s": 889, "text": "Now, we will set the x-axis range of the plot as [0, 60]. Following is the code for restricting the range of the x-axis:" }, { "code": null, "e": 1021, "s": 1010, "text": "Example 2:" }, { "code": null, "e": 1028, "s": 1021, "text": "Python" }, { "code": "# import packagesimport matplotlib.pyplot as pltimport numpy as np # return values between 0 and 10 with # even space of 0.1x = np.arange(0, 10, 0.1) # generate value of sine function for # given x valuesy = np.sin(x) # plot graph of sine functionplt.plot(y, color='blue') # Set the range of x-axisplt.xlim(0, 60) # display plotplt.show()", "e": 1372, "s": 1028, "text": null }, { "code": null, "e": 1380, "s": 1372, "text": "Output:" }, { "code": null, "e": 1492, "s": 1380, "text": "Now, we will set the y axis range of plot as [0, 1]. Following is the code for restricting the range of y-axis:" }, { "code": null, "e": 1503, "s": 1492, "text": "Example 3:" }, { "code": null, "e": 1510, "s": 1503, "text": "Python" }, { "code": "# import packagesimport matplotlib.pyplot as pltimport numpy as np # return values between 0 and 10 with # even space of 0.1x = np.arange(0, 10, 0.1) # generate value of sine function for # given x valuesy = np.sin(x) # plot graph of sine functionplt.plot(y, color='blue') # Set the range of y-axisplt.ylim(0, 1) # display plotplt.show()", "e": 1853, "s": 1510, "text": null }, { "code": null, "e": 1861, "s": 1853, "text": "Output:" }, { "code": null, "e": 2078, "s": 1861, "text": "We can also set the range for both the axis of the plot at the same time. Now, we will set the x-axis range as [0, 32] and y axis range as [0, 1]. Following is the code for restricting the range of x-axis and y-axis:" }, { "code": null, "e": 2089, "s": 2078, "text": "Example 4:" }, { "code": null, "e": 2096, "s": 2089, "text": "Python" }, { "code": "# import packagesimport matplotlib.pyplot as pltimport numpy as np # return values between 0 and 10 with # even space of 0.1x = np.arange(0, 10, 0.1) # generate value of sine function for# given x valuesy = np.sin(x) # plot graph of sine functionplt.plot(y, color='blue') # Set the range of x-axisplt.xlim(0, 32)# Set the range of y-axisplt.ylim(0, 1) # display plotplt.show()", "e": 2478, "s": 2096, "text": null }, { "code": null, "e": 2486, "s": 2478, "text": "Output:" }, { "code": null, "e": 2493, "s": 2486, "text": "Picked" }, { "code": null, "e": 2511, "s": 2493, "text": "Python-matplotlib" }, { "code": null, "e": 2518, "s": 2511, "text": "Python" }, { "code": null, "e": 2616, "s": 2518, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2648, "s": 2616, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2675, "s": 2648, "text": "Python Classes and Objects" }, { "code": null, "e": 2696, "s": 2675, "text": "Python OOPs Concepts" }, { "code": null, "e": 2719, "s": 2696, "text": "Introduction To PYTHON" }, { "code": null, "e": 2775, "s": 2719, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2806, "s": 2775, "text": "Python | os.path.join() method" }, { "code": null, "e": 2848, "s": 2806, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2890, "s": 2848, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2929, "s": 2890, "text": "Python | datetime.timedelta() function" } ]
Convolutional Neural Network: Feature Map and Filter Visualization | by Renu Khandelwal | Towards Data Science
In this article, we will visualize the intermediate feature representations across different CNN layers to understand what happens inside CNN’s to classify images. Convolutional Neural Network Basics, Building Powerful Image Classification Convolutional Neural Network using Keras Building powerful image classification CNN using Keras Supervised Deep Learning and Machine Learning take data and results as an input during training to generate the rules or data patterns. Understanding of data patterns or rules generated by the model helps us understand how the results were derived from the input data. Training: Convolutional neural network takes a two-dimensional image and the class of the image, like a cat or a dog as an input. As a result of the training, we get trained weights, which are the data patterns or rules extracted from the images. Inference or Prediction: Image will be the only input passed to the trained model, and the trained model will output the class of the image. The class of the image will be based on the learned data patterns during the training. Apply filters or feature detectors to the input image to generate the feature maps or the activation maps using the Relu activation function. Feature detectors or filters help identify different features present in an image like edges, vertical lines, horizontal lines, bends, etc. Pooling is then applied over the feature maps for invariance to translation. Pooling is based on the concept that when we change the input by a small amount, the pooled outputs do not change. We can use min pooling, average pooling, or max pooling. Max pooling provides better performance compared to min or average pooling. Flatten all the input and pass these flattened inputs to a deep neural network that outputs the class of the object The class of the image can be binary like a cat or dog, or it can be a multi-class classification like identifying digits or classifying different apparel items. Neural networks are like a black box, and learned features in a Neural Network are not interpretable. You pass an input image, and the model returns the results. What if you get an incorrect prediction and would like to figure out why such a decision was made by CNN? If only you could visualize the intermediate representation applied across different Convolutional layers in CNN to understand how the model learns. Understanding the working of the model will help to know the reason for incorrect predition that will lead to better fine tuning of the model and explain the decisions The example used here is a deep CNN model for classifying cats and dogs. Before you dive in to learn to visualize both the filters and the feature maps generated by CNN, you will need to understand some of the critical points about Convolutional layers and the filters applied to them. The depth of a filter in a CNN must match the depth of the input image. The number of color channels in the filter must remain the same as the input image. Different Conv2D filters are created for each of the three channels for a color image. Filters for each layer are randomly initialized based on either Normal or Gaussian distribution. Initial layers of a convolutional network extract high-level features from the image, so use fewer filters. As we build further deeper layers, we increase the number of filters to twice or thrice the size of the filter of the previous layer. Filters of the deeper layers learn more features but are computationally very intensive. We build a CNN for classifying dogs and cats and later visualize the feature maps or activation maps and filters applied to generate them on an input image Importing required libraries import tensorflow as tffrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2Dfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_imgimport osimport numpy as npimport matplotlib.pyplot as plt Creating data for image processing Dataset can be downloaded from here We will unzip the file and create the folders as shown below and split the data into the training dataset with 10,000 cats and 10,000 dogs images and validation dataset containing 2500 cats and 2500 dogs images Set key parameters batch_size = 64 epochs = 50IMG_HEIGHT = 150IMG_WIDTH = 150 Rescale and Apply different Augmentation to the training image train_image_generator = ImageDataGenerator( rescale=1./255, rotation_range=45, width_shift_range=.15, height_shift_range=.15, horizontal_flip=True, zoom_range=0.3) Rescale Validation data validation_image_generator = ImageDataGenerator(rescale=1./255) Generate batches of normalized data for train and validation data set your data is stored in directories, so use the flow_from_directory() method. flow_from_directory() will take the data from the specified path and generates batches of augmented normalized data. train_data_gen = train_image_generator.flow_from_directory(batch_size=batch_size, directory=TRAIN_PATH, shuffle=True, target_size=(IMG_HEIGHT, IMG_WIDTH), class_mode='binary')val_data_gen = validation_image_generator.flow_from_directory(batch_size=batch_size, directory=VAL_PATH, target_size=(IMG_HEIGHT, IMG_WIDTH), class_mode='binary') Create the Deep Convolutional Neural network model #Build the modelmodel = Sequential([ Conv2D(16, 3, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH ,3)), MaxPooling2D(), Dropout(0.2), Conv2D(32, 3, padding='same', activation='relu'), MaxPooling2D(), Conv2D(64, 3, padding='same', activation='relu'), MaxPooling2D(), Dropout(0.2), Flatten(), Dense(512, activation='relu'), Dense(1)])# Compile the modelmodel.compile(optimizer='adam', loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), metrics=['accuracy'])# print the model architecturemodel.summary() Training the Model We train the model for 50 epochs history = model.fit_generator( train_data_gen, steps_per_epoch=1000, epochs=epochs, validation_data=val_data_gen, validation_steps=1000) Feature Visualization translates the internal features present in an image into visually perceptible or recognizable image patterns. Feature visualization will help us understand the learned features explicitly. First, you will visualize the different filters or feature detectors that are applied to the input image and, in the next step, visualize the feature maps or activation maps that are generated. CNN uses learned filters to convolve the feature maps from the previous layer. Filters are two- dimensional weights and these weights have a spatial relationship with each other. The steps you will follow to visualize the filters. Iterate through all the layers of the model using model.layersIf the layer is a convolutional layer, then extract the weights and bias values using get_weights() for that layer.Normalize the weights for the filters between 0 and 1Plot the filters for each of the convolutional layers and all the channels. For Color image, you will have three channels for RGB. For a grayscale image, the number of channels will be 1 Iterate through all the layers of the model using model.layers If the layer is a convolutional layer, then extract the weights and bias values using get_weights() for that layer. Normalize the weights for the filters between 0 and 1 Plot the filters for each of the convolutional layers and all the channels. For Color image, you will have three channels for RGB. For a grayscale image, the number of channels will be 1 #Iterate thru all the layers of the modelfor layer in model.layers: if 'conv' in layer.name: weights, bias= layer.get_weights() print(layer.name, filters.shape) #normalize filter values between 0 and 1 for visualization f_min, f_max = weights.min(), weights.max() filters = (weights - f_min) / (f_max - f_min) print(filters.shape[3]) filter_cnt=1 #plotting all the filters for i in range(filters.shape[3]): #get the filters filt=filters[:,:,:, i] #plotting each of the channel, color image RGB channels for j in range(filters.shape[0]): ax= plt.subplot(filters.shape[3], filters.shape[0], filter_cnt ) ax.set_xticks([]) ax.set_yticks([]) plt.imshow(filt[:,:, j]) filter_cnt+=1 plt.show() Feature maps are generated by applying Filters or Feature detectors to the input image or the feature map output of the prior layers. Feature map visualization will provide insight into the internal representations for specific input for each of the Convolutional layers in the model. The steps you will follow to visualize the feature maps. Define a new model, visualization_model that will take an image as the input. The output of the model will be feature maps, which are an intermediate representation for all layers after the first layer. This is based on the model we have used for training.Load the input image for which we want to view the Feature map to understand which features were prominent to classify the image.Convert the image to NumPy arrayNormalize the array by rescaling itRun the input image through the visualization model to obtain allintermediate representations for the input image.Create the plot for all of the convolutional layers and the max pool layers but not for the fully connected layer. For plotting the Feature maps, retrieve the layer name for each of the layers in the model. Define a new model, visualization_model that will take an image as the input. The output of the model will be feature maps, which are an intermediate representation for all layers after the first layer. This is based on the model we have used for training. Load the input image for which we want to view the Feature map to understand which features were prominent to classify the image. Convert the image to NumPy array Normalize the array by rescaling it Run the input image through the visualization model to obtain allintermediate representations for the input image. Create the plot for all of the convolutional layers and the max pool layers but not for the fully connected layer. For plotting the Feature maps, retrieve the layer name for each of the layers in the model. img_path='\\dogs-vs-cats\\test1\\137.jpg' #dog# Define a new Model, Input= image # Output= intermediate representations for all layers in the # previous model after the first.successive_outputs = [layer.output for layer in model.layers[1:]]#visualization_model = Model(img_input, successive_outputs)visualization_model = tf.keras.models.Model(inputs = model.input, outputs = successive_outputs)#Load the input imageimg = load_img(img_path, target_size=(150, 150))# Convert ht image to Array of dimension (150,150,3)x = img_to_array(img) x = x.reshape((1,) + x.shape)# Rescale by 1/255x /= 255.0# Let's run input image through our vislauization network# to obtain all intermediate representations for the image.successive_feature_maps = visualization_model.predict(x)# Retrieve are the names of the layers, so can have them as part of our plotlayer_names = [layer.name for layer in model.layers]for layer_name, feature_map in zip(layer_names, successive_feature_maps): print(feature_map.shape) if len(feature_map.shape) == 4: # Plot Feature maps for the conv / maxpool layers, not the fully-connected layers n_features = feature_map.shape[-1] # number of features in the feature map size = feature_map.shape[ 1] # feature map shape (1, size, size, n_features) # We will tile our images in this matrix display_grid = np.zeros((size, size * n_features)) # Postprocess the feature to be visually palatable for i in range(n_features): x = feature_map[0, :, :, i] x -= x.mean() x /= x.std () x *= 64 x += 128 x = np.clip(x, 0, 255).astype('uint8') # Tile each filter into a horizontal grid display_grid[:, i * size : (i + 1) * size] = x# Display the grid scale = 20. / n_features plt.figure( figsize=(scale * n_features, scale) ) plt.title ( layer_name ) plt.grid ( False ) plt.imshow( display_grid, aspect='auto', cmap='viridis' ) We can see that for the dog image, the snout and the tongue are very prominent features, and for the cat image, the ears and tail are prominent in the feature maps. Code available here Visualizing an inside story of how CNN learns to identify different features present in images provides a deeper insight into how the model works. It will also help to understand why the model might be failing to classify some of the images correctly and hence fine-tuning the model for better accuracy and precision. keras.io keras.io How Convolutional Neural Networks see the World — A survey of Convolutional Neural Network Visualization Methods Visualizing and Understanding Convolutional Networks Feature Visualization — Google AI Blog
[ { "code": null, "e": 336, "s": 172, "text": "In this article, we will visualize the intermediate feature representations across different CNN layers to understand what happens inside CNN’s to classify images." }, { "code": null, "e": 373, "s": 336, "text": "Convolutional Neural Network Basics," }, { "code": null, "e": 453, "s": 373, "text": "Building Powerful Image Classification Convolutional Neural Network using Keras" }, { "code": null, "e": 508, "s": 453, "text": "Building powerful image classification CNN using Keras" }, { "code": null, "e": 777, "s": 508, "text": "Supervised Deep Learning and Machine Learning take data and results as an input during training to generate the rules or data patterns. Understanding of data patterns or rules generated by the model helps us understand how the results were derived from the input data." }, { "code": null, "e": 1024, "s": 777, "text": "Training: Convolutional neural network takes a two-dimensional image and the class of the image, like a cat or a dog as an input. As a result of the training, we get trained weights, which are the data patterns or rules extracted from the images." }, { "code": null, "e": 1252, "s": 1024, "text": "Inference or Prediction: Image will be the only input passed to the trained model, and the trained model will output the class of the image. The class of the image will be based on the learned data patterns during the training." }, { "code": null, "e": 1534, "s": 1252, "text": "Apply filters or feature detectors to the input image to generate the feature maps or the activation maps using the Relu activation function. Feature detectors or filters help identify different features present in an image like edges, vertical lines, horizontal lines, bends, etc." }, { "code": null, "e": 1859, "s": 1534, "text": "Pooling is then applied over the feature maps for invariance to translation. Pooling is based on the concept that when we change the input by a small amount, the pooled outputs do not change. We can use min pooling, average pooling, or max pooling. Max pooling provides better performance compared to min or average pooling." }, { "code": null, "e": 1975, "s": 1859, "text": "Flatten all the input and pass these flattened inputs to a deep neural network that outputs the class of the object" }, { "code": null, "e": 2137, "s": 1975, "text": "The class of the image can be binary like a cat or dog, or it can be a multi-class classification like identifying digits or classifying different apparel items." }, { "code": null, "e": 2299, "s": 2137, "text": "Neural networks are like a black box, and learned features in a Neural Network are not interpretable. You pass an input image, and the model returns the results." }, { "code": null, "e": 2405, "s": 2299, "text": "What if you get an incorrect prediction and would like to figure out why such a decision was made by CNN?" }, { "code": null, "e": 2722, "s": 2405, "text": "If only you could visualize the intermediate representation applied across different Convolutional layers in CNN to understand how the model learns. Understanding the working of the model will help to know the reason for incorrect predition that will lead to better fine tuning of the model and explain the decisions" }, { "code": null, "e": 3008, "s": 2722, "text": "The example used here is a deep CNN model for classifying cats and dogs. Before you dive in to learn to visualize both the filters and the feature maps generated by CNN, you will need to understand some of the critical points about Convolutional layers and the filters applied to them." }, { "code": null, "e": 3164, "s": 3008, "text": "The depth of a filter in a CNN must match the depth of the input image. The number of color channels in the filter must remain the same as the input image." }, { "code": null, "e": 3251, "s": 3164, "text": "Different Conv2D filters are created for each of the three channels for a color image." }, { "code": null, "e": 3348, "s": 3251, "text": "Filters for each layer are randomly initialized based on either Normal or Gaussian distribution." }, { "code": null, "e": 3590, "s": 3348, "text": "Initial layers of a convolutional network extract high-level features from the image, so use fewer filters. As we build further deeper layers, we increase the number of filters to twice or thrice the size of the filter of the previous layer." }, { "code": null, "e": 3679, "s": 3590, "text": "Filters of the deeper layers learn more features but are computationally very intensive." }, { "code": null, "e": 3835, "s": 3679, "text": "We build a CNN for classifying dogs and cats and later visualize the feature maps or activation maps and filters applied to generate them on an input image" }, { "code": null, "e": 3864, "s": 3835, "text": "Importing required libraries" }, { "code": null, "e": 4164, "s": 3864, "text": "import tensorflow as tffrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2Dfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_imgimport osimport numpy as npimport matplotlib.pyplot as plt" }, { "code": null, "e": 4199, "s": 4164, "text": "Creating data for image processing" }, { "code": null, "e": 4235, "s": 4199, "text": "Dataset can be downloaded from here" }, { "code": null, "e": 4446, "s": 4235, "text": "We will unzip the file and create the folders as shown below and split the data into the training dataset with 10,000 cats and 10,000 dogs images and validation dataset containing 2500 cats and 2500 dogs images" }, { "code": null, "e": 4465, "s": 4446, "text": "Set key parameters" }, { "code": null, "e": 4524, "s": 4465, "text": "batch_size = 64 epochs = 50IMG_HEIGHT = 150IMG_WIDTH = 150" }, { "code": null, "e": 4587, "s": 4524, "text": "Rescale and Apply different Augmentation to the training image" }, { "code": null, "e": 5031, "s": 4587, "text": "train_image_generator = ImageDataGenerator( rescale=1./255, rotation_range=45, width_shift_range=.15, height_shift_range=.15, horizontal_flip=True, zoom_range=0.3)" }, { "code": null, "e": 5055, "s": 5031, "text": "Rescale Validation data" }, { "code": null, "e": 5119, "s": 5055, "text": "validation_image_generator = ImageDataGenerator(rescale=1./255)" }, { "code": null, "e": 5189, "s": 5119, "text": "Generate batches of normalized data for train and validation data set" }, { "code": null, "e": 5383, "s": 5189, "text": "your data is stored in directories, so use the flow_from_directory() method. flow_from_directory() will take the data from the specified path and generates batches of augmented normalized data." }, { "code": null, "e": 6112, "s": 5383, "text": "train_data_gen = train_image_generator.flow_from_directory(batch_size=batch_size, directory=TRAIN_PATH, shuffle=True, target_size=(IMG_HEIGHT, IMG_WIDTH), class_mode='binary')val_data_gen = validation_image_generator.flow_from_directory(batch_size=batch_size, directory=VAL_PATH, target_size=(IMG_HEIGHT, IMG_WIDTH), class_mode='binary')" }, { "code": null, "e": 6163, "s": 6112, "text": "Create the Deep Convolutional Neural network model" }, { "code": null, "e": 6765, "s": 6163, "text": "#Build the modelmodel = Sequential([ Conv2D(16, 3, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH ,3)), MaxPooling2D(), Dropout(0.2), Conv2D(32, 3, padding='same', activation='relu'), MaxPooling2D(), Conv2D(64, 3, padding='same', activation='relu'), MaxPooling2D(), Dropout(0.2), Flatten(), Dense(512, activation='relu'), Dense(1)])# Compile the modelmodel.compile(optimizer='adam', loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), metrics=['accuracy'])# print the model architecturemodel.summary()" }, { "code": null, "e": 6784, "s": 6765, "text": "Training the Model" }, { "code": null, "e": 6817, "s": 6784, "text": "We train the model for 50 epochs" }, { "code": null, "e": 6969, "s": 6817, "text": "history = model.fit_generator( train_data_gen, steps_per_epoch=1000, epochs=epochs, validation_data=val_data_gen, validation_steps=1000)" }, { "code": null, "e": 7181, "s": 6969, "text": "Feature Visualization translates the internal features present in an image into visually perceptible or recognizable image patterns. Feature visualization will help us understand the learned features explicitly." }, { "code": null, "e": 7375, "s": 7181, "text": "First, you will visualize the different filters or feature detectors that are applied to the input image and, in the next step, visualize the feature maps or activation maps that are generated." }, { "code": null, "e": 7554, "s": 7375, "text": "CNN uses learned filters to convolve the feature maps from the previous layer. Filters are two- dimensional weights and these weights have a spatial relationship with each other." }, { "code": null, "e": 7606, "s": 7554, "text": "The steps you will follow to visualize the filters." }, { "code": null, "e": 8023, "s": 7606, "text": "Iterate through all the layers of the model using model.layersIf the layer is a convolutional layer, then extract the weights and bias values using get_weights() for that layer.Normalize the weights for the filters between 0 and 1Plot the filters for each of the convolutional layers and all the channels. For Color image, you will have three channels for RGB. For a grayscale image, the number of channels will be 1" }, { "code": null, "e": 8086, "s": 8023, "text": "Iterate through all the layers of the model using model.layers" }, { "code": null, "e": 8202, "s": 8086, "text": "If the layer is a convolutional layer, then extract the weights and bias values using get_weights() for that layer." }, { "code": null, "e": 8256, "s": 8202, "text": "Normalize the weights for the filters between 0 and 1" }, { "code": null, "e": 8443, "s": 8256, "text": "Plot the filters for each of the convolutional layers and all the channels. For Color image, you will have three channels for RGB. For a grayscale image, the number of channels will be 1" }, { "code": null, "e": 9343, "s": 8443, "text": "#Iterate thru all the layers of the modelfor layer in model.layers: if 'conv' in layer.name: weights, bias= layer.get_weights() print(layer.name, filters.shape) #normalize filter values between 0 and 1 for visualization f_min, f_max = weights.min(), weights.max() filters = (weights - f_min) / (f_max - f_min) print(filters.shape[3]) filter_cnt=1 #plotting all the filters for i in range(filters.shape[3]): #get the filters filt=filters[:,:,:, i] #plotting each of the channel, color image RGB channels for j in range(filters.shape[0]): ax= plt.subplot(filters.shape[3], filters.shape[0], filter_cnt ) ax.set_xticks([]) ax.set_yticks([]) plt.imshow(filt[:,:, j]) filter_cnt+=1 plt.show()" }, { "code": null, "e": 9628, "s": 9343, "text": "Feature maps are generated by applying Filters or Feature detectors to the input image or the feature map output of the prior layers. Feature map visualization will provide insight into the internal representations for specific input for each of the Convolutional layers in the model." }, { "code": null, "e": 9685, "s": 9628, "text": "The steps you will follow to visualize the feature maps." }, { "code": null, "e": 10458, "s": 9685, "text": "Define a new model, visualization_model that will take an image as the input. The output of the model will be feature maps, which are an intermediate representation for all layers after the first layer. This is based on the model we have used for training.Load the input image for which we want to view the Feature map to understand which features were prominent to classify the image.Convert the image to NumPy arrayNormalize the array by rescaling itRun the input image through the visualization model to obtain allintermediate representations for the input image.Create the plot for all of the convolutional layers and the max pool layers but not for the fully connected layer. For plotting the Feature maps, retrieve the layer name for each of the layers in the model." }, { "code": null, "e": 10715, "s": 10458, "text": "Define a new model, visualization_model that will take an image as the input. The output of the model will be feature maps, which are an intermediate representation for all layers after the first layer. This is based on the model we have used for training." }, { "code": null, "e": 10845, "s": 10715, "text": "Load the input image for which we want to view the Feature map to understand which features were prominent to classify the image." }, { "code": null, "e": 10878, "s": 10845, "text": "Convert the image to NumPy array" }, { "code": null, "e": 10914, "s": 10878, "text": "Normalize the array by rescaling it" }, { "code": null, "e": 11029, "s": 10914, "text": "Run the input image through the visualization model to obtain allintermediate representations for the input image." }, { "code": null, "e": 11236, "s": 11029, "text": "Create the plot for all of the convolutional layers and the max pool layers but not for the fully connected layer. For plotting the Feature maps, retrieve the layer name for each of the layers in the model." }, { "code": null, "e": 13198, "s": 11236, "text": "img_path='\\\\dogs-vs-cats\\\\test1\\\\137.jpg' #dog# Define a new Model, Input= image # Output= intermediate representations for all layers in the # previous model after the first.successive_outputs = [layer.output for layer in model.layers[1:]]#visualization_model = Model(img_input, successive_outputs)visualization_model = tf.keras.models.Model(inputs = model.input, outputs = successive_outputs)#Load the input imageimg = load_img(img_path, target_size=(150, 150))# Convert ht image to Array of dimension (150,150,3)x = img_to_array(img) x = x.reshape((1,) + x.shape)# Rescale by 1/255x /= 255.0# Let's run input image through our vislauization network# to obtain all intermediate representations for the image.successive_feature_maps = visualization_model.predict(x)# Retrieve are the names of the layers, so can have them as part of our plotlayer_names = [layer.name for layer in model.layers]for layer_name, feature_map in zip(layer_names, successive_feature_maps): print(feature_map.shape) if len(feature_map.shape) == 4: # Plot Feature maps for the conv / maxpool layers, not the fully-connected layers n_features = feature_map.shape[-1] # number of features in the feature map size = feature_map.shape[ 1] # feature map shape (1, size, size, n_features) # We will tile our images in this matrix display_grid = np.zeros((size, size * n_features)) # Postprocess the feature to be visually palatable for i in range(n_features): x = feature_map[0, :, :, i] x -= x.mean() x /= x.std () x *= 64 x += 128 x = np.clip(x, 0, 255).astype('uint8') # Tile each filter into a horizontal grid display_grid[:, i * size : (i + 1) * size] = x# Display the grid scale = 20. / n_features plt.figure( figsize=(scale * n_features, scale) ) plt.title ( layer_name ) plt.grid ( False ) plt.imshow( display_grid, aspect='auto', cmap='viridis' )" }, { "code": null, "e": 13363, "s": 13198, "text": "We can see that for the dog image, the snout and the tongue are very prominent features, and for the cat image, the ears and tail are prominent in the feature maps." }, { "code": null, "e": 13383, "s": 13363, "text": "Code available here" }, { "code": null, "e": 13701, "s": 13383, "text": "Visualizing an inside story of how CNN learns to identify different features present in images provides a deeper insight into how the model works. It will also help to understand why the model might be failing to classify some of the images correctly and hence fine-tuning the model for better accuracy and precision." }, { "code": null, "e": 13710, "s": 13701, "text": "keras.io" }, { "code": null, "e": 13719, "s": 13710, "text": "keras.io" }, { "code": null, "e": 13832, "s": 13719, "text": "How Convolutional Neural Networks see the World — A survey of Convolutional Neural Network Visualization Methods" }, { "code": null, "e": 13885, "s": 13832, "text": "Visualizing and Understanding Convolutional Networks" } ]
What is strlen function in C language?
The C library function size_t strlen(const char *str) computes the length of the string str up to, but not including the terminating null character. An array of characters is called a string. Given below is the declaration of an array − char stringname [size]; For example − char a[50]; string of length 50 characters Using single character constant − char a[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’} Using string constants − char a[10] = "Hello":; Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’ This function gives the length of the string, i.e., the number of characters in a string. The syntax of strlen() function is as follows − int strlen (string name) The following program shows the usage of strlen() function. Live Demo #include <string.h> main ( ){ char a[30] = "Hello"; int l; l = strlen (a); printf ("length of the string = %d", l); getch ( ); } When the above program is executed, it produces the following result − length of the string = 5 Note : "\0" not counted as a character. Consider another example. Following is the C program to find the length of a string − Live Demo #include<stdio.h> #include<string.h> int main(){ int str1, str2; //initializing the strings char string1[] = "Welcome To"; char string2[] = {'T','U','T','O','R','I','A','L','\0'}; //calculating the length of the two strings str1 = strlen(string1); str2 = strlen(string2); printf("string1 length is: %d \n", str1); printf("string2 length is: %d \n", str2); } When the above program is executed, it produces the following result − string1 length is: 10 string2 length is: 8
[ { "code": null, "e": 1211, "s": 1062, "text": "The C library function size_t strlen(const char *str) computes the length of the string str up to, but not including the terminating null character." }, { "code": null, "e": 1254, "s": 1211, "text": "An array of characters is called a string." }, { "code": null, "e": 1299, "s": 1254, "text": "Given below is the declaration of an array −" }, { "code": null, "e": 1323, "s": 1299, "text": "char stringname [size];" }, { "code": null, "e": 1380, "s": 1323, "text": "For example − char a[50]; string of length 50 characters" }, { "code": null, "e": 1414, "s": 1380, "text": "Using single character constant −" }, { "code": null, "e": 1460, "s": 1414, "text": "char a[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\\0’}" }, { "code": null, "e": 1485, "s": 1460, "text": "Using string constants −" }, { "code": null, "e": 1508, "s": 1485, "text": "char a[10] = \"Hello\":;" }, { "code": null, "e": 1605, "s": 1508, "text": "Accessing − There is a control string \"%s\" used for accessing the string till it encounters ‘\\0’" }, { "code": null, "e": 1695, "s": 1605, "text": "This function gives the length of the string, i.e., the number of characters in a string." }, { "code": null, "e": 1743, "s": 1695, "text": "The syntax of strlen() function is as follows −" }, { "code": null, "e": 1768, "s": 1743, "text": "int strlen (string name)" }, { "code": null, "e": 1828, "s": 1768, "text": "The following program shows the usage of strlen() function." }, { "code": null, "e": 1839, "s": 1828, "text": " Live Demo" }, { "code": null, "e": 1983, "s": 1839, "text": "#include <string.h>\nmain ( ){\n char a[30] = \"Hello\";\n int l;\n l = strlen (a);\n printf (\"length of the string = %d\", l);\n getch ( );\n}" }, { "code": null, "e": 2054, "s": 1983, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2119, "s": 2054, "text": "length of the string = 5\nNote : \"\\0\" not counted as a character." }, { "code": null, "e": 2145, "s": 2119, "text": "Consider another example." }, { "code": null, "e": 2205, "s": 2145, "text": "Following is the C program to find the length of a string −" }, { "code": null, "e": 2216, "s": 2205, "text": " Live Demo" }, { "code": null, "e": 2601, "s": 2216, "text": "#include<stdio.h>\n#include<string.h>\nint main(){\n int str1, str2;\n //initializing the strings\n char string1[] = \"Welcome To\";\n char string2[] = {'T','U','T','O','R','I','A','L','\\0'};\n //calculating the length of the two strings\n str1 = strlen(string1);\n str2 = strlen(string2);\n printf(\"string1 length is: %d \\n\", str1);\n printf(\"string2 length is: %d \\n\", str2);\n}" }, { "code": null, "e": 2672, "s": 2601, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2715, "s": 2672, "text": "string1 length is: 10\nstring2 length is: 8" } ]
XSLT <apply-template>
<xsl:apply-template> tag signals the XSLT processor to find the appropriate template to apply, based on the type and context of each selected node. Following is the syntax declaration of <xsl:apply-template> element. <xsl:apply-template select = Expression mode = QName > </xsl:apply-template> select Used to process nodes selected by an XPath expression, instead of processing all the children. mode Allows an element as specified by its Qualified Names to be processed multiple times, each time producing a different result. Parent elements xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:foreach, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processinginstruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, output elements Child elements xsl:sort, xsl:with-param This example creates a list of <student> element with its attribute rollno and its child <firstname>, <lastname>, <nickname>, and <marks> by iterating over each student. students.xml <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "students.xsl"?> <class> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> students.xsl <?xml version = "1.0" encoding = "UTF-8"?> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <xsl:template match = "/"> <html> <body> <h2>Students</h2> <xsl:apply-templates select = "class/student" /> </body> </html> </xsl:template> <xsl:template match = "class/student"> <xsl:apply-templates select = "@rollno" /> <xsl:apply-templates select = "firstname" /> <xsl:apply-templates select = "lastname" /> <xsl:apply-templates select = "nickname" /> <xsl:apply-templates select = "marks" /> <br /> </xsl:template> <xsl:template match = "@rollno"> <span style = "font-size = 22px;"> <xsl:value-of select = "." /> </span> <br /> </xsl:template> <xsl:template match = "firstname"> First Name:<span style = "color:blue;"> <xsl:value-of select = "." /> </span> <br /> </xsl:template> <xsl:template match = "lastname"> Last Name:<span style = "color:green;"> <xsl:value-of select = "." /> </span> <br /> </xsl:template> <xsl:template match = "nickname"> Nick Name:<span style = "color:red;"> <xsl:value-of select = "." /> </span> <br /> </xsl:template> <xsl:template match = "marks"> Marks:<span style = "color:gray;"> <xsl:value-of select = "." /> </span> <br /> </xsl:template> </xsl:stylesheet> Print Add Notes Bookmark this page
[ { "code": null, "e": 1907, "s": 1759, "text": "<xsl:apply-template> tag signals the XSLT processor to find the appropriate template to apply, based on the type and context of each selected node." }, { "code": null, "e": 1976, "s": 1907, "text": "Following is the syntax declaration of <xsl:apply-template> element." }, { "code": null, "e": 2064, "s": 1976, "text": "<xsl:apply-template \n select = Expression \n mode = QName > \n</xsl:apply-template> \n" }, { "code": null, "e": 2071, "s": 2064, "text": "select" }, { "code": null, "e": 2166, "s": 2071, "text": "Used to process nodes selected by an XPath expression, instead of processing all the children." }, { "code": null, "e": 2171, "s": 2166, "text": "mode" }, { "code": null, "e": 2297, "s": 2171, "text": "Allows an element as specified by its Qualified Names to be processed multiple times, each time producing a different result." }, { "code": null, "e": 2313, "s": 2297, "text": "Parent elements" }, { "code": null, "e": 2535, "s": 2313, "text": "xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:foreach, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processinginstruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, output elements" }, { "code": null, "e": 2550, "s": 2535, "text": "Child elements" }, { "code": null, "e": 2575, "s": 2550, "text": "xsl:sort, xsl:with-param" }, { "code": null, "e": 2745, "s": 2575, "text": "This example creates a list of <student> element with its attribute rollno and its child <firstname>, <lastname>, <nickname>, and <marks> by iterating over each student." }, { "code": null, "e": 2758, "s": 2745, "text": "students.xml" }, { "code": null, "e": 3381, "s": 2758, "text": "<?xml version = \"1.0\"?> \n<?xml-stylesheet type = \"text/xsl\" href = \"students.xsl\"?> \n<class> \n <student rollno = \"393\"> \n <firstname>Dinkar</firstname> \n <lastname>Kad</lastname> \n <nickname>Dinkar</nickname> \n <marks>85</marks> \n </student> \n <student rollno = \"493\"> \n <firstname>Vaneet</firstname> \n <lastname>Gupta</lastname> \n <nickname>Vinni</nickname> \n <marks>95</marks> \n </student> \n <student rollno = \"593\"> \n <firstname>Jasvir</firstname> \n <lastname>Singh</lastname> \n <nickname>Jazz</nickname> \n <marks>90</marks> \n </student> \n</class>" }, { "code": null, "e": 3394, "s": 3381, "text": "students.xsl" }, { "code": null, "e": 4954, "s": 3394, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?> \n<xsl:stylesheet version = \"1.0\" \n xmlns:xsl = \"http://www.w3.org/1999/XSL/Transform\"> \n <xsl:template match = \"/\"> \n <html> \n <body> \n <h2>Students</h2> \n <xsl:apply-templates select = \"class/student\" /> \n </body> \n </html> \n </xsl:template> \n\n <xsl:template match = \"class/student\"> \n <xsl:apply-templates select = \"@rollno\" /> \n <xsl:apply-templates select = \"firstname\" /> \n <xsl:apply-templates select = \"lastname\" /> \n <xsl:apply-templates select = \"nickname\" /> \n <xsl:apply-templates select = \"marks\" /> \n <br /> \n </xsl:template> \n\n <xsl:template match = \"@rollno\"> \n <span style = \"font-size = 22px;\"> \n <xsl:value-of select = \".\" /> \n </span> \n <br /> \n </xsl:template> \n\n <xsl:template match = \"firstname\"> \n First Name:<span style = \"color:blue;\"> \n <xsl:value-of select = \".\" /> \n </span> \n <br /> \n </xsl:template> \n\n <xsl:template match = \"lastname\"> \n Last Name:<span style = \"color:green;\"> \n <xsl:value-of select = \".\" /> \n </span> \n <br /> \n </xsl:template> \n\n <xsl:template match = \"nickname\"> \n Nick Name:<span style = \"color:red;\"> \n <xsl:value-of select = \".\" /> \n </span> \n <br /> \n </xsl:template> \n\n <xsl:template match = \"marks\"> \n Marks:<span style = \"color:gray;\"> \n <xsl:value-of select = \".\" /> \n </span> \n <br /> \n </xsl:template> \n\t\n</xsl:stylesheet>" }, { "code": null, "e": 4961, "s": 4954, "text": " Print" }, { "code": null, "e": 4972, "s": 4961, "text": " Add Notes" } ]
Program to Find Out the Occurrence of a Digit from a Given Range in Python
Suppose we have been provided with two positive integers n and d where d is a digit within 0 to 9. We have to determine how many times the digit d appears within the integer numbers between 1 and n. So, if the input is like n = 45, d = 5, then the output will be 5. These numbers have the digit 5: [5, 15, 25, 35, 45]. To solve this, we will follow these steps − Define a function solve(). This will take n and d as inputs. Define a function solve(). This will take n and d as inputs. if n < 0, thenreturn 0 if n < 0, then return 0 return 0 k := floor of (n /10) − 1 k := floor of (n /10) − 1 ans := solve(k, d) * 10 + k + 1 ans := solve(k, d) * 10 + k + 1 if d is same as 0, thenans := ans − 1 if d is same as 0, then ans := ans − 1 ans := ans − 1 m := floor of (n / 10) * 10 m := floor of (n / 10) * 10 while m <= n, doans := ans + count of occurrences of string representation of d in string representation of m.m := m + 1 while m <= n, do ans := ans + count of occurrences of string representation of d in string representation of m. ans := ans + count of occurrences of string representation of d in string representation of m. m := m + 1 m := m + 1 return ans return ans From the main function, now call the function − From the main function, now call the function − value := solve(n,d) value := solve(n,d) print(value) print(value) Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, n, d): if n < 0: return 0 k = n // 10 − 1 ans = self.solve(k, d) * 10 + k + 1 if d == 0: ans −= 1 m = n // 10 * 10 while m <= n: ans += str(m).count(str(d)) m += 1 return ans ob = Solution() print(ob.solve(45,5)) 45, 5 5
[ { "code": null, "e": 1261, "s": 1062, "text": "Suppose we have been provided with two positive integers n and d where d is a digit within 0 to 9. We have to determine how many times the digit d appears within the integer numbers between 1 and n." }, { "code": null, "e": 1328, "s": 1261, "text": "So, if the input is like n = 45, d = 5, then the output will be 5." }, { "code": null, "e": 1381, "s": 1328, "text": "These numbers have the digit 5: [5, 15, 25, 35, 45]." }, { "code": null, "e": 1425, "s": 1381, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1486, "s": 1425, "text": "Define a function solve(). This will take n and d as inputs." }, { "code": null, "e": 1547, "s": 1486, "text": "Define a function solve(). This will take n and d as inputs." }, { "code": null, "e": 1570, "s": 1547, "text": "if n < 0, thenreturn 0" }, { "code": null, "e": 1585, "s": 1570, "text": "if n < 0, then" }, { "code": null, "e": 1594, "s": 1585, "text": "return 0" }, { "code": null, "e": 1603, "s": 1594, "text": "return 0" }, { "code": null, "e": 1629, "s": 1603, "text": "k := floor of (n /10) − 1" }, { "code": null, "e": 1655, "s": 1629, "text": "k := floor of (n /10) − 1" }, { "code": null, "e": 1687, "s": 1655, "text": "ans := solve(k, d) * 10 + k + 1" }, { "code": null, "e": 1719, "s": 1687, "text": "ans := solve(k, d) * 10 + k + 1" }, { "code": null, "e": 1757, "s": 1719, "text": "if d is same as 0, thenans := ans − 1" }, { "code": null, "e": 1781, "s": 1757, "text": "if d is same as 0, then" }, { "code": null, "e": 1796, "s": 1781, "text": "ans := ans − 1" }, { "code": null, "e": 1811, "s": 1796, "text": "ans := ans − 1" }, { "code": null, "e": 1839, "s": 1811, "text": "m := floor of (n / 10) * 10" }, { "code": null, "e": 1867, "s": 1839, "text": "m := floor of (n / 10) * 10" }, { "code": null, "e": 1988, "s": 1867, "text": "while m <= n, doans := ans + count of occurrences of string representation of d in string\nrepresentation of m.m := m + 1" }, { "code": null, "e": 2005, "s": 1988, "text": "while m <= n, do" }, { "code": null, "e": 2100, "s": 2005, "text": "ans := ans + count of occurrences of string representation of d in string\nrepresentation of m." }, { "code": null, "e": 2195, "s": 2100, "text": "ans := ans + count of occurrences of string representation of d in string\nrepresentation of m." }, { "code": null, "e": 2206, "s": 2195, "text": "m := m + 1" }, { "code": null, "e": 2217, "s": 2206, "text": "m := m + 1" }, { "code": null, "e": 2228, "s": 2217, "text": "return ans" }, { "code": null, "e": 2239, "s": 2228, "text": "return ans" }, { "code": null, "e": 2287, "s": 2239, "text": "From the main function, now call the function −" }, { "code": null, "e": 2335, "s": 2287, "text": "From the main function, now call the function −" }, { "code": null, "e": 2355, "s": 2335, "text": "value := solve(n,d)" }, { "code": null, "e": 2375, "s": 2355, "text": "value := solve(n,d)" }, { "code": null, "e": 2388, "s": 2375, "text": "print(value)" }, { "code": null, "e": 2401, "s": 2388, "text": "print(value)" }, { "code": null, "e": 2471, "s": 2401, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2482, "s": 2471, "text": " Live Demo" }, { "code": null, "e": 2808, "s": 2482, "text": "class Solution:\n def solve(self, n, d):\n if n < 0:\n return 0\n k = n // 10 − 1\n ans = self.solve(k, d) * 10 + k + 1\n if d == 0:\n ans −= 1\n m = n // 10 * 10\n while m <= n:\n ans += str(m).count(str(d))\n m += 1\n return ans\nob = Solution()\nprint(ob.solve(45,5))" }, { "code": null, "e": 2814, "s": 2808, "text": "45, 5" }, { "code": null, "e": 2816, "s": 2814, "text": "5" } ]
Retrieve the last element from a LinkedList in Java
The last element of a Linked List can be retrieved using the method java.util.LinkedList.getLast() respectively. This method does not require any parameters and it returns the last element of the LinkedList. A program that demonstrates this is given as follows − Live Demo import java.util.LinkedList; public class Demo { public static void main(String[] args) { LinkedList<String> l = new LinkedList<String>(); l.add("Andy"); l.add("Sara"); l.add("James"); l.add("Betty"); l.add("Bruce"); System.out.println("The last element of the Linked List is : " + l.getLast()); } } The last element of the Linked List is : Bruce Now let us understand the above program. The LinkedList l is created. LinkedList.add() is used to add the elements to the LinkedList. Then LinkedList.getLast() is used to retrieve the last element of the linked list. A code snippet which demonstrates this is as follows − LinkedList<String> l = new LinkedList<String>(); l.add("Andy"); l.add("Sara"); l.add("James"); l.add("Betty"); l.add("Bruce"); System.out.println("The last element of the Linked List is : " + l.getLast());
[ { "code": null, "e": 1270, "s": 1062, "text": "The last element of a Linked List can be retrieved using the method java.util.LinkedList.getLast() respectively. This method does not require any parameters and it returns the last element of the LinkedList." }, { "code": null, "e": 1325, "s": 1270, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1336, "s": 1325, "text": " Live Demo" }, { "code": null, "e": 1684, "s": 1336, "text": "import java.util.LinkedList;\npublic class Demo {\n public static void main(String[] args) {\n LinkedList<String> l = new LinkedList<String>();\n l.add(\"Andy\");\n l.add(\"Sara\");\n l.add(\"James\");\n l.add(\"Betty\");\n l.add(\"Bruce\");\n System.out.println(\"The last element of the Linked List is : \" + l.getLast());\n }\n}" }, { "code": null, "e": 1731, "s": 1684, "text": "The last element of the Linked List is : Bruce" }, { "code": null, "e": 1772, "s": 1731, "text": "Now let us understand the above program." }, { "code": null, "e": 2003, "s": 1772, "text": "The LinkedList l is created. LinkedList.add() is used to add the elements to the LinkedList. Then LinkedList.getLast() is used to retrieve the last element of the linked list. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2209, "s": 2003, "text": "LinkedList<String> l = new LinkedList<String>();\nl.add(\"Andy\");\nl.add(\"Sara\");\nl.add(\"James\");\nl.add(\"Betty\");\nl.add(\"Bruce\");\nSystem.out.println(\"The last element of the Linked List is : \" + l.getLast());" } ]
Java Program for Longest Increasing Subsequence
Following is the Java program for longest increasing subsequence − Live Demo public class Demo{ static int incre_subseq(int my_arr[], int arr_len){ int seq_arr[] = new int[arr_len]; int i, j, max = 0; for (i = 0; i < arr_len; i++) seq_arr[i] = 1; for (i = 1; i < arr_len; i++) for (j = 0; j < i; j++) if (my_arr[i] > my_arr[j] && seq_arr[i] < seq_arr[j] + 1) seq_arr[i] = seq_arr[j] + 1; for (i = 0; i < arr_len; i++) if (max < seq_arr[i]) max = seq_arr[i]; return max; } public static void main(String args[]){ int my_arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; int arr_len = my_arr.length; System.out.println("The length of the longest increasing subsequence is " + incre_subseq(my_arr, arr_len)); } } The length of the longest increasing subsequence is 5 A class named Demo contains a static function named 'incre_subseq’ that takes the array and the length of the array as parameters. Inside this function, a new array is created that is empty. A 'max' variable is assigned the value 0. A 'for' loop iterates over the length of the array and every element is initialized to 1. Again, 'for' loop is iterated, and another 'for' loop is initiated that checks if first element in the array is equal to the second element and if the array (seq_arr, that had all 1s initialized) has first element lesser than the second element + 1. The maximum of the elements in the seq_arr is found and returned. This is dynamic programming technique wherein one value is computed and stored in an array, removing the need to compute it again and again as in recursion. Whenever a previously computed element is required, it is fetched from the array.
[ { "code": null, "e": 1129, "s": 1062, "text": "Following is the Java program for longest increasing subsequence −" }, { "code": null, "e": 1140, "s": 1129, "text": " Live Demo" }, { "code": null, "e": 1872, "s": 1140, "text": "public class Demo{\n static int incre_subseq(int my_arr[], int arr_len){\n int seq_arr[] = new int[arr_len];\n int i, j, max = 0;\n for (i = 0; i < arr_len; i++)\n seq_arr[i] = 1;\n for (i = 1; i < arr_len; i++)\n for (j = 0; j < i; j++)\n if (my_arr[i] > my_arr[j] && seq_arr[i] < seq_arr[j] + 1)\n seq_arr[i] = seq_arr[j] + 1;\n for (i = 0; i < arr_len; i++)\n if (max < seq_arr[i])\n max = seq_arr[i];\n return max;\n }\n public static void main(String args[]){\n int my_arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };\n int arr_len = my_arr.length;\n System.out.println(\"The length of the longest increasing subsequence is \" + incre_subseq(my_arr, arr_len));\n }\n}" }, { "code": null, "e": 1926, "s": 1872, "text": "The length of the longest increasing subsequence is 5" }, { "code": null, "e": 2249, "s": 1926, "text": "A class named Demo contains a static function named 'incre_subseq’ that takes the array and the length of the array as parameters. Inside this function, a new array is created that is empty. A 'max' variable is assigned the value 0. A 'for' loop iterates over the length of the array and every element is initialized to 1." }, { "code": null, "e": 2804, "s": 2249, "text": "Again, 'for' loop is iterated, and another 'for' loop is initiated that checks if first element in the array is equal to the second element and if the array (seq_arr, that had all 1s initialized) has first element lesser than the second element + 1. The maximum of the elements in the seq_arr is found and returned. This is dynamic programming technique wherein one value is computed and stored in an array, removing the need to compute it again and again as in recursion. Whenever a previously computed element is required, it is fetched from the array." } ]
How to apply antialiasing in HTML5 canvas drawImage()?
For antialiasing, you need to set resampling quality. ctx.imageSmoothingQuality = "low|medium|high" Use an off-screen canvas to reduce the image to half − var c = document.createElement('canvas'), ocx = c.getContext('2d'); c.width = img.width * 0.5; c.height = img.height * 0.5; ocxx.drawImage(img, 0, 0, c.width, c.height); // drawing images reducing to half again and repeating it ocx.drawImage(c, 0, 0, c.width * 0.5, cc.height * 0.5);
[ { "code": null, "e": 1116, "s": 1062, "text": "For antialiasing, you need to set resampling quality." }, { "code": null, "e": 1162, "s": 1116, "text": "ctx.imageSmoothingQuality = \"low|medium|high\"" }, { "code": null, "e": 1217, "s": 1162, "text": "Use an off-screen canvas to reduce the image to half −" }, { "code": null, "e": 1388, "s": 1217, "text": "var c = document.createElement('canvas'),\nocx = c.getContext('2d');\nc.width = img.width * 0.5;\nc.height = img.height * 0.5;\n\nocxx.drawImage(img, 0, 0, c.width, c.height);" }, { "code": null, "e": 1446, "s": 1388, "text": "// drawing images reducing to half again and repeating it" }, { "code": null, "e": 1502, "s": 1446, "text": "ocx.drawImage(c, 0, 0, c.width * 0.5, cc.height * 0.5);" } ]
C/C++ Program to Count trailing zeroes in factorial of a number?
Here we will see how to calculate the number of trailing 0s for the result of factorial of any number. So if the n = 5, then 5! = 120. There is only one trailing 0. For 20!, it will be 4 zeros as 20! = 2432902008176640000. The easiest approach is just calculating the factorial and count the 0s. But this approach fails for large value of n. So we will follow another approach. The trailing zeros will be there, if the prime factors are 2 and 5. If we count the 2s and 5s we can get the result. For that we will follow this rule. Trailing 0s = Count of 5s in prime factors of factorial(n) begin count := 0 for i := 5, (n/i) >= 1, increase i := i * 5, do count := count + (n / i) done return count; end #include <iostream> #include <cmath> #define MAX 20 using namespace std; int countTrailingZeros(int n) { int count = 0; for (int i = 5; n / i >= 1; i *= 5) count += n / i; return count; } main() { int n = 20; cout << "Number of trailing zeros: " << countTrailingZeros(n); } Number of trailing zeros: 4
[ { "code": null, "e": 1285, "s": 1062, "text": "Here we will see how to calculate the number of trailing 0s for the result of factorial of any number. So if the n = 5, then 5! = 120. There is only one trailing 0. For 20!, it will be 4 zeros as 20! = 2432902008176640000." }, { "code": null, "e": 1592, "s": 1285, "text": "The easiest approach is just calculating the factorial and count the 0s. But this approach fails for large value of n. So we will follow another approach. The trailing zeros will be there, if the prime factors are 2 and 5. If we count the 2s and 5s we can get the result. For that we will follow this rule." }, { "code": null, "e": 1651, "s": 1592, "text": "Trailing 0s = Count of 5s in prime factors of factorial(n)" }, { "code": null, "e": 1782, "s": 1651, "text": "begin\n count := 0\n for i := 5, (n/i) >= 1, increase i := i * 5, do\n count := count + (n / i)\n done\n return count;\nend" }, { "code": null, "e": 2077, "s": 1782, "text": "#include <iostream>\n#include <cmath>\n#define MAX 20\nusing namespace std;\nint countTrailingZeros(int n) {\n int count = 0;\n for (int i = 5; n / i >= 1; i *= 5)\n count += n / i;\n return count;\n}\nmain() {\n int n = 20;\n cout << \"Number of trailing zeros: \" << countTrailingZeros(n);\n}" }, { "code": null, "e": 2105, "s": 2077, "text": "Number of trailing zeros: 4" } ]
How Can Chipotle Regain Customers? | by cqye | Towards Data Science
This is the final project of our team (Crystal Huang, Jack Ye, Hao Hao, Yuting Li) in Machine Learning class of UC Davis MSBA program. The step-by-step guidance of python coding has been shared at Github: https://github.com/Cryyyystal/Analysis-of-Yelp-Review-for-Chipotle-Mexican-Grill Chipotle has been losing customers and isn’t performing well in the competitive fast-casual dining industry these years. It tried many methods to improve customer experience and regain customers such as establishing new safety protocols and introducing digital ordering channels such as online and mobile app ordering. As Chipotle embraces increasingly modern strategies, we recommend a data-driven approach to help it improve business. In this project, we use several natural language processing tools to analyze its reviews on Yelp to discover areas of improvement and propose suggestions accordingly. Main components of the Chipotle project: Apply Textblob to calculate the sentiment polarity of each review. Draw word clouds for positive and negative reviews respectively to see what words appear frequently in positive or negative reviews. Use the LDA Mallet to do topic modeling to extract six topics from all reviews, and calculate the average sentiment scores for each topic. Draw a radar graph to show which topics are Chipotle’s advantages and which are its disadvantages. Do time series analysis of word sentiment, through which we see the monthly change of occurrence frequency of important words such as “line” and “burrito” in the positive or negative reviews. Based on this, we can detect the pain points of Chipotle’s key business. Based on our analysis, we provide Chipotle with four suggestions in the areas of ingredient quality, wait times and digital ordering. The first one is to improve the freshness and quality of its ingredients to regain its strategic strength. The second one is to investigate the supply chain to see how to improve the quality and taste of its proteins, especially chicken. The third one is to investigate the current quality of its most important product, burrito, which has gone fewer and fewer positive reviews. At last, Chipotle should improve the online ordering system and mobile app, in order to better solve the wait time problem and improve customers’ buying experience. Yelp provides a comprehensive dataset in Yelp Challenge Dataset that includes all the merchants information such as addresses, tips, reviews, and reviewers. We merge the “business” table and the “review” table, and extract Chipotle’s information. There are 9590 reviews of Chipotle in total. The dataset link: https://www.yelp.com/dataset/challenge We calculate Chipotle’s monthly average star rating of reviews since 2006, and find that it gradually declines over time: back in 2010, the average review star was about 4.0, but now it is about 3.0 (Graph 1) Graph 2 shows how the number and proportion of different stars change over time. As the time passes, 5-star and 1-star reviews increase in both number and proportion, with 1-star reviews increasing more significantly. This might be the main reason why the average star rating gradually declines in Graph 1. After the EDA, we have done several text preprocessing to improve the performance of NLP models, including: Text Decontraction. For instance, replace “won\’t” with “will not”, replace “\’ve” with “ have”, and replace “\’d” with “ would”. Making Everything Lower-case. Removing Stop Words using NLTK library. Stop words are the very common words like ‘if’, ‘but’, ‘we’, ‘he’, ‘she’, and ‘they’. We can usually remove these words without changing the semantics of a text. Removing White Spaces and Punctuations. After the above processing, there might be some white spaces mixed with words, so we need to remove the white spaces. Plus, we also remove punctuations such as “,.?!:” and just keep words. Word Lemmatization using NLTK stem. Lemmatization is the process of grouping together the different inflected forms of a word so they can be analyzed as a single item. For instance, after Lemmatization, “cries” would be “cry”. The comparison of a review between before text preprocessing and after text preprocessing is as follows: Before "I'm a regular at chipotle in California, this is my first visit to this chipotle on s.las Vegas strip.this is pretty new place I think, I took a veggie bowl in which the rice was undone and the fajitas were all burnt, the quantity offered was less than usual. I'm very unhappy with this place." After 'regular chipotle california first visit chipotle s la vega strip this pretty new place think took veggie bowl rice undone fajitas burnt quantity offered le usual unhappy place' We use Textblob to assign each review a sentiment score to measure how positive or how negative the review is. If the sentiment score is greater than 0, the review is positive, and on the contrary, the review is negative. From Graph 3, we can see that positive reviews are twice as many as negative reviews. Graph 4 is drawn to see the relationship between reviews stars and sentiment scores. Obviously, as the stars increase, the average sentiment score also increases. However, for 1-star reviews, they might be either positive or negative, but for 4-star and 5-star reviews, they are basically positive. We first use word cloud to see the big picture of the reviews. We draw one word cloud for positive reviews and negative reviews respectively to see the difference. We remove the words that appear very frequently in both positive and negative reviews, including “chipotle”, “burrito”, and “place”, because they are very large in both graphs. We can see that the largest words in positive reviews are “meat”, “staff”, and “service”, while the largest words in negative reviews are “line” and “chicken”. Customers like the meat at Chipotle, but it seems that it is not the case for chicken. Even though the line in Chipotle may be a little long and customers have to wait for a little while, they are satisfied with Chipotle’s staff and service. With the big picture of the reviews in mind, we use topic modeling, specifically Latent Dirichlet Allocation via Mallet (LdaMallet), to extract key topics from all the words. Then, we measure the sentiment score of each topic to see in which aspects Chipotle does well and in which it does poorly. We draw a hexagon and add 0.1 for each score to make the comparison clearer. We can see from Graph 7 that the ingredient-related topic (fresh/ingredient/quality) gets the highest score, echoing Chipotle’s values of “freshness” and “integrity”. The environment-related topic (location/clean/nice/friendly) gets the second highest. Line-related topic (time/line/wait/long/online), food-related topic (meat/chicken/chip/rice/guacamole/steak/lettuce), service-related topic (service/employee/bad), and payment-related topic (pay/manager/cashier) get the lower scores. We assign each review to the topic that takes the greatest proportion of that review and calculate the average sentiment score for all the six topics over time. To see the trends of 4 lower-score topics more clearly, we draw the graphs that compare each one of them with ingredient-related topic (fresh/ingredient/quality). We found that the average sentiment score of line-related topic (time/line/wait/long/online) floats around 0.1 before 2013, significantly declines in 2013, and then floats around 0 (Graph 8). With a time-series approach, we visualize the change of sentiments of Words of Interest (WOI) together with the change of star rating on a monthly basis. We first define the metrics with which we measure the words’ sentiments: Like word cloud, we determine the sentiments of WOI based on its occurrence frequency in the positive/negative reviews. We normalize the occurrence because the total number of reviews varies from month to month. Thus, the metric measures the normalized frequency of WOI in reviews of either sentiment category. As shown in Appendix 1.1, both positive reviews and negative reviews gradually increase overtime. We also decide to only analyze reviews after 2012, because there were too few reviews before 2012 (Appendix 1.1). We use three approaches to interpret our visualizations of the metrics. 1. Decrease of Occurrence Ratio of WOI in Positive Reviews If a word used to have a high positive ratio, we can say it served as the strength of the business. The decrease of positive ratio indicates the restaurant is losing edge in this aspect. Based on Graph 9, Chipotle should investigate the freshness of its menu items and the quality of its burrito products. 2. Increase of Occurrence Ratio of WOI in Negative Reviews A WOI that has a higher occurrence ratio in negative reviews indicates Chipotle may underperform in this aspect. It can be seen from Graph 10 that the occurrence ratio of “line” increases from 2012 and decreases from 2015 onward. The decrease reflects Chipotle’s launch of its mobile ordering app in 2014, which aims to reduce line. Therefore, we may infer that Chipotle’s strategy in alleviating customers’ wait times through digital ordering was a success. Moving forward, Chipotle should pursue this initiative. 3. Comparison of Occurrence Ratios of WOI in Both Reviews If a WOI has a higher occurrence ratio in positive reviews than in negative reviews, it is a positive sentiment. We visualize “great” as the baseline (Appendix 1.2). Consequently, when a neutral WOI has a higher occurrence ratio in positive reviews than in negative reviews, it can be regarded as a positive aspect of the business. Vice versa. Graph 11 shows that both “online” and “app” are neutral words but have consistently higher occurrence ratios in negative reviews than in positive reviews. This indicates that Chipotle is underperforming in the digital commerce channel. It needs to improve its mobile ordering app and online ordering system to enhance customer buying experience. Based on our analysis findings, we make recommendations to Chipotle in the areas of ingredient quality, wait times and digital ordering. From topic modeling, we find that the ingredient-related topic (fresh/ingredient/quality) has the highest sentiment score, which aligns with Chipotle’s strategic advantage of providing fresh food with integrity. However, by visualizing the sentiment of the key word “fresh” over time, we discover that “fresh” is slowly disappearing in the positive reviews. This indicates that, from the perspective of consumers, Chipotle is losing its edge in sourcing fresh ingredients. Thus, Chipotle should investigate the freshness and quality of its ingredients for improvement to regain its strategic strength. On another note, we recommend Chipotle investigate its supply chain to see how to improve the quality and taste of its proteins, especially chicken, which appears very frequently in negative reviews according to the word cloud. In terms of its menu items, Chipotle also needs to investigate the current quality of its most important product, burrito, which is seen less and less in positive reviews. Some market research can also be done on burrito to see why burrito is losing its appeal to customers. On the other hand, wait times and lines are clearly a problem at Chipotle. Both topic modeling and word cloud show that “line” is a big contributor to customers’ negative sentiment towards Chipotle. To address this, Chipotle has sought digital channels such as online ordering and mobile app ordering. The wait time issue was ameliorated by the introduction of mobile app ordering in 2014, as shown in the sentiment analysis. However, this is not enough. We find that both “online” and “app” have a more negative note in the customers’ reviews, indicating dissatisfaction with Chipotle’s digital ordering experience. In this light, Chipotle needs to improve its online ordering system and mobile app, in order to better solve the wait time problem and improve customers’ buying experience.
[ { "code": null, "e": 458, "s": 172, "text": "This is the final project of our team (Crystal Huang, Jack Ye, Hao Hao, Yuting Li) in Machine Learning class of UC Davis MSBA program. The step-by-step guidance of python coding has been shared at Github: https://github.com/Cryyyystal/Analysis-of-Yelp-Review-for-Chipotle-Mexican-Grill" }, { "code": null, "e": 1062, "s": 458, "text": "Chipotle has been losing customers and isn’t performing well in the competitive fast-casual dining industry these years. It tried many methods to improve customer experience and regain customers such as establishing new safety protocols and introducing digital ordering channels such as online and mobile app ordering. As Chipotle embraces increasingly modern strategies, we recommend a data-driven approach to help it improve business. In this project, we use several natural language processing tools to analyze its reviews on Yelp to discover areas of improvement and propose suggestions accordingly." }, { "code": null, "e": 1103, "s": 1062, "text": "Main components of the Chipotle project:" }, { "code": null, "e": 1170, "s": 1103, "text": "Apply Textblob to calculate the sentiment polarity of each review." }, { "code": null, "e": 1303, "s": 1170, "text": "Draw word clouds for positive and negative reviews respectively to see what words appear frequently in positive or negative reviews." }, { "code": null, "e": 1541, "s": 1303, "text": "Use the LDA Mallet to do topic modeling to extract six topics from all reviews, and calculate the average sentiment scores for each topic. Draw a radar graph to show which topics are Chipotle’s advantages and which are its disadvantages." }, { "code": null, "e": 1806, "s": 1541, "text": "Do time series analysis of word sentiment, through which we see the monthly change of occurrence frequency of important words such as “line” and “burrito” in the positive or negative reviews. Based on this, we can detect the pain points of Chipotle’s key business." }, { "code": null, "e": 2484, "s": 1806, "text": "Based on our analysis, we provide Chipotle with four suggestions in the areas of ingredient quality, wait times and digital ordering. The first one is to improve the freshness and quality of its ingredients to regain its strategic strength. The second one is to investigate the supply chain to see how to improve the quality and taste of its proteins, especially chicken. The third one is to investigate the current quality of its most important product, burrito, which has gone fewer and fewer positive reviews. At last, Chipotle should improve the online ordering system and mobile app, in order to better solve the wait time problem and improve customers’ buying experience." }, { "code": null, "e": 2776, "s": 2484, "text": "Yelp provides a comprehensive dataset in Yelp Challenge Dataset that includes all the merchants information such as addresses, tips, reviews, and reviewers. We merge the “business” table and the “review” table, and extract Chipotle’s information. There are 9590 reviews of Chipotle in total." }, { "code": null, "e": 2833, "s": 2776, "text": "The dataset link: https://www.yelp.com/dataset/challenge" }, { "code": null, "e": 3042, "s": 2833, "text": "We calculate Chipotle’s monthly average star rating of reviews since 2006, and find that it gradually declines over time: back in 2010, the average review star was about 4.0, but now it is about 3.0 (Graph 1)" }, { "code": null, "e": 3349, "s": 3042, "text": "Graph 2 shows how the number and proportion of different stars change over time. As the time passes, 5-star and 1-star reviews increase in both number and proportion, with 1-star reviews increasing more significantly. This might be the main reason why the average star rating gradually declines in Graph 1." }, { "code": null, "e": 3457, "s": 3349, "text": "After the EDA, we have done several text preprocessing to improve the performance of NLP models, including:" }, { "code": null, "e": 3587, "s": 3457, "text": "Text Decontraction. For instance, replace “won\\’t” with “will not”, replace “\\’ve” with “ have”, and replace “\\’d” with “ would”." }, { "code": null, "e": 3617, "s": 3587, "text": "Making Everything Lower-case." }, { "code": null, "e": 3819, "s": 3617, "text": "Removing Stop Words using NLTK library. Stop words are the very common words like ‘if’, ‘but’, ‘we’, ‘he’, ‘she’, and ‘they’. We can usually remove these words without changing the semantics of a text." }, { "code": null, "e": 4048, "s": 3819, "text": "Removing White Spaces and Punctuations. After the above processing, there might be some white spaces mixed with words, so we need to remove the white spaces. Plus, we also remove punctuations such as “,.?!:” and just keep words." }, { "code": null, "e": 4275, "s": 4048, "text": "Word Lemmatization using NLTK stem. Lemmatization is the process of grouping together the different inflected forms of a word so they can be analyzed as a single item. For instance, after Lemmatization, “cries” would be “cry”." }, { "code": null, "e": 4380, "s": 4275, "text": "The comparison of a review between before text preprocessing and after text preprocessing is as follows:" }, { "code": null, "e": 4387, "s": 4380, "text": "Before" }, { "code": null, "e": 4683, "s": 4387, "text": "\"I'm a regular at chipotle in California, this is my first visit to this chipotle on s.las Vegas strip.this is pretty new place I think, I took a veggie bowl in which the rice was undone and the fajitas were all burnt, the quantity offered was less than usual. I'm very unhappy with this place.\"" }, { "code": null, "e": 4689, "s": 4683, "text": "After" }, { "code": null, "e": 4867, "s": 4689, "text": "'regular chipotle california first visit chipotle s la vega strip this pretty new place think took veggie bowl rice undone fajitas burnt quantity offered le usual unhappy place'" }, { "code": null, "e": 5175, "s": 4867, "text": "We use Textblob to assign each review a sentiment score to measure how positive or how negative the review is. If the sentiment score is greater than 0, the review is positive, and on the contrary, the review is negative. From Graph 3, we can see that positive reviews are twice as many as negative reviews." }, { "code": null, "e": 5474, "s": 5175, "text": "Graph 4 is drawn to see the relationship between reviews stars and sentiment scores. Obviously, as the stars increase, the average sentiment score also increases. However, for 1-star reviews, they might be either positive or negative, but for 4-star and 5-star reviews, they are basically positive." }, { "code": null, "e": 6217, "s": 5474, "text": "We first use word cloud to see the big picture of the reviews. We draw one word cloud for positive reviews and negative reviews respectively to see the difference. We remove the words that appear very frequently in both positive and negative reviews, including “chipotle”, “burrito”, and “place”, because they are very large in both graphs. We can see that the largest words in positive reviews are “meat”, “staff”, and “service”, while the largest words in negative reviews are “line” and “chicken”. Customers like the meat at Chipotle, but it seems that it is not the case for chicken. Even though the line in Chipotle may be a little long and customers have to wait for a little while, they are satisfied with Chipotle’s staff and service." }, { "code": null, "e": 6515, "s": 6217, "text": "With the big picture of the reviews in mind, we use topic modeling, specifically Latent Dirichlet Allocation via Mallet (LdaMallet), to extract key topics from all the words. Then, we measure the sentiment score of each topic to see in which aspects Chipotle does well and in which it does poorly." }, { "code": null, "e": 7079, "s": 6515, "text": "We draw a hexagon and add 0.1 for each score to make the comparison clearer. We can see from Graph 7 that the ingredient-related topic (fresh/ingredient/quality) gets the highest score, echoing Chipotle’s values of “freshness” and “integrity”. The environment-related topic (location/clean/nice/friendly) gets the second highest. Line-related topic (time/line/wait/long/online), food-related topic (meat/chicken/chip/rice/guacamole/steak/lettuce), service-related topic (service/employee/bad), and payment-related topic (pay/manager/cashier) get the lower scores." }, { "code": null, "e": 7595, "s": 7079, "text": "We assign each review to the topic that takes the greatest proportion of that review and calculate the average sentiment score for all the six topics over time. To see the trends of 4 lower-score topics more clearly, we draw the graphs that compare each one of them with ingredient-related topic (fresh/ingredient/quality). We found that the average sentiment score of line-related topic (time/line/wait/long/online) floats around 0.1 before 2013, significantly declines in 2013, and then floats around 0 (Graph 8)." }, { "code": null, "e": 7822, "s": 7595, "text": "With a time-series approach, we visualize the change of sentiments of Words of Interest (WOI) together with the change of star rating on a monthly basis. We first define the metrics with which we measure the words’ sentiments:" }, { "code": null, "e": 8417, "s": 7822, "text": "Like word cloud, we determine the sentiments of WOI based on its occurrence frequency in the positive/negative reviews. We normalize the occurrence because the total number of reviews varies from month to month. Thus, the metric measures the normalized frequency of WOI in reviews of either sentiment category. As shown in Appendix 1.1, both positive reviews and negative reviews gradually increase overtime. We also decide to only analyze reviews after 2012, because there were too few reviews before 2012 (Appendix 1.1). We use three approaches to interpret our visualizations of the metrics." }, { "code": null, "e": 8476, "s": 8417, "text": "1. Decrease of Occurrence Ratio of WOI in Positive Reviews" }, { "code": null, "e": 8782, "s": 8476, "text": "If a word used to have a high positive ratio, we can say it served as the strength of the business. The decrease of positive ratio indicates the restaurant is losing edge in this aspect. Based on Graph 9, Chipotle should investigate the freshness of its menu items and the quality of its burrito products." }, { "code": null, "e": 8841, "s": 8782, "text": "2. Increase of Occurrence Ratio of WOI in Negative Reviews" }, { "code": null, "e": 9356, "s": 8841, "text": "A WOI that has a higher occurrence ratio in negative reviews indicates Chipotle may underperform in this aspect. It can be seen from Graph 10 that the occurrence ratio of “line” increases from 2012 and decreases from 2015 onward. The decrease reflects Chipotle’s launch of its mobile ordering app in 2014, which aims to reduce line. Therefore, we may infer that Chipotle’s strategy in alleviating customers’ wait times through digital ordering was a success. Moving forward, Chipotle should pursue this initiative." }, { "code": null, "e": 9414, "s": 9356, "text": "3. Comparison of Occurrence Ratios of WOI in Both Reviews" }, { "code": null, "e": 10104, "s": 9414, "text": "If a WOI has a higher occurrence ratio in positive reviews than in negative reviews, it is a positive sentiment. We visualize “great” as the baseline (Appendix 1.2). Consequently, when a neutral WOI has a higher occurrence ratio in positive reviews than in negative reviews, it can be regarded as a positive aspect of the business. Vice versa. Graph 11 shows that both “online” and “app” are neutral words but have consistently higher occurrence ratios in negative reviews than in positive reviews. This indicates that Chipotle is underperforming in the digital commerce channel. It needs to improve its mobile ordering app and online ordering system to enhance customer buying experience." }, { "code": null, "e": 10241, "s": 10104, "text": "Based on our analysis findings, we make recommendations to Chipotle in the areas of ingredient quality, wait times and digital ordering." }, { "code": null, "e": 11346, "s": 10241, "text": "From topic modeling, we find that the ingredient-related topic (fresh/ingredient/quality) has the highest sentiment score, which aligns with Chipotle’s strategic advantage of providing fresh food with integrity. However, by visualizing the sentiment of the key word “fresh” over time, we discover that “fresh” is slowly disappearing in the positive reviews. This indicates that, from the perspective of consumers, Chipotle is losing its edge in sourcing fresh ingredients. Thus, Chipotle should investigate the freshness and quality of its ingredients for improvement to regain its strategic strength. On another note, we recommend Chipotle investigate its supply chain to see how to improve the quality and taste of its proteins, especially chicken, which appears very frequently in negative reviews according to the word cloud. In terms of its menu items, Chipotle also needs to investigate the current quality of its most important product, burrito, which is seen less and less in positive reviews. Some market research can also be done on burrito to see why burrito is losing its appeal to customers." } ]
Linking Files having same variables with different data types in C - GeeksforGeeks
23 May, 2018 Suppose there are two codes foo1.c and foo2.c as below and here the task is to link foo1.c and foo2.c which have same variable name x but different data type i.e int in foo1.c and double in foo2.c.Note that none of the variables is declared as extern. What do you expect to be the output of the following command with given two programs? $ gcc -o myprog foo1.c foo2.c $ ./myprog // foo1.c#include<stdio.h>void f(void);int x = 38;int y = 39; int main() { f(); printf("x = % d\n", x); printf("y = % d\n", y); return 0;} // foo2.cdouble x;void f() { x = 42.0;} Output: x = 0 y = 1078263808 Explanation of Output: Output of the program looks unpredictable but reason is: In foo1.c, there are two variables x and y each having 4 bytes(total 8 bytes). In foo2.c there is x variable as double.While execution, x in foo1 (4 bytes) is replaced by x in foo2 (8 bytes). Ultimately memory of x and y (total 8 bytes) in foo1 is overwritten by x in foo2 (8 bytes). 1078263808 value is floating point representation of 42 in double. NOTE : x and y addresses in foo1.c are successive. Related Article : External and Internal Linkages in C C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Ways to copy a vector in C++ Smart Pointers in C++ and How to Use Them Understanding "extern" keyword in C Multiple Inheritance in C++ How to split a string in C/C++, Python and Java?
[ { "code": null, "e": 25453, "s": 25425, "text": "\n23 May, 2018" }, { "code": null, "e": 25705, "s": 25453, "text": "Suppose there are two codes foo1.c and foo2.c as below and here the task is to link foo1.c and foo2.c which have same variable name x but different data type i.e int in foo1.c and double in foo2.c.Note that none of the variables is declared as extern." }, { "code": null, "e": 25791, "s": 25705, "text": "What do you expect to be the output of the following command with given two programs?" }, { "code": null, "e": 25833, "s": 25791, "text": "$ gcc -o myprog foo1.c foo2.c\n$ ./myprog\n" }, { "code": "// foo1.c#include<stdio.h>void f(void);int x = 38;int y = 39; int main() { f(); printf(\"x = % d\\n\", x); printf(\"y = % d\\n\", y); return 0;}", "e": 25985, "s": 25833, "text": null }, { "code": "// foo2.cdouble x;void f() { x = 42.0;}", "e": 26028, "s": 25985, "text": null }, { "code": null, "e": 26036, "s": 26028, "text": "Output:" }, { "code": null, "e": 26058, "s": 26036, "text": "x = 0\ny = 1078263808\n" }, { "code": null, "e": 26422, "s": 26058, "text": "Explanation of Output: Output of the program looks unpredictable but reason is: In foo1.c, there are two variables x and y each having 4 bytes(total 8 bytes). In foo2.c there is x variable as double.While execution, x in foo1 (4 bytes) is replaced by x in foo2 (8 bytes). Ultimately memory of x and y (total 8 bytes) in foo1 is overwritten by x in foo2 (8 bytes)." }, { "code": null, "e": 26489, "s": 26422, "text": "1078263808 value is floating point representation of 42 in double." }, { "code": null, "e": 26540, "s": 26489, "text": "NOTE : x and y addresses in foo1.c are successive." }, { "code": null, "e": 26594, "s": 26540, "text": "Related Article : External and Internal Linkages in C" }, { "code": null, "e": 26605, "s": 26594, "text": "C Language" }, { "code": null, "e": 26703, "s": 26605, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26741, "s": 26703, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26767, "s": 26741, "text": "Exception Handling in C++" }, { "code": null, "e": 26787, "s": 26767, "text": "Multithreading in C" }, { "code": null, "e": 26809, "s": 26787, "text": "'this' pointer in C++" }, { "code": null, "e": 26850, "s": 26809, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26879, "s": 26850, "text": "Ways to copy a vector in C++" }, { "code": null, "e": 26921, "s": 26879, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 26957, "s": 26921, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 26985, "s": 26957, "text": "Multiple Inheritance in C++" } ]
Python | Convert list of tuples to list of strings - GeeksforGeeks
26 Feb, 2019 The interconversion between datatypes is quite useful utility and many articles have been written to perform the same. This article discusses the interconversion between a tuple of characters to individual strings. This kind of interconversion is useful in Machine Learning in which we need to give the input to train model in a specific format. Let’s discuss certain ways in which this can be done. Method #1 : Using list comprehension + join()The list comprehension performs the task of iterating the entire list of tuples and join function performs the task of aggregating the elements of tuple into a one list. # Python3 code to demonstrate# conversion of list of tuple to list of list # using list comprehension + join() # initializing list test_list = [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'), ('G', 'E', 'E', 'K', 'S')] # printing the original listprint ("The original list is : " + str(test_list)) # using list comprehension + join()# conversion of list of tuple to list of list res = [''.join(i) for i in test_list] # printing resultprint ("The list after conversion to list of string : " + str(res)) Output : The original list is : [(‘G’, ‘E’, ‘E’, ‘K’, ‘S’), (‘F’, ‘O’, ‘R’), (‘G’, ‘E’, ‘E’, ‘K’, ‘S’)]The list after conversion to list of string : [‘GEEKS’, ‘FOR’, ‘GEEKS’] Method #2 : Using map() + join()The task performed by the list comprehension can be performed by the map function which can perform extension of logic of one tuple to all tuple in list. # Python3 code to demonstrate# conversion of list of tuple to list of list # using map() + join() # initializing list test_list = [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'), ('G', 'E', 'E', 'K', 'S')] # printing the original listprint ("The original list is : " + str(test_list)) # using map() + join()# conversion of list of tuple to list of list res = list(map(''.join, test_list)) # printing resultprint ("The list after conversion to list of string : " + str(res)) Output : The original list is : [(‘G’, ‘E’, ‘E’, ‘K’, ‘S’), (‘F’, ‘O’, ‘R’), (‘G’, ‘E’, ‘E’, ‘K’, ‘S’)]The list after conversion to list of string : [‘GEEKS’, ‘FOR’, ‘GEEKS’] Python list-programs python-list python-tuple Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary How to print without newline in Python? Python | Convert string dictionary to dictionary
[ { "code": null, "e": 25739, "s": 25711, "text": "\n26 Feb, 2019" }, { "code": null, "e": 26139, "s": 25739, "text": "The interconversion between datatypes is quite useful utility and many articles have been written to perform the same. This article discusses the interconversion between a tuple of characters to individual strings. This kind of interconversion is useful in Machine Learning in which we need to give the input to train model in a specific format. Let’s discuss certain ways in which this can be done." }, { "code": null, "e": 26354, "s": 26139, "text": "Method #1 : Using list comprehension + join()The list comprehension performs the task of iterating the entire list of tuples and join function performs the task of aggregating the elements of tuple into a one list." }, { "code": "# Python3 code to demonstrate# conversion of list of tuple to list of list # using list comprehension + join() # initializing list test_list = [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'), ('G', 'E', 'E', 'K', 'S')] # printing the original listprint (\"The original list is : \" + str(test_list)) # using list comprehension + join()# conversion of list of tuple to list of list res = [''.join(i) for i in test_list] # printing resultprint (\"The list after conversion to list of string : \" + str(res))", "e": 26885, "s": 26354, "text": null }, { "code": null, "e": 26894, "s": 26885, "text": "Output :" }, { "code": null, "e": 27060, "s": 26894, "text": "The original list is : [(‘G’, ‘E’, ‘E’, ‘K’, ‘S’), (‘F’, ‘O’, ‘R’), (‘G’, ‘E’, ‘E’, ‘K’, ‘S’)]The list after conversion to list of string : [‘GEEKS’, ‘FOR’, ‘GEEKS’]" }, { "code": null, "e": 27248, "s": 27062, "text": "Method #2 : Using map() + join()The task performed by the list comprehension can be performed by the map function which can perform extension of logic of one tuple to all tuple in list." }, { "code": "# Python3 code to demonstrate# conversion of list of tuple to list of list # using map() + join() # initializing list test_list = [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'), ('G', 'E', 'E', 'K', 'S')] # printing the original listprint (\"The original list is : \" + str(test_list)) # using map() + join()# conversion of list of tuple to list of list res = list(map(''.join, test_list)) # printing resultprint (\"The list after conversion to list of string : \" + str(res))", "e": 27751, "s": 27248, "text": null }, { "code": null, "e": 27760, "s": 27751, "text": "Output :" }, { "code": null, "e": 27926, "s": 27760, "text": "The original list is : [(‘G’, ‘E’, ‘E’, ‘K’, ‘S’), (‘F’, ‘O’, ‘R’), (‘G’, ‘E’, ‘E’, ‘K’, ‘S’)]The list after conversion to list of string : [‘GEEKS’, ‘FOR’, ‘GEEKS’]" }, { "code": null, "e": 27947, "s": 27926, "text": "Python list-programs" }, { "code": null, "e": 27959, "s": 27947, "text": "python-list" }, { "code": null, "e": 27972, "s": 27959, "text": "python-tuple" }, { "code": null, "e": 27979, "s": 27972, "text": "Python" }, { "code": null, "e": 27995, "s": 27979, "text": "Python Programs" }, { "code": null, "e": 28007, "s": 27995, "text": "python-list" }, { "code": null, "e": 28105, "s": 28007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28123, "s": 28105, "text": "Python Dictionary" }, { "code": null, "e": 28155, "s": 28123, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28177, "s": 28155, "text": "Enumerate() in Python" }, { "code": null, "e": 28219, "s": 28177, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28245, "s": 28219, "text": "Python String | replace()" }, { "code": null, "e": 28267, "s": 28245, "text": "Defaultdict in Python" }, { "code": null, "e": 28306, "s": 28267, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28344, "s": 28306, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 28384, "s": 28344, "text": "How to print without newline in Python?" } ]
PySpark DataFrame - Drop Rows with NULL or None Values - GeeksforGeeks
30 Apr, 2021 Sometimes while handling data inside a dataframe we may get null values. In order to clean the dataset we have to remove all the null values in the dataframe. So in this article, we will learn how to drop rows with NULL or None Values in PySpark DataFrame. In pyspark the drop() function can be used to remove null values from the dataframe. It takes the following parameters:- Syntax: dataframe_name.na.drop(how=”any/all”,thresh=threshold_value,subset=[“column_name_1′′,”column_name_2”]) how – This takes either of the two values ‘any’ or ‘all’. ‘any’, drop a row if it contains NULLs on any columns and ‘all’, drop a row only if all columns have NULL values. By default it is set to ‘any’ thresh – This takes an integer value and drops rows that have less than that thresh hold non-null values. By default it is set to ‘None’. subset – This parameter is used to select a specific column to target the NULL values in it. By default it’s ‘None Note: DataFrame has a variable na which represents an instance of class DataFrameNaFunctions. Thus, we use na variable on DataFrame to use drop() function. We are specifying our path to spark directory using the findspark.init() function in order to enable our program to find the location of apache spark in our local machine. Ignore this line if you are running the program on cloud. Suppose we have our spark folder in c drive by name of spark so the function would look something like :- findspark.init(‘c:/spark’). Not specifying the path sometimes may lead to py4j.protocol.Py4JError error when running the program locally. Example 1: Dropping All rows with any Null Values In this example, we are going to create our own custom dataset and use the drop() function to eliminate the rows that have null values. We are going to drop all the rows in that have Null values in the dataframe. Since we are creating our own data we need to specify our schema along with it in order to create the dataset. Python3 from pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatTypefrom pyspark.sql import SparkSessionimport findspark # spark location# add the respective path to your sparkfindspark.init('_path-to-spark_') # Initialize our datadata2 = [("Pulkit", 12, "CS32", 82, "Programming"), ("Ritika", 20, "CS32", 94, "Writing"), ("Atirikt", 4, "BB21", 78, None), ("Reshav", 18, None, 56, None) ] # Start spark sessionspark = SparkSession.builder.appName("Student_Info").getOrCreate() # Define schemaschema = StructType([ StructField("Name", StringType(), True), StructField("Roll Number", IntegerType(), True), StructField("Class ID", StringType(), True), StructField("Marks", IntegerType(), True), StructField("Extracurricular", StringType(), True)]) # create the dataframedf = spark.createDataFrame(data=data2, schema=schema) # drop None Valuesdf.na.drop(how="any").show(truncate=False) # stop spark sessionspark.stop() Output: Example 2: Dropping All rows with any Null Values in Specific Column We can also select particular columns to check from by using the subset field. In this example we are using our custom-built dataset and will remove the data of the row which has null value in Class ID column only. Since we are creating our own data we need to specify our schema along with it in order to create the dataset. We can perform the operation in the following way:- Python3 from pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatTypefrom pyspark.sql import SparkSessionimport findspark # spark location# add the respective path to your sparkfindspark.init('_path-to-spark_') # Initialize our datadata2 = [("Pulkit", 12, "CS32", 82, "Programming"), ("Ritika", 20, "CS32", 94, "Writing"), ("Atirikt", 4, "BB21", 78, None), ("Reshav", 18, None, 56, None) ] # Start spark sessionspark = SparkSession.builder.appName("Student_Info").getOrCreate() # Define schemaschema = StructType([ StructField("Name", StringType(), True), StructField("Roll Number", IntegerType(), True), StructField("Class ID", StringType(), True), StructField("Marks", IntegerType(), True), StructField("Extracurricular", StringType(), True)]) # create the dataframedf = spark.createDataFrame(data=data2, schema=schema) # drop None Valuesdf.na.drop(subset=["Class ID"]).show(truncate=False) # stop spark sessionspark.stop() Output: Example 3: Dropping All rows with any Null Values Using dropna() method A third way to drop null valued rows is to use dropna() function. The dropna() function performs in the similar way as of na.drop() does. Here we don’t need to specify any variable as it detects the null values and deletes the rows on it’s own. Since we are creating our own data we need to specify our schema along with it in order to create the dataset. We can use it in pyspark in the following way:- Python3 from pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatTypefrom pyspark.sql import SparkSessionimport findspark # spark location# add the respective path to your sparkfindspark.init('_path-to-spark_') # Initialize our datadata2 = [("Pulkit", 12, "CS32", 82, "Programming"), ("Ritika", 20, "CS32", 94, "Writing"), ("Atirikt", 4, "BB21", 78, None), ("Reshav", 18, None, 56, None) ] # Start spark sessionspark = SparkSession.builder.appName("Student_Info").getOrCreate() # Define schemaschema = StructType([ StructField("Name", StringType(), True), StructField("Roll Number", IntegerType(), True), StructField("Class ID", StringType(), True), StructField("Marks", IntegerType(), True), StructField("Extracurricular", StringType(), True)]) # create the dataframedf = spark.createDataFrame(data=data2, schema=schema) # drop None Valuesdf.dropna().show(truncate=False) # stop spark sessionspark.stop() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects 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": 25555, "s": 25527, "text": "\n30 Apr, 2021" }, { "code": null, "e": 25813, "s": 25555, "text": "Sometimes while handling data inside a dataframe we may get null values. In order to clean the dataset we have to remove all the null values in the dataframe. So in this article, we will learn how to drop rows with NULL or None Values in PySpark DataFrame. " }, { "code": null, "e": 25934, "s": 25813, "text": "In pyspark the drop() function can be used to remove null values from the dataframe. It takes the following parameters:-" }, { "code": null, "e": 26045, "s": 25934, "text": "Syntax: dataframe_name.na.drop(how=”any/all”,thresh=threshold_value,subset=[“column_name_1′′,”column_name_2”])" }, { "code": null, "e": 26248, "s": 26045, "text": "how – This takes either of the two values ‘any’ or ‘all’. ‘any’, drop a row if it contains NULLs on any columns and ‘all’, drop a row only if all columns have NULL values. By default it is set to ‘any’" }, { "code": null, "e": 26386, "s": 26248, "text": "thresh – This takes an integer value and drops rows that have less than that thresh hold non-null values. By default it is set to ‘None’." }, { "code": null, "e": 26501, "s": 26386, "text": "subset – This parameter is used to select a specific column to target the NULL values in it. By default it’s ‘None" }, { "code": null, "e": 26657, "s": 26501, "text": "Note: DataFrame has a variable na which represents an instance of class DataFrameNaFunctions. Thus, we use na variable on DataFrame to use drop() function." }, { "code": null, "e": 27131, "s": 26657, "text": "We are specifying our path to spark directory using the findspark.init() function in order to enable our program to find the location of apache spark in our local machine. Ignore this line if you are running the program on cloud. Suppose we have our spark folder in c drive by name of spark so the function would look something like :- findspark.init(‘c:/spark’). Not specifying the path sometimes may lead to py4j.protocol.Py4JError error when running the program locally." }, { "code": null, "e": 27181, "s": 27131, "text": "Example 1: Dropping All rows with any Null Values" }, { "code": null, "e": 27505, "s": 27181, "text": "In this example, we are going to create our own custom dataset and use the drop() function to eliminate the rows that have null values. We are going to drop all the rows in that have Null values in the dataframe. Since we are creating our own data we need to specify our schema along with it in order to create the dataset." }, { "code": null, "e": 27513, "s": 27505, "text": "Python3" }, { "code": "from pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatTypefrom pyspark.sql import SparkSessionimport findspark # spark location# add the respective path to your sparkfindspark.init('_path-to-spark_') # Initialize our datadata2 = [(\"Pulkit\", 12, \"CS32\", 82, \"Programming\"), (\"Ritika\", 20, \"CS32\", 94, \"Writing\"), (\"Atirikt\", 4, \"BB21\", 78, None), (\"Reshav\", 18, None, 56, None) ] # Start spark sessionspark = SparkSession.builder.appName(\"Student_Info\").getOrCreate() # Define schemaschema = StructType([ StructField(\"Name\", StringType(), True), StructField(\"Roll Number\", IntegerType(), True), StructField(\"Class ID\", StringType(), True), StructField(\"Marks\", IntegerType(), True), StructField(\"Extracurricular\", StringType(), True)]) # create the dataframedf = spark.createDataFrame(data=data2, schema=schema) # drop None Valuesdf.na.drop(how=\"any\").show(truncate=False) # stop spark sessionspark.stop()", "e": 28505, "s": 27513, "text": null }, { "code": null, "e": 28513, "s": 28505, "text": "Output:" }, { "code": null, "e": 28582, "s": 28513, "text": "Example 2: Dropping All rows with any Null Values in Specific Column" }, { "code": null, "e": 28961, "s": 28582, "text": "We can also select particular columns to check from by using the subset field. In this example we are using our custom-built dataset and will remove the data of the row which has null value in Class ID column only. Since we are creating our own data we need to specify our schema along with it in order to create the dataset. We can perform the operation in the following way:-" }, { "code": null, "e": 28969, "s": 28961, "text": "Python3" }, { "code": "from pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatTypefrom pyspark.sql import SparkSessionimport findspark # spark location# add the respective path to your sparkfindspark.init('_path-to-spark_') # Initialize our datadata2 = [(\"Pulkit\", 12, \"CS32\", 82, \"Programming\"), (\"Ritika\", 20, \"CS32\", 94, \"Writing\"), (\"Atirikt\", 4, \"BB21\", 78, None), (\"Reshav\", 18, None, 56, None) ] # Start spark sessionspark = SparkSession.builder.appName(\"Student_Info\").getOrCreate() # Define schemaschema = StructType([ StructField(\"Name\", StringType(), True), StructField(\"Roll Number\", IntegerType(), True), StructField(\"Class ID\", StringType(), True), StructField(\"Marks\", IntegerType(), True), StructField(\"Extracurricular\", StringType(), True)]) # create the dataframedf = spark.createDataFrame(data=data2, schema=schema) # drop None Valuesdf.na.drop(subset=[\"Class ID\"]).show(truncate=False) # stop spark sessionspark.stop()", "e": 29971, "s": 28969, "text": null }, { "code": null, "e": 29979, "s": 29971, "text": "Output:" }, { "code": null, "e": 30051, "s": 29979, "text": "Example 3: Dropping All rows with any Null Values Using dropna() method" }, { "code": null, "e": 30455, "s": 30051, "text": "A third way to drop null valued rows is to use dropna() function. The dropna() function performs in the similar way as of na.drop() does. Here we don’t need to specify any variable as it detects the null values and deletes the rows on it’s own. Since we are creating our own data we need to specify our schema along with it in order to create the dataset. We can use it in pyspark in the following way:-" }, { "code": null, "e": 30463, "s": 30455, "text": "Python3" }, { "code": "from pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatTypefrom pyspark.sql import SparkSessionimport findspark # spark location# add the respective path to your sparkfindspark.init('_path-to-spark_') # Initialize our datadata2 = [(\"Pulkit\", 12, \"CS32\", 82, \"Programming\"), (\"Ritika\", 20, \"CS32\", 94, \"Writing\"), (\"Atirikt\", 4, \"BB21\", 78, None), (\"Reshav\", 18, None, 56, None) ] # Start spark sessionspark = SparkSession.builder.appName(\"Student_Info\").getOrCreate() # Define schemaschema = StructType([ StructField(\"Name\", StringType(), True), StructField(\"Roll Number\", IntegerType(), True), StructField(\"Class ID\", StringType(), True), StructField(\"Marks\", IntegerType(), True), StructField(\"Extracurricular\", StringType(), True)]) # create the dataframedf = spark.createDataFrame(data=data2, schema=schema) # drop None Valuesdf.dropna().show(truncate=False) # stop spark sessionspark.stop()", "e": 31445, "s": 30463, "text": null }, { "code": null, "e": 31453, "s": 31445, "text": "Output:" }, { "code": null, "e": 31460, "s": 31453, "text": "Picked" }, { "code": null, "e": 31475, "s": 31460, "text": "Python-Pyspark" }, { "code": null, "e": 31482, "s": 31475, "text": "Python" }, { "code": null, "e": 31580, "s": 31482, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31612, "s": 31580, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31654, "s": 31612, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31696, "s": 31654, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31752, "s": 31696, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31779, "s": 31752, "text": "Python Classes and Objects" }, { "code": null, "e": 31810, "s": 31779, "text": "Python | os.path.join() method" }, { "code": null, "e": 31849, "s": 31810, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31878, "s": 31849, "text": "Create a directory in Python" }, { "code": null, "e": 31900, "s": 31878, "text": "Defaultdict in Python" } ]
OffsetDateTime format() method in Java with examples - GeeksforGeeks
13 Aug, 2021 The format() method of OffsetDateTime class in Java formats this date-time using the specified formatter. Syntax : public String format(DateTimeFormatter formatter) Parameter : This method accepts a single parameter formatter which specifies the formatter to use, not null.Return Value: It returns the formatted date string, not null.Exceptions: The function throws a DateTimeException that is when an error occurs during printing. Below programs illustrate the format() method:Program 1 : Java // Java program to demonstrate the format() methodimport java.time.OffsetDateTime;import java.time.format.DateTimeFormatter; public class GFG { public static void main(String[] args) { // Parses the date1 OffsetDateTime date1 = OffsetDateTime.parse("2018-12-12T13:30:30+05:00"); // Prints the date System.out.println("Date1: " + date1); DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME; System.out.println(formatter.format(date1)); }} Date1: 2018-12-12T13:30:30+05:00 13:30:30+05:00 Program 2 : Java // Java program to demonstrate the format() method// Exceptions import java.time.OffsetDateTime;import java.time.format.DateTimeFormatter; public class GFG { public static void main(String[] args) { try { // Parses the date1 OffsetDateTime date1 = OffsetDateTime.parse("2018-13-12T13:30:30+05:00"); // Prints the date System.out.println("Date1: " + date1); DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME; System.out.println(formatter.format(date1)); } catch (Exception e) { System.out.println(e); } }} java.time.format.DateTimeParseException: Text '2018-13-12T13:30:30+05:00' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 13 Reference: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html#format-java.time.format.DateTimeFormatter- akshaysingh98088 Java-Functions Java-OffsetDateTime Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 26273, "s": 26245, "text": "\n13 Aug, 2021" }, { "code": null, "e": 26380, "s": 26273, "text": "The format() method of OffsetDateTime class in Java formats this date-time using the specified formatter. " }, { "code": null, "e": 26391, "s": 26380, "text": "Syntax : " }, { "code": null, "e": 26441, "s": 26391, "text": "public String format(DateTimeFormatter formatter)" }, { "code": null, "e": 26768, "s": 26441, "text": "Parameter : This method accepts a single parameter formatter which specifies the formatter to use, not null.Return Value: It returns the formatted date string, not null.Exceptions: The function throws a DateTimeException that is when an error occurs during printing. Below programs illustrate the format() method:Program 1 : " }, { "code": null, "e": 26773, "s": 26768, "text": "Java" }, { "code": "// Java program to demonstrate the format() methodimport java.time.OffsetDateTime;import java.time.format.DateTimeFormatter; public class GFG { public static void main(String[] args) { // Parses the date1 OffsetDateTime date1 = OffsetDateTime.parse(\"2018-12-12T13:30:30+05:00\"); // Prints the date System.out.println(\"Date1: \" + date1); DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME; System.out.println(formatter.format(date1)); }}", "e": 27270, "s": 26773, "text": null }, { "code": null, "e": 27318, "s": 27270, "text": "Date1: 2018-12-12T13:30:30+05:00\n13:30:30+05:00" }, { "code": null, "e": 27333, "s": 27320, "text": "Program 2 : " }, { "code": null, "e": 27338, "s": 27333, "text": "Java" }, { "code": "// Java program to demonstrate the format() method// Exceptions import java.time.OffsetDateTime;import java.time.format.DateTimeFormatter; public class GFG { public static void main(String[] args) { try { // Parses the date1 OffsetDateTime date1 = OffsetDateTime.parse(\"2018-13-12T13:30:30+05:00\"); // Prints the date System.out.println(\"Date1: \" + date1); DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME; System.out.println(formatter.format(date1)); } catch (Exception e) { System.out.println(e); } }}", "e": 27966, "s": 27338, "text": null }, { "code": null, "e": 28117, "s": 27966, "text": "java.time.format.DateTimeParseException: Text '2018-13-12T13:30:30+05:00' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 13" }, { "code": null, "e": 28245, "s": 28119, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html#format-java.time.format.DateTimeFormatter-" }, { "code": null, "e": 28262, "s": 28245, "text": "akshaysingh98088" }, { "code": null, "e": 28277, "s": 28262, "text": "Java-Functions" }, { "code": null, "e": 28297, "s": 28277, "text": "Java-OffsetDateTime" }, { "code": null, "e": 28315, "s": 28297, "text": "Java-time package" }, { "code": null, "e": 28320, "s": 28315, "text": "Java" }, { "code": null, "e": 28325, "s": 28320, "text": "Java" }, { "code": null, "e": 28423, "s": 28325, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28474, "s": 28423, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28504, "s": 28474, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28519, "s": 28504, "text": "Stream In Java" }, { "code": null, "e": 28538, "s": 28519, "text": "Interfaces in Java" }, { "code": null, "e": 28569, "s": 28538, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28587, "s": 28569, "text": "ArrayList in Java" }, { "code": null, "e": 28619, "s": 28587, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28639, "s": 28619, "text": "Stack Class in Java" }, { "code": null, "e": 28663, "s": 28639, "text": "Singleton Class in Java" } ]
Combinatorics - GeeksforGeeks
21 Jan, 2014 How many onto (or surjective) functions are there from an n-element (n >= 2) set to a 2-element set? 2(2n - 2) 2n - 2 2n - 1 2n Total possible number of functions is 2n. In mathematics, a function f from a set X to a set Y is surjective (or onto), or a surjection, if every element y in Y has a corresponding element x in X such that f(x) = yThere are total 2 functions out of 2n that are NOT onto: one that maps to all 1s and other that maps to all 2s. Therefore total number of onto functions is 2n - 2. What is the possible number of reflexive relations on a set of 5 elements? 225 220 215 210 Number of reflexive relations is 2n2-n which is 220 for n = 5 No of inputs sequences possible for a n variable Boolean function = 2n Each input sequence can give either T or F as output ( 2 possible values ) So, Total no of Boolean functions are - 2X2X2X2X2X2X.............X2X2X2X2X2X2 <-------------------- 2n Times --------------> 22n Suppose that a robot is placed on the Cartesian plane. At each step it is allowed to move either one unit up or one unit right, i.e., if it is at (i,j) then it can move to either (i+1,j) or (i,j+1). How many distinct paths are there for the robot to reach the point (10,10) starting from the initial position (0, 0) D C B A At each move, robot can move either 1 unit right, or 1 unit up, and there will be 20 such moves required to reach (10,10) from (0,0). So we have to divide these 20 moves, numbered from 1 to 20, into 2 groups: right group and up group. Right group contains those moves in which we move right, and up group contains those moves in which we move up. Each group contains 10 elements each. So basically, we have to divide 20 things into 2 groups of 10 10 things each, i.e., we need to find all possible arrangements of {r, r, r, r, r, r, r, r, r, r, u, u, u, u, u, u, u, u, u, u} where r represents right move and u represents up move. The arrangements can can be done in 20! / (10!∗10!) = 20C10 ways. So option (A) is correct. Consider the data given in above question.Suppose that the robot is not allowed to traverse the line segment from (4,4) to (5,4). With this constraint, how many distinct paths are there for the robot to reach (10,10) starting from (0,0)? D C B A Since we are not allowed to traverse from (4,4) to (5,4), we subtract all those paths which were passing through (4,4) to (5,4). To count number of paths passing through (4,4) to (5,4), we find number of paths from (0,0) to (4,4), and then from (5,4) to (10,10). From (0,0) to (4,4), number of paths = 8C4 [found in same way as in previous question]. From (5,4) to (10,10), number of paths = 11C5. So total number of paths required : 20C10 − 8C4 ∗ 11C5. So option (D) is correct. Mala has a colouring book in which each English letter is drawn two times. She wants to paint each of these 52 prints with one of k colours, such that the colour-pairs used to colour any two letters are different. Both prints of a letter can also be coloured with the same colour. What is the minimum value of k that satisfies this requirement ? 9 8 7 6 This question is slightly ambiguous. So first let us understand what question is asking. So in a book, we have letters A-Z and each letter is printed twice, so there are 52 letters. Now we have to color each letter, so we need a pair of colors for that, because each letter is printed twice. Also in a pair, both colors can be some. Now condition is that a pair of colors can't be used more than once. So suppose Mala has 3 colors : Red, Blue, Green. She can color as follows : (A,A) : (Red,Red), (B,B) : (Blue,Blue), (C,C) : (Green,Green), (D,D) : (Red,Blue), (E,E) : (Red,Green), (F,F) : (Blue,Green). Now we don't have more pairs of colors left, we have used all pairs, but could color only 6 letters out of 26. So question is to find minimum no. of colors, so that we could color all 26 letters. So if Mala has k colors, she can have k pairs of same colors, thus coloring k letters, then kC2 other pairs of colors, thus coloring kC2 more letters. So total no. of letters colored = k+kC2=k+k(k−1)2=k(k+1)2. So we want k(k+1)2≥26 i.e. k(k+1)≥52, so k≥7, so option (C) is correct. Let A be a sequence of 8 distinct integers sorted in ascending order. How many distinct pairs of sequences, B and C are there such that (i) each is sorted in ascending order, (ii) B has 5 and C has 3 elements, and (iii) the result of merging B and C gives A? 256 56 30 2 Suppose you have selected 3 elements from 8 in 8C3 ways, the remaining elements are treated as another array and merging both the arrays gives the sorted array. Here, you can select either 3 or 5. => 8C3 = 8C5 = 8!/(3!5!) = 7*8 = 56 Ways. 1) Nobody goes to gathering 2) Wife alone goes 2) Both go m identical balls are to be placed in n distinct bags. You are given that m ≥ kn, where, k is a natural number ≥ 1. In how many ways can the balls be placed in the bags if each bag must contain at least k balls? D C B A This is very simple application of stars and bars. Since we want atleast k balls in each bag, so first we put kn balls into bags, k balls in each bag. Now we are left with m - kn balls, and we have to put them into n bags such that each bag may receive 0 or more balls. So applying theorem 2 of stars and bars with m - nk stars and n bars, we get number of ways to be m−kn+n-1 Cn−1. So option (B) is correct. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Program for Breadth First Search or BFS for a Graph Best Time to Buy and Sell Stock Must Do Coding Questions for Product Based Companies How to calculate MOVING AVERAGE in a Pandas DataFrame? What is "network ID" and "host ID" in IP Addresses? What is Transmission Control Protocol (TCP)? How to Calculate Number of Host in a Subnet? Python OpenCV - Canny() Function How to Convert Categorical Variable to Numeric in Pandas? How to Replace Values in Column Based on Condition in Pandas?
[ { "code": null, "e": 31253, "s": 31225, "text": "\n21 Jan, 2014" }, { "code": null, "e": 31355, "s": 31253, "text": "How many onto (or surjective) functions are there from an n-element (n >= 2) set to a 2-element set? " }, { "code": null, "e": 31366, "s": 31355, "text": "2(2n - 2) " }, { "code": null, "e": 31374, "s": 31366, "text": "2n - 2 " }, { "code": null, "e": 31382, "s": 31374, "text": "2n - 1 " }, { "code": null, "e": 31386, "s": 31382, "text": "2n " }, { "code": null, "e": 31766, "s": 31386, "text": "Total possible number of functions is 2n. In mathematics, a function f from a set X to a set Y is surjective (or onto), or a surjection, if every element y in Y has a corresponding element x in X such that f(x) = yThere are total 2 functions out of 2n that are NOT onto: one that maps to all 1s and other that maps to all 2s. Therefore total number of onto functions is 2n - 2. " }, { "code": null, "e": 31842, "s": 31766, "text": "What is the possible number of reflexive relations on a set of 5 elements? " }, { "code": null, "e": 31847, "s": 31842, "text": "225 " }, { "code": null, "e": 31852, "s": 31847, "text": "220 " }, { "code": null, "e": 31857, "s": 31852, "text": "215 " }, { "code": null, "e": 31862, "s": 31857, "text": "210 " }, { "code": null, "e": 31925, "s": 31862, "text": "Number of reflexive relations is 2n2-n which is 220 for n = 5 " }, { "code": null, "e": 32206, "s": 31925, "text": "No of inputs sequences possible for a n variable Boolean function = 2n\n\nEach input sequence can give either T or F as output ( 2 possible values )\n\nSo, Total no of Boolean functions are -\n\n2X2X2X2X2X2X.............X2X2X2X2X2X2\n\n<-------------------- 2n Times -------------->\n\n22n\n" }, { "code": null, "e": 32524, "s": 32206, "text": "Suppose that a robot is placed on the Cartesian plane. At each step it is allowed to move either one unit up or one unit right, i.e., if it is at (i,j) then it can move to either (i+1,j) or (i,j+1). How many distinct paths are there for the robot to reach the point (10,10) starting from the initial position (0, 0) " }, { "code": null, "e": 32529, "s": 32526, "text": "D " }, { "code": null, "e": 32532, "s": 32529, "text": "C " }, { "code": null, "e": 32535, "s": 32532, "text": "B " }, { "code": null, "e": 32538, "s": 32535, "text": "A " }, { "code": null, "e": 33263, "s": 32538, "text": "At each move, robot can move either 1 unit right, or 1 unit up, and there will be 20 such moves required to reach (10,10) from (0,0). So we have to divide these 20 moves, numbered from 1 to 20, into 2 groups: right group and up group. Right group contains those moves in which we move right, and up group contains those moves in which we move up. Each group contains 10 elements each. So basically, we have to divide 20 things into 2 groups of 10 10 things each, i.e., we need to find all possible arrangements of {r, r, r, r, r, r, r, r, r, r, u, u, u, u, u, u, u, u, u, u} where r represents right move and u represents up move. The arrangements can can be done in 20! / (10!∗10!) = 20C10 ways. So option (A) is correct. " }, { "code": null, "e": 33503, "s": 33263, "text": "Consider the data given in above question.Suppose that the robot is not allowed to traverse the line segment from (4,4) to (5,4). With this constraint, how many distinct paths are there for the robot to reach (10,10) starting from (0,0)? " }, { "code": null, "e": 33508, "s": 33505, "text": "D " }, { "code": null, "e": 33511, "s": 33508, "text": "C " }, { "code": null, "e": 33514, "s": 33511, "text": "B " }, { "code": null, "e": 33517, "s": 33514, "text": "A " }, { "code": null, "e": 33782, "s": 33517, "text": "Since we are not allowed to traverse from (4,4) to (5,4), we subtract all those paths which were passing through (4,4) to (5,4). To count number of paths passing through (4,4) to (5,4), we find number of paths from (0,0) to (4,4), and then from (5,4) to (10,10). " }, { "code": null, "e": 33974, "s": 33782, "text": "From (0,0) to (4,4), number of paths = 8C4\n[found in same way as in previous question].\n\nFrom (5,4) to (10,10), number of paths = 11C5.\nSo total number of paths required : 20C10 − 8C4 ∗ 11C5." }, { "code": null, "e": 34001, "s": 33974, "text": "So option (D) is correct. " }, { "code": null, "e": 34348, "s": 34001, "text": "Mala has a colouring book in which each English letter is drawn two times. She wants to paint each of these 52 prints with one of k colours, such that the colour-pairs used to colour any two letters are different. Both prints of a letter can also be coloured with the same colour. What is the minimum value of k that satisfies this requirement ? " }, { "code": null, "e": 34351, "s": 34348, "text": "9 " }, { "code": null, "e": 34354, "s": 34351, "text": "8 " }, { "code": null, "e": 34357, "s": 34354, "text": "7 " }, { "code": null, "e": 34360, "s": 34357, "text": "6 " }, { "code": null, "e": 35443, "s": 34360, "text": "This question is slightly ambiguous. So first let us understand what question is asking. So in a book, we have letters A-Z and each letter is printed twice, so there are 52 letters. Now we have to color each letter, so we need a pair of colors for that, because each letter is printed twice. Also in a pair, both colors can be some. Now condition is that a pair of colors can't be used more than once. So suppose Mala has 3 colors : Red, Blue, Green. She can color as follows : (A,A) : (Red,Red), (B,B) : (Blue,Blue), (C,C) : (Green,Green), (D,D) : (Red,Blue), (E,E) : (Red,Green), (F,F) : (Blue,Green). Now we don't have more pairs of colors left, we have used all pairs, but could color only 6 letters out of 26. So question is to find minimum no. of colors, so that we could color all 26 letters. So if Mala has k colors, she can have k pairs of same colors, thus coloring k letters, then kC2 other pairs of colors, thus coloring kC2 more letters. So total no. of letters colored = k+kC2=k+k(k−1)2=k(k+1)2. So we want k(k+1)2≥26 i.e. k(k+1)≥52, so k≥7, so option (C) is correct. " }, { "code": null, "e": 35703, "s": 35443, "text": "Let A be a sequence of 8 distinct integers sorted in ascending order. How many distinct pairs of sequences, B and C are there such that (i) each is sorted in ascending order, (ii) B has 5 and C has 3 elements, and (iii) the result of merging B and C gives A? " }, { "code": null, "e": 35708, "s": 35703, "text": "256 " }, { "code": null, "e": 35712, "s": 35708, "text": "56 " }, { "code": null, "e": 35716, "s": 35712, "text": "30 " }, { "code": null, "e": 35719, "s": 35716, "text": "2 " }, { "code": null, "e": 35960, "s": 35719, "text": "Suppose you have selected 3 elements from 8 in 8C3 ways, the remaining elements are treated as another array and merging both the arrays gives the sorted array. Here, you can select either 3 or 5. => 8C3 = 8C5 = 8!/(3!5!) = 7*8 = 56 Ways. " }, { "code": null, "e": 36018, "s": 35960, "text": "1) Nobody goes to gathering\n2) Wife alone goes\n2) Both go" }, { "code": null, "e": 36232, "s": 36018, "text": "m identical balls are to be placed in n distinct bags. You are given that m ≥ kn, where, k is a natural number ≥ 1. In how many ways can the balls be placed in the bags if each bag must contain at least k balls? " }, { "code": null, "e": 36237, "s": 36234, "text": "D " }, { "code": null, "e": 36240, "s": 36237, "text": "C " }, { "code": null, "e": 36243, "s": 36240, "text": "B " }, { "code": null, "e": 36246, "s": 36243, "text": "A " }, { "code": null, "e": 36656, "s": 36246, "text": "This is very simple application of stars and bars. Since we want atleast k balls in each bag, so first we put kn balls into bags, k balls in each bag. Now we are left with m - kn balls, and we have to put them into n bags such that each bag may receive 0 or more balls. So applying theorem 2 of stars and bars with m - nk stars and n bars, we get number of ways to be m−kn+n-1 Cn−1. So option (B) is correct. " }, { "code": null, "e": 36754, "s": 36656, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 36813, "s": 36754, "text": "Python Program for Breadth First Search or BFS for a Graph" }, { "code": null, "e": 36845, "s": 36813, "text": "Best Time to Buy and Sell Stock" }, { "code": null, "e": 36898, "s": 36845, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 36953, "s": 36898, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 37005, "s": 36953, "text": "What is \"network ID\" and \"host ID\" in IP Addresses?" }, { "code": null, "e": 37050, "s": 37005, "text": "What is Transmission Control Protocol (TCP)?" }, { "code": null, "e": 37095, "s": 37050, "text": "How to Calculate Number of Host in a Subnet?" }, { "code": null, "e": 37128, "s": 37095, "text": "Python OpenCV - Canny() Function" }, { "code": null, "e": 37186, "s": 37128, "text": "How to Convert Categorical Variable to Numeric in Pandas?" } ]
Next.js Introduction - GeeksforGeeks
03 Nov, 2021 Next.js is a react based framework. It has powers to Develop beautiful Web application for different platform like Windows, Linux and mac. If you have little experience in react and looking forward to know more about react ecosystem then you should have knowledge about Next.js framework.Let’s have a brief introduction about Next.js. Introduction: Next.js is based on react, webpack and babel. It is an awesome tool for creating web application and famous for server-side rendering. Next.js is build by Zeit. Developers with knowledge of HTML, CSS, Java Script and React can easily learn and switch to next.js. Main Features: Hot Code Reloading: It automatically reloads the application when changes in the code get saved. Automatic Code Splitting: By this feature, every import in the code get bundled and served with each page. It means that unnecessary code never get loaded on the page. Ecosystem Compatibility: Compatible with JavaScript, Node and react. Server Rendering: Easily render react component on server before sending HTML to client. Styled-JSX: Styled-JSX allows you to write CSS directly inside JavaScript code. Example: function Home() { return ( <div className="container"> <p>Hello Geeks</p> <style jsx>{` .container { margin: 50px; } p { color: blue; } `}</style> </div> )} export default Home Steps to Install and Run Next.js Application: Step 1: Installation of next.js require npm and node.js. You can install node.js from here. Confirm the installation by running these command on terminal.node -v npm -v node -v npm -v Step 2: Now create a folder for your project on desktop navigate to folder through your code editor and run the following command on terminal.npm init -y npm install --save next react react-domAfter this step, we have all the dependencies installed in our system. Now add the following script in package.json file{ "scripts": { "dev": "next", "build": "next build", "start": "next start" }}To run the application in the browser use the command npm start in terminal. npm init -y npm install --save next react react-dom After this step, we have all the dependencies installed in our system. Now add the following script in package.json file { "scripts": { "dev": "next", "build": "next build", "start": "next start" }} To run the application in the browser use the command npm start in terminal. Step 3: Add a file index.js in page folder and add the following code inside it.import React from'react';import Link from'next/link'; export default class extends React.Component { render() { return ( { // This is Jsx contains HTML // code in Javascript} <div> <h1>Hello Geeks</h1> { // This is Styled-jsx contains // CSS code in Javascript} <style jsx>{` a{ color:grey; text-decoration:none; } `}</style> } </div> ) } } import React from'react';import Link from'next/link'; export default class extends React.Component { render() { return ( { // This is Jsx contains HTML // code in Javascript} <div> <h1>Hello Geeks</h1> { // This is Styled-jsx contains // CSS code in Javascript} <style jsx>{` a{ color:grey; text-decoration:none; } `}</style> } </div> ) } } Step 4: Now start the application by running npm start.Output: Output: Reference: https://nextjs.org/docs/getting-started Next.js ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to pass data from one component to other component in ReactJS ? ReactJS useNavigate() Hook ReactJS defaultProps How to set background images in ReactJS ? Re-rendering Components in ReactJS Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25618, "s": 25590, "text": "\n03 Nov, 2021" }, { "code": null, "e": 25953, "s": 25618, "text": "Next.js is a react based framework. It has powers to Develop beautiful Web application for different platform like Windows, Linux and mac. If you have little experience in react and looking forward to know more about react ecosystem then you should have knowledge about Next.js framework.Let’s have a brief introduction about Next.js." }, { "code": null, "e": 26230, "s": 25953, "text": "Introduction: Next.js is based on react, webpack and babel. It is an awesome tool for creating web application and famous for server-side rendering. Next.js is build by Zeit. Developers with knowledge of HTML, CSS, Java Script and React can easily learn and switch to next.js." }, { "code": null, "e": 26245, "s": 26230, "text": "Main Features:" }, { "code": null, "e": 26342, "s": 26245, "text": "Hot Code Reloading: It automatically reloads the application when changes in the code get saved." }, { "code": null, "e": 26510, "s": 26342, "text": "Automatic Code Splitting: By this feature, every import in the code get bundled and served with each page. It means that unnecessary code never get loaded on the page." }, { "code": null, "e": 26579, "s": 26510, "text": "Ecosystem Compatibility: Compatible with JavaScript, Node and react." }, { "code": null, "e": 26668, "s": 26579, "text": "Server Rendering: Easily render react component on server before sending HTML to client." }, { "code": null, "e": 26748, "s": 26668, "text": "Styled-JSX: Styled-JSX allows you to write CSS directly inside JavaScript code." }, { "code": null, "e": 26757, "s": 26748, "text": "Example:" }, { "code": "function Home() { return ( <div className=\"container\"> <p>Hello Geeks</p> <style jsx>{` .container { margin: 50px; } p { color: blue; } `}</style> </div> )} export default Home", "e": 27050, "s": 26757, "text": null }, { "code": null, "e": 27096, "s": 27050, "text": "Steps to Install and Run Next.js Application:" }, { "code": null, "e": 27265, "s": 27096, "text": "Step 1: Installation of next.js require npm and node.js. You can install node.js from here. Confirm the installation by running these command on terminal.node -v\nnpm -v" }, { "code": null, "e": 27280, "s": 27265, "text": "node -v\nnpm -v" }, { "code": null, "e": 27758, "s": 27280, "text": "Step 2: Now create a folder for your project on desktop navigate to folder through your code editor and run the following command on terminal.npm init -y\nnpm install --save next react react-domAfter this step, we have all the dependencies installed in our system. Now add the following script in package.json file{ \"scripts\": { \"dev\": \"next\", \"build\": \"next build\", \"start\": \"next start\" }}To run the application in the browser use the command npm start in terminal." }, { "code": null, "e": 27810, "s": 27758, "text": "npm init -y\nnpm install --save next react react-dom" }, { "code": null, "e": 27931, "s": 27810, "text": "After this step, we have all the dependencies installed in our system. Now add the following script in package.json file" }, { "code": "{ \"scripts\": { \"dev\": \"next\", \"build\": \"next build\", \"start\": \"next start\" }}", "e": 28020, "s": 27931, "text": null }, { "code": null, "e": 28097, "s": 28020, "text": "To run the application in the browser use the command npm start in terminal." }, { "code": null, "e": 28755, "s": 28097, "text": "Step 3: Add a file index.js in page folder and add the following code inside it.import React from'react';import Link from'next/link'; export default class extends React.Component { render() { return ( { // This is Jsx contains HTML // code in Javascript} <div> <h1>Hello Geeks</h1> { // This is Styled-jsx contains // CSS code in Javascript} <style jsx>{` a{ color:grey; text-decoration:none; } `}</style> } </div> ) } }" }, { "code": "import React from'react';import Link from'next/link'; export default class extends React.Component { render() { return ( { // This is Jsx contains HTML // code in Javascript} <div> <h1>Hello Geeks</h1> { // This is Styled-jsx contains // CSS code in Javascript} <style jsx>{` a{ color:grey; text-decoration:none; } `}</style> } </div> ) } }", "e": 29333, "s": 28755, "text": null }, { "code": null, "e": 29396, "s": 29333, "text": "Step 4: Now start the application by running npm start.Output:" }, { "code": null, "e": 29404, "s": 29396, "text": "Output:" }, { "code": null, "e": 29455, "s": 29404, "text": "Reference: https://nextjs.org/docs/getting-started" }, { "code": null, "e": 29463, "s": 29455, "text": "Next.js" }, { "code": null, "e": 29471, "s": 29463, "text": "ReactJS" }, { "code": null, "e": 29488, "s": 29471, "text": "Web Technologies" }, { "code": null, "e": 29586, "s": 29488, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29654, "s": 29586, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 29681, "s": 29654, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 29702, "s": 29681, "text": "ReactJS defaultProps" }, { "code": null, "e": 29744, "s": 29702, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 29779, "s": 29744, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 29819, "s": 29779, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29852, "s": 29819, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29897, "s": 29852, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29947, "s": 29897, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Application of Partial Derivative – Two variable Maxima and Minima - GeeksforGeeks
22 Oct, 2021 Partial derivatives can be used to find the maximum and minimum value (if they exist) of a two-variable function. We try to locate a stationary point that has zero slope and then trace maximum and minimum values near it. The practical application of maxima/minima is to maximize profit for a given curve or minimizing losses. Let f(x,y) be a real-valued function and let (pt,pt’) be the interior points in the domain of f(x,y) then, pt, pt’ is called a point of local maxima if there is an h > 0 such that f(pt,pt’) ≥f(x,y), for all x in (pt – h, pt’ + h), x≠a The value f(pt,pt’) is called the local maximum value of f(x,y). pt, pt’ is called a point of local minima if there is an h < 0 such that f(pt,pt’) ≥f(x,y), for all x in (pt – h, pt’ + h), x≠a The value f(pt,pt’) is called the local minimum value of f(x,y). Algorithm to find maxima and minima of two-variable functions : Find the values of x and y using fxx=0 and fyy=0 [NOTE: fxx and fyy are the partial double derivatives of the function with respect to x and y respectively.]The Obtained result will be considered as stationary/turning points for the curve.Create 3 new variables r,t and s.Find the values of r,t and s using r=fxx, t=fyy, s=fxyIf (rt-s2)|(stationary pts)>0 (Maxima/Minima) existsIf (rt-s2)|(stationary pts) <0 (No Maxima/Minima)/(Saddle point)If r=fxx>0 (Minima) If r=fxx<0 (Maxima) Find the values of x and y using fxx=0 and fyy=0 [NOTE: fxx and fyy are the partial double derivatives of the function with respect to x and y respectively.] The Obtained result will be considered as stationary/turning points for the curve. Create 3 new variables r,t and s. Find the values of r,t and s using r=fxx, t=fyy, s=fxy If (rt-s2)|(stationary pts)>0 (Maxima/Minima) exists If (rt-s2)|(stationary pts) <0 (No Maxima/Minima)/(Saddle point) If r=fxx>0 (Minima) If r=fxx<0 (Maxima) Example-1 : The function f(x,y)=x2y−3xy+2y+x has (a) No local extremum (b) One local minimum but no local maximum (c) One local maximum but no local minimum (d) One local minimum and one local maximum Explanation : Answer: A r=∂2f/∂x2=2y s=∂2f/∂x∂y=2x−3 t=∂2f/∂y2=0 Since, rt−s2≤0, (if rt-s2< 0 then we have no maxima or minima, if = 0 then we can’t say anything). Maxima will exist when rt−s2>0 and r<0. Minima will exist when rt−s2>0 and r>0. As rt−s2 is never greater than 0 so we have no local extremum. Example-2 : Find the local minima of the function f(x , y) = 2x2 + 2xy + 2y2 – 6x fx(x,y) = 4x + 2y - 6=0 (1) fy(x,y) = 2x + 4y=0 (2) On solving (1) and (2) we get, x=2,y=-1 r=∂2f/∂x2=4 s=∂2f/∂x∂y=2 t=∂2f/∂y2=4 rt−s2=12 As rt−s2>0 and r>0. Thus, (2,-1) is the point of local minima. Example-3 : Find the maxima/minima of f(x , y) = x2+y2 + 6x +12 fx(x,y) = 2x+6=0 (1) fy(x,y) = 2y=0 (2) On solving (1) and (2) we get, x=-3,y=0 r=∂2f/∂x2=2 s=∂2f/∂x∂y=0 t=∂2f/∂y2=2 As rt−s2>0 and r>0. Thus, (-3,0) is the point of local minima. TrueGeek-2021 Engineering Mathematics GATE CS TrueGeek Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Activation Functions Difference between Propositional Logic and Predicate Logic Logic Notations in LaTeX Univariate, Bivariate and Multivariate data and its analysis Z-test Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 26137, "s": 26109, "text": "\n22 Oct, 2021" }, { "code": null, "e": 26463, "s": 26137, "text": "Partial derivatives can be used to find the maximum and minimum value (if they exist) of a two-variable function. We try to locate a stationary point that has zero slope and then trace maximum and minimum values near it. The practical application of maxima/minima is to maximize profit for a given curve or minimizing losses." }, { "code": null, "e": 26570, "s": 26463, "text": "Let f(x,y) be a real-valued function and let (pt,pt’) be the interior points in the domain of f(x,y) then," }, { "code": null, "e": 26764, "s": 26570, "text": "pt, pt’ is called a point of local maxima if there is an h > 0 such that f(pt,pt’) ≥f(x,y), for all x in (pt – h, pt’ + h), x≠a The value f(pt,pt’) is called the local maximum value of f(x,y)." }, { "code": null, "e": 26958, "s": 26764, "text": "pt, pt’ is called a point of local minima if there is an h < 0 such that f(pt,pt’) ≥f(x,y), for all x in (pt – h, pt’ + h), x≠a The value f(pt,pt’) is called the local minimum value of f(x,y)." }, { "code": null, "e": 27022, "s": 26958, "text": "Algorithm to find maxima and minima of two-variable functions :" }, { "code": null, "e": 27506, "s": 27022, "text": "Find the values of x and y using fxx=0 and fyy=0 [NOTE: fxx and fyy are the partial double derivatives of the function with respect to x and y respectively.]The Obtained result will be considered as stationary/turning points for the curve.Create 3 new variables r,t and s.Find the values of r,t and s using r=fxx, t=fyy, s=fxyIf (rt-s2)|(stationary pts)>0 (Maxima/Minima) existsIf (rt-s2)|(stationary pts) <0 (No Maxima/Minima)/(Saddle point)If r=fxx>0 (Minima) If r=fxx<0 (Maxima)" }, { "code": null, "e": 27665, "s": 27506, "text": "Find the values of x and y using fxx=0 and fyy=0 [NOTE: fxx and fyy are the partial double derivatives of the function with respect to x and y respectively.]" }, { "code": null, "e": 27748, "s": 27665, "text": "The Obtained result will be considered as stationary/turning points for the curve." }, { "code": null, "e": 27782, "s": 27748, "text": "Create 3 new variables r,t and s." }, { "code": null, "e": 27837, "s": 27782, "text": "Find the values of r,t and s using r=fxx, t=fyy, s=fxy" }, { "code": null, "e": 27891, "s": 27837, "text": "If (rt-s2)|(stationary pts)>0 (Maxima/Minima) exists" }, { "code": null, "e": 27956, "s": 27891, "text": "If (rt-s2)|(stationary pts) <0 (No Maxima/Minima)/(Saddle point)" }, { "code": null, "e": 27977, "s": 27956, "text": "If r=fxx>0 (Minima) " }, { "code": null, "e": 27997, "s": 27977, "text": "If r=fxx<0 (Maxima)" }, { "code": null, "e": 28009, "s": 27997, "text": "Example-1 :" }, { "code": null, "e": 28062, "s": 28009, "text": "The function f(x,y)=x2y−3xy+2y+x has " }, { "code": null, "e": 28084, "s": 28062, "text": "(a) No local extremum" }, { "code": null, "e": 28127, "s": 28084, "text": "(b) One local minimum but no local maximum" }, { "code": null, "e": 28170, "s": 28127, "text": "(c) One local maximum but no local minimum" }, { "code": null, "e": 28214, "s": 28170, "text": "(d) One local minimum and one local maximum" }, { "code": null, "e": 28228, "s": 28214, "text": "Explanation :" }, { "code": null, "e": 28238, "s": 28228, "text": "Answer: A" }, { "code": null, "e": 28279, "s": 28238, "text": "r=∂2f/∂x2=2y\ns=∂2f/∂x∂y=2x−3\nt=∂2f/∂y2=0" }, { "code": null, "e": 28378, "s": 28279, "text": "Since, rt−s2≤0, (if rt-s2< 0 then we have no maxima or minima, if = 0 then we can’t say anything)." }, { "code": null, "e": 28418, "s": 28378, "text": "Maxima will exist when rt−s2>0 and r<0." }, { "code": null, "e": 28458, "s": 28418, "text": "Minima will exist when rt−s2>0 and r>0." }, { "code": null, "e": 28521, "s": 28458, "text": "As rt−s2 is never greater than 0 so we have no local extremum." }, { "code": null, "e": 28533, "s": 28521, "text": "Example-2 :" }, { "code": null, "e": 28603, "s": 28533, "text": "Find the local minima of the function f(x , y) = 2x2 + 2xy + 2y2 – 6x" }, { "code": null, "e": 28665, "s": 28603, "text": "fx(x,y) = 4x + 2y - 6=0 (1)\nfy(x,y) = 2x + 4y=0 (2)" }, { "code": null, "e": 28696, "s": 28665, "text": "On solving (1) and (2) we get," }, { "code": null, "e": 28751, "s": 28696, "text": "x=2,y=-1\nr=∂2f/∂x2=4\ns=∂2f/∂x∂y=2\nt=∂2f/∂y2=4\nrt−s2=12" }, { "code": null, "e": 28814, "s": 28751, "text": "As rt−s2>0 and r>0. Thus, (2,-1) is the point of local minima." }, { "code": null, "e": 28826, "s": 28814, "text": "Example-3 :" }, { "code": null, "e": 28879, "s": 28826, "text": "Find the maxima/minima of f(x , y) = x2+y2 + 6x +12" }, { "code": null, "e": 28929, "s": 28879, "text": "fx(x,y) = 2x+6=0 (1)\nfy(x,y) = 2y=0 (2)" }, { "code": null, "e": 28960, "s": 28929, "text": "On solving (1) and (2) we get," }, { "code": null, "e": 29006, "s": 28960, "text": "x=-3,y=0\nr=∂2f/∂x2=2\ns=∂2f/∂x∂y=0\nt=∂2f/∂y2=2" }, { "code": null, "e": 29069, "s": 29006, "text": "As rt−s2>0 and r>0. Thus, (-3,0) is the point of local minima." }, { "code": null, "e": 29083, "s": 29069, "text": "TrueGeek-2021" }, { "code": null, "e": 29107, "s": 29083, "text": "Engineering Mathematics" }, { "code": null, "e": 29115, "s": 29107, "text": "GATE CS" }, { "code": null, "e": 29124, "s": 29115, "text": "TrueGeek" }, { "code": null, "e": 29222, "s": 29124, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29243, "s": 29222, "text": "Activation Functions" }, { "code": null, "e": 29302, "s": 29243, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 29327, "s": 29302, "text": "Logic Notations in LaTeX" }, { "code": null, "e": 29388, "s": 29327, "text": "Univariate, Bivariate and Multivariate data and its analysis" }, { "code": null, "e": 29395, "s": 29388, "text": "Z-test" }, { "code": null, "e": 29415, "s": 29395, "text": "Layers of OSI Model" }, { "code": null, "e": 29439, "s": 29415, "text": "ACID Properties in DBMS" }, { "code": null, "e": 29452, "s": 29439, "text": "TCP/IP Model" }, { "code": null, "e": 29479, "s": 29452, "text": "Types of Operating Systems" } ]
How to check for IP address using regular expression in javascript? - GeeksforGeeks
14 Jan, 2022 The task is to validate the IP address both IPv4 as well as IPv6. Here we are going to use RegExp to solve the problem. Approach 1: RegExp: Which split the IP address on .(dot) and check for each element whether they are valid or not(0-255). Example 1: This example using the approach discussed above. html <!DOCTYPE HTML><html> <head> <title> How to check for IP address using regular expression in javascript? </title></head><center> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var addr = '172.169.43.1'; up.innerHTML = "Click on the button to validate the IP Address.<br>" + addr; function GFG_Fun() { down.innerHTML =/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(addr); } </script> </body></center> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: RegExp: Which split the IP address on :(colon) and check for each element whether they are valid or not(0000-ffff). Example 2: This example using the approach discussed above. html <!DOCTYPE HTML><html> <head> <title> How to check for IP address using regular expression in javascript? </title></head><center> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var addr = '2001:0db8:0000:0000:0000:ff00:0042:8329'; up.innerHTML = "Click on the button to validate the IP Address.<br>" + addr; function GFG_Fun() { down.innerHTML =/^[a-fA-F0-9]{1, 4}\:[a-fA-F0-9]{1, 4}\:[a-fA-F0-9]{1, 4}\:[a-fA-F0-9]{1, 4}\:[a-fA-F0-9]{1, 4}\:[a-fA-F0-9]{1, 4}\:[a-fA-F0-9]{1, 4}\:[a-fA-F0-9]{1, 4}$/.test(addr); } </script> </body></center> </html> Output: Before clicking on the button: After clicking on the button: sumitgumber28 JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26277, "s": 26249, "text": "\n14 Jan, 2022" }, { "code": null, "e": 26411, "s": 26277, "text": "The task is to validate the IP address both IPv4 as well as IPv6. Here we are going to use RegExp to solve the problem. Approach 1: " }, { "code": null, "e": 26521, "s": 26411, "text": "RegExp: Which split the IP address on .(dot) and check for each element whether they are valid or not(0-255)." }, { "code": null, "e": 26582, "s": 26521, "text": "Example 1: This example using the approach discussed above. " }, { "code": null, "e": 26587, "s": 26582, "text": "html" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to check for IP address using regular expression in javascript? </title></head><center> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var addr = '172.169.43.1'; up.innerHTML = \"Click on the button to validate the IP Address.<br>\" + addr; function GFG_Fun() { down.innerHTML =/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(addr); } </script> </body></center> </html>", "e": 27734, "s": 26587, "text": null }, { "code": null, "e": 27743, "s": 27734, "text": "Output: " }, { "code": null, "e": 27775, "s": 27743, "text": "Before clicking on the button: " }, { "code": null, "e": 27806, "s": 27775, "text": "After clicking on the button: " }, { "code": null, "e": 27820, "s": 27806, "text": "Approach 2: " }, { "code": null, "e": 27936, "s": 27820, "text": "RegExp: Which split the IP address on :(colon) and check for each element whether they are valid or not(0000-ffff)." }, { "code": null, "e": 27997, "s": 27936, "text": "Example 2: This example using the approach discussed above. " }, { "code": null, "e": 28002, "s": 27997, "text": "html" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to check for IP address using regular expression in javascript? </title></head><center> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var addr = '2001:0db8:0000:0000:0000:ff00:0042:8329'; up.innerHTML = \"Click on the button to validate the IP Address.<br>\" + addr; function GFG_Fun() { down.innerHTML =/^[a-fA-F0-9]{1, 4}\\:[a-fA-F0-9]{1, 4}\\:[a-fA-F0-9]{1, 4}\\:[a-fA-F0-9]{1, 4}\\:[a-fA-F0-9]{1, 4}\\:[a-fA-F0-9]{1, 4}\\:[a-fA-F0-9]{1, 4}\\:[a-fA-F0-9]{1, 4}$/.test(addr); } </script> </body></center> </html>", "e": 29168, "s": 28002, "text": null }, { "code": null, "e": 29177, "s": 29168, "text": "Output: " }, { "code": null, "e": 29209, "s": 29177, "text": "Before clicking on the button: " }, { "code": null, "e": 29240, "s": 29209, "text": "After clicking on the button: " }, { "code": null, "e": 29254, "s": 29240, "text": "sumitgumber28" }, { "code": null, "e": 29270, "s": 29254, "text": "JavaScript-Misc" }, { "code": null, "e": 29281, "s": 29270, "text": "JavaScript" }, { "code": null, "e": 29298, "s": 29281, "text": "Web Technologies" }, { "code": null, "e": 29325, "s": 29298, "text": "Web technologies Questions" }, { "code": null, "e": 29423, "s": 29325, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29463, "s": 29423, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29508, "s": 29463, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29569, "s": 29508, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29641, "s": 29569, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29687, "s": 29641, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 29727, "s": 29687, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29760, "s": 29727, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29805, "s": 29760, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29848, "s": 29805, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | Pandas dataframe.assign() - GeeksforGeeks
16 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Dataframe.assign() method assign new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original ones. Existing columns that are re-assigned will be overwritten. Length of newly assigned column must match the number of rows in the dataframe. Syntax: DataFrame.assign(**kwargs) Parameters:kwargs : keywords are the column names. If the values are callable, they are computed on the DataFrame and assigned to the new columns. The callable must not change input DataFrame (though pandas don’t check it). If the values are not callable, (e.g. a Series, scalar, or array), they are simply assigned. Returns: A new DataFrame with the new columns in addition to all the existing columns. For link to CSV file Used in Code, click here Example #1: Assign a new column called Revised_Salary with 10% increment of the original Salary. # importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv("nba.csv") # Printing the first 10 rows of# the data frame for visualizationdf[:10] # increase the salary by 10 % df.assign(Revised_Salary = lambda x: df['Salary'] + df['Salary']/10) Output: Example #2: Assigning more than one column at a time # importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv("nba.csv") # First column ='New_Team', this column# will append '_GO' at the end of each team name.# Second column ='Revised_Salary' will increase # the salary of all employees by 10 % df.assign(New_team = lambda x: df['Team']+'_GO', Revised_Salary = lambda x: df['Salary'] + df['Salary'] / 10) Output: Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python sum() function in Python
[ { "code": null, "e": 26129, "s": 26101, "text": "\n16 Nov, 2018" }, { "code": null, "e": 26343, "s": 26129, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26544, "s": 26343, "text": "Dataframe.assign() method assign new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original ones. Existing columns that are re-assigned will be overwritten." }, { "code": null, "e": 26624, "s": 26544, "text": "Length of newly assigned column must match the number of rows in the dataframe." }, { "code": null, "e": 26659, "s": 26624, "text": "Syntax: DataFrame.assign(**kwargs)" }, { "code": null, "e": 26976, "s": 26659, "text": "Parameters:kwargs : keywords are the column names. If the values are callable, they are computed on the DataFrame and assigned to the new columns. The callable must not change input DataFrame (though pandas don’t check it). If the values are not callable, (e.g. a Series, scalar, or array), they are simply assigned." }, { "code": null, "e": 27063, "s": 26976, "text": "Returns: A new DataFrame with the new columns in addition to all the existing columns." }, { "code": null, "e": 27109, "s": 27063, "text": "For link to CSV file Used in Code, click here" }, { "code": null, "e": 27206, "s": 27109, "text": "Example #1: Assign a new column called Revised_Salary with 10% increment of the original Salary." }, { "code": "# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv(\"nba.csv\") # Printing the first 10 rows of# the data frame for visualizationdf[:10]", "e": 27390, "s": 27206, "text": null }, { "code": "# increase the salary by 10 % df.assign(Revised_Salary = lambda x: df['Salary'] + df['Salary']/10)", "e": 27519, "s": 27390, "text": null }, { "code": null, "e": 27527, "s": 27519, "text": "Output:" }, { "code": null, "e": 27581, "s": 27527, "text": " Example #2: Assigning more than one column at a time" }, { "code": "# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv(\"nba.csv\") # First column ='New_Team', this column# will append '_GO' at the end of each team name.# Second column ='Revised_Salary' will increase # the salary of all employees by 10 % df.assign(New_team = lambda x: df['Team']+'_GO', Revised_Salary = lambda x: df['Salary'] + df['Salary'] / 10)", "e": 28015, "s": 27581, "text": null }, { "code": null, "e": 28023, "s": 28015, "text": "Output:" }, { "code": null, "e": 28047, "s": 28023, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28079, "s": 28047, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 28093, "s": 28079, "text": "Python-pandas" }, { "code": null, "e": 28100, "s": 28093, "text": "Python" }, { "code": null, "e": 28198, "s": 28100, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28216, "s": 28198, "text": "Python Dictionary" }, { "code": null, "e": 28248, "s": 28216, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28270, "s": 28248, "text": "Enumerate() in Python" }, { "code": null, "e": 28312, "s": 28270, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28341, "s": 28312, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28385, "s": 28341, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28422, "s": 28385, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28458, "s": 28422, "text": "Convert integer to string in Python" }, { "code": null, "e": 28500, "s": 28458, "text": "Check if element exists in list in Python" } ]
Last Minute Notes - DBMS - GeeksforGeeks
28 Jun, 2021 See Last Minute Notes on all subjects here. We will discuss the important key points useful for GATE exams in summarized form. For details you may refer this. E-R Diagram: The most common asked questions in ER diagram is minimum number of tables required for a given ER diagram. Generally, following criteria are used: Note: This is a general observation. Special cases need to be taken care. We may need extra table if attribute of a relationship can’t be moved to any entity side. Keys of a relation: There are various types of keys in a relation which are: Candidate Key: The minimal set of attributes which can determine a tuple uniquely. There can be more than 1 candidate key of a relation and its proper subset can’t determine tuple uniquely and it can’t be NULL. Super Key: The set of attributes which can determine a tuple uniquely. A candidate key is always a super key but vice versa is not true. Primary Key and Alternate Key: Among various candidate keys, one key is taken primary key and others are alternate keys. Foreign Key: Foreign Key is a set of attributes in a table which is used to refer the primary key or alternative key of the same or other table. Normal Forms First Normal Form: A relation is in first normal form if it does not contain any multi-valued or composite attribute. Second Normal Form: A relation is in second normal form if it does not contain any partial dependency. A dependency is called partial dependency if any proper subset of candidate key determines non-prime (which are not part of candidate key) attribute. Third Normal Form: A relation is in third normal form if it does not contain any transitive dependency. For a relation to be in Third Normal Form, either LHS of FD should be super key or RHS should be prime attribute. Boyce-Codd Normal Form: A relation is in Boyce-Codd Normal Form if LHS of every FD is super key. The relationship between Normal Forms can be represented as: 1NF⊃2NF ⊃3NF ⊃BCNF Relational Algebra: Procedural language with basic and extended operators. ⋈c(Conditional Join) ⋈(Equi Join) ⋈(Natural Join) ⟕(Left Outer Join) ⟖(Right Outer Join) ⟗(Full Outer Join) /(Division Operator) How to solve Relational Algebra problems for GATE – SET 1How to solve Relational Algebra problems for GATE – SET 2 SQL: As opposed to Relational Algebra, SQL is a non-procedural language. Conflict serializable and Conflict Equivalent: A schedule is conflict serializable if it is conflict equivalent to a serial schedule. Checking for Conflict Serializability To check whether a schedule is conflict serializable or not, find all conflicting operations pairs of a schedule and draw precedence graph ( For all conflicting operation pair, an edge from Ti to Tj if one operation of conflicting pair is from Ti and other from Tj and operation of Ti occurs before Tj in schedule). If graph does not contain cycle, the schedule is conflict serializable else it is not conflict serializable. Schedules are said to be conflict equivalent if 1 schedule can be converted into another by swapping non conflicting operations. Note: Two phase locking protocol produce conflict serializable schedule but may suffer from deadlock. On the other hand, Time-Stamp based protocols are free from deadlock yet produce conflict serializable schedule. View Serializable and View Equivalence : Two schedules S1 and S2 are said to be view-equivalent if all conditions are satisfied for all objects: If the transaction Ti in S1 reads an initial value for object X, in S2 also, Ti must read the initial value of X. If the transaction Ti in S1 reads an initial value for object X, in S2 also, Ti must read the initial value of X. If the transaction Ti in S1 reads the value written by transaction Tj in S1 for object X, same should be done in S2. If the transaction Ti in S1 reads the value written by transaction Tj in S1 for object X, same should be done in S2. If the transaction Ti in S1 is the final transaction to write the value for an object X, in S2 also, Ti must write the final value of X. If the transaction Ti in S1 is the final transaction to write the value for an object X, in S2 also, Ti must write the final value of X. A schedule is view serializable if it is view equivalent to any serial schedule. Irrecoverable Schedules: For a transaction pair < Ti, Tj >, if Tj is reading the value updated by Ti and Tj is committed before commit of Ti, the schedule will be irrecoverable. Recoverable Schedules: For a transaction pair < Ti, Tj >, if Tj is reading the value updated by Ti and Tj is committed after commit of Ti, the schedule will be recoverable. Cascadeless Recoverable Schedules: For a transaction pair < Ti, Tj >, if value updated by Ti is read by Tj only after commit of Ti, the schedule will be cascadeless recoverable. Strict Recoverable: For a transaction pair < Ti, Tj >, if value updated by Ti is read or written by Tj only after commit of Ti, the schedule will be strict recoverable. The relationship between them can be represented as: Strict ⊂ Cascadeless Recoverable ⊂ recoverable ⊂ all schedules Primary Index :: A primary index is an ordered file, records of fixed length with two fields. First field is same as primary key as data file and second field is a pointer to data block, where the key is available. The average number of block accesses using index = log2 Bi + 1, where Bi = number of index blocks. Clustering Index : Clustering index is created on data file whose records are physically ordered on a non-key field (called Clustering field). Secondary Index : Secondary index provides secondary means of accessing a file for which primary access already exists. Number of index entries = Number of records B TreesAt every level , we have Key and Data Pointer and data pointer points to either block or record. Properties of B-Trees :Root of B-tree can have children between 2 and P, where P is Order of tree. Order of tree – Maximum number of children a node can have. Internal node can have children between ⌈ P/2 ⌉ and PInternal node can have keys between ⌈ P/2 ⌉ – 1 and P-1 B+ TreesIn B+ trees structure of leaf and non-leaf are different, so their order is. Order of non-leaf will be higher as compared to leaf nodes. Searching time will be less in B+ tress, since it doesn’t have record pointers in non-leaf because of which depth will decrease. This article has been contributed by Sonal Tuteja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Difference between Clustered and Non-clustered index Data Preprocessing in Data Mining Difference between SQL and NoSQL Difference between DDL and DML in DBMS Difference between DELETE, DROP and TRUNCATE Indexing in Databases | Set 1 Third Normal Form (3NF) Deadlock in DBMS Difference between DELETE and TRUNCATE
[ { "code": null, "e": 25497, "s": 25469, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25541, "s": 25497, "text": "See Last Minute Notes on all subjects here." }, { "code": null, "e": 25656, "s": 25541, "text": "We will discuss the important key points useful for GATE exams in summarized form. For details you may refer this." }, { "code": null, "e": 25820, "s": 25660, "text": "E-R Diagram: The most common asked questions in ER diagram is minimum number of tables required for a given ER diagram. Generally, following criteria are used:" }, { "code": null, "e": 25990, "s": 25826, "text": "Note: This is a general observation. Special cases need to be taken care. We may need extra table if attribute of a relationship can’t be moved to any entity side." }, { "code": null, "e": 26071, "s": 25994, "text": "Keys of a relation: There are various types of keys in a relation which are:" }, { "code": null, "e": 26282, "s": 26071, "text": "Candidate Key: The minimal set of attributes which can determine a tuple uniquely. There can be more than 1 candidate key of a relation and its proper subset can’t determine tuple uniquely and it can’t be NULL." }, { "code": null, "e": 26419, "s": 26282, "text": "Super Key: The set of attributes which can determine a tuple uniquely. A candidate key is always a super key but vice versa is not true." }, { "code": null, "e": 26540, "s": 26419, "text": "Primary Key and Alternate Key: Among various candidate keys, one key is taken primary key and others are alternate keys." }, { "code": null, "e": 26685, "s": 26540, "text": "Foreign Key: Foreign Key is a set of attributes in a table which is used to refer the primary key or alternative key of the same or other table." }, { "code": null, "e": 26700, "s": 26687, "text": "Normal Forms" }, { "code": null, "e": 26818, "s": 26700, "text": "First Normal Form: A relation is in first normal form if it does not contain any multi-valued or composite attribute." }, { "code": null, "e": 27071, "s": 26818, "text": "Second Normal Form: A relation is in second normal form if it does not contain any partial dependency. A dependency is called partial dependency if any proper subset of candidate key determines non-prime (which are not part of candidate key) attribute." }, { "code": null, "e": 27289, "s": 27071, "text": "Third Normal Form: A relation is in third normal form if it does not contain any transitive dependency. For a relation to be in Third Normal Form, either LHS of FD should be super key or RHS should be prime attribute." }, { "code": null, "e": 27466, "s": 27289, "text": "Boyce-Codd Normal Form: A relation is in Boyce-Codd Normal Form if LHS of every FD is super key. The relationship between Normal Forms can be represented as: 1NF⊃2NF ⊃3NF ⊃BCNF" }, { "code": null, "e": 27545, "s": 27470, "text": "Relational Algebra: Procedural language with basic and extended operators." }, { "code": null, "e": 27574, "s": 27553, "text": "⋈c(Conditional Join)" }, { "code": null, "e": 27587, "s": 27574, "text": "⋈(Equi Join)" }, { "code": null, "e": 27603, "s": 27587, "text": "⋈(Natural Join)" }, { "code": null, "e": 27622, "s": 27603, "text": "⟕(Left Outer Join)" }, { "code": null, "e": 27642, "s": 27622, "text": "⟖(Right Outer Join)" }, { "code": null, "e": 27661, "s": 27642, "text": "⟗(Full Outer Join)" }, { "code": null, "e": 27682, "s": 27661, "text": "/(Division Operator)" }, { "code": null, "e": 27872, "s": 27682, "text": " How to solve Relational Algebra problems for GATE – SET 1How to solve Relational Algebra problems for GATE – SET 2 SQL: As opposed to Relational Algebra, SQL is a non-procedural language." }, { "code": null, "e": 28010, "s": 27876, "text": "Conflict serializable and Conflict Equivalent: A schedule is conflict serializable if it is conflict equivalent to a serial schedule." }, { "code": null, "e": 28048, "s": 28010, "text": "Checking for Conflict Serializability" }, { "code": null, "e": 28473, "s": 28048, "text": "To check whether a schedule is conflict serializable or not, find all conflicting operations pairs of a schedule and draw precedence graph ( For all conflicting operation pair, an edge from Ti to Tj if one operation of conflicting pair is from Ti and other from Tj and operation of Ti occurs before Tj in schedule). If graph does not contain cycle, the schedule is conflict serializable else it is not conflict serializable." }, { "code": null, "e": 28602, "s": 28473, "text": "Schedules are said to be conflict equivalent if 1 schedule can be converted into another by swapping non conflicting operations." }, { "code": null, "e": 28817, "s": 28602, "text": "Note: Two phase locking protocol produce conflict serializable schedule but may suffer from deadlock. On the other hand, Time-Stamp based protocols are free from deadlock yet produce conflict serializable schedule." }, { "code": null, "e": 28962, "s": 28817, "text": "View Serializable and View Equivalence : Two schedules S1 and S2 are said to be view-equivalent if all conditions are satisfied for all objects:" }, { "code": null, "e": 29076, "s": 28962, "text": "If the transaction Ti in S1 reads an initial value for object X, in S2 also, Ti must read the initial value of X." }, { "code": null, "e": 29190, "s": 29076, "text": "If the transaction Ti in S1 reads an initial value for object X, in S2 also, Ti must read the initial value of X." }, { "code": null, "e": 29307, "s": 29190, "text": "If the transaction Ti in S1 reads the value written by transaction Tj in S1 for object X, same should be done in S2." }, { "code": null, "e": 29424, "s": 29307, "text": "If the transaction Ti in S1 reads the value written by transaction Tj in S1 for object X, same should be done in S2." }, { "code": null, "e": 29561, "s": 29424, "text": "If the transaction Ti in S1 is the final transaction to write the value for an object X, in S2 also, Ti must write the final value of X." }, { "code": null, "e": 29698, "s": 29561, "text": "If the transaction Ti in S1 is the final transaction to write the value for an object X, in S2 also, Ti must write the final value of X." }, { "code": null, "e": 29779, "s": 29698, "text": "A schedule is view serializable if it is view equivalent to any serial schedule." }, { "code": null, "e": 29959, "s": 29781, "text": "Irrecoverable Schedules: For a transaction pair < Ti, Tj >, if Tj is reading the value updated by Ti and Tj is committed before commit of Ti, the schedule will be irrecoverable." }, { "code": null, "e": 30134, "s": 29961, "text": "Recoverable Schedules: For a transaction pair < Ti, Tj >, if Tj is reading the value updated by Ti and Tj is committed after commit of Ti, the schedule will be recoverable." }, { "code": null, "e": 30314, "s": 30136, "text": "Cascadeless Recoverable Schedules: For a transaction pair < Ti, Tj >, if value updated by Ti is read by Tj only after commit of Ti, the schedule will be cascadeless recoverable." }, { "code": null, "e": 30539, "s": 30316, "text": "Strict Recoverable: For a transaction pair < Ti, Tj >, if value updated by Ti is read or written by Tj only after commit of Ti, the schedule will be strict recoverable. The relationship between them can be represented as: " }, { "code": null, "e": 30604, "s": 30541, "text": "Strict ⊂ Cascadeless Recoverable ⊂ recoverable ⊂ all schedules" }, { "code": null, "e": 30821, "s": 30606, "text": "Primary Index :: A primary index is an ordered file, records of fixed length with two fields. First field is same as primary key as data file and second field is a pointer to data block, where the key is available." }, { "code": null, "e": 31183, "s": 30821, "text": "The average number of block accesses using index = log2 Bi + 1, where Bi = number of index blocks. Clustering Index : Clustering index is created on data file whose records are physically ordered on a non-key field (called Clustering field). Secondary Index : Secondary index provides secondary means of accessing a file for which primary access already exists." }, { "code": null, "e": 31228, "s": 31183, "text": " Number of index entries = Number of records" }, { "code": null, "e": 31334, "s": 31230, "text": "B TreesAt every level , we have Key and Data Pointer and data pointer points to either block or record." }, { "code": null, "e": 31433, "s": 31334, "text": "Properties of B-Trees :Root of B-tree can have children between 2 and P, where P is Order of tree." }, { "code": null, "e": 31493, "s": 31433, "text": "Order of tree – Maximum number of children a node can have." }, { "code": null, "e": 31602, "s": 31493, "text": "Internal node can have children between ⌈ P/2 ⌉ and PInternal node can have keys between ⌈ P/2 ⌉ – 1 and P-1" }, { "code": null, "e": 31747, "s": 31602, "text": "B+ TreesIn B+ trees structure of leaf and non-leaf are different, so their order is. Order of non-leaf will be higher as compared to leaf nodes." }, { "code": null, "e": 31876, "s": 31747, "text": "Searching time will be less in B+ tress, since it doesn’t have record pointers in non-leaf because of which depth will decrease." }, { "code": null, "e": 31928, "s": 31876, "text": "This article has been contributed by Sonal Tuteja. " }, { "code": null, "e": 32052, "s": 31928, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 32057, "s": 32052, "text": "DBMS" }, { "code": null, "e": 32062, "s": 32057, "text": "DBMS" }, { "code": null, "e": 32160, "s": 32062, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32171, "s": 32160, "text": "CTE in SQL" }, { "code": null, "e": 32224, "s": 32171, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 32258, "s": 32224, "text": "Data Preprocessing in Data Mining" }, { "code": null, "e": 32291, "s": 32258, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 32330, "s": 32291, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 32375, "s": 32330, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 32405, "s": 32375, "text": "Indexing in Databases | Set 1" }, { "code": null, "e": 32429, "s": 32405, "text": "Third Normal Form (3NF)" }, { "code": null, "e": 32446, "s": 32429, "text": "Deadlock in DBMS" } ]
Find index of an extra element present in one sorted array - GeeksforGeeks
25 Jun, 2021 Given two sorted arrays. There is only 1 difference between the arrays. The first array has one element extra added in between. Find the index of the extra element. Examples: Input: {2, 4, 6, 8, 9, 10, 12}; {2, 4, 6, 8, 10, 12}; Output: 4 Explanation: The first array has an extra element 9. The extra element is present at index 4. Input: {3, 5, 7, 9, 11, 13} {3, 5, 7, 11, 13} Output: 3 Explanation: The first array has an extra element 9. The extra element is present at index 3. Method 1: This includes the basic approach to solve this particular problem. Approach: The basic method is to iterate through the whole second array and check element by element if they are different. As the array is sorted, checking the adjacent position of two arrays should be similar until and unless the missing element is found. Algorithm: Traverse through the array from start to end.Check if the element at i’th element of the two arrays is similar or not.If the elements are not similar then print the index and break Traverse through the array from start to end. Check if the element at i’th element of the two arrays is similar or not. If the elements are not similar then print the index and break Implementation: C++ Java Python3 C# PHP Javascript // C++ program to find an extra// element present in arr1[]#include <iostream>using namespace std; // Returns index of extra element// in arr1[]. n is size of arr2[].// Size of arr1[] is n-1.int findExtra(int arr1[], int arr2[], int n){for (int i = 0; i < n; i++) if (arr1[i] != arr2[i]) return i; return n;} // Driver codeint main(){ int arr1[] = {2, 4, 6, 8, 10, 12, 13}; int arr2[] = {2, 4, 6, 8, 10, 12}; int n = sizeof(arr2) / sizeof(arr2[0]); // Solve is passed both arrays cout << findExtra(arr1, arr2, n); return 0;} // Java program to find an extra// element present in arr1[]class GFG{ // Returns index of extra element // in arr1[]. n is size of arr2[]. // Size of arr1[] is n-1. static int findExtra(int arr1[], int arr2[], int n) { for (int i = 0; i < n; i++) if (arr1[i] != arr2[i]) return i; return n; } // Driver Code public static void main (String[] args) { int arr1[] = {2, 4, 6, 8, 10, 12, 13}; int arr2[] = {2, 4, 6, 8, 10, 12}; int n = arr2.length; // Solve is passed both arrays System.out.println(findExtra(arr1, arr2, n)); }} // This code is contributed by Harsh Agarwal # Python 3 program to find an# extra element present in arr1[] # Returns index of extra .# element in arr1[] n is# size of arr2[]. Size of# arr1[] is n-1.def findExtra(arr1, arr2, n) : for i in range(0, n) : if (arr1[i] != arr2[i]) : return i return n # Driver codearr1 = [2, 4, 6, 8, 10, 12, 13]arr2 = [2, 4, 6, 8, 10, 12]n = len(arr2) # Solve is passed both arraysprint(findExtra(arr1, arr2, n)) # This code is contributed# by Nikita Tiwari. // C# program to find an extra// element present in arr1[]using System; class GfG{ // Returns index of extra // element in arr1[]. n is // size of arr2[]. Size of // arr1[] is n-1. static int findExtra(int []arr1, int []arr2, int n) { for (int i = 0; i < n; i++) if (arr1[i] != arr2[i]) return i; return n; } // Driver code public static void Main () { int []arr1 = {2, 4, 6, 8, 10, 12, 13}; int []arr2 = {2, 4, 6, 8, 10, 12}; int n = arr2.Length; // Solve is passed both arrays Console.Write(findExtra(arr1, arr2, n)); }} // This code is contributed by parashar. <?php// PHP program to find an extra// element present in arr1[] // Returns index of extra element// in arr1[]. n is size of arr2[].// Size of arr1[] is n-1.function findExtra($arr1, $arr2, $n){for ($i = 0; $i < $n; $i++) if ($arr1[$i] != $arr2[$i]) return $i; return $n;} // Driver code$arr1 = array (2, 4, 6, 8, 10, 12, 13);$arr2 = array(2, 4, 6, 8, 10, 12);$n = sizeof($arr2); // Solve is passed// both arraysecho findExtra($arr1, $arr2, $n); // This code is contributed by ajit?> <script>// JavaScript program to find an extra// element present in arr1[] // Returns index of extra element// in arr1[]. n is size of arr2[].// Size of arr1[] is n-1.function findExtra(arr1, arr2, n){for (let i = 0; i < n; i++) if (arr1[i] != arr2[i]) return i; return n;} // Driver code let arr1 = [2, 4, 6, 8, 10, 12, 13]; let arr2 = [2, 4, 6, 8, 10, 12]; let n = arr2.length; // Solve is passed both arrays document.write(findExtra(arr1, arr2, n)); // This code is contributed by Surbhi Tyagi.</script> Output : 6 Complexity Analysis: Time complexity: O(n). As one traversal through the array is needed, so the time complexity is linear. Space complexity: O(1). Since no extra space is required, the time complexity is constant. Method 2: This method is a better way to solve the above problem and uses the concept of binary search. Approach:To find the index of the missing element in less than linear time, binary search can be used, the idea is all the indices greater than or equal to the index of the missing element will have different elements in both the arrays and all the indices less than that index will have the similar elements in both arrays. Algorithm: Create three variables, low = 0, high = n-1, mid, ans = nRun a loop until low is less than or equal to high, i.e till our search range is less than zero.If the mid element, i.e (low + high)/2, of both arrays is similar then update the search to second half of the search range, i.e low = mid + 1Else update the search to the first half of the search range, i.e high = mid – 1, and update the answer to the current index, ans = midPrint the index. Create three variables, low = 0, high = n-1, mid, ans = n Run a loop until low is less than or equal to high, i.e till our search range is less than zero. If the mid element, i.e (low + high)/2, of both arrays is similar then update the search to second half of the search range, i.e low = mid + 1 Else update the search to the first half of the search range, i.e high = mid – 1, and update the answer to the current index, ans = mid Print the index. Implementation: C++ Java Python3 C# PHP Javascript // C++ program to find an extra// element present in arr1[]#include <iostream>using namespace std; // Returns index of extra element// in arr1[]. n is size of arr2[].// Size of arr1[] is n-1.int findExtra(int arr1[], int arr2[], int n){ // Initialize result int index = n; // left and right are end // points denoting the current range. int left = 0, right = n - 1; while (left <= right) { int mid = (left + right) / 2; // If middle element is same // of both arrays, it means // that extra element is after // mid so we update left to mid+1 if (arr2[mid] == arr1[mid]) left = mid + 1; // If middle element is different // of the arrays, it means that // the index we are searching for // is either mid, or before mid. // Hence we update right to mid-1. else { index = mid; right = mid - 1; } } // when right is greater than // left our search is complete. return index;} // Driver codeint main(){ int arr1[] = {2, 4, 6, 8, 10, 12, 13}; int arr2[] = {2, 4, 6, 8, 10, 12}; int n = sizeof(arr2) / sizeof(arr2[0]); // Solve is passed both arrays cout << findExtra(arr1, arr2, n); return 0;} // Java program to find an extra// element present in arr1[]class GFG{ // Returns index of extra element // in arr1[]. n is size of arr2[]. // Size of arr1[] is n-1. static int findExtra(int arr1[], int arr2[], int n) { // Initialize result int index = n; // left and right are end // points denoting the current range. int left = 0, right = n - 1; while (left <= right) { int mid = (left+right) / 2; // If middle element is same // of both arrays, it means // that extra element is after // mid so we update left to mid+1 if (arr2[mid] == arr1[mid]) left = mid + 1; // If middle element is different // of the arrays, it means that // the index we are searching for // is either mid, or before mid. // Hence we update right to mid-1. else { index = mid; right = mid - 1; } } // when right is greater than // left, our search is complete. return index; } // Driver Code public static void main (String[] args) { int arr1[] = {2, 4, 6, 8, 10, 12,13}; int arr2[] = {2, 4, 6, 8, 10, 12}; int n = arr2.length; // Solve is passed both arrays System.out.println(findExtra(arr1, arr2, n)); }} // This code is contributed by Harsh Agarwal # Python3 program to find an extra# element present in arr1[] # Returns index of extra element# in arr1[]. n is size of arr2[].# Size of arr1[] is n-1.def findExtra(arr1, arr2, n) : index = n # Initialize result # left and right are end points # denoting the current range. left = 0 right = n - 1 while (left <= right) : mid = (int)((left + right) / 2) # If middle element is same # of both arrays, it means # that extra element is after # mid so we update left to # mid + 1 if (arr2[mid] == arr1[mid]) : left = mid + 1 # If middle element is different # of the arrays, it means that # the index we are searching for # is either mid, or before mid. # Hence we update right to mid-1. else : index = mid right = mid - 1 # when right is greater than left our # search is complete. return index # Driver codearr1 = [2, 4, 6, 8, 10, 12, 13]arr2 = [2, 4, 6, 8, 10, 12]n = len(arr2) # Solve is passed both arraysprint(findExtra(arr1, arr2, n)) # This code is contributed by Nikita Tiwari. // C# program to find an extra// element present in arr1[]using System; class GFG { // Returns index of extra // element in arr1[]. n is // size of arr2[]. // Size of arr1[] is // n - 1. static int findExtra(int []arr1, int []arr2, int n) { // Initialize result int index = n; // left and right are // end points denoting // the current range. int left = 0, right = n - 1; while (left <= right) { int mid = (left+right) / 2; // If middle element is // same of both arrays, // it means that extra // element is after mid // so we update left // to mid + 1 if (arr2[mid] == arr1[mid]) left = mid + 1; // If middle element is // different of the arrays, // it means that the index // we are searching for is // either mid, or before mid. // Hence we update right to mid-1. else { index = mid; right = mid - 1; } } // when right is greater // than left our // search is complete. return index; } // Driver Code public static void Main () { int []arr1 = {2, 4, 6, 8, 10, 12,13}; int []arr2 = {2, 4, 6, 8, 10, 12}; int n = arr2.Length; // Solve is passed // both arrays Console.Write(findExtra(arr1, arr2, n)); }} // This code is contributed by nitin mittal. <?php// PHP program to find an extra// element present in arr1[] // Returns index of extra element// in arr1[]. n is size of arr2[].// Size of arr1[] is n-1.function findExtra($arr1, $arr2, $n){ // Initialize result $index = $n; // left and right are // end points denoting // the current range. $left = 0; $right = $n - 1; while ($left <= $right) { $mid = ($left+$right) / 2; // If middle element is same // of both arrays, it means // that extra element is after // mid so we update left to mid+1 if ($arr2[$mid] == $arr1[$mid]) $left = $mid + 1; // If middle element is different // of the arrays, it means that the // index we are searching for is either // mid, or before mid. Hence we update // right to mid-1. else { $index = $mid; $right = $mid - 1; } } // when right is greater than // left, our search is complete. return $index;} // Driver code{ $arr1 = array(2, 4, 6, 8, 10, 12, 13); $arr2 = array(2, 4, 6, 8, 10, 12); $n = sizeof($arr2) / sizeof($arr2[0]); // Solve is passed both arrays echo findExtra($arr1, $arr2, $n); return 0;} // This code is contributed by nitin mittal?> <script> // Javascript program to find an extra// element present in arr1[] // Returns index of extra element// in arr1[]. n is size of arr2[].// Size of arr1[] is n-1.function findExtra( arr1, arr2, n){ // Initialize result let index = n; // left and right are end // points denoting the current range. let left = 0, right = n - 1; while (left <= right) { let mid = Math.floor((left + right) / 2); // If middle element is same // of both arrays, it means // that extra element is after // mid so we update left to mid+1 if (arr2[mid] == arr1[mid]) left = mid + 1; // If middle element is different // of the arrays, it means that // the index we are searching for // is either mid, or before mid. // Hence we update right to mid-1. else { index = mid; right = mid - 1; } } // when right is greater than // left our search is complete. return index;} // Driver program let arr1 = [2, 4, 6, 8, 10, 12, 13]; let arr2 = [2, 4, 6, 8, 10, 12]; let n = arr2.length; // Solve is passed both arrays document.write(findExtra(arr1, arr2, n)); </script> Output : 6 Complexity Analysis: Time complexity : O(log n). The time complexity of binary search is O(log n) Space complexity : O(1). As no extra space is required, so the time complexity is constant. Method 3: This method solves the given problem using the predefined function. Approach: To find the element which is different, find the sum of each array and subtract the sums and find the absolute value. Search the larger array and check if the absolute is equal to an index and return that index. If an element is missing and all the other elements are the same, then the difference of sums will be equal to missing element. Algorithm: Create a function to calculate the sum of two arrays.Find the absolute difference between the sum of two arrays (value).Traverse the larger array from start too endIf the element at any index is equal to value, then print the index and break the loop. Create a function to calculate the sum of two arrays. Find the absolute difference between the sum of two arrays (value). Traverse the larger array from start too end If the element at any index is equal to value, then print the index and break the loop. Implementation: C++ Java Python3 C# Javascript // C++ code for above approach#include<bits/stdc++.h>using namespace std; // function return sum of array elementsint sum(int arr[], int n){ int summ = 0; for (int i = 0; i < n; i++) { summ += arr[i]; } return summ;} // function return index of given elementint indexOf(int arr[], int element, int n){ for (int i = 0; i < n; i++) { if (arr[i] == element) { return i; } } return -1;} // Function to find Indexint find_extra_element_index(int arrA[], int arrB[], int n, int m){ // Calculating extra element int extra_element = sum(arrA, n) - sum(arrB, m); // returns index of extra element return indexOf(arrA, extra_element, n);} // Driver Codeint main(){ int arrA[] = {2, 4, 6, 8, 10, 12, 13}; int arrB[] = {2, 4, 6, 8, 10, 12}; int n = sizeof(arrA) / sizeof(arrA[0]); int m = sizeof(arrB) / sizeof(arrB[0]); cout << find_extra_element_index(arrA, arrB, n, m);} // This code is contributed by mohit kumar // Java code for above approachclass GFG{ // Function to find Index static int find_extra_element_index(int[] arrA, int[] arrB) { // Calculating extra element int extra_element = sum(arrA) - sum(arrB); // returns index of extra element return indexOf(arrA, extra_element); } // function return sum of array elements static int sum(int[] arr) { int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } // function return index of given element static int indexOf(int[] arr, int element) { for (int i = 0; i < arr.length; i++) { if (arr[i] == element) { return i; } } return -1; } // Driver Code public static void main(String[] args) { int[] arrA = {2, 4, 6, 8, 10, 12, 13}; int[] arrB = {2, 4, 6, 8, 10, 12}; System.out.println(find_extra_element_index(arrA, arrB)); }} /* This code contributed by PrinciRaj1992 */ # Python3 code for above approach # Function to find Indexdef find_extra_element_index(arrA, arrB): # Calculating extra element extra_element = sum(arrA) - sum(arrB) # returns index of extra element return arrA.index(extra_element) # Driver CodearrA = [2, 4, 6, 8, 10, 12, 13]arrB = [2, 4, 6, 8, 10, 12]print(find_extra_element_index(arrA,arrB)) # This code is contributed by Dravid // C# code for above approachusing System; class GFG{ // Function to find Index static int find_extra_element_index(int[] arrA, int[] arrB) { // Calculating extra element int extra_element = sum(arrA) - sum(arrB); // returns index of extra element return indexOf(arrA, extra_element); } // function return sum of array elements static int sum(int[] arr) { int sum = 0; for (int i = 0; i < arr.Length; i++) { sum += arr[i]; } return sum; } // function return index of given element static int indexOf(int[] arr, int element) { for (int i = 0; i < arr.Length; i++) { if (arr[i] == element) { return i; } } return -1; } // Driver Code public static void Main(String[] args) { int[] arrA = {2, 4, 6, 8, 10, 12, 13}; int[] arrB = {2, 4, 6, 8, 10, 12}; Console.WriteLine(find_extra_element_index(arrA, arrB)); }} // This code has been contributed by 29AjayKumar <script> // Javascript code for above approach // Function to find Index function find_extra_element_index(arrA, arrB) { // Calculating extra element let extra_element = sum(arrA) - sum(arrB); // returns index of extra element return indexOf(arrA, extra_element); } // function return sum of array elements function sum(arr) { let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } // function return index of given element function indexOf(arr, element) { for (let i = 0; i < arr.length; i++) { if (arr[i] == element) { return i; } } return -1; } let arrA = [2, 4, 6, 8, 10, 12, 13]; let arrB = [2, 4, 6, 8, 10, 12]; document.write(find_extra_element_index(arrA, arrB)); </script> Output : 6 Complexity Analysis: Time Complexity: O(n). Since only three traversals through the array is needed, So the time complexity is linear. Space Complexity: O(1). As no extra space is required, so the time complexity is constant. This article is contributed by Abhishek Khatri . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. parashar nitin mittal jit_t princiraj1992 29AjayKumar mohit kumar 29 niteeshkumar2 andrew1234 tridib_samanta surbhityagi15 jana_sayantan decode2207 abhishek0719kadiyan sagar0719kumar Amazon Binary Search Zoho Arrays Divide and Conquer Searching Zoho Amazon Arrays Searching Divide and Conquer Binary Search 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 Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Merge Sort QuickSort Binary Search Maximum and minimum of an array using minimum number of comparisons Program for Tower of Hanoi
[ { "code": null, "e": 26699, "s": 26671, "text": "\n25 Jun, 2021" }, { "code": null, "e": 26864, "s": 26699, "text": "Given two sorted arrays. There is only 1 difference between the arrays. The first array has one element extra added in between. Find the index of the extra element." }, { "code": null, "e": 26875, "s": 26864, "text": "Examples: " }, { "code": null, "e": 27199, "s": 26875, "text": "Input: {2, 4, 6, 8, 9, 10, 12};\n {2, 4, 6, 8, 10, 12};\nOutput: 4\nExplanation: The first array has an extra element 9.\nThe extra element is present at index 4.\n\nInput: {3, 5, 7, 9, 11, 13}\n {3, 5, 7, 11, 13}\nOutput: 3\nExplanation: The first array has an extra element 9.\nThe extra element is present at index 3." }, { "code": null, "e": 27277, "s": 27199, "text": "Method 1: This includes the basic approach to solve this particular problem. " }, { "code": null, "e": 27536, "s": 27277, "text": "Approach: The basic method is to iterate through the whole second array and check element by element if they are different. As the array is sorted, checking the adjacent position of two arrays should be similar until and unless the missing element is found. " }, { "code": null, "e": 27548, "s": 27536, "text": "Algorithm: " }, { "code": null, "e": 27729, "s": 27548, "text": "Traverse through the array from start to end.Check if the element at i’th element of the two arrays is similar or not.If the elements are not similar then print the index and break" }, { "code": null, "e": 27775, "s": 27729, "text": "Traverse through the array from start to end." }, { "code": null, "e": 27849, "s": 27775, "text": "Check if the element at i’th element of the two arrays is similar or not." }, { "code": null, "e": 27912, "s": 27849, "text": "If the elements are not similar then print the index and break" }, { "code": null, "e": 27929, "s": 27912, "text": "Implementation: " }, { "code": null, "e": 27933, "s": 27929, "text": "C++" }, { "code": null, "e": 27938, "s": 27933, "text": "Java" }, { "code": null, "e": 27946, "s": 27938, "text": "Python3" }, { "code": null, "e": 27949, "s": 27946, "text": "C#" }, { "code": null, "e": 27953, "s": 27949, "text": "PHP" }, { "code": null, "e": 27964, "s": 27953, "text": "Javascript" }, { "code": "// C++ program to find an extra// element present in arr1[]#include <iostream>using namespace std; // Returns index of extra element// in arr1[]. n is size of arr2[].// Size of arr1[] is n-1.int findExtra(int arr1[], int arr2[], int n){for (int i = 0; i < n; i++) if (arr1[i] != arr2[i]) return i; return n;} // Driver codeint main(){ int arr1[] = {2, 4, 6, 8, 10, 12, 13}; int arr2[] = {2, 4, 6, 8, 10, 12}; int n = sizeof(arr2) / sizeof(arr2[0]); // Solve is passed both arrays cout << findExtra(arr1, arr2, n); return 0;}", "e": 28565, "s": 27964, "text": null }, { "code": "// Java program to find an extra// element present in arr1[]class GFG{ // Returns index of extra element // in arr1[]. n is size of arr2[]. // Size of arr1[] is n-1. static int findExtra(int arr1[], int arr2[], int n) { for (int i = 0; i < n; i++) if (arr1[i] != arr2[i]) return i; return n; } // Driver Code public static void main (String[] args) { int arr1[] = {2, 4, 6, 8, 10, 12, 13}; int arr2[] = {2, 4, 6, 8, 10, 12}; int n = arr2.length; // Solve is passed both arrays System.out.println(findExtra(arr1, arr2, n)); }} // This code is contributed by Harsh Agarwal", "e": 29343, "s": 28565, "text": null }, { "code": "# Python 3 program to find an# extra element present in arr1[] # Returns index of extra .# element in arr1[] n is# size of arr2[]. Size of# arr1[] is n-1.def findExtra(arr1, arr2, n) : for i in range(0, n) : if (arr1[i] != arr2[i]) : return i return n # Driver codearr1 = [2, 4, 6, 8, 10, 12, 13]arr2 = [2, 4, 6, 8, 10, 12]n = len(arr2) # Solve is passed both arraysprint(findExtra(arr1, arr2, n)) # This code is contributed# by Nikita Tiwari.", "e": 29815, "s": 29343, "text": null }, { "code": "// C# program to find an extra// element present in arr1[]using System; class GfG{ // Returns index of extra // element in arr1[]. n is // size of arr2[]. Size of // arr1[] is n-1. static int findExtra(int []arr1, int []arr2, int n) { for (int i = 0; i < n; i++) if (arr1[i] != arr2[i]) return i; return n; } // Driver code public static void Main () { int []arr1 = {2, 4, 6, 8, 10, 12, 13}; int []arr2 = {2, 4, 6, 8, 10, 12}; int n = arr2.Length; // Solve is passed both arrays Console.Write(findExtra(arr1, arr2, n)); }} // This code is contributed by parashar.", "e": 30577, "s": 29815, "text": null }, { "code": "<?php// PHP program to find an extra// element present in arr1[] // Returns index of extra element// in arr1[]. n is size of arr2[].// Size of arr1[] is n-1.function findExtra($arr1, $arr2, $n){for ($i = 0; $i < $n; $i++) if ($arr1[$i] != $arr2[$i]) return $i; return $n;} // Driver code$arr1 = array (2, 4, 6, 8, 10, 12, 13);$arr2 = array(2, 4, 6, 8, 10, 12);$n = sizeof($arr2); // Solve is passed// both arraysecho findExtra($arr1, $arr2, $n); // This code is contributed by ajit?>", "e": 31116, "s": 30577, "text": null }, { "code": "<script>// JavaScript program to find an extra// element present in arr1[] // Returns index of extra element// in arr1[]. n is size of arr2[].// Size of arr1[] is n-1.function findExtra(arr1, arr2, n){for (let i = 0; i < n; i++) if (arr1[i] != arr2[i]) return i; return n;} // Driver code let arr1 = [2, 4, 6, 8, 10, 12, 13]; let arr2 = [2, 4, 6, 8, 10, 12]; let n = arr2.length; // Solve is passed both arrays document.write(findExtra(arr1, arr2, n)); // This code is contributed by Surbhi Tyagi.</script>", "e": 31680, "s": 31116, "text": null }, { "code": null, "e": 31690, "s": 31680, "text": "Output : " }, { "code": null, "e": 31693, "s": 31690, "text": " 6" }, { "code": null, "e": 31715, "s": 31693, "text": "Complexity Analysis: " }, { "code": null, "e": 31818, "s": 31715, "text": "Time complexity: O(n). As one traversal through the array is needed, so the time complexity is linear." }, { "code": null, "e": 31909, "s": 31818, "text": "Space complexity: O(1). Since no extra space is required, the time complexity is constant." }, { "code": null, "e": 32014, "s": 31909, "text": "Method 2: This method is a better way to solve the above problem and uses the concept of binary search. " }, { "code": null, "e": 32339, "s": 32014, "text": "Approach:To find the index of the missing element in less than linear time, binary search can be used, the idea is all the indices greater than or equal to the index of the missing element will have different elements in both the arrays and all the indices less than that index will have the similar elements in both arrays." }, { "code": null, "e": 32351, "s": 32339, "text": "Algorithm: " }, { "code": null, "e": 32798, "s": 32351, "text": "Create three variables, low = 0, high = n-1, mid, ans = nRun a loop until low is less than or equal to high, i.e till our search range is less than zero.If the mid element, i.e (low + high)/2, of both arrays is similar then update the search to second half of the search range, i.e low = mid + 1Else update the search to the first half of the search range, i.e high = mid – 1, and update the answer to the current index, ans = midPrint the index." }, { "code": null, "e": 32856, "s": 32798, "text": "Create three variables, low = 0, high = n-1, mid, ans = n" }, { "code": null, "e": 32953, "s": 32856, "text": "Run a loop until low is less than or equal to high, i.e till our search range is less than zero." }, { "code": null, "e": 33096, "s": 32953, "text": "If the mid element, i.e (low + high)/2, of both arrays is similar then update the search to second half of the search range, i.e low = mid + 1" }, { "code": null, "e": 33232, "s": 33096, "text": "Else update the search to the first half of the search range, i.e high = mid – 1, and update the answer to the current index, ans = mid" }, { "code": null, "e": 33249, "s": 33232, "text": "Print the index." }, { "code": null, "e": 33266, "s": 33249, "text": "Implementation: " }, { "code": null, "e": 33270, "s": 33266, "text": "C++" }, { "code": null, "e": 33275, "s": 33270, "text": "Java" }, { "code": null, "e": 33283, "s": 33275, "text": "Python3" }, { "code": null, "e": 33286, "s": 33283, "text": "C#" }, { "code": null, "e": 33290, "s": 33286, "text": "PHP" }, { "code": null, "e": 33301, "s": 33290, "text": "Javascript" }, { "code": "// C++ program to find an extra// element present in arr1[]#include <iostream>using namespace std; // Returns index of extra element// in arr1[]. n is size of arr2[].// Size of arr1[] is n-1.int findExtra(int arr1[], int arr2[], int n){ // Initialize result int index = n; // left and right are end // points denoting the current range. int left = 0, right = n - 1; while (left <= right) { int mid = (left + right) / 2; // If middle element is same // of both arrays, it means // that extra element is after // mid so we update left to mid+1 if (arr2[mid] == arr1[mid]) left = mid + 1; // If middle element is different // of the arrays, it means that // the index we are searching for // is either mid, or before mid. // Hence we update right to mid-1. else { index = mid; right = mid - 1; } } // when right is greater than // left our search is complete. return index;} // Driver codeint main(){ int arr1[] = {2, 4, 6, 8, 10, 12, 13}; int arr2[] = {2, 4, 6, 8, 10, 12}; int n = sizeof(arr2) / sizeof(arr2[0]); // Solve is passed both arrays cout << findExtra(arr1, arr2, n); return 0;}", "e": 34589, "s": 33301, "text": null }, { "code": "// Java program to find an extra// element present in arr1[]class GFG{ // Returns index of extra element // in arr1[]. n is size of arr2[]. // Size of arr1[] is n-1. static int findExtra(int arr1[], int arr2[], int n) { // Initialize result int index = n; // left and right are end // points denoting the current range. int left = 0, right = n - 1; while (left <= right) { int mid = (left+right) / 2; // If middle element is same // of both arrays, it means // that extra element is after // mid so we update left to mid+1 if (arr2[mid] == arr1[mid]) left = mid + 1; // If middle element is different // of the arrays, it means that // the index we are searching for // is either mid, or before mid. // Hence we update right to mid-1. else { index = mid; right = mid - 1; } } // when right is greater than // left, our search is complete. return index; } // Driver Code public static void main (String[] args) { int arr1[] = {2, 4, 6, 8, 10, 12,13}; int arr2[] = {2, 4, 6, 8, 10, 12}; int n = arr2.length; // Solve is passed both arrays System.out.println(findExtra(arr1, arr2, n)); }} // This code is contributed by Harsh Agarwal", "e": 36115, "s": 34589, "text": null }, { "code": "# Python3 program to find an extra# element present in arr1[] # Returns index of extra element# in arr1[]. n is size of arr2[].# Size of arr1[] is n-1.def findExtra(arr1, arr2, n) : index = n # Initialize result # left and right are end points # denoting the current range. left = 0 right = n - 1 while (left <= right) : mid = (int)((left + right) / 2) # If middle element is same # of both arrays, it means # that extra element is after # mid so we update left to # mid + 1 if (arr2[mid] == arr1[mid]) : left = mid + 1 # If middle element is different # of the arrays, it means that # the index we are searching for # is either mid, or before mid. # Hence we update right to mid-1. else : index = mid right = mid - 1 # when right is greater than left our # search is complete. return index # Driver codearr1 = [2, 4, 6, 8, 10, 12, 13]arr2 = [2, 4, 6, 8, 10, 12]n = len(arr2) # Solve is passed both arraysprint(findExtra(arr1, arr2, n)) # This code is contributed by Nikita Tiwari.", "e": 37261, "s": 36115, "text": null }, { "code": "// C# program to find an extra// element present in arr1[]using System; class GFG { // Returns index of extra // element in arr1[]. n is // size of arr2[]. // Size of arr1[] is // n - 1. static int findExtra(int []arr1, int []arr2, int n) { // Initialize result int index = n; // left and right are // end points denoting // the current range. int left = 0, right = n - 1; while (left <= right) { int mid = (left+right) / 2; // If middle element is // same of both arrays, // it means that extra // element is after mid // so we update left // to mid + 1 if (arr2[mid] == arr1[mid]) left = mid + 1; // If middle element is // different of the arrays, // it means that the index // we are searching for is // either mid, or before mid. // Hence we update right to mid-1. else { index = mid; right = mid - 1; } } // when right is greater // than left our // search is complete. return index; } // Driver Code public static void Main () { int []arr1 = {2, 4, 6, 8, 10, 12,13}; int []arr2 = {2, 4, 6, 8, 10, 12}; int n = arr2.Length; // Solve is passed // both arrays Console.Write(findExtra(arr1, arr2, n)); }} // This code is contributed by nitin mittal.", "e": 38907, "s": 37261, "text": null }, { "code": "<?php// PHP program to find an extra// element present in arr1[] // Returns index of extra element// in arr1[]. n is size of arr2[].// Size of arr1[] is n-1.function findExtra($arr1, $arr2, $n){ // Initialize result $index = $n; // left and right are // end points denoting // the current range. $left = 0; $right = $n - 1; while ($left <= $right) { $mid = ($left+$right) / 2; // If middle element is same // of both arrays, it means // that extra element is after // mid so we update left to mid+1 if ($arr2[$mid] == $arr1[$mid]) $left = $mid + 1; // If middle element is different // of the arrays, it means that the // index we are searching for is either // mid, or before mid. Hence we update // right to mid-1. else { $index = $mid; $right = $mid - 1; } } // when right is greater than // left, our search is complete. return $index;} // Driver code{ $arr1 = array(2, 4, 6, 8, 10, 12, 13); $arr2 = array(2, 4, 6, 8, 10, 12); $n = sizeof($arr2) / sizeof($arr2[0]); // Solve is passed both arrays echo findExtra($arr1, $arr2, $n); return 0;} // This code is contributed by nitin mittal?>", "e": 40223, "s": 38907, "text": null }, { "code": "<script> // Javascript program to find an extra// element present in arr1[] // Returns index of extra element// in arr1[]. n is size of arr2[].// Size of arr1[] is n-1.function findExtra( arr1, arr2, n){ // Initialize result let index = n; // left and right are end // points denoting the current range. let left = 0, right = n - 1; while (left <= right) { let mid = Math.floor((left + right) / 2); // If middle element is same // of both arrays, it means // that extra element is after // mid so we update left to mid+1 if (arr2[mid] == arr1[mid]) left = mid + 1; // If middle element is different // of the arrays, it means that // the index we are searching for // is either mid, or before mid. // Hence we update right to mid-1. else { index = mid; right = mid - 1; } } // when right is greater than // left our search is complete. return index;} // Driver program let arr1 = [2, 4, 6, 8, 10, 12, 13]; let arr2 = [2, 4, 6, 8, 10, 12]; let n = arr2.length; // Solve is passed both arrays document.write(findExtra(arr1, arr2, n)); </script>", "e": 41474, "s": 40223, "text": null }, { "code": null, "e": 41484, "s": 41474, "text": "Output : " }, { "code": null, "e": 41487, "s": 41484, "text": " 6" }, { "code": null, "e": 41509, "s": 41487, "text": "Complexity Analysis: " }, { "code": null, "e": 41586, "s": 41509, "text": "Time complexity : O(log n). The time complexity of binary search is O(log n)" }, { "code": null, "e": 41678, "s": 41586, "text": "Space complexity : O(1). As no extra space is required, so the time complexity is constant." }, { "code": null, "e": 41758, "s": 41678, "text": "Method 3: This method solves the given problem using the predefined function. " }, { "code": null, "e": 42108, "s": 41758, "text": "Approach: To find the element which is different, find the sum of each array and subtract the sums and find the absolute value. Search the larger array and check if the absolute is equal to an index and return that index. If an element is missing and all the other elements are the same, then the difference of sums will be equal to missing element." }, { "code": null, "e": 42119, "s": 42108, "text": "Algorithm:" }, { "code": null, "e": 42371, "s": 42119, "text": "Create a function to calculate the sum of two arrays.Find the absolute difference between the sum of two arrays (value).Traverse the larger array from start too endIf the element at any index is equal to value, then print the index and break the loop." }, { "code": null, "e": 42425, "s": 42371, "text": "Create a function to calculate the sum of two arrays." }, { "code": null, "e": 42493, "s": 42425, "text": "Find the absolute difference between the sum of two arrays (value)." }, { "code": null, "e": 42538, "s": 42493, "text": "Traverse the larger array from start too end" }, { "code": null, "e": 42626, "s": 42538, "text": "If the element at any index is equal to value, then print the index and break the loop." }, { "code": null, "e": 42643, "s": 42626, "text": "Implementation: " }, { "code": null, "e": 42647, "s": 42643, "text": "C++" }, { "code": null, "e": 42652, "s": 42647, "text": "Java" }, { "code": null, "e": 42660, "s": 42652, "text": "Python3" }, { "code": null, "e": 42663, "s": 42660, "text": "C#" }, { "code": null, "e": 42674, "s": 42663, "text": "Javascript" }, { "code": "// C++ code for above approach#include<bits/stdc++.h>using namespace std; // function return sum of array elementsint sum(int arr[], int n){ int summ = 0; for (int i = 0; i < n; i++) { summ += arr[i]; } return summ;} // function return index of given elementint indexOf(int arr[], int element, int n){ for (int i = 0; i < n; i++) { if (arr[i] == element) { return i; } } return -1;} // Function to find Indexint find_extra_element_index(int arrA[], int arrB[], int n, int m){ // Calculating extra element int extra_element = sum(arrA, n) - sum(arrB, m); // returns index of extra element return indexOf(arrA, extra_element, n);} // Driver Codeint main(){ int arrA[] = {2, 4, 6, 8, 10, 12, 13}; int arrB[] = {2, 4, 6, 8, 10, 12}; int n = sizeof(arrA) / sizeof(arrA[0]); int m = sizeof(arrB) / sizeof(arrB[0]); cout << find_extra_element_index(arrA, arrB, n, m);} // This code is contributed by mohit kumar", "e": 43757, "s": 42674, "text": null }, { "code": "// Java code for above approachclass GFG{ // Function to find Index static int find_extra_element_index(int[] arrA, int[] arrB) { // Calculating extra element int extra_element = sum(arrA) - sum(arrB); // returns index of extra element return indexOf(arrA, extra_element); } // function return sum of array elements static int sum(int[] arr) { int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } // function return index of given element static int indexOf(int[] arr, int element) { for (int i = 0; i < arr.length; i++) { if (arr[i] == element) { return i; } } return -1; } // Driver Code public static void main(String[] args) { int[] arrA = {2, 4, 6, 8, 10, 12, 13}; int[] arrB = {2, 4, 6, 8, 10, 12}; System.out.println(find_extra_element_index(arrA, arrB)); }} /* This code contributed by PrinciRaj1992 */", "e": 44882, "s": 43757, "text": null }, { "code": "# Python3 code for above approach # Function to find Indexdef find_extra_element_index(arrA, arrB): # Calculating extra element extra_element = sum(arrA) - sum(arrB) # returns index of extra element return arrA.index(extra_element) # Driver CodearrA = [2, 4, 6, 8, 10, 12, 13]arrB = [2, 4, 6, 8, 10, 12]print(find_extra_element_index(arrA,arrB)) # This code is contributed by Dravid", "e": 45287, "s": 44882, "text": null }, { "code": "// C# code for above approachusing System; class GFG{ // Function to find Index static int find_extra_element_index(int[] arrA, int[] arrB) { // Calculating extra element int extra_element = sum(arrA) - sum(arrB); // returns index of extra element return indexOf(arrA, extra_element); } // function return sum of array elements static int sum(int[] arr) { int sum = 0; for (int i = 0; i < arr.Length; i++) { sum += arr[i]; } return sum; } // function return index of given element static int indexOf(int[] arr, int element) { for (int i = 0; i < arr.Length; i++) { if (arr[i] == element) { return i; } } return -1; } // Driver Code public static void Main(String[] args) { int[] arrA = {2, 4, 6, 8, 10, 12, 13}; int[] arrB = {2, 4, 6, 8, 10, 12}; Console.WriteLine(find_extra_element_index(arrA, arrB)); }} // This code has been contributed by 29AjayKumar", "e": 46427, "s": 45287, "text": null }, { "code": "<script> // Javascript code for above approach // Function to find Index function find_extra_element_index(arrA, arrB) { // Calculating extra element let extra_element = sum(arrA) - sum(arrB); // returns index of extra element return indexOf(arrA, extra_element); } // function return sum of array elements function sum(arr) { let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } // function return index of given element function indexOf(arr, element) { for (let i = 0; i < arr.length; i++) { if (arr[i] == element) { return i; } } return -1; } let arrA = [2, 4, 6, 8, 10, 12, 13]; let arrB = [2, 4, 6, 8, 10, 12]; document.write(find_extra_element_index(arrA, arrB)); </script>", "e": 47373, "s": 46427, "text": null }, { "code": null, "e": 47383, "s": 47373, "text": "Output : " }, { "code": null, "e": 47386, "s": 47383, "text": " 6" }, { "code": null, "e": 47408, "s": 47386, "text": "Complexity Analysis: " }, { "code": null, "e": 47522, "s": 47408, "text": "Time Complexity: O(n). Since only three traversals through the array is needed, So the time complexity is linear." }, { "code": null, "e": 47613, "s": 47522, "text": "Space Complexity: O(1). As no extra space is required, so the time complexity is constant." }, { "code": null, "e": 48038, "s": 47613, "text": "This article is contributed by Abhishek Khatri . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 48047, "s": 48038, "text": "parashar" }, { "code": null, "e": 48060, "s": 48047, "text": "nitin mittal" }, { "code": null, "e": 48066, "s": 48060, "text": "jit_t" }, { "code": null, "e": 48080, "s": 48066, "text": "princiraj1992" }, { "code": null, "e": 48092, "s": 48080, "text": "29AjayKumar" }, { "code": null, "e": 48107, "s": 48092, "text": "mohit kumar 29" }, { "code": null, "e": 48121, "s": 48107, "text": "niteeshkumar2" }, { "code": null, "e": 48132, "s": 48121, "text": "andrew1234" }, { "code": null, "e": 48147, "s": 48132, "text": "tridib_samanta" }, { "code": null, "e": 48161, "s": 48147, "text": "surbhityagi15" }, { "code": null, "e": 48175, "s": 48161, "text": "jana_sayantan" }, { "code": null, "e": 48186, "s": 48175, "text": "decode2207" }, { "code": null, "e": 48206, "s": 48186, "text": "abhishek0719kadiyan" }, { "code": null, "e": 48221, "s": 48206, "text": "sagar0719kumar" }, { "code": null, "e": 48228, "s": 48221, "text": "Amazon" }, { "code": null, "e": 48242, "s": 48228, "text": "Binary Search" }, { "code": null, "e": 48247, "s": 48242, "text": "Zoho" }, { "code": null, "e": 48254, "s": 48247, "text": "Arrays" }, { "code": null, "e": 48273, "s": 48254, "text": "Divide and Conquer" }, { "code": null, "e": 48283, "s": 48273, "text": "Searching" }, { "code": null, "e": 48288, "s": 48283, "text": "Zoho" }, { "code": null, "e": 48295, "s": 48288, "text": "Amazon" }, { "code": null, "e": 48302, "s": 48295, "text": "Arrays" }, { "code": null, "e": 48312, "s": 48302, "text": "Searching" }, { "code": null, "e": 48331, "s": 48312, "text": "Divide and Conquer" }, { "code": null, "e": 48345, "s": 48331, "text": "Binary Search" }, { "code": null, "e": 48443, "s": 48345, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48511, "s": 48443, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 48555, "s": 48511, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 48603, "s": 48555, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 48626, "s": 48603, "text": "Introduction to Arrays" }, { "code": null, "e": 48658, "s": 48626, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 48669, "s": 48658, "text": "Merge Sort" }, { "code": null, "e": 48679, "s": 48669, "text": "QuickSort" }, { "code": null, "e": 48693, "s": 48679, "text": "Binary Search" }, { "code": null, "e": 48761, "s": 48693, "text": "Maximum and minimum of an array using minimum number of comparisons" } ]
NULL pointer in C - GeeksforGeeks
14 Aug, 2019 At the very high level, we can think of NULL as a null pointer which is used in C for various purposes. Some of the most common use cases for NULL area) To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet.b) To check for a null pointer before accessing any pointer variable. By doing so, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL.c) To pass a null pointer to a function argument when we don’t want to pass any valid memory address. The example of a is int * pInt = NULL; The example of b is if(pInt != NULL) /*We could use if(pInt) as well*/{ /*Some code*/}else{ /*Some code*/} The example of c is int fun(int *ptr){ /*Fun specific stuff is done with ptr here*/ return 10;}fun(NULL); It should be noted that NULL pointer is different from an uninitialized and dangling pointer. In a specific program context, all uninitialized or dangling or NULL pointers are invalid but NULL is a specific invalid pointer which is mentioned in C standard and has specific purposes. What we mean is that uninitialized and dangling pointers are invalid but they can point to some memory address that may be accessible through the memory access is unintended. #include <stdio.h>int main(){ int *i, *j; int *ii = NULL, *jj = NULL; if(i == j) { printf("This might get printed if both i and j are same by chance."); } if(ii == jj) { printf("This is always printed coz ii and jj are same."); } return 0;} By specifically mentioning NULL pointer, C standard gives mechanism using which a C programmer can use and check whether a given pointer is legitimate or not. But what exactly is NULL and how it’s defined? Strictly speaking, NULL expands to an implementation-defined null pointer constant which is defined in many header files such as “stdio.h”, “stddef.h”, “stdlib.h” etc. Let us see what C standards say about null pointer. From C11 standard clause 6.3.2.3, “An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.” Before we proceed further on this NULL discussion :), let’s mention few lines about C standard just in case you wants to refer it for further study. Please note that ISO/IEC 9899:2011 is the C language’s latest standard which was published in Dec 2011. This is also called the C11 standard. For completeness, let us mention that previous standards for C were C99, C90 (also known as ISO C) and C89 (also known as ANSI C). Though the actual C11 standard can be purchased from ISO, there’s a draft document which is available in public domain for free. Coming to our discussion, NULL macro is defined as ((void *)0) in header files of most of the C compiler implementations. But C standard is saying that 0 is also a null pointer constant. It means that the following is also perfectly legal as per standard. int * ptr = 0; Please note that 0 in the above C statement is used in pointer-context and it’s different from 0 as integer. This is one of the reasons why the usage of NULL is preferred because it makes it explicit in code that programmer is using null pointer, not integer 0. Another important concept about NULL is that “NULL expands to an implementation-defined null pointer constant”. This statement is also from C11 clause 7.19. It means that internal representation of the null pointer could be non-zero bit pattern to convey NULL pointer. That’s why NULL always needn’t be internally represented as all zeros bit pattern. A compiler implementation can choose to represent “null pointer constant” as a bit pattern for all 1s or anything else. But again, as a C programmer, we needn’t worry much on the internal value of the null pointer unless we are involved in Compiler coding or even below the level of coding. Having said so, typically NULL is represented as all bits set to 0 only. To know this on a specific platform, one can use the following #include<stdio.h>int main(){ printf("%d",NULL); return 0;} Most likely, it’s printing 0 which is the typical internal null pointer value but again it can vary depending on the C compiler/platform. You can try few other things in above program such as printf(“‘%c“,NULL) or printf(“%s”,NULL) and even printf(“%f”,NULL). The outputs of these are going to be different depending on the platform used but it’d be interesting especially usage of %f with NULL! Can we use sizeof() operator on NULL in C? Well, usage of sizeof(NULL) is allowed but the exact size would depend on platform. #include<stdio.h>int main(){ printf("%lu",sizeof(NULL)); return 0;} Since NULL is defined as ((void*)0), we can think of NULL as a special pointer and its size would be equal to any pointer. If the pointer size of a platform is 4 bytes, the output of the above program would be 4. But if pointer size on a platform is 8 bytes, the output of the above program would be 8. What about dereferencing of NULL? What’s going to happen if we use the following C code #include<stdio.h>int main(){ int * ptr = NULL; printf("%d",*ptr); return 0;} On some machines, the above would compile successfully but crashes when the program is run through it needn’t show the same behaviour across all the machines. Again it depends on a lot of factors. But the idea of mentioning the above snippet is that we should always check for NULL before accessing it. Since NULL is typically defined as ((void*)0), let us discuss a little bit about void type as well. As per C11 standard clause 6.2.5, “The void type comprises an empty set of values; it is an incomplete object type that cannot be completed”. Even C11 clause 6.5.3.4 mentions that “The sizeof operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member.” Basically, it means that void is an incomplete type whose size doesn’t make any sense in C programs but implementations (such as gcc) can choose sizeof(void) as 1 so that the flat memory pointed by void pointer can be viewed as untyped memory i.e. a sequence of bytes. But the output of the following needn’t to same on all platforms. #include<stdio.h>int main(){ printf("%lu",sizeof(void)); return 0;} On gcc, the above would output 1. What about sizeof(void *)? Here C11 has mentioned guidelines. From clause 6.2.5, “A pointer to void shall have the same representation and alignment requirements as a pointer to a character type”. That’s why the output of the following would be same as any pointer size on a machine. #include<stdio.h>int main(){ printf("%lu",sizeof(void *)); return 0;} Inspite of mentioning machine dependent stuff as above, we as C programmers should always strive to make our code as portable as possible. So we can conclude on NULL as follows: 1. Always initialize pointer variables as NULL.2. Always perform a NULL check before accessing any pointer. Please do Like/Tweet/G+1 if you find the above useful. Also, please do leave us to comment for further clarification or info. We would love to help and learn nishant2raj C-Pointers cpp-pointer C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Substring in C++ Core Dump (Segmentation fault) in C/C++ rand() and srand() in C/C++ fork() in C std::string class in C++ Converting Strings to Numbers in C/C++ Enumeration (or enum) in C Command line arguments in C/C++
[ { "code": null, "e": 25987, "s": 25959, "text": "\n14 Aug, 2019" }, { "code": null, "e": 26539, "s": 25987, "text": "At the very high level, we can think of NULL as a null pointer which is used in C for various purposes. Some of the most common use cases for NULL area) To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet.b) To check for a null pointer before accessing any pointer variable. By doing so, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL.c) To pass a null pointer to a function argument when we don’t want to pass any valid memory address." }, { "code": null, "e": 26559, "s": 26539, "text": "The example of a is" }, { "code": "int * pInt = NULL;", "e": 26578, "s": 26559, "text": null }, { "code": null, "e": 26598, "s": 26578, "text": "The example of b is" }, { "code": "if(pInt != NULL) /*We could use if(pInt) as well*/{ /*Some code*/}else{ /*Some code*/}", "e": 26685, "s": 26598, "text": null }, { "code": null, "e": 26705, "s": 26685, "text": "The example of c is" }, { "code": "int fun(int *ptr){ /*Fun specific stuff is done with ptr here*/ return 10;}fun(NULL);", "e": 26791, "s": 26705, "text": null }, { "code": null, "e": 27249, "s": 26791, "text": "It should be noted that NULL pointer is different from an uninitialized and dangling pointer. In a specific program context, all uninitialized or dangling or NULL pointers are invalid but NULL is a specific invalid pointer which is mentioned in C standard and has specific purposes. What we mean is that uninitialized and dangling pointers are invalid but they can point to some memory address that may be accessible through the memory access is unintended." }, { "code": "#include <stdio.h>int main(){ int *i, *j; int *ii = NULL, *jj = NULL; if(i == j) { printf(\"This might get printed if both i and j are same by chance.\"); } if(ii == jj) { printf(\"This is always printed coz ii and jj are same.\"); } return 0;}", "e": 27492, "s": 27249, "text": null }, { "code": null, "e": 27952, "s": 27492, "text": "By specifically mentioning NULL pointer, C standard gives mechanism using which a C programmer can use and check whether a given pointer is legitimate or not. But what exactly is NULL and how it’s defined? Strictly speaking, NULL expands to an implementation-defined null pointer constant which is defined in many header files such as “stdio.h”, “stddef.h”, “stdlib.h” etc. Let us see what C standards say about null pointer. From C11 standard clause 6.3.2.3," }, { "code": null, "e": 28259, "s": 27952, "text": "“An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.”" }, { "code": null, "e": 28810, "s": 28259, "text": "Before we proceed further on this NULL discussion :), let’s mention few lines about C standard just in case you wants to refer it for further study. Please note that ISO/IEC 9899:2011 is the C language’s latest standard which was published in Dec 2011. This is also called the C11 standard. For completeness, let us mention that previous standards for C were C99, C90 (also known as ISO C) and C89 (also known as ANSI C). Though the actual C11 standard can be purchased from ISO, there’s a draft document which is available in public domain for free." }, { "code": null, "e": 29066, "s": 28810, "text": "Coming to our discussion, NULL macro is defined as ((void *)0) in header files of most of the C compiler implementations. But C standard is saying that 0 is also a null pointer constant. It means that the following is also perfectly legal as per standard." }, { "code": "int * ptr = 0;", "e": 29081, "s": 29066, "text": null }, { "code": null, "e": 30122, "s": 29081, "text": "Please note that 0 in the above C statement is used in pointer-context and it’s different from 0 as integer. This is one of the reasons why the usage of NULL is preferred because it makes it explicit in code that programmer is using null pointer, not integer 0. Another important concept about NULL is that “NULL expands to an implementation-defined null pointer constant”. This statement is also from C11 clause 7.19. It means that internal representation of the null pointer could be non-zero bit pattern to convey NULL pointer. That’s why NULL always needn’t be internally represented as all zeros bit pattern. A compiler implementation can choose to represent “null pointer constant” as a bit pattern for all 1s or anything else. But again, as a C programmer, we needn’t worry much on the internal value of the null pointer unless we are involved in Compiler coding or even below the level of coding. Having said so, typically NULL is represented as all bits set to 0 only. To know this on a specific platform, one can use the following" }, { "code": "#include<stdio.h>int main(){ printf(\"%d\",NULL); return 0;}", "e": 30181, "s": 30122, "text": null }, { "code": null, "e": 30577, "s": 30181, "text": "Most likely, it’s printing 0 which is the typical internal null pointer value but again it can vary depending on the C compiler/platform. You can try few other things in above program such as printf(“‘%c“,NULL) or printf(“%s”,NULL) and even printf(“%f”,NULL). The outputs of these are going to be different depending on the platform used but it’d be interesting especially usage of %f with NULL!" }, { "code": null, "e": 30704, "s": 30577, "text": "Can we use sizeof() operator on NULL in C? Well, usage of sizeof(NULL) is allowed but the exact size would depend on platform." }, { "code": "#include<stdio.h>int main(){ printf(\"%lu\",sizeof(NULL)); return 0;}", "e": 30772, "s": 30704, "text": null }, { "code": null, "e": 31075, "s": 30772, "text": "Since NULL is defined as ((void*)0), we can think of NULL as a special pointer and its size would be equal to any pointer. If the pointer size of a platform is 4 bytes, the output of the above program would be 4. But if pointer size on a platform is 8 bytes, the output of the above program would be 8." }, { "code": null, "e": 31163, "s": 31075, "text": "What about dereferencing of NULL? What’s going to happen if we use the following C code" }, { "code": "#include<stdio.h>int main(){ int * ptr = NULL; printf(\"%d\",*ptr); return 0;}", "e": 31240, "s": 31163, "text": null }, { "code": null, "e": 31543, "s": 31240, "text": "On some machines, the above would compile successfully but crashes when the program is run through it needn’t show the same behaviour across all the machines. Again it depends on a lot of factors. But the idea of mentioning the above snippet is that we should always check for NULL before accessing it." }, { "code": null, "e": 32362, "s": 31543, "text": "Since NULL is typically defined as ((void*)0), let us discuss a little bit about void type as well. As per C11 standard clause 6.2.5, “The void type comprises an empty set of values; it is an incomplete object type that cannot be completed”. Even C11 clause 6.5.3.4 mentions that “The sizeof operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member.” Basically, it means that void is an incomplete type whose size doesn’t make any sense in C programs but implementations (such as gcc) can choose sizeof(void) as 1 so that the flat memory pointed by void pointer can be viewed as untyped memory i.e. a sequence of bytes. But the output of the following needn’t to same on all platforms." }, { "code": "#include<stdio.h>int main(){ printf(\"%lu\",sizeof(void)); return 0;}", "e": 32430, "s": 32362, "text": null }, { "code": null, "e": 32748, "s": 32430, "text": "On gcc, the above would output 1. What about sizeof(void *)? Here C11 has mentioned guidelines. From clause 6.2.5, “A pointer to void shall have the same representation and alignment requirements as a pointer to a character type”. That’s why the output of the following would be same as any pointer size on a machine." }, { "code": "#include<stdio.h>int main(){ printf(\"%lu\",sizeof(void *)); return 0;}", "e": 32818, "s": 32748, "text": null }, { "code": null, "e": 32996, "s": 32818, "text": "Inspite of mentioning machine dependent stuff as above, we as C programmers should always strive to make our code as portable as possible. So we can conclude on NULL as follows:" }, { "code": null, "e": 33104, "s": 32996, "text": "1. Always initialize pointer variables as NULL.2. Always perform a NULL check before accessing any pointer." }, { "code": null, "e": 33263, "s": 33104, "text": "Please do Like/Tweet/G+1 if you find the above useful. Also, please do leave us to comment for further clarification or info. We would love to help and learn " }, { "code": null, "e": 33275, "s": 33263, "text": "nishant2raj" }, { "code": null, "e": 33286, "s": 33275, "text": "C-Pointers" }, { "code": null, "e": 33298, "s": 33286, "text": "cpp-pointer" }, { "code": null, "e": 33309, "s": 33298, "text": "C Language" }, { "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": 33442, "s": 33407, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 33488, "s": 33442, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 33505, "s": 33488, "text": "Substring in C++" }, { "code": null, "e": 33545, "s": 33505, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 33573, "s": 33545, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 33585, "s": 33573, "text": "fork() in C" }, { "code": null, "e": 33610, "s": 33585, "text": "std::string class in C++" }, { "code": null, "e": 33649, "s": 33610, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 33676, "s": 33649, "text": "Enumeration (or enum) in C" } ]
Java.Lang.Float class in Java - GeeksforGeeks
09 Aug, 2021 Float class is a wrapper class for the primitive type float which contains several methods to effectively deal with a float value like converting it to a string representation, and vice-versa. An object of Float class can hold a single float value. There are mainly two constructors to initialize a Float object- Float(float b: Creates a Float object initialized with the value provided. Syntax: public Float(Float d) Parameters: d : value with which to initialize Float(String s): Creates a Float object initialized with the parsed float value provided by string representation. Default radix is taken to be 10. Syntax: public Float(String s) throws NumberFormatException Parameters: s : string representation of the byte value Throws: NumberFormatException: If the string provided does not represent any float value. Methods: 1.toString(): Returns the string corresponding to the float value. Syntax : public String toString(float b) Parameters : b : float value for which string representation required. 2.valueOf() : returns the Float object initialized with the value provided. Syntax : public static Float valueOf(float b) Parameters : b : a float value Another overloaded function valueOf(String val) which provides function similar to new Float(Float.parseFloat(val,10)) Syntax : public static Float valueOf(String s) throws NumberFormatException Parameters : s : a String object to be parsed as float Throws : NumberFormatException : if String cannot be parsed to a float value. 3.parseFloat() : returns float value by parsing the string. Differs from valueOf() as it returns a primitive float value and valueOf() return Float object. Syntax : public static float parseFloat(String val) throws NumberFormatException Parameters : val : String representation of float Throws : NumberFormatException : if String cannot be parsed to a float value in given radix. 4.byteValue() : returns a byte value corresponding to this Float Object. Syntax : public byte byteValue() 5.shortValue() : returns a short value corresponding to this Float Object. Syntax : public short shortValue() 6.intValue() : returns a int value corresponding to this Float Object. Syntax : public int intValue() 7.longValue() : returns a long value corresponding to this Float Object. Syntax : public long longValue() 8.doubleValue() : returns a double value corresponding to this Float Object. Syntax : public double doubleValue() 9.floatValue() : returns a float value corresponding to this Float Object. Syntax : public float floatValue() 10.hashCode() : returns the hashcode corresponding to this Float Object. Syntax : public int hashCode() 11.isNaN() : returns true if the float object in consideration is not a number, otherwise false. Syntax : public boolean isNaN() Another static method isNaN(float val) can be used if we don’t need any object of float to be created. It provides similar functionality as the above version. Syntax : public static boolean isNaN(float val) Parameters : val : float value to check for 12.isInfinite() : returns true if the float object in consideration is very large, otherwise false. Specifically any number beyond 0x7f800000 on positive side and below 0xff800000 on negative side are the infinity values. Syntax : public boolean isInfinite() Another static method isInfinite(float val) can be used if we don’t need any object of float to be created. It provides similar functionality as the above version. Syntax : public static boolean isInfinte(float val) Parameters : val : float value to check for 13.toHexString() : Returns the hexadecimal representation of the argument float value. Syntax : public static String toHexString(float val) Parameters : val : float value to be represented as hex string 14. floatToIntBits() : returns the IEEE 754 floating-point “single format” bit layout of the given float argument. Detailed summary of IEEE 754 floating-point “single format” can be found here. Syntax : public static int floatToIntBits(float val) Parameters : val : float value to convert 15.floatToRawIntBits() : returns the IEEE 754 floating-point “single format” bit layout of the given float argument. It differs from previous method as it preserves the Nan values. Syntax : public static int floatToRawIntBits(float val) Parameters : val : float value to convert 16.IntBitsToFloat() : Returns the float value corresponding to the long bit pattern of the argument. It does reverse work of the previous two methods. Syntax : public static float IntBitsToFloat(long b) Parameters : b : long bit pattern 17.equals() : Used to compare the equality of two Float objects. This method returns true if both the objects contain the same float value. Should be used only if checking for equality. In all other cases, compareTo method should be preferred. Syntax : public boolean equals(Object obj) Parameters : obj : object to compare with 18. compareTo() : Used to compare two Float objects for numerical equality. This should be used when comparing two Float values for numerical equality as it would differentiate between less and greater values. Returns a value less than 0,0,value greater than 0 for less than,equal to and greater than. Syntax : public int compareTo(Float b) Parameters : b : Float object to compare with 19. compare() : Used to compare two primitive float values for numerical equality. As it is a static method therefore it can be used without creating any object of Float. Syntax : public static int compare(float x,float y) Parameters : x : float value y : another float value Example: Java // Java program to illustrate// various float class methods// of Java.lang classpublic class GfG{ public static void main(String[] args) { float b = 55.05F; String bb = "45"; // Construct two Float objects Float x = new Float(b); Float y = new Float(bb); // toString() System.out.println("toString(b) = " + Float.toString(b)); // valueOf() // return Float object Float z = Float.valueOf(b); System.out.println("valueOf(b) = " + z); z = Float.valueOf(bb); System.out.println("ValueOf(bb) = " + z); // parseFloat() // return primitive float value float zz = Float.parseFloat(bb); System.out.println("parseFloat(bb) = " + zz); System.out.println("bytevalue(x) = " + x.byteValue()); System.out.println("shortvalue(x) = " + x.shortValue()); System.out.println("intvalue(x) = " + x.intValue()); System.out.println("longvalue(x) = " + x.longValue()); System.out.println("doublevalue(x) = " + x.doubleValue()); System.out.println("floatvalue(x) = " + x.floatValue()); int hash = x.hashCode(); System.out.println("hashcode(x) = " + hash); boolean eq = x.equals(y); System.out.println("x.equals(y) = " + eq); int e = Float.compare(x, y); System.out.println("compare(x,y) = " + e); int f = x.compareTo(y); System.out.println("x.compareTo(y) = " + f); Float d = Float.valueOf("1010.54789654123654"); System.out.println("isNaN(d) = " + d.isNaN()); System.out.println("Float.isNaN(45.12452) = " + Float.isNaN(45.12452F)); // Float.POSITIVE_INFINITY stores // the positive infinite value d = Float.valueOf(Float.POSITIVE_INFINITY + 1); System.out.println("Float.isInfinite(d) = " + Float.isInfinite(d.floatValue())); float dd = 10245.21452F; System.out.println("Float.toString(dd) = " + Float.toHexString(dd)); int float_to_int = Float.floatToIntBits(dd); System.out.println("Float.floatToLongBits(dd) = " + float_to_int); float int_to_float = Float.intBitsToFloat(float_to_int); System.out.println("Float.intBitsToFloat(float_to_long) = " + int_to_float); } } Output : toString(b) = 55.05 valueOf(b) = 55.05 ValueOf(bb) = 45.0 parseFloat(bb) = 45.0 bytevalue(x) = 55 shortvalue(x) = 55 intvalue(x) = 55 longvalue(x) = 55 doublevalue(x) = 55.04999923706055 floatvalue(x) = 55.05 hashcode(x) = 1113338675 x.equals(y) = false compare(x,y) = 1 x.compareTo(y) = 1 isNaN(d) = false Float.isNaN(45.12452) = false Float.isInfinite(d) = true Float.toString(dd) = 0x1.4029b8p13 Float.floatToLongBits(dd) = 1176507612 Float.intBitsToFloat(float_to_long) = 10245.215 References : Official Java Documentation This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sagar0719kumar sumitgumber28 abhishek0719kadiyan Java-lang package java-wrapper-class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Reverse a string in Java Arrays.sort() in Java with examples Stream In Java Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 24284, "s": 24256, "text": "\n09 Aug, 2021" }, { "code": null, "e": 24599, "s": 24284, "text": "Float class is a wrapper class for the primitive type float which contains several methods to effectively deal with a float value like converting it to a string representation, and vice-versa. An object of Float class can hold a single float value. There are mainly two constructors to initialize a Float object- " }, { "code": null, "e": 24676, "s": 24599, "text": "Float(float b: Creates a Float object initialized with the value provided. " }, { "code": null, "e": 24754, "s": 24676, "text": "Syntax: public Float(Float d)\nParameters:\n\nd : value with which to initialize" }, { "code": null, "e": 24904, "s": 24754, "text": "Float(String s): Creates a Float object initialized with the parsed float value provided by string representation. Default radix is taken to be 10. " }, { "code": null, "e": 25115, "s": 24904, "text": "Syntax: public Float(String s) throws NumberFormatException\nParameters: \ns : string representation of the byte value \nThrows: \nNumberFormatException: If the string provided does not represent any \nfloat value." }, { "code": null, "e": 25126, "s": 25115, "text": "Methods: " }, { "code": null, "e": 25195, "s": 25126, "text": "1.toString(): Returns the string corresponding to the float value. " }, { "code": null, "e": 25307, "s": 25195, "text": "Syntax : public String toString(float b)\nParameters :\nb : float value for which string representation required." }, { "code": null, "e": 25385, "s": 25307, "text": "2.valueOf() : returns the Float object initialized with the value provided. " }, { "code": null, "e": 25462, "s": 25385, "text": "Syntax : public static Float valueOf(float b)\nParameters :\nb : a float value" }, { "code": null, "e": 25582, "s": 25462, "text": "Another overloaded function valueOf(String val) which provides function similar to new Float(Float.parseFloat(val,10)) " }, { "code": null, "e": 25802, "s": 25582, "text": "Syntax : public static Float valueOf(String s)\n throws NumberFormatException\nParameters :\ns : a String object to be parsed as float\nThrows :\nNumberFormatException : if String cannot be parsed to a float value." }, { "code": null, "e": 25959, "s": 25802, "text": "3.parseFloat() : returns float value by parsing the string. Differs from valueOf() as it returns a primitive float value and valueOf() return Float object. " }, { "code": null, "e": 26198, "s": 25959, "text": "Syntax : public static float parseFloat(String val)\n throws NumberFormatException\nParameters :\nval : String representation of float \nThrows :\nNumberFormatException : if String cannot be parsed to a float value \nin given radix." }, { "code": null, "e": 26273, "s": 26198, "text": "4.byteValue() : returns a byte value corresponding to this Float Object. " }, { "code": null, "e": 26306, "s": 26273, "text": "Syntax : public byte byteValue()" }, { "code": null, "e": 26383, "s": 26306, "text": "5.shortValue() : returns a short value corresponding to this Float Object. " }, { "code": null, "e": 26418, "s": 26383, "text": "Syntax : public short shortValue()" }, { "code": null, "e": 26491, "s": 26418, "text": "6.intValue() : returns a int value corresponding to this Float Object. " }, { "code": null, "e": 26522, "s": 26491, "text": "Syntax : public int intValue()" }, { "code": null, "e": 26597, "s": 26522, "text": "7.longValue() : returns a long value corresponding to this Float Object. " }, { "code": null, "e": 26630, "s": 26597, "text": "Syntax : public long longValue()" }, { "code": null, "e": 26709, "s": 26630, "text": "8.doubleValue() : returns a double value corresponding to this Float Object. " }, { "code": null, "e": 26746, "s": 26709, "text": "Syntax : public double doubleValue()" }, { "code": null, "e": 26823, "s": 26746, "text": "9.floatValue() : returns a float value corresponding to this Float Object. " }, { "code": null, "e": 26858, "s": 26823, "text": "Syntax : public float floatValue()" }, { "code": null, "e": 26933, "s": 26858, "text": "10.hashCode() : returns the hashcode corresponding to this Float Object. " }, { "code": null, "e": 26964, "s": 26933, "text": "Syntax : public int hashCode()" }, { "code": null, "e": 27063, "s": 26964, "text": "11.isNaN() : returns true if the float object in consideration is not a number, otherwise false. " }, { "code": null, "e": 27095, "s": 27063, "text": "Syntax : public boolean isNaN()" }, { "code": null, "e": 27256, "s": 27095, "text": "Another static method isNaN(float val) can be used if we don’t need any object of float to be created. It provides similar functionality as the above version. " }, { "code": null, "e": 27348, "s": 27256, "text": "Syntax : public static boolean isNaN(float val)\nParameters :\nval : float value to check for" }, { "code": null, "e": 27572, "s": 27348, "text": "12.isInfinite() : returns true if the float object in consideration is very large, otherwise false. Specifically any number beyond 0x7f800000 on positive side and below 0xff800000 on negative side are the infinity values. " }, { "code": null, "e": 27609, "s": 27572, "text": "Syntax : public boolean isInfinite()" }, { "code": null, "e": 27775, "s": 27609, "text": "Another static method isInfinite(float val) can be used if we don’t need any object of float to be created. It provides similar functionality as the above version. " }, { "code": null, "e": 27871, "s": 27775, "text": "Syntax : public static boolean isInfinte(float val)\nParameters :\nval : float value to check for" }, { "code": null, "e": 27960, "s": 27871, "text": "13.toHexString() : Returns the hexadecimal representation of the argument float value. " }, { "code": null, "e": 28077, "s": 27960, "text": "Syntax : public static String toHexString(float val)\nParameters : \nval : float value to be represented as hex string" }, { "code": null, "e": 28273, "s": 28077, "text": "14. floatToIntBits() : returns the IEEE 754 floating-point “single format” bit layout of the given float argument. Detailed summary of IEEE 754 floating-point “single format” can be found here. " }, { "code": null, "e": 28368, "s": 28273, "text": "Syntax : public static int floatToIntBits(float val)\nParameters :\nval : float value to convert" }, { "code": null, "e": 28551, "s": 28368, "text": "15.floatToRawIntBits() : returns the IEEE 754 floating-point “single format” bit layout of the given float argument. It differs from previous method as it preserves the Nan values. " }, { "code": null, "e": 28649, "s": 28551, "text": "Syntax : public static int floatToRawIntBits(float val)\nParameters :\nval : float value to convert" }, { "code": null, "e": 28802, "s": 28649, "text": "16.IntBitsToFloat() : Returns the float value corresponding to the long bit pattern of the argument. It does reverse work of the previous two methods. " }, { "code": null, "e": 28888, "s": 28802, "text": "Syntax : public static float IntBitsToFloat(long b)\nParameters :\nb : long bit pattern" }, { "code": null, "e": 29134, "s": 28888, "text": "17.equals() : Used to compare the equality of two Float objects. This method returns true if both the objects contain the same float value. Should be used only if checking for equality. In all other cases, compareTo method should be preferred. " }, { "code": null, "e": 29219, "s": 29134, "text": "Syntax : public boolean equals(Object obj)\nParameters :\nobj : object to compare with" }, { "code": null, "e": 29523, "s": 29219, "text": "18. compareTo() : Used to compare two Float objects for numerical equality. This should be used when comparing two Float values for numerical equality as it would differentiate between less and greater values. Returns a value less than 0,0,value greater than 0 for less than,equal to and greater than. " }, { "code": null, "e": 29608, "s": 29523, "text": "Syntax : public int compareTo(Float b)\nParameters :\nb : Float object to compare with" }, { "code": null, "e": 29781, "s": 29608, "text": "19. compare() : Used to compare two primitive float values for numerical equality. As it is a static method therefore it can be used without creating any object of Float. " }, { "code": null, "e": 29886, "s": 29781, "text": "Syntax : public static int compare(float x,float y)\nParameters :\nx : float value\ny : another float value" }, { "code": null, "e": 29896, "s": 29886, "text": "Example: " }, { "code": null, "e": 29901, "s": 29896, "text": "Java" }, { "code": "// Java program to illustrate// various float class methods// of Java.lang classpublic class GfG{ public static void main(String[] args) { float b = 55.05F; String bb = \"45\"; // Construct two Float objects Float x = new Float(b); Float y = new Float(bb); // toString() System.out.println(\"toString(b) = \" + Float.toString(b)); // valueOf() // return Float object Float z = Float.valueOf(b); System.out.println(\"valueOf(b) = \" + z); z = Float.valueOf(bb); System.out.println(\"ValueOf(bb) = \" + z); // parseFloat() // return primitive float value float zz = Float.parseFloat(bb); System.out.println(\"parseFloat(bb) = \" + zz); System.out.println(\"bytevalue(x) = \" + x.byteValue()); System.out.println(\"shortvalue(x) = \" + x.shortValue()); System.out.println(\"intvalue(x) = \" + x.intValue()); System.out.println(\"longvalue(x) = \" + x.longValue()); System.out.println(\"doublevalue(x) = \" + x.doubleValue()); System.out.println(\"floatvalue(x) = \" + x.floatValue()); int hash = x.hashCode(); System.out.println(\"hashcode(x) = \" + hash); boolean eq = x.equals(y); System.out.println(\"x.equals(y) = \" + eq); int e = Float.compare(x, y); System.out.println(\"compare(x,y) = \" + e); int f = x.compareTo(y); System.out.println(\"x.compareTo(y) = \" + f); Float d = Float.valueOf(\"1010.54789654123654\"); System.out.println(\"isNaN(d) = \" + d.isNaN()); System.out.println(\"Float.isNaN(45.12452) = \" + Float.isNaN(45.12452F)); // Float.POSITIVE_INFINITY stores // the positive infinite value d = Float.valueOf(Float.POSITIVE_INFINITY + 1); System.out.println(\"Float.isInfinite(d) = \" + Float.isInfinite(d.floatValue())); float dd = 10245.21452F; System.out.println(\"Float.toString(dd) = \" + Float.toHexString(dd)); int float_to_int = Float.floatToIntBits(dd); System.out.println(\"Float.floatToLongBits(dd) = \" + float_to_int); float int_to_float = Float.intBitsToFloat(float_to_int); System.out.println(\"Float.intBitsToFloat(float_to_long) = \" + int_to_float); } }", "e": 32375, "s": 29901, "text": null }, { "code": null, "e": 32385, "s": 32375, "text": "Output : " }, { "code": null, "e": 32871, "s": 32385, "text": "toString(b) = 55.05\nvalueOf(b) = 55.05\nValueOf(bb) = 45.0\nparseFloat(bb) = 45.0\nbytevalue(x) = 55\nshortvalue(x) = 55\nintvalue(x) = 55\nlongvalue(x) = 55\ndoublevalue(x) = 55.04999923706055\nfloatvalue(x) = 55.05\nhashcode(x) = 1113338675\nx.equals(y) = false\ncompare(x,y) = 1\nx.compareTo(y) = 1\nisNaN(d) = false\nFloat.isNaN(45.12452) = false\nFloat.isInfinite(d) = true\nFloat.toString(dd) = 0x1.4029b8p13\nFloat.floatToLongBits(dd) = 1176507612\nFloat.intBitsToFloat(float_to_long) = 10245.215" }, { "code": null, "e": 33336, "s": 32871, "text": "References : Official Java Documentation This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33351, "s": 33336, "text": "sagar0719kumar" }, { "code": null, "e": 33365, "s": 33351, "text": "sumitgumber28" }, { "code": null, "e": 33385, "s": 33365, "text": "abhishek0719kadiyan" }, { "code": null, "e": 33403, "s": 33385, "text": "Java-lang package" }, { "code": null, "e": 33422, "s": 33403, "text": "java-wrapper-class" }, { "code": null, "e": 33427, "s": 33422, "text": "Java" }, { "code": null, "e": 33432, "s": 33427, "text": "Java" }, { "code": null, "e": 33530, "s": 33432, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33545, "s": 33530, "text": "Arrays in Java" }, { "code": null, "e": 33589, "s": 33545, "text": "Split() String method in Java with examples" }, { "code": null, "e": 33611, "s": 33589, "text": "For-each loop in Java" }, { "code": null, "e": 33662, "s": 33611, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 33692, "s": 33662, "text": "HashMap in Java with Examples" }, { "code": null, "e": 33717, "s": 33692, "text": "Reverse a string in Java" }, { "code": null, "e": 33753, "s": 33717, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 33768, "s": 33753, "text": "Stream In Java" }, { "code": null, "e": 33787, "s": 33768, "text": "Interfaces in Java" } ]
How to Create Fragment Using Bottom Navigation in Social Media Android App? - GeeksforGeeks
06 Sep, 2021 This is the Part 2 of “Build a Social Media App in Android Studio” tutorial, and we are going to cover the following functionalities in this article: We are going to Create Bottom Navigation with 5 Fragments (Home, Users, AddBlog, ChatList, Profile). On HomeFragment we will be Showing all the added blogs. In the UsersFragment, we will be showing all the Registered Users. In the AddBlogFragment We will be adding our blogs. In the ChatlistFragment we will be showing a chat list of all users with whom we have chat. In the ProfileFragment We will be showing the Profile of the user where we will be showing users’ data and the blogs written by the user. Step 1: Firstly we will create a menu directory inside the res folder. Refer to this article How to Create Menu Folder & Menu File in Android Studio. And name the menus file as menu_nav.xml for creating the layout of bottom navigation. Below is the code for the menu_nav.xml file. XML <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/nav_home" android:icon="@drawable/ic_home" android:title="Home" /> <item android:id="@+id/nav_users" android:icon="@drawable/ic_users" android:title="Users" /> <item android:id="@+id/nav_addblogs" android:icon="@drawable/ic_add" android:title="Add Blogs" /> <item android:id="@+id/nav_chat" android:icon="@drawable/ic_chat" android:title="ChatList" /> <item android:id="@+id/nav_profile" android:icon="@drawable/ic_account" android:title="Profile" /> </menu> Step 2: Add dependency to build.gradle (Module: app) Navigate to the Gradle Scripts > build. gradle(Module: app) and add the below dependency in the dependencies section. implementation ‘com.google.android.material:material:1.2.0’ Step 3: Working with the activity_dashboard.xml file This page will be the first activity in our app after the user logged in. Navigate to the app > res > layout > activity_dashboard.xml and add the below code to that file. Below is the code for the activity_dashboard.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".DashboardActivity"> <FrameLayout android:id="@+id/content" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"></FrameLayout> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/navigation" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" android:background="?android:attr/windowBackground" app:labelVisibilityMode="labeled" app:menu="@menu/menu_nav"> </com.google.android.material.bottomnavigation.BottomNavigationView> </LinearLayout> Step 4: Create 5 new blank fragments Go to the app(right-click) > New > Fragment > Fragment (Blank) and name the fragment as HomeFragment, ProfileFragment, UsersFragment, ChatListFragment, and AddBlogsFragment. Step 5: Working with the DashboardActivity.java file In this file, we are just showing the fragment according to the navigation item selected. Then we will be showing the respective fragment. HomeFragment fragment=new HomeFragment(); FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.content,fragment,""); fragmentTransaction.commit(); Go to the DashboardActivity.java file and refer to the following code. Below is the code for the DashboardActivity.java file. Java package com.example.socialmediaapp; import android.os.Bundle;import android.view.MenuItem; import androidx.annotation.NonNull;import androidx.appcompat.app.ActionBar;import androidx.appcompat.app.AppCompatActivity;import androidx.fragment.app.FragmentTransaction; import com.google.android.material.bottomnavigation.BottomNavigationView;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser; public class DashboardActivity extends AppCompatActivity { private FirebaseAuth firebaseAuth; FirebaseUser firebaseUser; String myuid; ActionBar actionBar; BottomNavigationView navigationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard); actionBar = getSupportActionBar(); actionBar.setTitle("Profile Activity"); firebaseAuth = FirebaseAuth.getInstance(); navigationView = findViewById(R.id.navigation); navigationView.setOnNavigationItemSelectedListener(selectedListener); actionBar.setTitle("Home"); // When we open the application first // time the fragment should be shown to the user // in this case it is home fragment HomeFragment fragment = new HomeFragment(); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.content, fragment, ""); fragmentTransaction.commit(); } private BottomNavigationView.OnNavigationItemSelectedListener selectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.nav_home: actionBar.setTitle("Home"); HomeFragment fragment = new HomeFragment(); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.content, fragment, ""); fragmentTransaction.commit(); return true; case R.id.nav_profile: actionBar.setTitle("Profile"); ProfileFragment fragment1 = new ProfileFragment(); FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction(); fragmentTransaction1.replace(R.id.content, fragment1); fragmentTransaction1.commit(); return true; case R.id.nav_users: actionBar.setTitle("Users"); UsersFragment fragment2 = new UsersFragment(); FragmentTransaction fragmentTransaction2 = getSupportFragmentManager().beginTransaction(); fragmentTransaction2.replace(R.id.content, fragment2, ""); fragmentTransaction2.commit(); return true; case R.id.nav_chat: actionBar.setTitle("Chats"); ChatListFragment listFragment = new ChatListFragment(); FragmentTransaction fragmentTransaction3 = getSupportFragmentManager().beginTransaction(); fragmentTransaction3.replace(R.id.content, listFragment, ""); fragmentTransaction3.commit(); return true; case R.id.nav_addblogs: actionBar.setTitle("Add Blogs"); AddBlogsFragment fragment4 = new AddBlogsFragment(); FragmentTransaction fragmentTransaction4 = getSupportFragmentManager().beginTransaction(); fragmentTransaction4.replace(R.id.content, fragment4, ""); fragmentTransaction4.commit(); return true; } return false; } };} Output: For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing Below is the file structure after performing these operations: chhabradhanvi Firebase Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Resource Raw Folder in Android Studio Services in Android with Example Android RecyclerView in Kotlin Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26489, "s": 26461, "text": "\n06 Sep, 2021" }, { "code": null, "e": 26639, "s": 26489, "text": "This is the Part 2 of “Build a Social Media App in Android Studio” tutorial, and we are going to cover the following functionalities in this article:" }, { "code": null, "e": 26740, "s": 26639, "text": "We are going to Create Bottom Navigation with 5 Fragments (Home, Users, AddBlog, ChatList, Profile)." }, { "code": null, "e": 26796, "s": 26740, "text": "On HomeFragment we will be Showing all the added blogs." }, { "code": null, "e": 26863, "s": 26796, "text": "In the UsersFragment, we will be showing all the Registered Users." }, { "code": null, "e": 26915, "s": 26863, "text": "In the AddBlogFragment We will be adding our blogs." }, { "code": null, "e": 27007, "s": 26915, "text": "In the ChatlistFragment we will be showing a chat list of all users with whom we have chat." }, { "code": null, "e": 27145, "s": 27007, "text": "In the ProfileFragment We will be showing the Profile of the user where we will be showing users’ data and the blogs written by the user." }, { "code": null, "e": 27426, "s": 27145, "text": "Step 1: Firstly we will create a menu directory inside the res folder. Refer to this article How to Create Menu Folder & Menu File in Android Studio. And name the menus file as menu_nav.xml for creating the layout of bottom navigation. Below is the code for the menu_nav.xml file." }, { "code": null, "e": 27430, "s": 27426, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><menu xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item android:id=\"@+id/nav_home\" android:icon=\"@drawable/ic_home\" android:title=\"Home\" /> <item android:id=\"@+id/nav_users\" android:icon=\"@drawable/ic_users\" android:title=\"Users\" /> <item android:id=\"@+id/nav_addblogs\" android:icon=\"@drawable/ic_add\" android:title=\"Add Blogs\" /> <item android:id=\"@+id/nav_chat\" android:icon=\"@drawable/ic_chat\" android:title=\"ChatList\" /> <item android:id=\"@+id/nav_profile\" android:icon=\"@drawable/ic_account\" android:title=\"Profile\" /> </menu>", "e": 28137, "s": 27430, "text": null }, { "code": null, "e": 28190, "s": 28137, "text": "Step 2: Add dependency to build.gradle (Module: app)" }, { "code": null, "e": 28309, "s": 28190, "text": "Navigate to the Gradle Scripts > build. gradle(Module: app) and add the below dependency in the dependencies section. " }, { "code": null, "e": 28369, "s": 28309, "text": "implementation ‘com.google.android.material:material:1.2.0’" }, { "code": null, "e": 28422, "s": 28369, "text": "Step 3: Working with the activity_dashboard.xml file" }, { "code": null, "e": 28650, "s": 28422, "text": "This page will be the first activity in our app after the user logged in. Navigate to the app > res > layout > activity_dashboard.xml and add the below code to that file. Below is the code for the activity_dashboard.xml file. " }, { "code": null, "e": 28654, "s": 28650, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".DashboardActivity\"> <FrameLayout android:id=\"@+id/content\" android:layout_width=\"match_parent\" android:layout_height=\"0dp\" android:layout_weight=\"1\"></FrameLayout> <com.google.android.material.bottomnavigation.BottomNavigationView android:id=\"@+id/navigation\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"bottom\" android:background=\"?android:attr/windowBackground\" app:labelVisibilityMode=\"labeled\" app:menu=\"@menu/menu_nav\"> </com.google.android.material.bottomnavigation.BottomNavigationView> </LinearLayout>", "e": 29693, "s": 28654, "text": null }, { "code": null, "e": 29730, "s": 29693, "text": "Step 4: Create 5 new blank fragments" }, { "code": null, "e": 29904, "s": 29730, "text": "Go to the app(right-click) > New > Fragment > Fragment (Blank) and name the fragment as HomeFragment, ProfileFragment, UsersFragment, ChatListFragment, and AddBlogsFragment." }, { "code": null, "e": 29957, "s": 29904, "text": "Step 5: Working with the DashboardActivity.java file" }, { "code": null, "e": 30097, "s": 29957, "text": "In this file, we are just showing the fragment according to the navigation item selected. Then we will be showing the respective fragment. " }, { "code": null, "e": 30336, "s": 30097, "text": "HomeFragment fragment=new HomeFragment();\n FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();\n fragmentTransaction.replace(R.id.content,fragment,\"\");\n fragmentTransaction.commit();" }, { "code": null, "e": 30462, "s": 30336, "text": "Go to the DashboardActivity.java file and refer to the following code. Below is the code for the DashboardActivity.java file." }, { "code": null, "e": 30467, "s": 30462, "text": "Java" }, { "code": "package com.example.socialmediaapp; import android.os.Bundle;import android.view.MenuItem; import androidx.annotation.NonNull;import androidx.appcompat.app.ActionBar;import androidx.appcompat.app.AppCompatActivity;import androidx.fragment.app.FragmentTransaction; import com.google.android.material.bottomnavigation.BottomNavigationView;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser; public class DashboardActivity extends AppCompatActivity { private FirebaseAuth firebaseAuth; FirebaseUser firebaseUser; String myuid; ActionBar actionBar; BottomNavigationView navigationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard); actionBar = getSupportActionBar(); actionBar.setTitle(\"Profile Activity\"); firebaseAuth = FirebaseAuth.getInstance(); navigationView = findViewById(R.id.navigation); navigationView.setOnNavigationItemSelectedListener(selectedListener); actionBar.setTitle(\"Home\"); // When we open the application first // time the fragment should be shown to the user // in this case it is home fragment HomeFragment fragment = new HomeFragment(); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.content, fragment, \"\"); fragmentTransaction.commit(); } private BottomNavigationView.OnNavigationItemSelectedListener selectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.nav_home: actionBar.setTitle(\"Home\"); HomeFragment fragment = new HomeFragment(); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.content, fragment, \"\"); fragmentTransaction.commit(); return true; case R.id.nav_profile: actionBar.setTitle(\"Profile\"); ProfileFragment fragment1 = new ProfileFragment(); FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction(); fragmentTransaction1.replace(R.id.content, fragment1); fragmentTransaction1.commit(); return true; case R.id.nav_users: actionBar.setTitle(\"Users\"); UsersFragment fragment2 = new UsersFragment(); FragmentTransaction fragmentTransaction2 = getSupportFragmentManager().beginTransaction(); fragmentTransaction2.replace(R.id.content, fragment2, \"\"); fragmentTransaction2.commit(); return true; case R.id.nav_chat: actionBar.setTitle(\"Chats\"); ChatListFragment listFragment = new ChatListFragment(); FragmentTransaction fragmentTransaction3 = getSupportFragmentManager().beginTransaction(); fragmentTransaction3.replace(R.id.content, listFragment, \"\"); fragmentTransaction3.commit(); return true; case R.id.nav_addblogs: actionBar.setTitle(\"Add Blogs\"); AddBlogsFragment fragment4 = new AddBlogsFragment(); FragmentTransaction fragmentTransaction4 = getSupportFragmentManager().beginTransaction(); fragmentTransaction4.replace(R.id.content, fragment4, \"\"); fragmentTransaction4.commit(); return true; } return false; } };}", "e": 34545, "s": 30467, "text": null }, { "code": null, "e": 34553, "s": 34545, "text": "Output:" }, { "code": null, "e": 34712, "s": 34553, "text": "For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing" }, { "code": null, "e": 34776, "s": 34712, "text": "Below is the file structure after performing these operations: " }, { "code": null, "e": 34792, "s": 34778, "text": "chhabradhanvi" }, { "code": null, "e": 34801, "s": 34792, "text": "Firebase" }, { "code": null, "e": 34809, "s": 34801, "text": "Android" }, { "code": null, "e": 34814, "s": 34809, "text": "Java" }, { "code": null, "e": 34819, "s": 34814, "text": "Java" }, { "code": null, "e": 34827, "s": 34819, "text": "Android" }, { "code": null, "e": 34925, "s": 34827, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34983, "s": 34925, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 35026, "s": 34983, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 35064, "s": 35026, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 35097, "s": 35064, "text": "Services in Android with Example" }, { "code": null, "e": 35128, "s": 35097, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 35143, "s": 35128, "text": "Arrays in Java" }, { "code": null, "e": 35187, "s": 35143, "text": "Split() String method in Java with examples" }, { "code": null, "e": 35209, "s": 35187, "text": "For-each loop in Java" }, { "code": null, "e": 35260, "s": 35209, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Count possible ways to construct buildings - GeeksforGeeks
26 Aug, 2021 Given an input number of sections and each section has 2 plots on either sides of the road. Find all possible ways to construct buildings in the plots such that there is a space between any 2 buildings. Example : N = 1 Output = 4 Place a building on one side. Place a building on other side Do not place any building. Place a building on both sides. N = 3 Output = 25 3 sections, which means possible ways for one side are BSS, BSB, SSS, SBS, SSB where B represents a building and S represents an empty space Total possible ways are 25, because a way to place on one side can correspond to any of 5 ways on other side. N = 4 Output = 64 https://practice.geeksforgeeks.org/problems/count-possible-ways-to-construct-buildings5007/1 We strongly recommend to minimize your browser and try this yourself firstWe can simplify the problem to first calculate for one side only. If we know the result for one side, we can always do the square of the result and get the result for two sides. A new building can be placed on a section if section just before it has space. A space can be placed anywhere (it doesn’t matter whether the previous section has a building or not). Let countB(i) be count of possible ways with i sections ending with a building. countS(i) be count of possible ways with i sections ending with a space. // A space can be added after a building or after a space. countS(N) = countB(N-1) + countS(N-1) // A building can only be added after a space. countB[N] = countS(N-1) // Result for one side is sum of the above two counts. result1(N) = countS(N) + countB(N) // Result for two sides is square of result1(N) result2(N) = result1(N) * result1(N) Below is the implementation of the above idea. C++ Java Python3 C# PHP Javascript // C++ program to count all possible way to construct buildings#include<iostream>using namespace std; // Returns count of possible ways for N sectionsint countWays(int N){ // Base case if (N == 1) return 4; // 2 for one side and 4 for two sides // countB is count of ways with a building at the end // countS is count of ways with a space at the end // prev_countB and prev_countS are previous values of // countB and countS respectively. // Initialize countB and countS for one side int countB=1, countS=1, prev_countB, prev_countS; // Use the above recursive formula for calculating // countB and countS using previous values for (int i=2; i<=N; i++) { prev_countB = countB; prev_countS = countS; countS = prev_countB + prev_countS; countB = prev_countS; } // Result for one side is sum of ways ending with building // and ending with space int result = countS + countB; // Result for 2 sides is square of result for one side return (result*result);} // Driver programint main(){ int N = 3; cout << "Count of ways for " << N << " sections is " << countWays(N); return 0;} class Building{ // Returns count of possible ways for N sections static int countWays(int N) { // Base case if (N == 1) return 4; // 2 for one side and 4 for two sides // countB is count of ways with a building at the end // countS is count of ways with a space at the end // prev_countB and prev_countS are previous values of // countB and countS respectively. // Initialize countB and countS for one side int countB=1, countS=1, prev_countB, prev_countS; // Use the above recursive formula for calculating // countB and countS using previous values for (int i=2; i<=N; i++) { prev_countB = countB; prev_countS = countS; countS = prev_countB + prev_countS; countB = prev_countS; } // Result for one side is sum of ways ending with building // and ending with space int result = countS + countB; // Result for 2 sides is square of result for one side return (result*result); } public static void main(String args[]) { int N = 3; System.out.println("Count of ways for "+ N+" sections is " +countWays(N)); } }/* This code is contributed by Rajat Mishra */ # Python 3 program to count all possible# way to construct buildings # Returns count of possible ways# for N sectionsdef countWays(N) : # Base case if (N == 1) : # 2 for one side and 4 # for two sides return 4 # countB is count of ways with a # building at the end # countS is count of ways with a # space at the end # prev_countB and prev_countS are # previous values of # countB and countS respectively. # Initialize countB and countS # for one side countB=1 countS=1 # Use the above recursive formula # for calculating # countB and countS using previous values for i in range(2,N+1) : prev_countB = countB prev_countS = countS countS = prev_countB + prev_countS countB = prev_countS # Result for one side is sum of ways # ending with building # and ending with space result = countS + countB # Result for 2 sides is square of # result for one side return (result*result) # Driver programif __name__ == "__main__": N = 3 print ("Count of ways for ", N ," sections is " ,countWays(N)) # This code is contributed by# ChitraNayal // C# program to count all// possible way to construct// buildingsusing System; class GFG{ // Returns count of possible // ways for N sections static int countWays(int N) { // Base case if (N == 1) // 2 for one side and // 4 for two sides return 4; // countB is count of ways // with a building at the // end, countS is count of // ways with a space at the // end, prev_countB and // prev_countS are previous // values of countB and countS // respectively. // Initialize countB and // countS for one side int countB = 1, countS = 1, prev_countB, prev_countS; // Use the above recursive // formula for calculating // countB and countS using // previous values for (int i = 2; i <= N; i++) { prev_countB = countB; prev_countS = countS; countS = prev_countB + prev_countS; countB = prev_countS; } // Result for one side is sum // of ways ending with building // and ending with space int result = countS + countB; // Result for 2 sides is // square of result for // one side return (result * result); } // Driver Code public static void Main() { int N = 3; Console.Write(countWays(N)); } } // This code is contributed by nitin mittal. <?php// PHP program to count all possible// way to construct buildings // Returns count of possible// ways for N sectionsfunction countWays( $N){ // Base case if ($N == 1) // 2 for one side and // 4 for two sides return 4; // countB is count of ways // with a building at the end // countS is count of ways // with a space at the end // prev_countB and prev_countS // are previous values of // countB and countS respectively. // Initialize countB and // countS for one side $countB = 1; $countS = 1; $prev_countB; $prev_countS; // Use the above recursive // formula for calculating // countB and countS using // previous values for ($i = 2; $i <= $N; $i++) { $prev_countB = $countB; $prev_countS = $countS; $countS = $prev_countB + $prev_countS; $countB = $prev_countS; } // Result for one side is // sum of ways ending with // building and ending with // space $result = $countS + $countB; // Result for 2 sides is square // of result for one side return ($result*$result);} // Driver Code $N = 3; echo "Count of ways for " , $N , " sections is " , countWays($N); // This code is contributed by anuj_67.?> <script>// Javascript program to count all// possible way to construct buildings // Returns count of possible ways for N sectionsfunction countWays(N){ // Base case if (N == 1) // 2 for one side and // 4 for two sides return 4; // countB is count of ways with a building at the end // countS is count of ways with a space at the end // prev_countB and prev_countS are previous values of // countB and countS respectively. // Initialize countB and countS for one side let countB = 1, countS = 1, prev_countB, prev_countS; // Use the above recursive formula for calculating // countB and countS using previous values for(let i = 2; i <= N; i++) { prev_countB = countB; prev_countS = countS; countS = prev_countB + prev_countS; countB = prev_countS; } // Result for one side is sum of // ways ending with building // and ending with space let result = countS + countB; // Result for 2 sides is square // of result for one side return (result*result);} // Driver codeN = 3; document.write("Count of ways for " + N + " sections is " + countWays(N)); // This code is contributed by avanitrachhadiya2155 </script> Count of ways for 3 sections is 25 Output : Count of ways for 3 sections is 25 Time complexity: O(N)Auxiliary Space: O(1)Algorithmic Paradigm: Dynamic Programming Another Way of Thinking : (on one side only because for another side it will be the same) Let us think of buildings as the sequence of N (because there are N plots on either side) length binary string (each digit either 0 or 1) where : 1 => Represents building has been made on the ith plot 0 => Represents building has not been made on the ith plot Now as the problem states we have to find the number of ways such that we don’t have consecutive Buildings on plots, in the binary string, it can be interpreted as, we need to find the number of ways such that we do not have consecutive 1 in the binary string (as 1 represented building being made) Example : N = 3 Total Combinations = 2n = 23 = 8 This will contain some combination in there will be consecutive building, so we have to reject that 000 (No building) (Possible) 001 (Building on 3rd plot) (Possible) 010 (Building on 2nd plot) (Possible) 011 (Building on 2nd and 3rd plot) (Not Possible as there are consecutive buildings) 100 (Building on 1st plot) (Possible) 101 (Building on 1st and 3rd plot) (Possible) 110 (Building on 1st and 2nd plot) (Not Possible as there are consecutive buildings) 111 (Building on 1st, 2nd, 3rd plot) (Not Possible as there are consecutive buildings) Total Possible Ways = 5 These are only on one side, on other side it will also be same as there are N plots and same condition, so Answer = Total Possible Ways * Total Possible Ways = 25 So now our problem is reduced to find the number of ways to represent N length binary string such that it does not have consecutive 1 which is a pretty standard problem Optimized Solution: Note that the above solution can be further optimized. If we take a closer look at the results, for different values, we can notice that the results for the two sides are squares of Fibonacci Numbers.N = 1, result = 4 [result for one side = 2] N = 2, result = 9 [result for one side = 3] N = 3, result = 25 [result for one side = 5] N = 4, result = 64 [result for one side = 8] N = 5, result = 169 [result for one side = 13] ......................... .........................In general, we can say result(N) = fib(N+2)2 fib(N) is a function that returns N'th Fibonacci Number. Therefore, we can use the O(LogN) implementation of Fibonacci Numbers to find the number of ways in O(logN) time.This article is contributed by GOPINATH. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal vt_m ukasp avanitrachhadiya2155 RohitSingh32 udaigupta19311 anshkush92 Fibonacci Payu Dynamic Programming Payu Dynamic Programming Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Edit Distance | DP-5 Overlapping Subproblems Property in Dynamic Programming | DP-1 Maximum size square sub-matrix with all 1s Find minimum number of coins that make a given value Minimum number of jumps to reach end Tabulation vs Memoization Longest Common Substring | DP-29
[ { "code": null, "e": 26187, "s": 26159, "text": "\n26 Aug, 2021" }, { "code": null, "e": 26390, "s": 26187, "text": "Given an input number of sections and each section has 2 plots on either sides of the road. Find all possible ways to construct buildings in the plots such that there is a space between any 2 buildings." }, { "code": null, "e": 26401, "s": 26390, "text": "Example : " }, { "code": null, "e": 26832, "s": 26401, "text": "N = 1\nOutput = 4\nPlace a building on one side.\nPlace a building on other side\nDo not place any building.\nPlace a building on both sides.\n\nN = 3 \nOutput = 25\n3 sections, which means possible ways for one side are \nBSS, BSB, SSS, SBS, SSB where B represents a building \nand S represents an empty space\nTotal possible ways are 25, because a way to place on \none side can correspond to any of 5 ways on other side.\n\nN = 4 \nOutput = 64" }, { "code": null, "e": 26925, "s": 26832, "text": "https://practice.geeksforgeeks.org/problems/count-possible-ways-to-construct-buildings5007/1" }, { "code": null, "e": 27177, "s": 26925, "text": "We strongly recommend to minimize your browser and try this yourself firstWe can simplify the problem to first calculate for one side only. If we know the result for one side, we can always do the square of the result and get the result for two sides." }, { "code": null, "e": 27359, "s": 27177, "text": "A new building can be placed on a section if section just before it has space. A space can be placed anywhere (it doesn’t matter whether the previous section has a building or not)." }, { "code": null, "e": 27892, "s": 27359, "text": "Let countB(i) be count of possible ways with i sections\n ending with a building.\n countS(i) be count of possible ways with i sections\n ending with a space.\n\n// A space can be added after a building or after a space.\ncountS(N) = countB(N-1) + countS(N-1)\n\n// A building can only be added after a space.\ncountB[N] = countS(N-1)\n\n// Result for one side is sum of the above two counts.\nresult1(N) = countS(N) + countB(N)\n\n// Result for two sides is square of result1(N)\nresult2(N) = result1(N) * result1(N) " }, { "code": null, "e": 27940, "s": 27892, "text": "Below is the implementation of the above idea. " }, { "code": null, "e": 27944, "s": 27940, "text": "C++" }, { "code": null, "e": 27949, "s": 27944, "text": "Java" }, { "code": null, "e": 27957, "s": 27949, "text": "Python3" }, { "code": null, "e": 27960, "s": 27957, "text": "C#" }, { "code": null, "e": 27964, "s": 27960, "text": "PHP" }, { "code": null, "e": 27975, "s": 27964, "text": "Javascript" }, { "code": "// C++ program to count all possible way to construct buildings#include<iostream>using namespace std; // Returns count of possible ways for N sectionsint countWays(int N){ // Base case if (N == 1) return 4; // 2 for one side and 4 for two sides // countB is count of ways with a building at the end // countS is count of ways with a space at the end // prev_countB and prev_countS are previous values of // countB and countS respectively. // Initialize countB and countS for one side int countB=1, countS=1, prev_countB, prev_countS; // Use the above recursive formula for calculating // countB and countS using previous values for (int i=2; i<=N; i++) { prev_countB = countB; prev_countS = countS; countS = prev_countB + prev_countS; countB = prev_countS; } // Result for one side is sum of ways ending with building // and ending with space int result = countS + countB; // Result for 2 sides is square of result for one side return (result*result);} // Driver programint main(){ int N = 3; cout << \"Count of ways for \" << N << \" sections is \" << countWays(N); return 0;}", "e": 29162, "s": 27975, "text": null }, { "code": "class Building{ // Returns count of possible ways for N sections static int countWays(int N) { // Base case if (N == 1) return 4; // 2 for one side and 4 for two sides // countB is count of ways with a building at the end // countS is count of ways with a space at the end // prev_countB and prev_countS are previous values of // countB and countS respectively. // Initialize countB and countS for one side int countB=1, countS=1, prev_countB, prev_countS; // Use the above recursive formula for calculating // countB and countS using previous values for (int i=2; i<=N; i++) { prev_countB = countB; prev_countS = countS; countS = prev_countB + prev_countS; countB = prev_countS; } // Result for one side is sum of ways ending with building // and ending with space int result = countS + countB; // Result for 2 sides is square of result for one side return (result*result); } public static void main(String args[]) { int N = 3; System.out.println(\"Count of ways for \"+ N+\" sections is \" +countWays(N)); } }/* This code is contributed by Rajat Mishra */", "e": 30526, "s": 29162, "text": null }, { "code": "# Python 3 program to count all possible# way to construct buildings # Returns count of possible ways# for N sectionsdef countWays(N) : # Base case if (N == 1) : # 2 for one side and 4 # for two sides return 4 # countB is count of ways with a # building at the end # countS is count of ways with a # space at the end # prev_countB and prev_countS are # previous values of # countB and countS respectively. # Initialize countB and countS # for one side countB=1 countS=1 # Use the above recursive formula # for calculating # countB and countS using previous values for i in range(2,N+1) : prev_countB = countB prev_countS = countS countS = prev_countB + prev_countS countB = prev_countS # Result for one side is sum of ways # ending with building # and ending with space result = countS + countB # Result for 2 sides is square of # result for one side return (result*result) # Driver programif __name__ == \"__main__\": N = 3 print (\"Count of ways for \", N ,\" sections is \" ,countWays(N)) # This code is contributed by# ChitraNayal", "e": 31713, "s": 30526, "text": null }, { "code": "// C# program to count all// possible way to construct// buildingsusing System; class GFG{ // Returns count of possible // ways for N sections static int countWays(int N) { // Base case if (N == 1) // 2 for one side and // 4 for two sides return 4; // countB is count of ways // with a building at the // end, countS is count of // ways with a space at the // end, prev_countB and // prev_countS are previous // values of countB and countS // respectively. // Initialize countB and // countS for one side int countB = 1, countS = 1, prev_countB, prev_countS; // Use the above recursive // formula for calculating // countB and countS using // previous values for (int i = 2; i <= N; i++) { prev_countB = countB; prev_countS = countS; countS = prev_countB + prev_countS; countB = prev_countS; } // Result for one side is sum // of ways ending with building // and ending with space int result = countS + countB; // Result for 2 sides is // square of result for // one side return (result * result); } // Driver Code public static void Main() { int N = 3; Console.Write(countWays(N)); } } // This code is contributed by nitin mittal.", "e": 33230, "s": 31713, "text": null }, { "code": "<?php// PHP program to count all possible// way to construct buildings // Returns count of possible// ways for N sectionsfunction countWays( $N){ // Base case if ($N == 1) // 2 for one side and // 4 for two sides return 4; // countB is count of ways // with a building at the end // countS is count of ways // with a space at the end // prev_countB and prev_countS // are previous values of // countB and countS respectively. // Initialize countB and // countS for one side $countB = 1; $countS = 1; $prev_countB; $prev_countS; // Use the above recursive // formula for calculating // countB and countS using // previous values for ($i = 2; $i <= $N; $i++) { $prev_countB = $countB; $prev_countS = $countS; $countS = $prev_countB + $prev_countS; $countB = $prev_countS; } // Result for one side is // sum of ways ending with // building and ending with // space $result = $countS + $countB; // Result for 2 sides is square // of result for one side return ($result*$result);} // Driver Code $N = 3; echo \"Count of ways for \" , $N , \" sections is \" , countWays($N); // This code is contributed by anuj_67.?>", "e": 34522, "s": 33230, "text": null }, { "code": "<script>// Javascript program to count all// possible way to construct buildings // Returns count of possible ways for N sectionsfunction countWays(N){ // Base case if (N == 1) // 2 for one side and // 4 for two sides return 4; // countB is count of ways with a building at the end // countS is count of ways with a space at the end // prev_countB and prev_countS are previous values of // countB and countS respectively. // Initialize countB and countS for one side let countB = 1, countS = 1, prev_countB, prev_countS; // Use the above recursive formula for calculating // countB and countS using previous values for(let i = 2; i <= N; i++) { prev_countB = countB; prev_countS = countS; countS = prev_countB + prev_countS; countB = prev_countS; } // Result for one side is sum of // ways ending with building // and ending with space let result = countS + countB; // Result for 2 sides is square // of result for one side return (result*result);} // Driver codeN = 3; document.write(\"Count of ways for \" + N + \" sections is \" + countWays(N)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 35788, "s": 34522, "text": null }, { "code": null, "e": 35823, "s": 35788, "text": "Count of ways for 3 sections is 25" }, { "code": null, "e": 35833, "s": 35823, "text": "Output : " }, { "code": null, "e": 35868, "s": 35833, "text": "Count of ways for 3 sections is 25" }, { "code": null, "e": 35952, "s": 35868, "text": "Time complexity: O(N)Auxiliary Space: O(1)Algorithmic Paradigm: Dynamic Programming" }, { "code": null, "e": 36042, "s": 35952, "text": "Another Way of Thinking : (on one side only because for another side it will be the same)" }, { "code": null, "e": 36188, "s": 36042, "text": "Let us think of buildings as the sequence of N (because there are N plots on either side) length binary string (each digit either 0 or 1) where :" }, { "code": null, "e": 36304, "s": 36188, "text": "1 => Represents building has been made on the ith plot\n0 => Represents building has not been made on the ith plot " }, { "code": null, "e": 36603, "s": 36304, "text": "Now as the problem states we have to find the number of ways such that we don’t have consecutive Buildings on plots, in the binary string, it can be interpreted as, we need to find the number of ways such that we do not have consecutive 1 in the binary string (as 1 represented building being made)" }, { "code": null, "e": 36613, "s": 36603, "text": "Example :" }, { "code": null, "e": 37393, "s": 36613, "text": "N = 3 \nTotal Combinations = 2n = 23 = 8\nThis will contain some combination in there will be consecutive building, so we have to reject that\n\n000 (No building) (Possible)\n001 (Building on 3rd plot) (Possible)\n010 (Building on 2nd plot) (Possible)\n011 (Building on 2nd and 3rd plot) (Not Possible as there are consecutive buildings)\n100 (Building on 1st plot) (Possible)\n101 (Building on 1st and 3rd plot) (Possible)\n110 (Building on 1st and 2nd plot) (Not Possible as there are consecutive buildings)\n111 (Building on 1st, 2nd, 3rd plot) (Not Possible as there are consecutive buildings)\n\nTotal Possible Ways = 5 \nThese are only on one side, on other side it will also be same as there are N plots and same condition, so \n\nAnswer = Total Possible Ways * Total Possible Ways = 25 " }, { "code": null, "e": 37562, "s": 37393, "text": "So now our problem is reduced to find the number of ways to represent N length binary string such that it does not have consecutive 1 which is a pretty standard problem" }, { "code": null, "e": 38082, "s": 37562, "text": "Optimized Solution: Note that the above solution can be further optimized. If we take a closer look at the results, for different values, we can notice that the results for the two sides are squares of Fibonacci Numbers.N = 1, result = 4 [result for one side = 2] N = 2, result = 9 [result for one side = 3] N = 3, result = 25 [result for one side = 5] N = 4, result = 64 [result for one side = 8] N = 5, result = 169 [result for one side = 13] ......................... .........................In general, we can say " }, { "code": null, "e": 38183, "s": 38082, "text": " result(N) = fib(N+2)2\n \n fib(N) is a function that returns N'th \n Fibonacci Number. \n " }, { "code": null, "e": 38462, "s": 38183, "text": "Therefore, we can use the O(LogN) implementation of Fibonacci Numbers to find the number of ways in O(logN) time.This article is contributed by GOPINATH. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 38475, "s": 38462, "text": "nitin mittal" }, { "code": null, "e": 38480, "s": 38475, "text": "vt_m" }, { "code": null, "e": 38486, "s": 38480, "text": "ukasp" }, { "code": null, "e": 38507, "s": 38486, "text": "avanitrachhadiya2155" }, { "code": null, "e": 38520, "s": 38507, "text": "RohitSingh32" }, { "code": null, "e": 38535, "s": 38520, "text": "udaigupta19311" }, { "code": null, "e": 38546, "s": 38535, "text": "anshkush92" }, { "code": null, "e": 38556, "s": 38546, "text": "Fibonacci" }, { "code": null, "e": 38561, "s": 38556, "text": "Payu" }, { "code": null, "e": 38581, "s": 38561, "text": "Dynamic Programming" }, { "code": null, "e": 38586, "s": 38581, "text": "Payu" }, { "code": null, "e": 38606, "s": 38586, "text": "Dynamic Programming" }, { "code": null, "e": 38616, "s": 38606, "text": "Fibonacci" }, { "code": null, "e": 38714, "s": 38616, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38747, "s": 38714, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 38782, "s": 38747, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 38850, "s": 38782, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 38871, "s": 38850, "text": "Edit Distance | DP-5" }, { "code": null, "e": 38934, "s": 38871, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" }, { "code": null, "e": 38977, "s": 38934, "text": "Maximum size square sub-matrix with all 1s" }, { "code": null, "e": 39030, "s": 38977, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 39067, "s": 39030, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 39093, "s": 39067, "text": "Tabulation vs Memoization" } ]
How to load the contents of a text file into a JavaScript variable? - GeeksforGeeks
10 May, 2022 In this article, we will examine how to read the contents of any text file that exists on your computer into a variable using JavaScript. The following are a few basic pointers that everybody should brush through before looking at the code: Event listeners: These are predefined functions that exist in JavaScript. They take two arguments, the first one is, the event that an element should look for/ listen to and the second one is, the action that the element should perform if the event mentioned in the first argument occurs. Regular Expressions: A regular expression is a sequence of characters. Every regular expression defines a certain pattern that can be used for multiple purposes. The most common one being, pattern matching. As mentioned above Regular Expressions are most commonly used for pattern matching and after the expected pattern of characters is spotted, many functions can be applied on them, like split(), join(), replace() etc. Example: In this example we will just create a text area where the text will appear from the text file that has been used as an input in the index.html. The JavaScript code will be able to extract the text from any text file and display it in script.js. index.html: html <!DOCTYPE html><html> <head> <title>Text file reading</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head><style type="text/css"> div { display: flex; flex-direction: column; align-items: center; } input { margin-top: 10px; } textarea { margin-top: 15px; width: 70%; }</style> <body> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <div> <input type="file"> <textarea cols="30" rows="20" placeholder="text will appear here"> </textarea> </div> </center> <script src="script.js"></script></body> </html> script.js: javascript let input = document.querySelector('input') let textarea = document.querySelector('textarea') // This event listener has been implemented to identify a// Change in the input section of the html code// It will be triggered when a file is chosen.input.addEventListener('change', () => { let files = input.files; if (files.length == 0) return; /* If any further modifications have to be made on the Extracted text. The text can be accessed using the file variable. But since this is const, it is a read only variable, hence immutable. To make any changes, changing const to var, here and In the reader.onload function would be advisible */ const file = files[0]; let reader = new FileReader(); reader.onload = (e) => { const file = e.target.result; // This is a regular expression to identify carriage // Returns and line breaks const lines = file.split(/\r\n|\n/); textarea.value = lines.join('\n'); }; reader.onerror = (e) => alert(e.target.error.name); reader.readAsText(file);}); Output: JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. hardikkoriintern CSS-Misc HTML-Misc Picked CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to set space between the flexbox ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 25925, "s": 25897, "text": "\n10 May, 2022" }, { "code": null, "e": 26166, "s": 25925, "text": "In this article, we will examine how to read the contents of any text file that exists on your computer into a variable using JavaScript. The following are a few basic pointers that everybody should brush through before looking at the code:" }, { "code": null, "e": 26455, "s": 26166, "text": "Event listeners: These are predefined functions that exist in JavaScript. They take two arguments, the first one is, the event that an element should look for/ listen to and the second one is, the action that the element should perform if the event mentioned in the first argument occurs." }, { "code": null, "e": 26878, "s": 26455, "text": "Regular Expressions: A regular expression is a sequence of characters. Every regular expression defines a certain pattern that can be used for multiple purposes. The most common one being, pattern matching. As mentioned above Regular Expressions are most commonly used for pattern matching and after the expected pattern of characters is spotted, many functions can be applied on them, like split(), join(), replace() etc." }, { "code": null, "e": 27132, "s": 26878, "text": "Example: In this example we will just create a text area where the text will appear from the text file that has been used as an input in the index.html. The JavaScript code will be able to extract the text from any text file and display it in script.js." }, { "code": null, "e": 27145, "s": 27132, "text": "index.html: " }, { "code": null, "e": 27150, "s": 27145, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Text file reading</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> </head><style type=\"text/css\"> div { display: flex; flex-direction: column; align-items: center; } input { margin-top: 10px; } textarea { margin-top: 15px; width: 70%; }</style> <body> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div> <input type=\"file\"> <textarea cols=\"30\" rows=\"20\" placeholder=\"text will appear here\"> </textarea> </div> </center> <script src=\"script.js\"></script></body> </html>", "e": 27906, "s": 27150, "text": null }, { "code": null, "e": 27918, "s": 27906, "text": "script.js: " }, { "code": null, "e": 27929, "s": 27918, "text": "javascript" }, { "code": "let input = document.querySelector('input') let textarea = document.querySelector('textarea') // This event listener has been implemented to identify a// Change in the input section of the html code// It will be triggered when a file is chosen.input.addEventListener('change', () => { let files = input.files; if (files.length == 0) return; /* If any further modifications have to be made on the Extracted text. The text can be accessed using the file variable. But since this is const, it is a read only variable, hence immutable. To make any changes, changing const to var, here and In the reader.onload function would be advisible */ const file = files[0]; let reader = new FileReader(); reader.onload = (e) => { const file = e.target.result; // This is a regular expression to identify carriage // Returns and line breaks const lines = file.split(/\\r\\n|\\n/); textarea.value = lines.join('\\n'); }; reader.onerror = (e) => alert(e.target.error.name); reader.readAsText(file);});", "e": 29010, "s": 27929, "text": null }, { "code": null, "e": 29073, "s": 29019, "text": "Output: " }, { "code": null, "e": 29332, "s": 29113, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 29349, "s": 29332, "text": "hardikkoriintern" }, { "code": null, "e": 29358, "s": 29349, "text": "CSS-Misc" }, { "code": null, "e": 29368, "s": 29358, "text": "HTML-Misc" }, { "code": null, "e": 29375, "s": 29368, "text": "Picked" }, { "code": null, "e": 29379, "s": 29375, "text": "CSS" }, { "code": null, "e": 29384, "s": 29379, "text": "HTML" }, { "code": null, "e": 29395, "s": 29384, "text": "JavaScript" }, { "code": null, "e": 29412, "s": 29395, "text": "Web Technologies" }, { "code": null, "e": 29439, "s": 29412, "text": "Web technologies Questions" }, { "code": null, "e": 29444, "s": 29439, "text": "HTML" }, { "code": null, "e": 29542, "s": 29444, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29597, "s": 29542, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 29634, "s": 29597, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 29698, "s": 29634, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 29735, "s": 29698, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29774, "s": 29735, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29834, "s": 29774, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29887, "s": 29834, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29948, "s": 29887, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29972, "s": 29948, "text": "REST API (Introduction)" } ]
PYGLET – Drawing Rectangle - GeeksforGeeks
09 Jul, 2021 In this article we will see how we can draw rectangle on window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). A rectangle is a four-sided shape where every angle is a right angle (90°). Also opposite sides are parallel and of equal length. Rectangle is drawn with the help of shapes module in pyglet.We can create a window with the help of command given below # creating a window window = pyglet.window.Window(width, height, title) In order to create window we use Rectangle method with pyglet.shapesSyntax : shapes.Rectangle(x, y, width, height, color=(255, 255, 255), batch=None)Argument : It takes position i.e pair of integer, width and height of rectangle, color of rectangle and last is batch objectReturn : It returns Line object Below is the implementation Python3 # importing pyglet moduleimport pyglet # importing shapes from the pygletfrom pyglet import shapes # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = "Geeksforgeeks" # creating a windowwindow = pyglet.window.Window(width, height, title) # creating a batch objectbatch = pyglet.graphics.Batch() # properties of rectangle# co-ordinates of rectangleco_x = 150co_y = 150 # width of rectanglewidth = 300 # height of rectangleheight = 200 # color = greencolor = (50, 225, 30) # creating a rectanglerec1 = shapes.Rectangle(co_x, co_y, width, height, color = color, batch = batch) # changing opacity of the rect1# opacity is visibility (0 = invisible, 255 means visible)rec1.opacity = 250 # creating another rectangle with properties# x, y co ordinate : 50, 250# width, height of rectangle : 300, 200# color = redcolor = (255, 25, 25) # creating rectanglerec2 = shapes.Rectangle(50, 250, 300, 200, color = color, batch = batch) # changing opacity of the rec2# opacity is visibility (0 = invisible, 255 means visible)rec2.opacity = 100 # window draw event to draw rectangles@window.eventdef on_draw(): # clear the window window.clear() # draw the batch batch.draw() # run the pyglet applicationpyglet.app.run() sagartomar9927 Python-gui Python-Pyglet Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n09 Jul, 2021" }, { "code": null, "e": 26163, "s": 25537, "text": "In this article we will see how we can draw rectangle on window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). A rectangle is a four-sided shape where every angle is a right angle (90°). Also opposite sides are parallel and of equal length. Rectangle is drawn with the help of shapes module in pyglet.We can create a window with the help of command given below " }, { "code": null, "e": 26235, "s": 26163, "text": "# creating a window\nwindow = pyglet.window.Window(width, height, title)" }, { "code": null, "e": 26544, "s": 26237, "text": "In order to create window we use Rectangle method with pyglet.shapesSyntax : shapes.Rectangle(x, y, width, height, color=(255, 255, 255), batch=None)Argument : It takes position i.e pair of integer, width and height of rectangle, color of rectangle and last is batch objectReturn : It returns Line object " }, { "code": null, "e": 26574, "s": 26544, "text": "Below is the implementation " }, { "code": null, "e": 26582, "s": 26574, "text": "Python3" }, { "code": "# importing pyglet moduleimport pyglet # importing shapes from the pygletfrom pyglet import shapes # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = \"Geeksforgeeks\" # creating a windowwindow = pyglet.window.Window(width, height, title) # creating a batch objectbatch = pyglet.graphics.Batch() # properties of rectangle# co-ordinates of rectangleco_x = 150co_y = 150 # width of rectanglewidth = 300 # height of rectangleheight = 200 # color = greencolor = (50, 225, 30) # creating a rectanglerec1 = shapes.Rectangle(co_x, co_y, width, height, color = color, batch = batch) # changing opacity of the rect1# opacity is visibility (0 = invisible, 255 means visible)rec1.opacity = 250 # creating another rectangle with properties# x, y co ordinate : 50, 250# width, height of rectangle : 300, 200# color = redcolor = (255, 25, 25) # creating rectanglerec2 = shapes.Rectangle(50, 250, 300, 200, color = color, batch = batch) # changing opacity of the rec2# opacity is visibility (0 = invisible, 255 means visible)rec2.opacity = 100 # window draw event to draw rectangles@window.eventdef on_draw(): # clear the window window.clear() # draw the batch batch.draw() # run the pyglet applicationpyglet.app.run()", "e": 27865, "s": 26582, "text": null }, { "code": null, "e": 27880, "s": 27865, "text": "sagartomar9927" }, { "code": null, "e": 27891, "s": 27880, "text": "Python-gui" }, { "code": null, "e": 27905, "s": 27891, "text": "Python-Pyglet" }, { "code": null, "e": 27912, "s": 27905, "text": "Python" }, { "code": null, "e": 28010, "s": 27912, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28042, "s": 28010, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28084, "s": 28042, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28126, "s": 28084, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28182, "s": 28126, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28209, "s": 28182, "text": "Python Classes and Objects" }, { "code": null, "e": 28248, "s": 28209, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28279, "s": 28248, "text": "Python | os.path.join() method" }, { "code": null, "e": 28301, "s": 28279, "text": "Defaultdict in Python" }, { "code": null, "e": 28330, "s": 28301, "text": "Create a directory in Python" } ]
Cryptocurrency Analysis with Python — Buy and Hold | by Roman Orac | Towards Data Science
In this part, I am going to analyze which coin (Bitcoin, Ethereum or Litecoin) was the most profitable in the last two months using buy and hold strategy. We’ll go through the analysis of these 3 cryptocurrencies and try to give an objective answer. In case you’ve missed my other articles about this topic: romanorac.medium.com Here are few links that might interest you: - Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course] Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything. I am not a trader and this blog post is not financial advice. This is purely introductory knowledge. The conclusion here can be misleading as we analyze the period with immense growth. seaborn: statistical data visualization For other requirements, see my previous blog post in this series. To get the latest data, go to the previous blog post, where I described how to download it using Cryptocompare API. You can also use the data I work within this example. First, let’s download hourly data for BTC, ETH, and LTC from Coinbase exchange. This time we work with an hourly time interval as it has higher granularity. Cryptocompare API limits response to 2000 samples, which is 2.7 months of data for each coin. import pandas as pddef get_filename(from_symbol, to_symbol, exchange, datetime_interval, download_date): return '%s_%s_%s_%s_%s.csv' % (from_symbol, to_symbol, exchange, datetime_interval, download_date)def read_dataset(filename): print('Reading data from %s' % filename) df = pd.read_csv(filename) df.datetime = pd.to_datetime(df.datetime) # change to datetime df = df.set_index('datetime') df = df.sort_index() # sort by datetime print(df.shape) return df df_btc = read_dataset(get_filename('BTC', 'USD', 'Coinbase', 'hour', '2017-12-24'))df_eth = read_dataset(get_filename('ETH', 'USD', 'Coinbase', 'hour', '2017-12-24'))df_ltc = read_dataset(get_filename('LTC', 'USD', 'Coinbase', 'hour', '2017-12-24'))df_btc.head() We are going to analyze closing prices, which are prices at which the hourly period closed. We merge BTC, ETH and LTC closing prices to a Dataframe to make analysis easier. df = pd.DataFrame({'BTC': df_btc.close, 'ETH': df_eth.close, 'LTC': df_ltc.close})df.head() In 2.7 months, all three cryptocurrencies fluctuated a lot as you can observe in the table below. For each coin, we count the number of events and calculate mean, standard deviation, minimum, quartiles, and maximum closing price. Observations The difference between the highest and the lowest BTC price was more than $15000 in 2.7 months. The LTC surged from $48.61 to $378.66 at a certain point, which is an increase of 678.98%. df.describe() We visualize the data in the table above with a box plot. A box plot shows the quartiles of the dataset with points that are determined to be outliers using a method of the inter-quartile range (IQR). In other words, the IQR is the first quartile (25%) subtracted from the third quartile (75%). On the box plot below, we see that LTC closing hourly price was most of the time between $50 and $100 in the last 2.7 months. All values over $150 are outliers (using IQR). Note that outliers are specific to this data sample. import seaborn as snsax = sns.boxplot(data=df['LTC'], orient="h") Let’s estimate the frequency distribution of LTC closing prices. The histogram shows the number of hours LTC had a certain value. Observations LTC closing price was not over $100 for many hours. it has right-skewed distribution because a natural limit prevents outcomes on one side. blue dashed line (median) shows that half of the time closing prices were under $63.50. df['LTC'].hist(bins=30, figsize=(15,10)).axvline(df['LTC'].median(), color='b', linestyle='dashed', linewidth=2) The chart below shows the absolute closing prices. It is not of much use as BTC closing prices are much higher than prices of ETH and LTC. df.plot(grid=True, figsize=(15, 10)) We are interested in a relative change of the price rather than in absolute price, so we use three different y-axis scales. We see that closing prices move in tandem. When one coin closing price increases so do the other. import matplotlib.pyplot as pltimport numpy as npfig, ax1 = plt.subplots(figsize=(20, 10))ax2 = ax1.twinx()rspine = ax2.spines['right']rspine.set_position(('axes', 1.15))ax2.set_frame_on(True)ax2.patch.set_visible(False)fig.subplots_adjust(right=0.7)df['BTC'].plot(ax=ax1, style='b-')df['ETH'].plot(ax=ax1, style='r-', secondary_y=True)df['LTC'].plot(ax=ax2, style='g-')# legendax2.legend([ax1.get_lines()[0], ax1.right_ax.get_lines()[0], ax2.get_lines()[0]], ['BTC', 'ETH', 'LTC']) We calculate the Pearson correlation between the closing prices of BTC, ETH, and LTC. Pearson correlation is a measure of the linear correlation between two variables X and Y. It has a value between +1 and −1, where 1 is the total positive linear correlation, 0 is no linear correlation, and −1 is the total negative linear correlation. The correlation matrix is symmetric so we only show the lower half. Sifr Data daily updates Pearson correlations for many cryptocurrencies. Observations Closing prices aren’t normalized, see Log Returns, where we normalize closing prices before calculating correlation, BTC, ETH and LTC were highly correlated in the past 2 months. This means, when BTC closing price increased, ETH and LTC followed. ETH and LTC were even more correlated with 0.9565 Pearson correlation coefficient. import seaborn as snsimport matplotlib.pyplot as plt# Compute the correlation matrixcorr = df.corr()# Generate a mask for the upper trianglemask = np.zeros_like(corr, dtype=np.bool)mask[np.triu_indices_from(mask)] = True# Set up the matplotlib figuref, ax = plt.subplots(figsize=(10, 10))# Draw the heatmap with the mask and correct aspect ratiosns.heatmap(corr, annot=True, fmt = '.4f', mask=mask, center=0, square=True, linewidths=.5) Buy and hold is a passive investment strategy in which an investor buys a cryptocurrency and holds it for a long period, regardless of fluctuations in the market. Let’s analyze returns using the Buy and hold strategy for the past 2.7 months. We calculate the return percentage, where t represents a certain period and price0 is the initial closing price: df_return = df.apply(lambda x: x / x[0])df_return.head() We show that LTC was the most profitable for the period between October 2, 2017 and December 24, 2017. df_return.plot(grid=True, figsize=(15, 10)).axhline(y = 1, color = "black", lw = 2) The cryptocurrencies we analyzed fluctuated a lot but all gained in a given 2.7 months period. To run this code download the Jupyter notebook. Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.
[ { "code": null, "e": 422, "s": 172, "text": "In this part, I am going to analyze which coin (Bitcoin, Ethereum or Litecoin) was the most profitable in the last two months using buy and hold strategy. We’ll go through the analysis of these 3 cryptocurrencies and try to give an objective answer." }, { "code": null, "e": 480, "s": 422, "text": "In case you’ve missed my other articles about this topic:" }, { "code": null, "e": 501, "s": 480, "text": "romanorac.medium.com" }, { "code": null, "e": 545, "s": 501, "text": "Here are few links that might interest you:" }, { "code": null, "e": 723, "s": 545, "text": "- Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course]" }, { "code": null, "e": 894, "s": 723, "text": "Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything." }, { "code": null, "e": 1079, "s": 894, "text": "I am not a trader and this blog post is not financial advice. This is purely introductory knowledge. The conclusion here can be misleading as we analyze the period with immense growth." }, { "code": null, "e": 1119, "s": 1079, "text": "seaborn: statistical data visualization" }, { "code": null, "e": 1185, "s": 1119, "text": "For other requirements, see my previous blog post in this series." }, { "code": null, "e": 1355, "s": 1185, "text": "To get the latest data, go to the previous blog post, where I described how to download it using Cryptocompare API. You can also use the data I work within this example." }, { "code": null, "e": 1606, "s": 1355, "text": "First, let’s download hourly data for BTC, ETH, and LTC from Coinbase exchange. This time we work with an hourly time interval as it has higher granularity. Cryptocompare API limits response to 2000 samples, which is 2.7 months of data for each coin." }, { "code": null, "e": 2089, "s": 1606, "text": "import pandas as pddef get_filename(from_symbol, to_symbol, exchange, datetime_interval, download_date): return '%s_%s_%s_%s_%s.csv' % (from_symbol, to_symbol, exchange, datetime_interval, download_date)def read_dataset(filename): print('Reading data from %s' % filename) df = pd.read_csv(filename) df.datetime = pd.to_datetime(df.datetime) # change to datetime df = df.set_index('datetime') df = df.sort_index() # sort by datetime print(df.shape) return df" }, { "code": null, "e": 2352, "s": 2089, "text": "df_btc = read_dataset(get_filename('BTC', 'USD', 'Coinbase', 'hour', '2017-12-24'))df_eth = read_dataset(get_filename('ETH', 'USD', 'Coinbase', 'hour', '2017-12-24'))df_ltc = read_dataset(get_filename('LTC', 'USD', 'Coinbase', 'hour', '2017-12-24'))df_btc.head()" }, { "code": null, "e": 2525, "s": 2352, "text": "We are going to analyze closing prices, which are prices at which the hourly period closed. We merge BTC, ETH and LTC closing prices to a Dataframe to make analysis easier." }, { "code": null, "e": 2653, "s": 2525, "text": "df = pd.DataFrame({'BTC': df_btc.close, 'ETH': df_eth.close, 'LTC': df_ltc.close})df.head()" }, { "code": null, "e": 2751, "s": 2653, "text": "In 2.7 months, all three cryptocurrencies fluctuated a lot as you can observe in the table below." }, { "code": null, "e": 2883, "s": 2751, "text": "For each coin, we count the number of events and calculate mean, standard deviation, minimum, quartiles, and maximum closing price." }, { "code": null, "e": 2896, "s": 2883, "text": "Observations" }, { "code": null, "e": 2992, "s": 2896, "text": "The difference between the highest and the lowest BTC price was more than $15000 in 2.7 months." }, { "code": null, "e": 3083, "s": 2992, "text": "The LTC surged from $48.61 to $378.66 at a certain point, which is an increase of 678.98%." }, { "code": null, "e": 3097, "s": 3083, "text": "df.describe()" }, { "code": null, "e": 3392, "s": 3097, "text": "We visualize the data in the table above with a box plot. A box plot shows the quartiles of the dataset with points that are determined to be outliers using a method of the inter-quartile range (IQR). In other words, the IQR is the first quartile (25%) subtracted from the third quartile (75%)." }, { "code": null, "e": 3618, "s": 3392, "text": "On the box plot below, we see that LTC closing hourly price was most of the time between $50 and $100 in the last 2.7 months. All values over $150 are outliers (using IQR). Note that outliers are specific to this data sample." }, { "code": null, "e": 3684, "s": 3618, "text": "import seaborn as snsax = sns.boxplot(data=df['LTC'], orient=\"h\")" }, { "code": null, "e": 3814, "s": 3684, "text": "Let’s estimate the frequency distribution of LTC closing prices. The histogram shows the number of hours LTC had a certain value." }, { "code": null, "e": 3827, "s": 3814, "text": "Observations" }, { "code": null, "e": 3879, "s": 3827, "text": "LTC closing price was not over $100 for many hours." }, { "code": null, "e": 3967, "s": 3879, "text": "it has right-skewed distribution because a natural limit prevents outcomes on one side." }, { "code": null, "e": 4055, "s": 3967, "text": "blue dashed line (median) shows that half of the time closing prices were under $63.50." }, { "code": null, "e": 4168, "s": 4055, "text": "df['LTC'].hist(bins=30, figsize=(15,10)).axvline(df['LTC'].median(), color='b', linestyle='dashed', linewidth=2)" }, { "code": null, "e": 4307, "s": 4168, "text": "The chart below shows the absolute closing prices. It is not of much use as BTC closing prices are much higher than prices of ETH and LTC." }, { "code": null, "e": 4344, "s": 4307, "text": "df.plot(grid=True, figsize=(15, 10))" }, { "code": null, "e": 4468, "s": 4344, "text": "We are interested in a relative change of the price rather than in absolute price, so we use three different y-axis scales." }, { "code": null, "e": 4566, "s": 4468, "text": "We see that closing prices move in tandem. When one coin closing price increases so do the other." }, { "code": null, "e": 5081, "s": 4566, "text": "import matplotlib.pyplot as pltimport numpy as npfig, ax1 = plt.subplots(figsize=(20, 10))ax2 = ax1.twinx()rspine = ax2.spines['right']rspine.set_position(('axes', 1.15))ax2.set_frame_on(True)ax2.patch.set_visible(False)fig.subplots_adjust(right=0.7)df['BTC'].plot(ax=ax1, style='b-')df['ETH'].plot(ax=ax1, style='r-', secondary_y=True)df['LTC'].plot(ax=ax2, style='g-')# legendax2.legend([ax1.get_lines()[0], ax1.right_ax.get_lines()[0], ax2.get_lines()[0]], ['BTC', 'ETH', 'LTC'])" }, { "code": null, "e": 5486, "s": 5081, "text": "We calculate the Pearson correlation between the closing prices of BTC, ETH, and LTC. Pearson correlation is a measure of the linear correlation between two variables X and Y. It has a value between +1 and −1, where 1 is the total positive linear correlation, 0 is no linear correlation, and −1 is the total negative linear correlation. The correlation matrix is symmetric so we only show the lower half." }, { "code": null, "e": 5558, "s": 5486, "text": "Sifr Data daily updates Pearson correlations for many cryptocurrencies." }, { "code": null, "e": 5571, "s": 5558, "text": "Observations" }, { "code": null, "e": 5688, "s": 5571, "text": "Closing prices aren’t normalized, see Log Returns, where we normalize closing prices before calculating correlation," }, { "code": null, "e": 5818, "s": 5688, "text": "BTC, ETH and LTC were highly correlated in the past 2 months. This means, when BTC closing price increased, ETH and LTC followed." }, { "code": null, "e": 5901, "s": 5818, "text": "ETH and LTC were even more correlated with 0.9565 Pearson correlation coefficient." }, { "code": null, "e": 6338, "s": 5901, "text": "import seaborn as snsimport matplotlib.pyplot as plt# Compute the correlation matrixcorr = df.corr()# Generate a mask for the upper trianglemask = np.zeros_like(corr, dtype=np.bool)mask[np.triu_indices_from(mask)] = True# Set up the matplotlib figuref, ax = plt.subplots(figsize=(10, 10))# Draw the heatmap with the mask and correct aspect ratiosns.heatmap(corr, annot=True, fmt = '.4f', mask=mask, center=0, square=True, linewidths=.5)" }, { "code": null, "e": 6501, "s": 6338, "text": "Buy and hold is a passive investment strategy in which an investor buys a cryptocurrency and holds it for a long period, regardless of fluctuations in the market." }, { "code": null, "e": 6693, "s": 6501, "text": "Let’s analyze returns using the Buy and hold strategy for the past 2.7 months. We calculate the return percentage, where t represents a certain period and price0 is the initial closing price:" }, { "code": null, "e": 6750, "s": 6693, "text": "df_return = df.apply(lambda x: x / x[0])df_return.head()" }, { "code": null, "e": 6853, "s": 6750, "text": "We show that LTC was the most profitable for the period between October 2, 2017 and December 24, 2017." }, { "code": null, "e": 6937, "s": 6853, "text": "df_return.plot(grid=True, figsize=(15, 10)).axhline(y = 1, color = \"black\", lw = 2)" }, { "code": null, "e": 7032, "s": 6937, "text": "The cryptocurrencies we analyzed fluctuated a lot but all gained in a given 2.7 months period." }, { "code": null, "e": 7080, "s": 7032, "text": "To run this code download the Jupyter notebook." } ]
Selection Sort Program in C
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list. #include <stdio.h> #include <stdbool.h> #define MAX 7 int intArray[MAX] = {4,6,3,2,1,9,7}; void printline(int count) { int i; for(i = 0;i < count-1;i++) { printf("="); } printf("=\n"); } void display() { int i; printf("["); // navigate through all items for(i = 0;i < MAX;i++) { printf("%d ", intArray[i]); } printf("]\n"); } void selectionSort() { int indexMin,i,j; // loop through all numbers for(i = 0; i < MAX-1; i++) { // set current element as minimum indexMin = i; // check the element to be minimum for(j = i+1;j < MAX;j++) { if(intArray[j] < intArray[indexMin]) { indexMin = j; } } if(indexMin != i) { printf("Items swapped: [ %d, %d ]\n" , intArray[i], intArray[indexMin]); // swap the numbers int temp = intArray[indexMin]; intArray[indexMin] = intArray[i]; intArray[i] = temp; } printf("Iteration %d#:",(i+1)); display(); } } void main() { printf("Input Array: "); display(); printline(50); selectionSort(); printf("Output Array: "); display(); printline(50); } If we compile and run the above program, it will produce the following result − Input Array: [4 6 3 2 1 9 7 ] ================================================== Items swapped: [ 4, 1 ] Iteration 1#:[1 6 3 2 4 9 7 ] Items swapped: [ 6, 2 ] Iteration 2#:[1 2 3 6 4 9 7 ] Iteration 3#:[1 2 3 6 4 9 7 ] Items swapped: [ 6, 4 ] Iteration 4#:[1 2 3 4 6 9 7 ] Iteration 5#:[1 2 3 4 6 9 7 ] Items swapped: [ 9, 7 ] Iteration 6#:[1 2 3 4 6 7 9 ] Output Array: [1 2 3 4 6 7 9 ] ================================================== 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2886, "s": 2580, "text": "Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list." }, { "code": null, "e": 4110, "s": 2886, "text": "#include <stdio.h>\n#include <stdbool.h>\n\n#define MAX 7\n\nint intArray[MAX] = {4,6,3,2,1,9,7};\n\nvoid printline(int count) {\n int i;\n\t\n for(i = 0;i < count-1;i++) {\n printf(\"=\");\n }\n\t\n printf(\"=\\n\");\n}\n\nvoid display() {\n int i;\n printf(\"[\");\n\t\n // navigate through all items \n for(i = 0;i < MAX;i++) {\n printf(\"%d \", intArray[i]);\n }\n\t\n printf(\"]\\n\");\n}\n\nvoid selectionSort() {\n int indexMin,i,j;\n\t\n // loop through all numbers \n for(i = 0; i < MAX-1; i++) { \n\t\n // set current element as minimum \n indexMin = i;\n\t\t\n // check the element to be minimum \n for(j = i+1;j < MAX;j++) {\n if(intArray[j] < intArray[indexMin]) {\n indexMin = j;\n }\n }\n\n if(indexMin != i) {\n printf(\"Items swapped: [ %d, %d ]\\n\" , intArray[i], intArray[indexMin]); \n\t\t\t\n // swap the numbers \n int temp = intArray[indexMin];\n intArray[indexMin] = intArray[i];\n intArray[i] = temp;\n } \n\n printf(\"Iteration %d#:\",(i+1));\n display();\n }\n} \n\nvoid main() {\n printf(\"Input Array: \");\n display();\n printline(50);\n selectionSort();\n printf(\"Output Array: \");\n display();\n printline(50);\n}" }, { "code": null, "e": 4190, "s": 4110, "text": "If we compile and run the above program, it will produce the following result −" }, { "code": null, "e": 4630, "s": 4190, "text": "Input Array: [4 6 3 2 1 9 7 ]\n==================================================\nItems swapped: [ 4, 1 ]\nIteration 1#:[1 6 3 2 4 9 7 ]\nItems swapped: [ 6, 2 ]\nIteration 2#:[1 2 3 6 4 9 7 ]\nIteration 3#:[1 2 3 6 4 9 7 ]\nItems swapped: [ 6, 4 ]\nIteration 4#:[1 2 3 4 6 9 7 ]\nIteration 5#:[1 2 3 4 6 9 7 ]\nItems swapped: [ 9, 7 ]\nIteration 6#:[1 2 3 4 6 7 9 ]\nOutput Array: [1 2 3 4 6 7 9 ]\n==================================================\n" }, { "code": null, "e": 4665, "s": 4630, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4677, "s": 4665, "text": " Ravi Kiran" }, { "code": null, "e": 4712, "s": 4677, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 4731, "s": 4712, "text": " Arnab Chakraborty" }, { "code": null, "e": 4766, "s": 4731, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4781, "s": 4766, "text": " Parth Panjabi" }, { "code": null, "e": 4814, "s": 4781, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 4833, "s": 4814, "text": " Arnab Chakraborty" }, { "code": null, "e": 4867, "s": 4833, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4895, "s": 4867, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4931, "s": 4895, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 4959, "s": 4931, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4966, "s": 4959, "text": " Print" }, { "code": null, "e": 4977, "s": 4966, "text": " Add Notes" } ]
MongoDB query to add new array element in document
To add new array element in a MongoDB document, use $(projection) along with update(). Let us create a collection with documents − >db.demo222.insertOne({"details":[{"StudentName":"Chris","StudentMarks":78},{"StudentName":"David","StudentMarks":89}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3ee31703d395bdc213472f") } Display all documents from a collection with the help of find() method − > db.demo222.find().pretty(); This will produce the following output − { "_id" : ObjectId("5e3ee31703d395bdc213472f"), "details" : [ { "StudentName" : "Chris", "StudentMarks" : 78 }, { "StudentName" : "David", "StudentMarks" : 89 } ] } Following is the query to add new array element in document − > db.demo222.update({"details.StudentName" : "Chris"},{"$set" : {"details.$.SubjectName":"MongoDB"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Display all documents from a collection with the help of find() method − > db.demo222.find().pretty(); This will produce the following output − { "_id" : ObjectId("5e3ee31703d395bdc213472f"), "details" : [ { "StudentName" : "Chris", "StudentMarks" : 78, "SubjectName" : "MongoDB" }, { "StudentName" : "David", "StudentMarks" : 89 } ] }
[ { "code": null, "e": 1193, "s": 1062, "text": "To add new array element in a MongoDB document, use $(projection) along with update(). Let us create a collection with documents −" }, { "code": null, "e": 1400, "s": 1193, "text": ">db.demo222.insertOne({\"details\":[{\"StudentName\":\"Chris\",\"StudentMarks\":78},{\"StudentName\":\"David\",\"StudentMarks\":89}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3ee31703d395bdc213472f\")\n}" }, { "code": null, "e": 1473, "s": 1400, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1503, "s": 1473, "text": "> db.demo222.find().pretty();" }, { "code": null, "e": 1544, "s": 1503, "text": "This will produce the following output −" }, { "code": null, "e": 1778, "s": 1544, "text": "{\n \"_id\" : ObjectId(\"5e3ee31703d395bdc213472f\"),\n \"details\" : [\n {\n \"StudentName\" : \"Chris\",\n \"StudentMarks\" : 78\n },\n {\n \"StudentName\" : \"David\",\n \"StudentMarks\" : 89\n }\n ]\n}" }, { "code": null, "e": 1840, "s": 1778, "text": "Following is the query to add new array element in document −" }, { "code": null, "e": 2009, "s": 1840, "text": "> db.demo222.update({\"details.StudentName\" : \"Chris\"},{\"$set\" : {\"details.$.SubjectName\":\"MongoDB\"}});\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })" }, { "code": null, "e": 2082, "s": 2009, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2112, "s": 2082, "text": "> db.demo222.find().pretty();" }, { "code": null, "e": 2153, "s": 2112, "text": "This will produce the following output −" }, { "code": null, "e": 2423, "s": 2153, "text": "{\n \"_id\" : ObjectId(\"5e3ee31703d395bdc213472f\"),\n \"details\" : [\n {\n \"StudentName\" : \"Chris\",\n \"StudentMarks\" : 78,\n \"SubjectName\" : \"MongoDB\"\n },\n {\n \"StudentName\" : \"David\",\n \"StudentMarks\" : 89\n }\n ]\n}" } ]
Java DIP - Understand Convolution
Convolution is a mathematical operation on two functions f and g. The function f and g in this case are images, since an image is also a two dimensional function. In order to perform convolution on an image, following steps are taken − Flip the mask (horizontally and vertically) only once. Slide the mask onto the image. Multiply the corresponding elements and then add them. Repeat this procedure until all values of the image has been calculated. We use OpenCV function filter2D to apply convolution to images. It can be found under Imgproc package. Its syntax is given below − filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT ); The function arguments are described below − src It is source image. dst It is destination image. depth It is the depth of dst. A negative value (such as -1) indicates that the depth is the same as the source. kernel It is the kernel to be scanned through the image. anchor It is the position of the anchor relative to its kernel. The location Point (-1, -1) indicates the center by default. delta It is a value to be added to each pixel during the convolution. By default it is 0. BORDER_DEFAULT We let this value by default. The following example demonstrates the use of Imgproc class to perform convolution on an image of Grayscale. import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; public class convolution { public static void main( String[] args ) { try { int kernelSize = 3; System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); Mat source = Highgui.imread("grayscale.jpg", Highgui.CV_LOAD_IMAGE_GRAYSCALE); Mat destination = new Mat(source.rows(),source.cols(),source.type()); Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) { { put(0,0,0); put(0,1,0); put(0,2,0); put(1,0,0); put(1,1,1); put(1,2,0); put(2,0,0); put(2,1,0); put(2,2,0); } }; Imgproc.filter2D(source, destination, -1, kernel); Highgui.imwrite("original.jpg", destination); } catch (Exception e) { System.out.println("Error:" + e.getMessage()); } } } In this example we convolve our image with the following filter(kernel). This filter results in producing original image as it is − 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2500, "s": 2337, "text": "Convolution is a mathematical operation on two functions f and g. The function f and g in this case are images, since an image is also a two dimensional function." }, { "code": null, "e": 2573, "s": 2500, "text": "In order to perform convolution on an image, following steps are taken −" }, { "code": null, "e": 2628, "s": 2573, "text": "Flip the mask (horizontally and vertically) only once." }, { "code": null, "e": 2659, "s": 2628, "text": "Slide the mask onto the image." }, { "code": null, "e": 2714, "s": 2659, "text": "Multiply the corresponding elements and then add them." }, { "code": null, "e": 2787, "s": 2714, "text": "Repeat this procedure until all values of the image has been calculated." }, { "code": null, "e": 2918, "s": 2787, "text": "We use OpenCV function filter2D to apply convolution to images. It can be found under Imgproc package. Its syntax is given below −" }, { "code": null, "e": 2987, "s": 2918, "text": "filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT );\n" }, { "code": null, "e": 3032, "s": 2987, "text": "The function arguments are described below −" }, { "code": null, "e": 3036, "s": 3032, "text": "src" }, { "code": null, "e": 3056, "s": 3036, "text": "It is source image." }, { "code": null, "e": 3060, "s": 3056, "text": "dst" }, { "code": null, "e": 3085, "s": 3060, "text": "It is destination image." }, { "code": null, "e": 3091, "s": 3085, "text": "depth" }, { "code": null, "e": 3197, "s": 3091, "text": "It is the depth of dst. A negative value (such as -1) indicates that the depth is the same as the source." }, { "code": null, "e": 3204, "s": 3197, "text": "kernel" }, { "code": null, "e": 3254, "s": 3204, "text": "It is the kernel to be scanned through the image." }, { "code": null, "e": 3261, "s": 3254, "text": "anchor" }, { "code": null, "e": 3379, "s": 3261, "text": "It is the position of the anchor relative to its kernel. The location Point (-1, -1) indicates the center by default." }, { "code": null, "e": 3385, "s": 3379, "text": "delta" }, { "code": null, "e": 3469, "s": 3385, "text": "It is a value to be added to each pixel during the convolution. By default it is 0." }, { "code": null, "e": 3484, "s": 3469, "text": "BORDER_DEFAULT" }, { "code": null, "e": 3514, "s": 3484, "text": "We let this value by default." }, { "code": null, "e": 3623, "s": 3514, "text": "The following example demonstrates the use of Imgproc class to perform convolution on an image of Grayscale." }, { "code": null, "e": 4738, "s": 3623, "text": "import org.opencv.core.Core;\nimport org.opencv.core.CvType;\nimport org.opencv.core.Mat;\n\nimport org.opencv.highgui.Highgui;\nimport org.opencv.imgproc.Imgproc;\n\npublic class convolution {\n public static void main( String[] args ) {\n \n try {\n int kernelSize = 3;\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n \n Mat source = Highgui.imread(\"grayscale.jpg\", Highgui.CV_LOAD_IMAGE_GRAYSCALE);\n Mat destination = new Mat(source.rows(),source.cols(),source.type());\n \n Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) {\n {\n put(0,0,0);\n put(0,1,0);\n put(0,2,0);\n\n put(1,0,0);\n put(1,1,1);\n put(1,2,0);\n\n put(2,0,0);\n put(2,1,0);\n put(2,2,0);\n }\n };\n \n Imgproc.filter2D(source, destination, -1, kernel);\n Highgui.imwrite(\"original.jpg\", destination);\n \n } catch (Exception e) {\n System.out.println(\"Error:\" + e.getMessage());\n }\n }\n}" }, { "code": null, "e": 4870, "s": 4738, "text": "In this example we convolve our image with the following filter(kernel). This filter results in producing original image as it is −" }, { "code": null, "e": 4903, "s": 4870, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4919, "s": 4903, "text": " Malhar Lathkar" }, { "code": null, "e": 4952, "s": 4919, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 4968, "s": 4952, "text": " Malhar Lathkar" }, { "code": null, "e": 5003, "s": 4968, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5017, "s": 5003, "text": " Anadi Sharma" }, { "code": null, "e": 5051, "s": 5017, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5065, "s": 5051, "text": " Tushar Kale" }, { "code": null, "e": 5102, "s": 5065, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5117, "s": 5102, "text": " Monica Mittal" }, { "code": null, "e": 5150, "s": 5117, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 5169, "s": 5150, "text": " Arnab Chakraborty" }, { "code": null, "e": 5176, "s": 5169, "text": " Print" }, { "code": null, "e": 5187, "s": 5176, "text": " Add Notes" } ]
Using machine learning to predict Kickstarter success | by Laura Lewis | Towards Data Science
In recent years, the range of funding options for projects created by individuals and small companies has expanded considerably. In addition to savings, bank loans, friends & family funding and other traditional options, crowdfunding has become a popular and readily available alternative. Kickstarter, founded in 2009, is one particularly well-known and popular crowdfunding platform. It has an all-or-nothing funding model, whereby a project is only funded if it meets its goal amount; otherwise no money is given by backers to a project. A huge variety of factors contribute to the success or failure of a project — in general, and also on Kickstarter. Some of these are able to be quantified or categorised, which allows for the construction of a model to attempt to predict whether a project will succeed or not. The aim of this project is to construct such a model and also to analyse Kickstarter project data more generally, in order to help potential project creators assess whether or not Kickstarter is a good funding option for them, and what their chances of success are. The dataset used in this project was downloaded in .csv format from a webscrape conducted by a webscraping site called Web Robots. The dataset contains data on all projects hosted on Kickstarter between the company’s launch in April 2009 until the date of the webscrape on 14 March 2019. The dataset contains 209,222 projects, although some of these are duplicates. A fair amount of cleaning was required to get the dataset into a format suitable for applying machine learning models. If you just can’t get enough of df.isna() and df.drop() you can check out the full Jupyter notebook code in my GitHub repository. After duplicates and irrelevant rows were dropped (e.g. projects which were cancelled mid-campaign, or which were still live), I was left with a decent sized dataset of 168,979 projects. The columns which were kept or calculated were: The project goal (in USD) Campaign length — number of days from launch to deadline Number of days from page creation to project launch Blurb word length Name word length Whether the project was highlighted as a staff pick (one-hot encoded) Category (one-hot encoded) Country (one-hot encoded) Month a project was launched in (one-hot encoded) Month of a project’s deadline (one-hot encoded) Day of the week a project was launched on (one-hot encoded) Day of the week of a project’s deadline (one-hot encoded) Two-hour time window a project was launched in (one-hot encoded) Two-hour time window of a project’s deadline (one-hot encoded) Some features were initially retained for exploratory data analysis (EDA) purposes, but were then dropped in order to use machine learning models. These included features that are related to outcomes (e.g. the amount pledged and the number of backers) rather than related to the properties of the project itself (e.g. category, goal, length of campaign). Now for the colourful part. Kickstarter has grown massively since its launch in 2009, particularly during 2014 when expansion really started to ramp up. The proportion of projects that succeed decreased considerably at this point, however, as the site was flooded with a much larger number of projects. The success rate has been on the increase in recent years though — so there’s still hope. Overall, 56% of completed projects (i.e. those that have finished and weren’t cancelled or suspended) were successful. The graphs below show the differences in some of the features between successful and failed projects. The key takeaways from this are: Unsurprisingly, successful projects tend to have smaller (and therefore more realistic) goals — the median amount sought by successful projects is about half that of failed projects (medians are used due to high positive skew of funding and goal amounts). The differences in the median amount pledged per project are more surprising. The median amount pledged per successful project is notably higher than the median amount requested, suggesting that projects that meet their goal tend to go on to gain even more funding, and become ‘over-funded’. On a related note, the difference between failed and successful companies is much larger in terms of amount pledged and the number of backers, compared to goal amount. Probably once potential backers see that a project looks like it will be successful, they are much more likely to jump on the bandwagon and fund it. Successful projects have slightly shorter campaign lengths, but take slightly longer to launch (measured from the time the project was first created on the site). Roughly 20% of successful projects were highlighted on the site as staff picks. It does not seem unreasonable to suggest a causative relationship here, i.e. that projects that are chosen as staff picks are much more likely to go on to be successful, and that only a few staff picks go on to fail. Various other features were explored, in terms of project number, goal and funding amounts, backers and success rates. For example, the graphs below show the differences between different project categories (the code is also provided). The key takeaways from this are: The best project types to launch on Kickstarter are comics (on the grounds of success rate, number of backers and amount pledged), dance (success rate and amount pledged) and games (amount pledged and number of backers). This is probably at least partly due to their relatively small funding goals — as noted above, projects with smaller goals tend to be more successful. Although comics and games tend to attract the most backers, each backer tends to pledge relatively little. Dance and film & video tend to attract the most generous backers. Technology projects have the highest median goal size by far. However, they are towards the bottom of the leaderboard in terms of the median amount actually pledged. The worst performing categories are food, journalism and technology. # Code used to create the graphs below# Importing the required librariesimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib import cmimport numpy as np# Creating a dataframe grouped by category with columns for failed and successfulcat_df = pd.get_dummies(df.set_index('category').state).groupby('category').sum()# Plottingfig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(3, 2, figsize=(12,12))color = cm.CMRmap(np.linspace(0.1,0.8,df.category.nunique()))df.groupby('category').category.count().plot(kind='bar', ax=ax1, color=color)ax1.set_title('Number of projects')ax1.set_xlabel('')df.groupby('category').usd_goal.median().plot(kind='bar', ax=ax2, color=color)ax2.set_title('Median project goal ($)')ax2.set_xlabel('')df.groupby('category').usd_pledged.median().plot(kind='bar', ax=ax3, color=color)ax3.set_title('Median pledged per project ($)')ax3.set_xlabel('')cat_df.div(cat_df.sum(axis=1), axis=0).successful.plot(kind='bar', ax=ax4, color=color) # Normalizes counts across rowsax4.set_title('Proportion of successful projects')ax4.set_xlabel('')df.groupby('category').backers_count.median().plot(kind='bar', ax=ax5, color=color)ax5.set_title('Median backers per project')ax5.set_xlabel('')df.groupby('category').pledge_per_backer.median().plot(kind='bar', ax=ax6, color=color)ax6.set_title('Median pledged per backer ($)')ax6.set_xlabel('')fig.subplots_adjust(hspace=0.6)plt.show() In the interests of space and retinas, only the ‘success proportion’ graphs will be shown below for additional features. Again, for more detail, feel free to check out my GitHub repository. The key takeaways from this are: Hong Kong is home to a greater proportion of successful projects (they also have a higher median number of backers and amount of funding). Tuesday is the best day to launch a project, and weekends are the worst (the same pattern holds for the amount raised and the number of backers). 12pm to 2pm UTC is the best time to launch a project — it also has the greatest median number of backers and amount of funding. 6pm to 4am UTC is the worst time to launch. October is the best month to launch a project — it also has the greatest median number of backers and amount of funding. July and December are the worst months. The ultimate goal of this project was to create a model that could predict, with a good level of accuracy, whether a project was likely to succeed or fail. In order to prepare the data for machine learning, the following steps were taken (code below): One-hot encoding categorical variables.Separating the data into the dependent target variable ‘y’ (in this case ‘state’, i.e. project success or failure) and the independent features ‘X’.Transforming the features in X so that they are all on the same scale. For this project, StandardScaler from Scikit-learn was used to transform each feature to a mean of 0 and a standard deviation of 1.The data was separated into a training and test set, for robust evaluation of the models. One-hot encoding categorical variables. Separating the data into the dependent target variable ‘y’ (in this case ‘state’, i.e. project success or failure) and the independent features ‘X’. Transforming the features in X so that they are all on the same scale. For this project, StandardScaler from Scikit-learn was used to transform each feature to a mean of 0 and a standard deviation of 1. The data was separated into a training and test set, for robust evaluation of the models. # Importing the required librariesimport pandas as pdfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_split# 1) Creating dummy variablesdf_transformed = pd.get_dummies(df_transformed)# 2) Separating into X and yX_unscaled = df_transformed.drop('state', axis=1)y = df_transformed.state# 3) Transforming the datascaler = StandardScaler()X = pd.DataFrame(scaler.fit_transform(X_unscaled), columns=list(X_unscaled.columns))# 4) Splitting into train and test setsX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.3, random_state=123) It is good practice to choose an evaluation method before running machine learning models — not after. The weighted average F1 score was chosen. The F1 score calculates the harmonic mean between precision and recall, and is a suitable measure because there is no preference for false positives or false negatives in this case (both are equally bad). The weighted average will be used because the classes are of slightly different sizes, and we want to be able to predict both successes and failures. It is good practice to choose an evaluation method before running machine learning models — not after. Logistic regression can be used as a binary classifier in order to predict which of two categories a data point falls in to. To create a baseline model to improve upon, a logistic regression model was fitted to the data, with default parameters. # Importing the required librariesfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import classification_report# Fitting a logistic regression model with default parameterslogreg = LogisticRegression()logreg.fit(X_train,y_train)# Making predictionsy_hat_train = logreg.predict(X_train)y_hat_test = logreg.predict(X_test)# Logistic regression scoresprint("Logistic regression score for training set:", round(logreg.score(X_train, y_train),5))print("Logistic regression score for test set:", round(logreg.score(X_test, y_test),5))print("\nClassification report:")print(classification_report(y_test, y_hat_test)) Not bad. The model has a weighted average F1 score of 0.70. The aim is now to improve upon this score. There were a large number of features (106) in the dataset used for the initial logistic regression model. PCA (Principal Component Analysis) was used to reduce this into a smaller number of components which still explain as much variation in the data as possible. This can help improve model fitting and accuracy. The graph below (produced by the code below) shows that there was no obvious cut-off for the number of components to use in PCA. # Importing the required librariesimport matplotlib.pyplot as pltfrom sklearn.decomposition import PCA# Fitting PCApca = PCA()pca.fit_transform(X)explained_var = np.cumsum(pca.explained_variance_ratio_)# Plotting the amount of variation explained by PCA with different numbers of componentsplt.plot(list(range(1, len(explained_var)+1)), explained_var)plt.title('Amount of variation explained by PCA', fontsize=14)plt.xlabel('Number of components')plt.ylabel('Explained variance'); The following results were found: Number of components explaining 80% of variance: 58Number of components explaining 90% of variance: 70Number of components explaining 99% of variance: 90 To choose the number of components to use in the machine learning models, each of these values was plugged into a pipeline for a logistic regression model using the default parameters: # Running a for loop to test different values of n_componentsn_comps = [58,70,90]for n in n_comps: pipe = Pipeline([(‘pca’, PCA(n_components=n)), (‘clf’, LogisticRegression())]) pipe.fit(X_train, y_train) print(“\nNumber of components:”, n) print(“Score:”, round(pipe.score(X_test, y_test),5)) The results showed that the score is highest for 90 components, although the difference is small (c. 3% improvement from 58 components): Number of components: 58Score: 0.67831Number of components: 70Score: 0.6858Number of components: 90Score: 0.70799 The logistic regression model can potentially be further improved by optimising its parameters. GridSearchCV was used to test multiple different regularisation parameters (values of C), penalties (l1 or l2) and models with and without an intercept. # Importing the required librariesfrom sklearn.model_selection import GridSearchCV# Timing how long the model takes to runlogreg_start = time.time()# Building the pipelinepipe_logreg = Pipeline([('pca', PCA(n_components=90)), ('clf', LogisticRegression())])# Creating the parameters to testparams_logreg = [ {'clf__penalty': ['l1', 'l2'], 'clf__fit_intercept': [True, False], 'clf__C': [0.001, 0.01, 1, 10] }]# Using GridSearchCV to test multiple different parametersgrid_logreg = GridSearchCV(estimator=pipe_logreg, param_grid=params_logreg, cv=5)grid_logreg.fit(X_train, y_train)logreg_end = time.time()logreg_best_score = grid_logreg.best_score_logreg_best_params = grid_logreg.best_params_# Printing the resultsprint(f"Time taken to run: {round((logreg_end - logreg_start)/60,1)} minutes")print("Best accuracy:", round(logreg_best_score,2))print("Best parameters:", logreg_best_params) Results: Time taken to run: 48.56 minutesBest accuracy: 0.71Best parameters: {‘clf__C’: 10, ‘clf__fit_intercept’: True, ‘clf__penalty’: ‘l2’} A classification report and a confusion matrix were then produced for the logistic regression model using the best parameters (according to the accuracy score). The confusion matrix was produced using the following function: def plot_cf(y_true, y_pred, class_names=None, model_name=None): """Plots a confusion matrix""" cf = confusion_matrix(y_true, y_pred) plt.imshow(cf, cmap=plt.cm.Blues) plt.grid(b=None) if model_name: plt.title("Confusion Matrix: {}".format(model_name)) else: plt.title("Confusion Matrix") plt.ylabel('True Label') plt.xlabel('Predicted Label') class_names = set(y_true) tick_marks = np.arange(len(class_names)) if class_names: plt.xticks(tick_marks, class_names) plt.yticks(tick_marks, class_names) thresh = cf.max() / 2. for i, j in itertools.product(range(cf.shape[0]), range(cf.shape[1])): plt.text(j, i, cf[i, j], horizontalalignment='center', color='white' if cf[i, j] > thresh else 'black')plt.colorbar() The full results for the best logistic regression model are below: After hyperparameter tuning, the model’s accuracy score is the same as the logistic regression model using default parameters (0.70 weighted average F1 score). Disappointing. Next, a Random Forest classifier was used. The Random Forest algorithm is a supervised learning algorithm that can be used for classification. It works by building multiple different decision trees to predict which category a data point belongs to. Again, GridSearchCV was used to test multiple different hyperparameters, in order to optimise the model. # Importing the required librariesfrom sklearn.ensemble import RandomForestClassifier# Using GridSearchCV to test multiple different parametersrf_start = time.time()pipe_rf = Pipeline([('pca', PCA(n_components=90)), ('clf', RandomForestClassifier())])params_rf = [ {'clf__n_estimators': [100], 'clf__max_depth': [20, 30, 40], 'clf__min_samples_split':[0.001, 0.01] }]grid_rf = GridSearchCV(estimator=pipe_rf, param_grid=params_rf, cv=5)grid_rf.fit(X_train, y_train)rf_end = time.time()rf_best_score = grid_rf.best_score_rf_best_params = grid_rf.best_params_print(f"Time taken to run: {round((rf_end - rf_start)/60,1)} minutes")print("Best accuracy:", round(rf_best_score,2))print("Best parameters:", rf_best_params) Results: Time taken to run: 72.2 minutesBest accuracy: 0.7Best parameters: {'clf__max_depth': 30, 'clf__min_samples_split': 0.001, 'clf__n_estimators': 100} The full results for the best Random Forest model are below: After hyperparameter tuning, the model’s weighted average F1 score increased from 0.65 for a model with default settings to 0.69. This is similar to, although slightly worse than, the logistic regression model. Also, the difference between the score for the training set and the test set suggests there might be some over-fitting. There may well be more scope for hyperparameter tuning here to further improve the model, but time precluded it. Ah, the darling of the Kaggle world. XGBoost is very ‘in’ right now. This is a form of gradient boosting algorithm. Similar to Random Forests, it is an ensemble method that produces multiple decision trees to improve classification of data points, but it uses gradient descent to improve the performance of the model for the data points that are particularly difficult to classify. Back to good ol’ GridSearchCV for hyperparameter testing: # Importing the required librariesfrom sklearn.model_selection import GridSearchCV# Using GridSearchCV to test multiple different parametersxgb_start = time.time()pipe_xgb = Pipeline([('pca', PCA(n_components=90)), ('clf', xgb.XGBClassifier())])params_xgb = [ {'clf__n_estimators': [100], 'clf__max_depth': [25, 35], 'clf__learning_rate': [0.01, 0.1], 'clf__subsample': [0.7, 1], 'clf__min_child_weight': [20, 100] }]grid_xgb = GridSearchCV(estimator=pipe_xgb, param_grid=params_xgb, cv=5)grid_xgb.fit(X_train, y_train)xgb_end = time.time()xgb_best_score = grid_xgb.best_score_xgb_best_params = grid_xgb.best_params_print(f"Time taken to run: {round((xgb_end - xgb_start)/60,1)} minutes")print("Best accuracy:", round(xgb_best_score,2))print("Best parameters:", xgb_best_params) Results: Time taken to run: 865.4 minutesBest accuracy: 0.7Best parameters: {'clf__learning_rate': 0.1, 'clf__max_depth': 35, 'clf__min_child_weight': 100, 'clf__n_estimators': 100, 'clf__subsample': 0.7} Yikes. 14 and a half hours, and it was still only able to achieve the same accuracy as the initial regression model (this was also only a 0.01 increase in accuracy from an XGBoost model that was run with default parameters). The full results for the best XGBoost model are below: As with the Random Forest model, the difference between the accuracy score for the training set and the test set suggests there might be some over-fitting. Again, there may well be more scope for hyperparameter tuning here to further improve the model — but I didn’t have another 14 and a half hours to spare. Each model was able to achieve an accuracy of about 70%, after parameter tuning. Although it was relatively easy to reach roughly this level of accuracy, parameter tuning was only able to increase accuracy levels by a small amount. Possibly the reasonably large amount of data for each of only two categories meant that there was enough data for even a relatively simple model (e.g. logistic regression with default settings) to achieve a good level of validation accuracy. The best Random Forest and XGBoost models created still showed some degree of over-fitting. Further parameter tuning would be required to attempt to reduce this. The final chosen model is the tuned logistic regression model. This is because, although each model was able to achieve a similar level of accuracy for the test set, this is the only model that did not exhibit overfitting. Interestingly, each model performed worse at predicting failures compared to successes, with a lower true negative rate than true positive rate. I.e. it classified quite a few failed projects as successes, but relatively few successful projects as failures. Possibly the factors that might cause a project to fail are more likely to be beyond the scope of the data, e.g. poor marketing, insufficient updates, or not replying to messages from potential backers. The false positive and false negative rates mean that, if the data about a new project is fed through the model to make a prediction about its success or failure: if the project is going to end up being a success, the model will correctly predict this as a success about 80% of the time if the project is going to end up being a failure, the model will only correctly predict this as a failure about 60% of the time (and the rest of the time will incorrectly predict it as a success) Some of the factors that had a positive effect on success rate and/or the amount of money received are: Most important: Smaller project goals Being chosen as a staff pick (a measure of quality) Comics, dance and games projects Projects from Hong Kong Less important: Shorter campaigns Taking longer between creation and launch Film & video and music projects (popular categories on the site, and fairly successful) Launching on a Tuesday (although this is also the most common day to launch a project, so beware the competition) Launching in October Launching between 12pm and 2pm UTC (this is of course related to the country a project is launched from, but remember that backers can come from all over the world) Factors which had a negative effect on success rate and/or the amount of money received are: Most negative: Large goals Food and journalism projects Projects from Italy Less negative: Longer campaigns Launching on a weekend Launching in July or December Launching between 6pm and 4am UTC Overall, Kickstarter is well suited to small, high-quality projects, particularly comics, dance and games. It is less suited to larger projects, particularly food (e.g. restaurants) and journalism projects. Thanks for reading this far! If you have any thoughts, comments or suggestions, please add them below.
[ { "code": null, "e": 712, "s": 171, "text": "In recent years, the range of funding options for projects created by individuals and small companies has expanded considerably. In addition to savings, bank loans, friends & family funding and other traditional options, crowdfunding has become a popular and readily available alternative. Kickstarter, founded in 2009, is one particularly well-known and popular crowdfunding platform. It has an all-or-nothing funding model, whereby a project is only funded if it meets its goal amount; otherwise no money is given by backers to a project." }, { "code": null, "e": 1255, "s": 712, "text": "A huge variety of factors contribute to the success or failure of a project — in general, and also on Kickstarter. Some of these are able to be quantified or categorised, which allows for the construction of a model to attempt to predict whether a project will succeed or not. The aim of this project is to construct such a model and also to analyse Kickstarter project data more generally, in order to help potential project creators assess whether or not Kickstarter is a good funding option for them, and what their chances of success are." }, { "code": null, "e": 1621, "s": 1255, "text": "The dataset used in this project was downloaded in .csv format from a webscrape conducted by a webscraping site called Web Robots. The dataset contains data on all projects hosted on Kickstarter between the company’s launch in April 2009 until the date of the webscrape on 14 March 2019. The dataset contains 209,222 projects, although some of these are duplicates." }, { "code": null, "e": 1870, "s": 1621, "text": "A fair amount of cleaning was required to get the dataset into a format suitable for applying machine learning models. If you just can’t get enough of df.isna() and df.drop() you can check out the full Jupyter notebook code in my GitHub repository." }, { "code": null, "e": 2057, "s": 1870, "text": "After duplicates and irrelevant rows were dropped (e.g. projects which were cancelled mid-campaign, or which were still live), I was left with a decent sized dataset of 168,979 projects." }, { "code": null, "e": 2105, "s": 2057, "text": "The columns which were kept or calculated were:" }, { "code": null, "e": 2131, "s": 2105, "text": "The project goal (in USD)" }, { "code": null, "e": 2188, "s": 2131, "text": "Campaign length — number of days from launch to deadline" }, { "code": null, "e": 2240, "s": 2188, "text": "Number of days from page creation to project launch" }, { "code": null, "e": 2258, "s": 2240, "text": "Blurb word length" }, { "code": null, "e": 2275, "s": 2258, "text": "Name word length" }, { "code": null, "e": 2345, "s": 2275, "text": "Whether the project was highlighted as a staff pick (one-hot encoded)" }, { "code": null, "e": 2372, "s": 2345, "text": "Category (one-hot encoded)" }, { "code": null, "e": 2398, "s": 2372, "text": "Country (one-hot encoded)" }, { "code": null, "e": 2448, "s": 2398, "text": "Month a project was launched in (one-hot encoded)" }, { "code": null, "e": 2496, "s": 2448, "text": "Month of a project’s deadline (one-hot encoded)" }, { "code": null, "e": 2556, "s": 2496, "text": "Day of the week a project was launched on (one-hot encoded)" }, { "code": null, "e": 2614, "s": 2556, "text": "Day of the week of a project’s deadline (one-hot encoded)" }, { "code": null, "e": 2679, "s": 2614, "text": "Two-hour time window a project was launched in (one-hot encoded)" }, { "code": null, "e": 2742, "s": 2679, "text": "Two-hour time window of a project’s deadline (one-hot encoded)" }, { "code": null, "e": 3097, "s": 2742, "text": "Some features were initially retained for exploratory data analysis (EDA) purposes, but were then dropped in order to use machine learning models. These included features that are related to outcomes (e.g. the amount pledged and the number of backers) rather than related to the properties of the project itself (e.g. category, goal, length of campaign)." }, { "code": null, "e": 3125, "s": 3097, "text": "Now for the colourful part." }, { "code": null, "e": 3490, "s": 3125, "text": "Kickstarter has grown massively since its launch in 2009, particularly during 2014 when expansion really started to ramp up. The proportion of projects that succeed decreased considerably at this point, however, as the site was flooded with a much larger number of projects. The success rate has been on the increase in recent years though — so there’s still hope." }, { "code": null, "e": 3609, "s": 3490, "text": "Overall, 56% of completed projects (i.e. those that have finished and weren’t cancelled or suspended) were successful." }, { "code": null, "e": 3744, "s": 3609, "text": "The graphs below show the differences in some of the features between successful and failed projects. The key takeaways from this are:" }, { "code": null, "e": 4000, "s": 3744, "text": "Unsurprisingly, successful projects tend to have smaller (and therefore more realistic) goals — the median amount sought by successful projects is about half that of failed projects (medians are used due to high positive skew of funding and goal amounts)." }, { "code": null, "e": 4292, "s": 4000, "text": "The differences in the median amount pledged per project are more surprising. The median amount pledged per successful project is notably higher than the median amount requested, suggesting that projects that meet their goal tend to go on to gain even more funding, and become ‘over-funded’." }, { "code": null, "e": 4609, "s": 4292, "text": "On a related note, the difference between failed and successful companies is much larger in terms of amount pledged and the number of backers, compared to goal amount. Probably once potential backers see that a project looks like it will be successful, they are much more likely to jump on the bandwagon and fund it." }, { "code": null, "e": 4772, "s": 4609, "text": "Successful projects have slightly shorter campaign lengths, but take slightly longer to launch (measured from the time the project was first created on the site)." }, { "code": null, "e": 5069, "s": 4772, "text": "Roughly 20% of successful projects were highlighted on the site as staff picks. It does not seem unreasonable to suggest a causative relationship here, i.e. that projects that are chosen as staff picks are much more likely to go on to be successful, and that only a few staff picks go on to fail." }, { "code": null, "e": 5338, "s": 5069, "text": "Various other features were explored, in terms of project number, goal and funding amounts, backers and success rates. For example, the graphs below show the differences between different project categories (the code is also provided). The key takeaways from this are:" }, { "code": null, "e": 5710, "s": 5338, "text": "The best project types to launch on Kickstarter are comics (on the grounds of success rate, number of backers and amount pledged), dance (success rate and amount pledged) and games (amount pledged and number of backers). This is probably at least partly due to their relatively small funding goals — as noted above, projects with smaller goals tend to be more successful." }, { "code": null, "e": 5883, "s": 5710, "text": "Although comics and games tend to attract the most backers, each backer tends to pledge relatively little. Dance and film & video tend to attract the most generous backers." }, { "code": null, "e": 6049, "s": 5883, "text": "Technology projects have the highest median goal size by far. However, they are towards the bottom of the leaderboard in terms of the median amount actually pledged." }, { "code": null, "e": 6118, "s": 6049, "text": "The worst performing categories are food, journalism and technology." }, { "code": null, "e": 7531, "s": 6118, "text": "# Code used to create the graphs below# Importing the required librariesimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib import cmimport numpy as np# Creating a dataframe grouped by category with columns for failed and successfulcat_df = pd.get_dummies(df.set_index('category').state).groupby('category').sum()# Plottingfig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(3, 2, figsize=(12,12))color = cm.CMRmap(np.linspace(0.1,0.8,df.category.nunique()))df.groupby('category').category.count().plot(kind='bar', ax=ax1, color=color)ax1.set_title('Number of projects')ax1.set_xlabel('')df.groupby('category').usd_goal.median().plot(kind='bar', ax=ax2, color=color)ax2.set_title('Median project goal ($)')ax2.set_xlabel('')df.groupby('category').usd_pledged.median().plot(kind='bar', ax=ax3, color=color)ax3.set_title('Median pledged per project ($)')ax3.set_xlabel('')cat_df.div(cat_df.sum(axis=1), axis=0).successful.plot(kind='bar', ax=ax4, color=color) # Normalizes counts across rowsax4.set_title('Proportion of successful projects')ax4.set_xlabel('')df.groupby('category').backers_count.median().plot(kind='bar', ax=ax5, color=color)ax5.set_title('Median backers per project')ax5.set_xlabel('')df.groupby('category').pledge_per_backer.median().plot(kind='bar', ax=ax6, color=color)ax6.set_title('Median pledged per backer ($)')ax6.set_xlabel('')fig.subplots_adjust(hspace=0.6)plt.show()" }, { "code": null, "e": 7754, "s": 7531, "text": "In the interests of space and retinas, only the ‘success proportion’ graphs will be shown below for additional features. Again, for more detail, feel free to check out my GitHub repository. The key takeaways from this are:" }, { "code": null, "e": 7893, "s": 7754, "text": "Hong Kong is home to a greater proportion of successful projects (they also have a higher median number of backers and amount of funding)." }, { "code": null, "e": 8039, "s": 7893, "text": "Tuesday is the best day to launch a project, and weekends are the worst (the same pattern holds for the amount raised and the number of backers)." }, { "code": null, "e": 8211, "s": 8039, "text": "12pm to 2pm UTC is the best time to launch a project — it also has the greatest median number of backers and amount of funding. 6pm to 4am UTC is the worst time to launch." }, { "code": null, "e": 8372, "s": 8211, "text": "October is the best month to launch a project — it also has the greatest median number of backers and amount of funding. July and December are the worst months." }, { "code": null, "e": 8528, "s": 8372, "text": "The ultimate goal of this project was to create a model that could predict, with a good level of accuracy, whether a project was likely to succeed or fail." }, { "code": null, "e": 8624, "s": 8528, "text": "In order to prepare the data for machine learning, the following steps were taken (code below):" }, { "code": null, "e": 9103, "s": 8624, "text": "One-hot encoding categorical variables.Separating the data into the dependent target variable ‘y’ (in this case ‘state’, i.e. project success or failure) and the independent features ‘X’.Transforming the features in X so that they are all on the same scale. For this project, StandardScaler from Scikit-learn was used to transform each feature to a mean of 0 and a standard deviation of 1.The data was separated into a training and test set, for robust evaluation of the models." }, { "code": null, "e": 9143, "s": 9103, "text": "One-hot encoding categorical variables." }, { "code": null, "e": 9292, "s": 9143, "text": "Separating the data into the dependent target variable ‘y’ (in this case ‘state’, i.e. project success or failure) and the independent features ‘X’." }, { "code": null, "e": 9495, "s": 9292, "text": "Transforming the features in X so that they are all on the same scale. For this project, StandardScaler from Scikit-learn was used to transform each feature to a mean of 0 and a standard deviation of 1." }, { "code": null, "e": 9585, "s": 9495, "text": "The data was separated into a training and test set, for robust evaluation of the models." }, { "code": null, "e": 10179, "s": 9585, "text": "# Importing the required librariesimport pandas as pdfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_split# 1) Creating dummy variablesdf_transformed = pd.get_dummies(df_transformed)# 2) Separating into X and yX_unscaled = df_transformed.drop('state', axis=1)y = df_transformed.state# 3) Transforming the datascaler = StandardScaler()X = pd.DataFrame(scaler.fit_transform(X_unscaled), columns=list(X_unscaled.columns))# 4) Splitting into train and test setsX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.3, random_state=123)" }, { "code": null, "e": 10679, "s": 10179, "text": "It is good practice to choose an evaluation method before running machine learning models — not after. The weighted average F1 score was chosen. The F1 score calculates the harmonic mean between precision and recall, and is a suitable measure because there is no preference for false positives or false negatives in this case (both are equally bad). The weighted average will be used because the classes are of slightly different sizes, and we want to be able to predict both successes and failures." }, { "code": null, "e": 10782, "s": 10679, "text": "It is good practice to choose an evaluation method before running machine learning models — not after." }, { "code": null, "e": 10907, "s": 10782, "text": "Logistic regression can be used as a binary classifier in order to predict which of two categories a data point falls in to." }, { "code": null, "e": 11028, "s": 10907, "text": "To create a baseline model to improve upon, a logistic regression model was fitted to the data, with default parameters." }, { "code": null, "e": 11661, "s": 11028, "text": "# Importing the required librariesfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import classification_report# Fitting a logistic regression model with default parameterslogreg = LogisticRegression()logreg.fit(X_train,y_train)# Making predictionsy_hat_train = logreg.predict(X_train)y_hat_test = logreg.predict(X_test)# Logistic regression scoresprint(\"Logistic regression score for training set:\", round(logreg.score(X_train, y_train),5))print(\"Logistic regression score for test set:\", round(logreg.score(X_test, y_test),5))print(\"\\nClassification report:\")print(classification_report(y_test, y_hat_test))" }, { "code": null, "e": 11764, "s": 11661, "text": "Not bad. The model has a weighted average F1 score of 0.70. The aim is now to improve upon this score." }, { "code": null, "e": 12079, "s": 11764, "text": "There were a large number of features (106) in the dataset used for the initial logistic regression model. PCA (Principal Component Analysis) was used to reduce this into a smaller number of components which still explain as much variation in the data as possible. This can help improve model fitting and accuracy." }, { "code": null, "e": 12208, "s": 12079, "text": "The graph below (produced by the code below) shows that there was no obvious cut-off for the number of components to use in PCA." }, { "code": null, "e": 12689, "s": 12208, "text": "# Importing the required librariesimport matplotlib.pyplot as pltfrom sklearn.decomposition import PCA# Fitting PCApca = PCA()pca.fit_transform(X)explained_var = np.cumsum(pca.explained_variance_ratio_)# Plotting the amount of variation explained by PCA with different numbers of componentsplt.plot(list(range(1, len(explained_var)+1)), explained_var)plt.title('Amount of variation explained by PCA', fontsize=14)plt.xlabel('Number of components')plt.ylabel('Explained variance');" }, { "code": null, "e": 12723, "s": 12689, "text": "The following results were found:" }, { "code": null, "e": 12877, "s": 12723, "text": "Number of components explaining 80% of variance: 58Number of components explaining 90% of variance: 70Number of components explaining 99% of variance: 90" }, { "code": null, "e": 13062, "s": 12877, "text": "To choose the number of components to use in the machine learning models, each of these values was plugged into a pipeline for a logistic regression model using the default parameters:" }, { "code": null, "e": 13356, "s": 13062, "text": "# Running a for loop to test different values of n_componentsn_comps = [58,70,90]for n in n_comps: pipe = Pipeline([(‘pca’, PCA(n_components=n)), (‘clf’, LogisticRegression())]) pipe.fit(X_train, y_train) print(“\\nNumber of components:”, n) print(“Score:”, round(pipe.score(X_test, y_test),5))" }, { "code": null, "e": 13493, "s": 13356, "text": "The results showed that the score is highest for 90 components, although the difference is small (c. 3% improvement from 58 components):" }, { "code": null, "e": 13607, "s": 13493, "text": "Number of components: 58Score: 0.67831Number of components: 70Score: 0.6858Number of components: 90Score: 0.70799" }, { "code": null, "e": 13856, "s": 13607, "text": "The logistic regression model can potentially be further improved by optimising its parameters. GridSearchCV was used to test multiple different regularisation parameters (values of C), penalties (l1 or l2) and models with and without an intercept." }, { "code": null, "e": 14816, "s": 13856, "text": "# Importing the required librariesfrom sklearn.model_selection import GridSearchCV# Timing how long the model takes to runlogreg_start = time.time()# Building the pipelinepipe_logreg = Pipeline([('pca', PCA(n_components=90)), ('clf', LogisticRegression())])# Creating the parameters to testparams_logreg = [ {'clf__penalty': ['l1', 'l2'], 'clf__fit_intercept': [True, False], 'clf__C': [0.001, 0.01, 1, 10] }]# Using GridSearchCV to test multiple different parametersgrid_logreg = GridSearchCV(estimator=pipe_logreg, param_grid=params_logreg, cv=5)grid_logreg.fit(X_train, y_train)logreg_end = time.time()logreg_best_score = grid_logreg.best_score_logreg_best_params = grid_logreg.best_params_# Printing the resultsprint(f\"Time taken to run: {round((logreg_end - logreg_start)/60,1)} minutes\")print(\"Best accuracy:\", round(logreg_best_score,2))print(\"Best parameters:\", logreg_best_params)" }, { "code": null, "e": 14825, "s": 14816, "text": "Results:" }, { "code": null, "e": 14958, "s": 14825, "text": "Time taken to run: 48.56 minutesBest accuracy: 0.71Best parameters: {‘clf__C’: 10, ‘clf__fit_intercept’: True, ‘clf__penalty’: ‘l2’}" }, { "code": null, "e": 15119, "s": 14958, "text": "A classification report and a confusion matrix were then produced for the logistic regression model using the best parameters (according to the accuracy score)." }, { "code": null, "e": 15183, "s": 15119, "text": "The confusion matrix was produced using the following function:" }, { "code": null, "e": 15979, "s": 15183, "text": "def plot_cf(y_true, y_pred, class_names=None, model_name=None): \"\"\"Plots a confusion matrix\"\"\" cf = confusion_matrix(y_true, y_pred) plt.imshow(cf, cmap=plt.cm.Blues) plt.grid(b=None) if model_name: plt.title(\"Confusion Matrix: {}\".format(model_name)) else: plt.title(\"Confusion Matrix\") plt.ylabel('True Label') plt.xlabel('Predicted Label') class_names = set(y_true) tick_marks = np.arange(len(class_names)) if class_names: plt.xticks(tick_marks, class_names) plt.yticks(tick_marks, class_names) thresh = cf.max() / 2. for i, j in itertools.product(range(cf.shape[0]), range(cf.shape[1])): plt.text(j, i, cf[i, j], horizontalalignment='center', color='white' if cf[i, j] > thresh else 'black')plt.colorbar()" }, { "code": null, "e": 16046, "s": 15979, "text": "The full results for the best logistic regression model are below:" }, { "code": null, "e": 16221, "s": 16046, "text": "After hyperparameter tuning, the model’s accuracy score is the same as the logistic regression model using default parameters (0.70 weighted average F1 score). Disappointing." }, { "code": null, "e": 16470, "s": 16221, "text": "Next, a Random Forest classifier was used. The Random Forest algorithm is a supervised learning algorithm that can be used for classification. It works by building multiple different decision trees to predict which category a data point belongs to." }, { "code": null, "e": 16575, "s": 16470, "text": "Again, GridSearchCV was used to test multiple different hyperparameters, in order to optimise the model." }, { "code": null, "e": 17355, "s": 16575, "text": "# Importing the required librariesfrom sklearn.ensemble import RandomForestClassifier# Using GridSearchCV to test multiple different parametersrf_start = time.time()pipe_rf = Pipeline([('pca', PCA(n_components=90)), ('clf', RandomForestClassifier())])params_rf = [ {'clf__n_estimators': [100], 'clf__max_depth': [20, 30, 40], 'clf__min_samples_split':[0.001, 0.01] }]grid_rf = GridSearchCV(estimator=pipe_rf, param_grid=params_rf, cv=5)grid_rf.fit(X_train, y_train)rf_end = time.time()rf_best_score = grid_rf.best_score_rf_best_params = grid_rf.best_params_print(f\"Time taken to run: {round((rf_end - rf_start)/60,1)} minutes\")print(\"Best accuracy:\", round(rf_best_score,2))print(\"Best parameters:\", rf_best_params)" }, { "code": null, "e": 17364, "s": 17355, "text": "Results:" }, { "code": null, "e": 17512, "s": 17364, "text": "Time taken to run: 72.2 minutesBest accuracy: 0.7Best parameters: {'clf__max_depth': 30, 'clf__min_samples_split': 0.001, 'clf__n_estimators': 100}" }, { "code": null, "e": 17573, "s": 17512, "text": "The full results for the best Random Forest model are below:" }, { "code": null, "e": 18017, "s": 17573, "text": "After hyperparameter tuning, the model’s weighted average F1 score increased from 0.65 for a model with default settings to 0.69. This is similar to, although slightly worse than, the logistic regression model. Also, the difference between the score for the training set and the test set suggests there might be some over-fitting. There may well be more scope for hyperparameter tuning here to further improve the model, but time precluded it." }, { "code": null, "e": 18399, "s": 18017, "text": "Ah, the darling of the Kaggle world. XGBoost is very ‘in’ right now. This is a form of gradient boosting algorithm. Similar to Random Forests, it is an ensemble method that produces multiple decision trees to improve classification of data points, but it uses gradient descent to improve the performance of the model for the data points that are particularly difficult to classify." }, { "code": null, "e": 18457, "s": 18399, "text": "Back to good ol’ GridSearchCV for hyperparameter testing:" }, { "code": null, "e": 19300, "s": 18457, "text": "# Importing the required librariesfrom sklearn.model_selection import GridSearchCV# Using GridSearchCV to test multiple different parametersxgb_start = time.time()pipe_xgb = Pipeline([('pca', PCA(n_components=90)), ('clf', xgb.XGBClassifier())])params_xgb = [ {'clf__n_estimators': [100], 'clf__max_depth': [25, 35], 'clf__learning_rate': [0.01, 0.1], 'clf__subsample': [0.7, 1], 'clf__min_child_weight': [20, 100] }]grid_xgb = GridSearchCV(estimator=pipe_xgb, param_grid=params_xgb, cv=5)grid_xgb.fit(X_train, y_train)xgb_end = time.time()xgb_best_score = grid_xgb.best_score_xgb_best_params = grid_xgb.best_params_print(f\"Time taken to run: {round((xgb_end - xgb_start)/60,1)} minutes\")print(\"Best accuracy:\", round(xgb_best_score,2))print(\"Best parameters:\", xgb_best_params)" }, { "code": null, "e": 19309, "s": 19300, "text": "Results:" }, { "code": null, "e": 19505, "s": 19309, "text": "Time taken to run: 865.4 minutesBest accuracy: 0.7Best parameters: {'clf__learning_rate': 0.1, 'clf__max_depth': 35, 'clf__min_child_weight': 100, 'clf__n_estimators': 100, 'clf__subsample': 0.7}" }, { "code": null, "e": 19730, "s": 19505, "text": "Yikes. 14 and a half hours, and it was still only able to achieve the same accuracy as the initial regression model (this was also only a 0.01 increase in accuracy from an XGBoost model that was run with default parameters)." }, { "code": null, "e": 19785, "s": 19730, "text": "The full results for the best XGBoost model are below:" }, { "code": null, "e": 20095, "s": 19785, "text": "As with the Random Forest model, the difference between the accuracy score for the training set and the test set suggests there might be some over-fitting. Again, there may well be more scope for hyperparameter tuning here to further improve the model — but I didn’t have another 14 and a half hours to spare." }, { "code": null, "e": 20569, "s": 20095, "text": "Each model was able to achieve an accuracy of about 70%, after parameter tuning. Although it was relatively easy to reach roughly this level of accuracy, parameter tuning was only able to increase accuracy levels by a small amount. Possibly the reasonably large amount of data for each of only two categories meant that there was enough data for even a relatively simple model (e.g. logistic regression with default settings) to achieve a good level of validation accuracy." }, { "code": null, "e": 20731, "s": 20569, "text": "The best Random Forest and XGBoost models created still showed some degree of over-fitting. Further parameter tuning would be required to attempt to reduce this." }, { "code": null, "e": 20954, "s": 20731, "text": "The final chosen model is the tuned logistic regression model. This is because, although each model was able to achieve a similar level of accuracy for the test set, this is the only model that did not exhibit overfitting." }, { "code": null, "e": 21415, "s": 20954, "text": "Interestingly, each model performed worse at predicting failures compared to successes, with a lower true negative rate than true positive rate. I.e. it classified quite a few failed projects as successes, but relatively few successful projects as failures. Possibly the factors that might cause a project to fail are more likely to be beyond the scope of the data, e.g. poor marketing, insufficient updates, or not replying to messages from potential backers." }, { "code": null, "e": 21578, "s": 21415, "text": "The false positive and false negative rates mean that, if the data about a new project is fed through the model to make a prediction about its success or failure:" }, { "code": null, "e": 21702, "s": 21578, "text": "if the project is going to end up being a success, the model will correctly predict this as a success about 80% of the time" }, { "code": null, "e": 21899, "s": 21702, "text": "if the project is going to end up being a failure, the model will only correctly predict this as a failure about 60% of the time (and the rest of the time will incorrectly predict it as a success)" }, { "code": null, "e": 22003, "s": 21899, "text": "Some of the factors that had a positive effect on success rate and/or the amount of money received are:" }, { "code": null, "e": 22019, "s": 22003, "text": "Most important:" }, { "code": null, "e": 22041, "s": 22019, "text": "Smaller project goals" }, { "code": null, "e": 22093, "s": 22041, "text": "Being chosen as a staff pick (a measure of quality)" }, { "code": null, "e": 22126, "s": 22093, "text": "Comics, dance and games projects" }, { "code": null, "e": 22150, "s": 22126, "text": "Projects from Hong Kong" }, { "code": null, "e": 22166, "s": 22150, "text": "Less important:" }, { "code": null, "e": 22184, "s": 22166, "text": "Shorter campaigns" }, { "code": null, "e": 22226, "s": 22184, "text": "Taking longer between creation and launch" }, { "code": null, "e": 22314, "s": 22226, "text": "Film & video and music projects (popular categories on the site, and fairly successful)" }, { "code": null, "e": 22428, "s": 22314, "text": "Launching on a Tuesday (although this is also the most common day to launch a project, so beware the competition)" }, { "code": null, "e": 22449, "s": 22428, "text": "Launching in October" }, { "code": null, "e": 22614, "s": 22449, "text": "Launching between 12pm and 2pm UTC (this is of course related to the country a project is launched from, but remember that backers can come from all over the world)" }, { "code": null, "e": 22707, "s": 22614, "text": "Factors which had a negative effect on success rate and/or the amount of money received are:" }, { "code": null, "e": 22722, "s": 22707, "text": "Most negative:" }, { "code": null, "e": 22734, "s": 22722, "text": "Large goals" }, { "code": null, "e": 22763, "s": 22734, "text": "Food and journalism projects" }, { "code": null, "e": 22783, "s": 22763, "text": "Projects from Italy" }, { "code": null, "e": 22798, "s": 22783, "text": "Less negative:" }, { "code": null, "e": 22815, "s": 22798, "text": "Longer campaigns" }, { "code": null, "e": 22838, "s": 22815, "text": "Launching on a weekend" }, { "code": null, "e": 22868, "s": 22838, "text": "Launching in July or December" }, { "code": null, "e": 22902, "s": 22868, "text": "Launching between 6pm and 4am UTC" }, { "code": null, "e": 23109, "s": 22902, "text": "Overall, Kickstarter is well suited to small, high-quality projects, particularly comics, dance and games. It is less suited to larger projects, particularly food (e.g. restaurants) and journalism projects." } ]
Custom Messages in ElectronJS - GeeksforGeeks
28 May, 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. One of the ways how an Electron application interacts with the user is through Message boxes and Alerts. Sometimes during the execution of the application, a condition arises which needs the user’s attention or the code encounters an error and the user needs to be made aware of it. In such cases, the execution flow cannot move forward without user intervention. Electron provides us with a convenient technique by which the user can be made aware of the problem and take necessary action on it. Electron provides us with a built-in dialog module to display Custom Message boxes and Alerts for interacting with the user. This tutorial will use the instance methods of the dialog module to demonstrate Custom Messages in Electron. 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. Custom Messages in Electron: The dialog Module is part of the Main Process. To import and use the dialog Module in the Renderer Process, we will be using Electron remote module. Project Structure: Example: Follow the given steps to build Custom Message boxes in Electron. Step 1: Navigate to an Empty Directory to setup the project, and run the following command,npm initTo generate the package.json file. Install Electron using npm if it is not installed.npm install electron --saveThis will install the required node_modules dependencies. Copy any Image file of your choosing into the assets folder and name it as image.png. In this tutorial, we will be using the Electron logo as the image.png file.package.json:{ "name": "electron-message", "version": "1.0.0", "description": "Custom Messages in Electron", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.2.5" } } npm init To generate the package.json file. Install Electron using npm if it is not installed. npm install electron --save This will install the required node_modules dependencies. Copy any Image file of your choosing into the assets folder and name it as image.png. In this tutorial, we will be using the Electron logo as the image.png file. package.json: { "name": "electron-message", "version": "1.0.0", "description": "Custom Messages in Electron", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.2.5" } } Step 2: For the Boilerplate code of the main.js file, Refer this link. We have modified the code to suit our project needs.main.js:const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs./* The 'dialog.showErrorBox()' method can be used before this event occurs. */ // This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // To stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // Put them in separate files and require them here. main.js: const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs./* The 'dialog.showErrorBox()' method can be used before this event occurs. */ // This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // To stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // Put them in separate files and require them here. Step 3: Create the index.html file and index.js file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We have modified the code to suit our project needs.index.html:<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <h3>Custom Messages in Electron</h3> <button id="show">Show Custom Message Box</button> <br><br> <button id="error">Show Error Message Box</button> <!-- Adding Individual Renderer Process JS File --> <script src="index.js"></script> </body></html>Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the command.npm start index.html: <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <h3>Custom Messages in Electron</h3> <button id="show">Show Custom Message Box</button> <br><br> <button id="error">Show Error Message Box</button> <!-- Adding Individual Renderer Process JS File --> <script src="index.js"></script> </body></html> Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the command. npm start Step 4: The Show Custom Message Box button does not have any functionality associated with it yet. To change this, add the following code in the index.js file.The dialog.showMessageBox(browserWindow, options) is used with all default/basic values for the options Object. Using this Instance method shows the Message box and will block the application execution until the message box is closed successfully with appropriate action from the user. It takes in the following parameters.browserWindow: BrowserWindow (Optional) The BrowserWindow Instance. This argument allows the dialog to attach itself to the parent window, making it a modal. A modal window is a child window that disables the parent window. If BrowserWindow is not shown, dialog will not be attached to it. In such case It will be displayed as independent window. In the above code, the BrowserWindow instance is not being passed to the dialog, therefore the dialog opens as an independent window on clicking the Show Custom Message Box button.options: Object It takes in the following parameters,type: String (Optional) It can hold the following values.noneinfoerrorquestionwarningEach of these values signifify the type of Message Box that you want to display to the user. Default value is none. On Windows, question displays the same icon as info, unless the icon property is explicitly set. On macOS, both warning and error display the same warning icon. Each of these values have a default System OS sound associated with it except for the default value.buttons: String[] (Optional) It represents an Array for the labels of the Buttons that you wish to display on the Custom Message box. An Empty array will result in one button being displayed, labeled OK.defaultId: Integer (Optional) The index of the button in the buttons array which will be selected by default when the Custom Message box is opened. This property is dependent on the noLink property. This is demonstrated in the following Steps.title: String (Optional) The title to be displayed on the Message box. Some OS platforms and their respective versions do not support this property.message: String The main contents of the Message box.detail: String (Optional) Extra Information to be displayed in the Message box below the message property.checkboxLabel: String (Optional) Label of the checkbox. This property automatically includes the checkbox with the given label in the custom Message box.checkboxChecked: Boolean (Optional) This property represents the initial state of the checkbox. The default value of this property is false.icon: NativeImage (Optional) The icon to be displayed on the Message box. If this property is defined, it will override the default system icons for the type property, irrespective of its value. This property takes in a NativeImage instance or the filepath of an image. In this tutorial, we will pass the filepath for the image.png file located in the assets folder using the path module.cancelId: Integer (Optional) The index of the button to be returned when the dialog is cancelled, via the Esc key. By default this is assigned to the first button with Cancel or No as the label in the buttons array property. If no such labeled buttons exist and this option is not set, 0 will be used as the return value. This is demonstrated in the following Steps.noLink: Boolean (Optional) This property is supported on Windows only. When this property is set, Electron will automatically try to figure out which one of the buttons are common button labels e.g. Cancel, Yes, No, OK etc, and show the other button labels as command links in the dialog. This property is used to make the dialog window appear in style with modern Windows OS apps and themes. By default, this property is set to false. In case all common button labels are used, this property will have no effect. This property is demonstrated in the following Steps.normalizeAccessKeys: Boolean (Optional) Normalize the keyboard access keys across platforms. Default value is false. Enabling this property assumes the ‘&’ wildcard is used in the button labels. These labels will be converted so that they work on each platform accordingly. ‘&’ characters are removed altogether on macOS, converted to _ on Linux, and no action is taken on Windows.The dialog.showMessageBox(browserWindow, options) returns a Promise. It resolves to an Object containing the following parameters,response: Integer The index of the button clicked as defined in the buttons array property.checkboxChecked: Boolean The checked state of the checkbox if checkboxLabel property was set. By default, will return false.index.js:const electron = require('electron');const path = require('path'); // Importing dialog module using remoteconst dialog = electron.remote.dialog; var showBox = document.getElementById('show'); showBox.addEventListener('click', (event) => { // Resolves to a Promise<Object> dialog.showMessageBox({ // option Object type: 'none', buttons: [], defaultId: 0, icon: '', title: 'This is the Title', message: 'This is a Message', detail: 'This is extra Information', checkboxLabel: 'Checkbox', checkboxChecked: false, cancelId: 0, noLink: false, normalizeAccessKeys: false, }).then(box => { console.log('Button Clicked Index - ', box.response); console.log('Checkbox Checked - ', box.checkboxChecked); }).catch(err => { console.log(err) }); });Output: We should now be able to successfully trigger a basic Custom Message Box on clicking the Show Custom Message Box button.Note: If the user tries to continue the execution of the application without successfully closing the Custom Message box, the following message is shown on the console:Attempting to call a function in a renderer window that has been closed or released. Function provided here: undefined The dialog.showMessageBox(browserWindow, options) is used with all default/basic values for the options Object. Using this Instance method shows the Message box and will block the application execution until the message box is closed successfully with appropriate action from the user. It takes in the following parameters. browserWindow: BrowserWindow (Optional) The BrowserWindow Instance. This argument allows the dialog to attach itself to the parent window, making it a modal. A modal window is a child window that disables the parent window. If BrowserWindow is not shown, dialog will not be attached to it. In such case It will be displayed as independent window. In the above code, the BrowserWindow instance is not being passed to the dialog, therefore the dialog opens as an independent window on clicking the Show Custom Message Box button. options: Object It takes in the following parameters,type: String (Optional) It can hold the following values.noneinfoerrorquestionwarningEach of these values signifify the type of Message Box that you want to display to the user. Default value is none. On Windows, question displays the same icon as info, unless the icon property is explicitly set. On macOS, both warning and error display the same warning icon. Each of these values have a default System OS sound associated with it except for the default value.buttons: String[] (Optional) It represents an Array for the labels of the Buttons that you wish to display on the Custom Message box. An Empty array will result in one button being displayed, labeled OK.defaultId: Integer (Optional) The index of the button in the buttons array which will be selected by default when the Custom Message box is opened. This property is dependent on the noLink property. This is demonstrated in the following Steps.title: String (Optional) The title to be displayed on the Message box. Some OS platforms and their respective versions do not support this property.message: String The main contents of the Message box.detail: String (Optional) Extra Information to be displayed in the Message box below the message property.checkboxLabel: String (Optional) Label of the checkbox. This property automatically includes the checkbox with the given label in the custom Message box.checkboxChecked: Boolean (Optional) This property represents the initial state of the checkbox. The default value of this property is false.icon: NativeImage (Optional) The icon to be displayed on the Message box. If this property is defined, it will override the default system icons for the type property, irrespective of its value. This property takes in a NativeImage instance or the filepath of an image. In this tutorial, we will pass the filepath for the image.png file located in the assets folder using the path module.cancelId: Integer (Optional) The index of the button to be returned when the dialog is cancelled, via the Esc key. By default this is assigned to the first button with Cancel or No as the label in the buttons array property. If no such labeled buttons exist and this option is not set, 0 will be used as the return value. This is demonstrated in the following Steps.noLink: Boolean (Optional) This property is supported on Windows only. When this property is set, Electron will automatically try to figure out which one of the buttons are common button labels e.g. Cancel, Yes, No, OK etc, and show the other button labels as command links in the dialog. This property is used to make the dialog window appear in style with modern Windows OS apps and themes. By default, this property is set to false. In case all common button labels are used, this property will have no effect. This property is demonstrated in the following Steps.normalizeAccessKeys: Boolean (Optional) Normalize the keyboard access keys across platforms. Default value is false. Enabling this property assumes the ‘&’ wildcard is used in the button labels. These labels will be converted so that they work on each platform accordingly. ‘&’ characters are removed altogether on macOS, converted to _ on Linux, and no action is taken on Windows. type: String (Optional) It can hold the following values.noneinfoerrorquestionwarningEach of these values signifify the type of Message Box that you want to display to the user. Default value is none. On Windows, question displays the same icon as info, unless the icon property is explicitly set. On macOS, both warning and error display the same warning icon. Each of these values have a default System OS sound associated with it except for the default value. none info error question warning Each of these values signifify the type of Message Box that you want to display to the user. Default value is none. On Windows, question displays the same icon as info, unless the icon property is explicitly set. On macOS, both warning and error display the same warning icon. Each of these values have a default System OS sound associated with it except for the default value. buttons: String[] (Optional) It represents an Array for the labels of the Buttons that you wish to display on the Custom Message box. An Empty array will result in one button being displayed, labeled OK. defaultId: Integer (Optional) The index of the button in the buttons array which will be selected by default when the Custom Message box is opened. This property is dependent on the noLink property. This is demonstrated in the following Steps. title: String (Optional) The title to be displayed on the Message box. Some OS platforms and their respective versions do not support this property. message: String The main contents of the Message box. detail: String (Optional) Extra Information to be displayed in the Message box below the message property. checkboxLabel: String (Optional) Label of the checkbox. This property automatically includes the checkbox with the given label in the custom Message box. checkboxChecked: Boolean (Optional) This property represents the initial state of the checkbox. The default value of this property is false. icon: NativeImage (Optional) The icon to be displayed on the Message box. If this property is defined, it will override the default system icons for the type property, irrespective of its value. This property takes in a NativeImage instance or the filepath of an image. In this tutorial, we will pass the filepath for the image.png file located in the assets folder using the path module. cancelId: Integer (Optional) The index of the button to be returned when the dialog is cancelled, via the Esc key. By default this is assigned to the first button with Cancel or No as the label in the buttons array property. If no such labeled buttons exist and this option is not set, 0 will be used as the return value. This is demonstrated in the following Steps. noLink: Boolean (Optional) This property is supported on Windows only. When this property is set, Electron will automatically try to figure out which one of the buttons are common button labels e.g. Cancel, Yes, No, OK etc, and show the other button labels as command links in the dialog. This property is used to make the dialog window appear in style with modern Windows OS apps and themes. By default, this property is set to false. In case all common button labels are used, this property will have no effect. This property is demonstrated in the following Steps. normalizeAccessKeys: Boolean (Optional) Normalize the keyboard access keys across platforms. Default value is false. Enabling this property assumes the ‘&’ wildcard is used in the button labels. These labels will be converted so that they work on each platform accordingly. ‘&’ characters are removed altogether on macOS, converted to _ on Linux, and no action is taken on Windows. The dialog.showMessageBox(browserWindow, options) returns a Promise. It resolves to an Object containing the following parameters, response: Integer The index of the button clicked as defined in the buttons array property. checkboxChecked: Boolean The checked state of the checkbox if checkboxLabel property was set. By default, will return false. index.js: const electron = require('electron');const path = require('path'); // Importing dialog module using remoteconst dialog = electron.remote.dialog; var showBox = document.getElementById('show'); showBox.addEventListener('click', (event) => { // Resolves to a Promise<Object> dialog.showMessageBox({ // option Object type: 'none', buttons: [], defaultId: 0, icon: '', title: 'This is the Title', message: 'This is a Message', detail: 'This is extra Information', checkboxLabel: 'Checkbox', checkboxChecked: false, cancelId: 0, noLink: false, normalizeAccessKeys: false, }).then(box => { console.log('Button Clicked Index - ', box.response); console.log('Checkbox Checked - ', box.checkboxChecked); }).catch(err => { console.log(err) }); }); Output: We should now be able to successfully trigger a basic Custom Message Box on clicking the Show Custom Message Box button. Note: If the user tries to continue the execution of the application without successfully closing the Custom Message box, the following message is shown on the console: Attempting to call a function in a renderer window that has been closed or released. Function provided here: undefined Step 5: We will now modify the options Object of the Custom Message Box to see the different outputs,type: String Defining the different types of Message boxes.type: ‘info’type: ‘warning’type: ‘error’buttons: String[] We will define Custom labels for the buttons array property and see the respective outputs by changing the noLink property.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], noLink: false, defaultId: 0Note: In this case the defaultId property should highlight the Cancel button, but instead the Button-1 label is selected. This is due to the behaviour defined by the noLink property.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], noLink: true, defaultId: 0Note: The Cancel button is selected by default as per expected behaviour.cancelId: Integer Evaluating the behaviour of the cancelId property. This behaviour is invoked by pressing the Esc key on the keyboard.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], cancelId: 100, noLink: trueNote: The value returned is 100 as set in the cancelId property.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], cancelId: 100, noLink: falseNote: The value returned is 0 despite setting the cancelId property value to 100.icon: NativeImage We will be passing the filepath of the image.png file located in the assets folder.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], icon: path.join(__dirname, ‘../assets/image.png’), noLink: truebuttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], icon: path.join(__dirname, ‘../assets/image.png’), noLink: falseNote: Using the icon property disables the default system OS sound for the type property, irrespective of its value.We can also assign different behaviours to each button in the Message box by simply comparing the index value of the buttons array property with the response parameter returned by Promise.index.js:.then(box => { console.log('Button Clicked Index - ', box.response); console.log('Checkbox Checked - ', box.checkboxChecked); if (box.response === 0) { console.log('Cancel Button was clicked'); } else if (box.response === 2) { console.log('Button-1 was clicked'); } }).catch(err => { console.log(err) }); Output: type: String Defining the different types of Message boxes.type: ‘info’type: ‘warning’type: ‘error’ type: ‘info’ type: ‘warning’ type: ‘error’ buttons: String[] We will define Custom labels for the buttons array property and see the respective outputs by changing the noLink property.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], noLink: false, defaultId: 0Note: In this case the defaultId property should highlight the Cancel button, but instead the Button-1 label is selected. This is due to the behaviour defined by the noLink property.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], noLink: true, defaultId: 0Note: The Cancel button is selected by default as per expected behaviour. buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], noLink: false, defaultId: 0Note: In this case the defaultId property should highlight the Cancel button, but instead the Button-1 label is selected. This is due to the behaviour defined by the noLink property. Note: In this case the defaultId property should highlight the Cancel button, but instead the Button-1 label is selected. This is due to the behaviour defined by the noLink property. buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], noLink: true, defaultId: 0Note: The Cancel button is selected by default as per expected behaviour. Note: The Cancel button is selected by default as per expected behaviour. cancelId: Integer Evaluating the behaviour of the cancelId property. This behaviour is invoked by pressing the Esc key on the keyboard.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], cancelId: 100, noLink: trueNote: The value returned is 100 as set in the cancelId property.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], cancelId: 100, noLink: falseNote: The value returned is 0 despite setting the cancelId property value to 100. buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], cancelId: 100, noLink: trueNote: The value returned is 100 as set in the cancelId property. Note: The value returned is 100 as set in the cancelId property. buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], cancelId: 100, noLink: falseNote: The value returned is 0 despite setting the cancelId property value to 100. Note: The value returned is 0 despite setting the cancelId property value to 100. icon: NativeImage We will be passing the filepath of the image.png file located in the assets folder.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], icon: path.join(__dirname, ‘../assets/image.png’), noLink: truebuttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], icon: path.join(__dirname, ‘../assets/image.png’), noLink: falseNote: Using the icon property disables the default system OS sound for the type property, irrespective of its value. buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], icon: path.join(__dirname, ‘../assets/image.png’), noLink: true buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], icon: path.join(__dirname, ‘../assets/image.png’), noLink: false Note: Using the icon property disables the default system OS sound for the type property, irrespective of its value. We can also assign different behaviours to each button in the Message box by simply comparing the index value of the buttons array property with the response parameter returned by Promise. index.js: .then(box => { console.log('Button Clicked Index - ', box.response); console.log('Checkbox Checked - ', box.checkboxChecked); if (box.response === 0) { console.log('Cancel Button was clicked'); } else if (box.response === 2) { console.log('Button-1 was clicked'); } }).catch(err => { console.log(err) }); Output: Step 6: Electron also provides us with an instance Method specifically designed for Error Messages. In the above code, the Show Error Message Box button does not have any functionality associated with it. To change this add the following code in the index.js file.The dialog.showErrorBox(title, info) takes in the following parameters. It does not have any return value. This method is not customizable like the dialog.showMessageBox() method but this method can be safely called before the ready event of the app module is emitted. Refer to the highlighted code in the main.js file. It is usually used to display errors in the application startup stages. If called before the ready event of the app module on Linux, the message will be emitted to stderr, and no GUI dialog will appear.title: String The title of the Error box.info: String The text information to display in the Error box below the title property.index.js:var error = document.getElementById('error'); error.addEventListener('click', (event) => { dialog.showErrorBox('This is the Title', 'This is the Content');});Output: The dialog.showErrorBox(title, info) takes in the following parameters. It does not have any return value. This method is not customizable like the dialog.showMessageBox() method but this method can be safely called before the ready event of the app module is emitted. Refer to the highlighted code in the main.js file. It is usually used to display errors in the application startup stages. If called before the ready event of the app module on Linux, the message will be emitted to stderr, and no GUI dialog will appear. title: String The title of the Error box. info: String The text information to display in the Error box below the title property. index.js: var error = document.getElementById('error'); error.addEventListener('click', (event) => { dialog.showErrorBox('This is the Title', 'This is the Content');}); Output: ElectronJS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to filter object array based on attributes? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25300, "s": 25272, "text": "\n28 May, 2020" }, { "code": null, "e": 25600, "s": 25300, "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": 26331, "s": 25600, "text": "One of the ways how an Electron application interacts with the user is through Message boxes and Alerts. Sometimes during the execution of the application, a condition arises which needs the user’s attention or the code encounters an error and the user needs to be made aware of it. In such cases, the execution flow cannot move forward without user intervention. Electron provides us with a convenient technique by which the user can be made aware of the problem and take necessary action on it. Electron provides us with a built-in dialog module to display Custom Message boxes and Alerts for interacting with the user. This tutorial will use the instance methods of the dialog module to demonstrate Custom Messages in Electron." }, { "code": null, "e": 26501, "s": 26331, "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": 26679, "s": 26501, "text": "Custom Messages in Electron: The dialog Module is part of the Main Process. To import and use the dialog Module in the Renderer Process, we will be using Electron remote module." }, { "code": null, "e": 26698, "s": 26679, "text": "Project Structure:" }, { "code": null, "e": 26773, "s": 26698, "text": "Example: Follow the given steps to build Custom Message boxes in Electron." }, { "code": null, "e": 27523, "s": 26773, "text": "Step 1: Navigate to an Empty Directory to setup the project, and run the following command,npm initTo generate the package.json file. Install Electron using npm if it is not installed.npm install electron --saveThis will install the required node_modules dependencies. Copy any Image file of your choosing into the assets folder and name it as image.png. In this tutorial, we will be using the Electron logo as the image.png file.package.json:{\n \"name\": \"electron-message\",\n \"version\": \"1.0.0\",\n \"description\": \"Custom Messages 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.2.5\"\n }\n}\n" }, { "code": null, "e": 27532, "s": 27523, "text": "npm init" }, { "code": null, "e": 27618, "s": 27532, "text": "To generate the package.json file. Install Electron using npm if it is not installed." }, { "code": null, "e": 27646, "s": 27618, "text": "npm install electron --save" }, { "code": null, "e": 27866, "s": 27646, "text": "This will install the required node_modules dependencies. Copy any Image file of your choosing into the assets folder and name it as image.png. In this tutorial, we will be using the Electron logo as the image.png file." }, { "code": null, "e": 27880, "s": 27866, "text": "package.json:" }, { "code": null, "e": 28187, "s": 27880, "text": "{\n \"name\": \"electron-message\",\n \"version\": \"1.0.0\",\n \"description\": \"Custom Messages 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.2.5\"\n }\n}\n" }, { "code": null, "e": 29674, "s": 28187, "text": "Step 2: For the Boilerplate code of the main.js file, Refer this link. We have modified the code to suit our project needs.main.js:const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs./* The 'dialog.showErrorBox()' method can be used before this event occurs. */ // This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // To stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // Put them in separate files and require them here." }, { "code": null, "e": 29683, "s": 29674, "text": "main.js:" }, { "code": "const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs./* The 'dialog.showErrorBox()' method can be used before this event occurs. */ // This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // To stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // Put them in separate files and require them here.", "e": 31039, "s": 29683, "text": null }, { "code": null, "e": 32315, "s": 31039, "text": "Step 3: Create the index.html file and index.js file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We have modified the code to suit our project needs.index.html:<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <h3>Custom Messages in Electron</h3> <button id=\"show\">Show Custom Message Box</button> <br><br> <button id=\"error\">Show Error Message Box</button> <!-- Adding Individual Renderer Process JS File --> <script src=\"index.js\"></script> </body></html>Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the command.npm start" }, { "code": null, "e": 32327, "s": 32315, "text": "index.html:" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <h3>Custom Messages in Electron</h3> <button id=\"show\">Show Custom Message Box</button> <br><br> <button id=\"error\">Show Error Message Box</button> <!-- Adding Individual Renderer Process JS File --> <script src=\"index.js\"></script> </body></html>", "e": 33198, "s": 32327, "text": null }, { "code": null, "e": 33359, "s": 33198, "text": "Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the command." }, { "code": null, "e": 33369, "s": 33359, "text": "npm start" }, { "code": null, "e": 39277, "s": 33369, "text": "Step 4: The Show Custom Message Box button does not have any functionality associated with it yet. To change this, add the following code in the index.js file.The dialog.showMessageBox(browserWindow, options) is used with all default/basic values for the options Object. Using this Instance method shows the Message box and will block the application execution until the message box is closed successfully with appropriate action from the user. It takes in the following parameters.browserWindow: BrowserWindow (Optional) The BrowserWindow Instance. This argument allows the dialog to attach itself to the parent window, making it a modal. A modal window is a child window that disables the parent window. If BrowserWindow is not shown, dialog will not be attached to it. In such case It will be displayed as independent window. In the above code, the BrowserWindow instance is not being passed to the dialog, therefore the dialog opens as an independent window on clicking the Show Custom Message Box button.options: Object It takes in the following parameters,type: String (Optional) It can hold the following values.noneinfoerrorquestionwarningEach of these values signifify the type of Message Box that you want to display to the user. Default value is none. On Windows, question displays the same icon as info, unless the icon property is explicitly set. On macOS, both warning and error display the same warning icon. Each of these values have a default System OS sound associated with it except for the default value.buttons: String[] (Optional) It represents an Array for the labels of the Buttons that you wish to display on the Custom Message box. An Empty array will result in one button being displayed, labeled OK.defaultId: Integer (Optional) The index of the button in the buttons array which will be selected by default when the Custom Message box is opened. This property is dependent on the noLink property. This is demonstrated in the following Steps.title: String (Optional) The title to be displayed on the Message box. Some OS platforms and their respective versions do not support this property.message: String The main contents of the Message box.detail: String (Optional) Extra Information to be displayed in the Message box below the message property.checkboxLabel: String (Optional) Label of the checkbox. This property automatically includes the checkbox with the given label in the custom Message box.checkboxChecked: Boolean (Optional) This property represents the initial state of the checkbox. The default value of this property is false.icon: NativeImage (Optional) The icon to be displayed on the Message box. If this property is defined, it will override the default system icons for the type property, irrespective of its value. This property takes in a NativeImage instance or the filepath of an image. In this tutorial, we will pass the filepath for the image.png file located in the assets folder using the path module.cancelId: Integer (Optional) The index of the button to be returned when the dialog is cancelled, via the Esc key. By default this is assigned to the first button with Cancel or No as the label in the buttons array property. If no such labeled buttons exist and this option is not set, 0 will be used as the return value. This is demonstrated in the following Steps.noLink: Boolean (Optional) This property is supported on Windows only. When this property is set, Electron will automatically try to figure out which one of the buttons are common button labels e.g. Cancel, Yes, No, OK etc, and show the other button labels as command links in the dialog. This property is used to make the dialog window appear in style with modern Windows OS apps and themes. By default, this property is set to false. In case all common button labels are used, this property will have no effect. This property is demonstrated in the following Steps.normalizeAccessKeys: Boolean (Optional) Normalize the keyboard access keys across platforms. Default value is false. Enabling this property assumes the ‘&’ wildcard is used in the button labels. These labels will be converted so that they work on each platform accordingly. ‘&’ characters are removed altogether on macOS, converted to _ on Linux, and no action is taken on Windows.The dialog.showMessageBox(browserWindow, options) returns a Promise. It resolves to an Object containing the following parameters,response: Integer The index of the button clicked as defined in the buttons array property.checkboxChecked: Boolean The checked state of the checkbox if checkboxLabel property was set. By default, will return false.index.js:const electron = require('electron');const path = require('path'); // Importing dialog module using remoteconst dialog = electron.remote.dialog; var showBox = document.getElementById('show'); showBox.addEventListener('click', (event) => { // Resolves to a Promise<Object> dialog.showMessageBox({ // option Object type: 'none', buttons: [], defaultId: 0, icon: '', title: 'This is the Title', message: 'This is a Message', detail: 'This is extra Information', checkboxLabel: 'Checkbox', checkboxChecked: false, cancelId: 0, noLink: false, normalizeAccessKeys: false, }).then(box => { console.log('Button Clicked Index - ', box.response); console.log('Checkbox Checked - ', box.checkboxChecked); }).catch(err => { console.log(err) }); });Output: We should now be able to successfully trigger a basic Custom Message Box on clicking the Show Custom Message Box button.Note: If the user tries to continue the execution of the application without successfully closing the Custom Message box, the following message is shown on the console:Attempting to call a function in a renderer window that \nhas been closed or released. Function provided here: undefined" }, { "code": null, "e": 39601, "s": 39277, "text": "The dialog.showMessageBox(browserWindow, options) is used with all default/basic values for the options Object. Using this Instance method shows the Message box and will block the application execution until the message box is closed successfully with appropriate action from the user. It takes in the following parameters." }, { "code": null, "e": 40129, "s": 39601, "text": "browserWindow: BrowserWindow (Optional) The BrowserWindow Instance. This argument allows the dialog to attach itself to the parent window, making it a modal. A modal window is a child window that disables the parent window. If BrowserWindow is not shown, dialog will not be attached to it. In such case It will be displayed as independent window. In the above code, the BrowserWindow instance is not being passed to the dialog, therefore the dialog opens as an independent window on clicking the Show Custom Message Box button." }, { "code": null, "e": 43393, "s": 40129, "text": "options: Object It takes in the following parameters,type: String (Optional) It can hold the following values.noneinfoerrorquestionwarningEach of these values signifify the type of Message Box that you want to display to the user. Default value is none. On Windows, question displays the same icon as info, unless the icon property is explicitly set. On macOS, both warning and error display the same warning icon. Each of these values have a default System OS sound associated with it except for the default value.buttons: String[] (Optional) It represents an Array for the labels of the Buttons that you wish to display on the Custom Message box. An Empty array will result in one button being displayed, labeled OK.defaultId: Integer (Optional) The index of the button in the buttons array which will be selected by default when the Custom Message box is opened. This property is dependent on the noLink property. This is demonstrated in the following Steps.title: String (Optional) The title to be displayed on the Message box. Some OS platforms and their respective versions do not support this property.message: String The main contents of the Message box.detail: String (Optional) Extra Information to be displayed in the Message box below the message property.checkboxLabel: String (Optional) Label of the checkbox. This property automatically includes the checkbox with the given label in the custom Message box.checkboxChecked: Boolean (Optional) This property represents the initial state of the checkbox. The default value of this property is false.icon: NativeImage (Optional) The icon to be displayed on the Message box. If this property is defined, it will override the default system icons for the type property, irrespective of its value. This property takes in a NativeImage instance or the filepath of an image. In this tutorial, we will pass the filepath for the image.png file located in the assets folder using the path module.cancelId: Integer (Optional) The index of the button to be returned when the dialog is cancelled, via the Esc key. By default this is assigned to the first button with Cancel or No as the label in the buttons array property. If no such labeled buttons exist and this option is not set, 0 will be used as the return value. This is demonstrated in the following Steps.noLink: Boolean (Optional) This property is supported on Windows only. When this property is set, Electron will automatically try to figure out which one of the buttons are common button labels e.g. Cancel, Yes, No, OK etc, and show the other button labels as command links in the dialog. This property is used to make the dialog window appear in style with modern Windows OS apps and themes. By default, this property is set to false. In case all common button labels are used, this property will have no effect. This property is demonstrated in the following Steps.normalizeAccessKeys: Boolean (Optional) Normalize the keyboard access keys across platforms. Default value is false. Enabling this property assumes the ‘&’ wildcard is used in the button labels. These labels will be converted so that they work on each platform accordingly. ‘&’ characters are removed altogether on macOS, converted to _ on Linux, and no action is taken on Windows." }, { "code": null, "e": 43856, "s": 43393, "text": "type: String (Optional) It can hold the following values.noneinfoerrorquestionwarningEach of these values signifify the type of Message Box that you want to display to the user. Default value is none. On Windows, question displays the same icon as info, unless the icon property is explicitly set. On macOS, both warning and error display the same warning icon. Each of these values have a default System OS sound associated with it except for the default value." }, { "code": null, "e": 43861, "s": 43856, "text": "none" }, { "code": null, "e": 43866, "s": 43861, "text": "info" }, { "code": null, "e": 43872, "s": 43866, "text": "error" }, { "code": null, "e": 43881, "s": 43872, "text": "question" }, { "code": null, "e": 43889, "s": 43881, "text": "warning" }, { "code": null, "e": 44267, "s": 43889, "text": "Each of these values signifify the type of Message Box that you want to display to the user. Default value is none. On Windows, question displays the same icon as info, unless the icon property is explicitly set. On macOS, both warning and error display the same warning icon. Each of these values have a default System OS sound associated with it except for the default value." }, { "code": null, "e": 44471, "s": 44267, "text": "buttons: String[] (Optional) It represents an Array for the labels of the Buttons that you wish to display on the Custom Message box. An Empty array will result in one button being displayed, labeled OK." }, { "code": null, "e": 44715, "s": 44471, "text": "defaultId: Integer (Optional) The index of the button in the buttons array which will be selected by default when the Custom Message box is opened. This property is dependent on the noLink property. This is demonstrated in the following Steps." }, { "code": null, "e": 44864, "s": 44715, "text": "title: String (Optional) The title to be displayed on the Message box. Some OS platforms and their respective versions do not support this property." }, { "code": null, "e": 44918, "s": 44864, "text": "message: String The main contents of the Message box." }, { "code": null, "e": 45025, "s": 44918, "text": "detail: String (Optional) Extra Information to be displayed in the Message box below the message property." }, { "code": null, "e": 45179, "s": 45025, "text": "checkboxLabel: String (Optional) Label of the checkbox. This property automatically includes the checkbox with the given label in the custom Message box." }, { "code": null, "e": 45320, "s": 45179, "text": "checkboxChecked: Boolean (Optional) This property represents the initial state of the checkbox. The default value of this property is false." }, { "code": null, "e": 45709, "s": 45320, "text": "icon: NativeImage (Optional) The icon to be displayed on the Message box. If this property is defined, it will override the default system icons for the type property, irrespective of its value. This property takes in a NativeImage instance or the filepath of an image. In this tutorial, we will pass the filepath for the image.png file located in the assets folder using the path module." }, { "code": null, "e": 46076, "s": 45709, "text": "cancelId: Integer (Optional) The index of the button to be returned when the dialog is cancelled, via the Esc key. By default this is assigned to the first button with Cancel or No as the label in the buttons array property. If no such labeled buttons exist and this option is not set, 0 will be used as the return value. This is demonstrated in the following Steps." }, { "code": null, "e": 46644, "s": 46076, "text": "noLink: Boolean (Optional) This property is supported on Windows only. When this property is set, Electron will automatically try to figure out which one of the buttons are common button labels e.g. Cancel, Yes, No, OK etc, and show the other button labels as command links in the dialog. This property is used to make the dialog window appear in style with modern Windows OS apps and themes. By default, this property is set to false. In case all common button labels are used, this property will have no effect. This property is demonstrated in the following Steps." }, { "code": null, "e": 47026, "s": 46644, "text": "normalizeAccessKeys: Boolean (Optional) Normalize the keyboard access keys across platforms. Default value is false. Enabling this property assumes the ‘&’ wildcard is used in the button labels. These labels will be converted so that they work on each platform accordingly. ‘&’ characters are removed altogether on macOS, converted to _ on Linux, and no action is taken on Windows." }, { "code": null, "e": 47157, "s": 47026, "text": "The dialog.showMessageBox(browserWindow, options) returns a Promise. It resolves to an Object containing the following parameters," }, { "code": null, "e": 47249, "s": 47157, "text": "response: Integer The index of the button clicked as defined in the buttons array property." }, { "code": null, "e": 47374, "s": 47249, "text": "checkboxChecked: Boolean The checked state of the checkbox if checkboxLabel property was set. By default, will return false." }, { "code": null, "e": 47384, "s": 47374, "text": "index.js:" }, { "code": "const electron = require('electron');const path = require('path'); // Importing dialog module using remoteconst dialog = electron.remote.dialog; var showBox = document.getElementById('show'); showBox.addEventListener('click', (event) => { // Resolves to a Promise<Object> dialog.showMessageBox({ // option Object type: 'none', buttons: [], defaultId: 0, icon: '', title: 'This is the Title', message: 'This is a Message', detail: 'This is extra Information', checkboxLabel: 'Checkbox', checkboxChecked: false, cancelId: 0, noLink: false, normalizeAccessKeys: false, }).then(box => { console.log('Button Clicked Index - ', box.response); console.log('Checkbox Checked - ', box.checkboxChecked); }).catch(err => { console.log(err) }); });", "e": 48251, "s": 47384, "text": null }, { "code": null, "e": 48380, "s": 48251, "text": "Output: We should now be able to successfully trigger a basic Custom Message Box on clicking the Show Custom Message Box button." }, { "code": null, "e": 48549, "s": 48380, "text": "Note: If the user tries to continue the execution of the application without successfully closing the Custom Message box, the following message is shown on the console:" }, { "code": null, "e": 48669, "s": 48549, "text": "Attempting to call a function in a renderer window that \nhas been closed or released. Function provided here: undefined" }, { "code": null, "e": 50847, "s": 48669, "text": "Step 5: We will now modify the options Object of the Custom Message Box to see the different outputs,type: String Defining the different types of Message boxes.type: ‘info’type: ‘warning’type: ‘error’buttons: String[] We will define Custom labels for the buttons array property and see the respective outputs by changing the noLink property.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], noLink: false, defaultId: 0Note: In this case the defaultId property should highlight the Cancel button, but instead the Button-1 label is selected. This is due to the behaviour defined by the noLink property.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], noLink: true, defaultId: 0Note: The Cancel button is selected by default as per expected behaviour.cancelId: Integer Evaluating the behaviour of the cancelId property. This behaviour is invoked by pressing the Esc key on the keyboard.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], cancelId: 100, noLink: trueNote: The value returned is 100 as set in the cancelId property.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], cancelId: 100, noLink: falseNote: The value returned is 0 despite setting the cancelId property value to 100.icon: NativeImage We will be passing the filepath of the image.png file located in the assets folder.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], icon: path.join(__dirname, ‘../assets/image.png’), noLink: truebuttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], icon: path.join(__dirname, ‘../assets/image.png’), noLink: falseNote: Using the icon property disables the default system OS sound for the type property, irrespective of its value.We can also assign different behaviours to each button in the Message box by simply comparing the index value of the buttons array property with the response parameter returned by Promise.index.js:.then(box => { console.log('Button Clicked Index - ', box.response); console.log('Checkbox Checked - ', box.checkboxChecked); if (box.response === 0) { console.log('Cancel Button was clicked'); } else if (box.response === 2) { console.log('Button-1 was clicked'); } }).catch(err => { console.log(err) }); Output:" }, { "code": null, "e": 50947, "s": 50847, "text": "type: String Defining the different types of Message boxes.type: ‘info’type: ‘warning’type: ‘error’" }, { "code": null, "e": 50960, "s": 50947, "text": "type: ‘info’" }, { "code": null, "e": 50976, "s": 50960, "text": "type: ‘warning’" }, { "code": null, "e": 50990, "s": 50976, "text": "type: ‘error’" }, { "code": null, "e": 51542, "s": 50990, "text": "buttons: String[] We will define Custom labels for the buttons array property and see the respective outputs by changing the noLink property.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], noLink: false, defaultId: 0Note: In this case the defaultId property should highlight the Cancel button, but instead the Button-1 label is selected. This is due to the behaviour defined by the noLink property.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], noLink: true, defaultId: 0Note: The Cancel button is selected by default as per expected behaviour." }, { "code": null, "e": 51803, "s": 51542, "text": "buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], noLink: false, defaultId: 0Note: In this case the defaultId property should highlight the Cancel button, but instead the Button-1 label is selected. This is due to the behaviour defined by the noLink property." }, { "code": null, "e": 51986, "s": 51803, "text": "Note: In this case the defaultId property should highlight the Cancel button, but instead the Button-1 label is selected. This is due to the behaviour defined by the noLink property." }, { "code": null, "e": 52137, "s": 51986, "text": "buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], noLink: true, defaultId: 0Note: The Cancel button is selected by default as per expected behaviour." }, { "code": null, "e": 52211, "s": 52137, "text": "Note: The Cancel button is selected by default as per expected behaviour." }, { "code": null, "e": 52649, "s": 52211, "text": "cancelId: Integer Evaluating the behaviour of the cancelId property. This behaviour is invoked by pressing the Esc key on the keyboard.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], cancelId: 100, noLink: trueNote: The value returned is 100 as set in the cancelId property.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], cancelId: 100, noLink: falseNote: The value returned is 0 despite setting the cancelId property value to 100." }, { "code": null, "e": 52792, "s": 52649, "text": "buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], cancelId: 100, noLink: trueNote: The value returned is 100 as set in the cancelId property." }, { "code": null, "e": 52857, "s": 52792, "text": "Note: The value returned is 100 as set in the cancelId property." }, { "code": null, "e": 53018, "s": 52857, "text": "buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], cancelId: 100, noLink: falseNote: The value returned is 0 despite setting the cancelId property value to 100." }, { "code": null, "e": 53100, "s": 53018, "text": "Note: The value returned is 0 despite setting the cancelId property value to 100." }, { "code": null, "e": 53547, "s": 53100, "text": "icon: NativeImage We will be passing the filepath of the image.png file located in the assets folder.buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], icon: path.join(__dirname, ‘../assets/image.png’), noLink: truebuttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], icon: path.join(__dirname, ‘../assets/image.png’), noLink: falseNote: Using the icon property disables the default system OS sound for the type property, irrespective of its value." }, { "code": null, "e": 53662, "s": 53547, "text": "buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], icon: path.join(__dirname, ‘../assets/image.png’), noLink: true" }, { "code": null, "e": 53778, "s": 53662, "text": "buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], icon: path.join(__dirname, ‘../assets/image.png’), noLink: false" }, { "code": null, "e": 53895, "s": 53778, "text": "Note: Using the icon property disables the default system OS sound for the type property, irrespective of its value." }, { "code": null, "e": 54084, "s": 53895, "text": "We can also assign different behaviours to each button in the Message box by simply comparing the index value of the buttons array property with the response parameter returned by Promise." }, { "code": null, "e": 54094, "s": 54084, "text": "index.js:" }, { "code": ".then(box => { console.log('Button Clicked Index - ', box.response); console.log('Checkbox Checked - ', box.checkboxChecked); if (box.response === 0) { console.log('Cancel Button was clicked'); } else if (box.response === 2) { console.log('Button-1 was clicked'); } }).catch(err => { console.log(err) }); ", "e": 54434, "s": 54094, "text": null }, { "code": null, "e": 54442, "s": 54434, "text": "Output:" }, { "code": null, "e": 55535, "s": 54442, "text": "Step 6: Electron also provides us with an instance Method specifically designed for Error Messages. In the above code, the Show Error Message Box button does not have any functionality associated with it. To change this add the following code in the index.js file.The dialog.showErrorBox(title, info) takes in the following parameters. It does not have any return value. This method is not customizable like the dialog.showMessageBox() method but this method can be safely called before the ready event of the app module is emitted. Refer to the highlighted code in the main.js file. It is usually used to display errors in the application startup stages. If called before the ready event of the app module on Linux, the message will be emitted to stderr, and no GUI dialog will appear.title: String The title of the Error box.info: String The text information to display in the Error box below the title property.index.js:var error = document.getElementById('error'); error.addEventListener('click', (event) => { dialog.showErrorBox('This is the Title', 'This is the Content');});Output:" }, { "code": null, "e": 56058, "s": 55535, "text": "The dialog.showErrorBox(title, info) takes in the following parameters. It does not have any return value. This method is not customizable like the dialog.showMessageBox() method but this method can be safely called before the ready event of the app module is emitted. Refer to the highlighted code in the main.js file. It is usually used to display errors in the application startup stages. If called before the ready event of the app module on Linux, the message will be emitted to stderr, and no GUI dialog will appear." }, { "code": null, "e": 56100, "s": 56058, "text": "title: String The title of the Error box." }, { "code": null, "e": 56188, "s": 56100, "text": "info: String The text information to display in the Error box below the title property." }, { "code": null, "e": 56198, "s": 56188, "text": "index.js:" }, { "code": "var error = document.getElementById('error'); error.addEventListener('click', (event) => { dialog.showErrorBox('This is the Title', 'This is the Content');});", "e": 56361, "s": 56198, "text": null }, { "code": null, "e": 56369, "s": 56361, "text": "Output:" }, { "code": null, "e": 56380, "s": 56369, "text": "ElectronJS" }, { "code": null, "e": 56391, "s": 56380, "text": "JavaScript" }, { "code": null, "e": 56408, "s": 56391, "text": "Web Technologies" }, { "code": null, "e": 56506, "s": 56408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 56567, "s": 56506, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 56608, "s": 56567, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 56662, "s": 56608, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 56702, "s": 56662, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 56750, "s": 56702, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 56792, "s": 56750, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 56825, "s": 56792, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 56868, "s": 56825, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 56918, "s": 56868, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python (Scikit-Learn): Logistic Regression Classification | by Maurizio Sluijmers | Towards Data Science
The process of differentiating categorical data using predictive techniques is called classification. One of the most widely used classification techniques is the logistic regression. For the theoretical foundation of the logistic regression, please see my previous article. In this article, we are going to apply the logistic regression to a binary classification problem, making use of the scikit-learn (sklearn) package available in the Python programming language. We will use the Titanic dataset (available on Kaggle), where the goal is to predict survival on the Titanic. That is, on the basis of the features (explanatory variables) included in the dataset, we want to predict whether a particular person survived the Titanic shipwreck. We start by importing the required packages and loading the titanic data set. import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn import metricsfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splittitanic = pd.read_csv(".../Titanic/train.csv")titanic.head() Here, we see the different variables included in the data set. Let us briefly describe each variable: PassengerId: The ID of the passenger; Survived: The target variable; whether the person survived the shipwreck (1) or did not survive the shipwreck (0); Pclass: The class the passenger was in on the ship (1, 2 or 3); Name: The name of the passenger; Sex: The gender of the passenger; Age: The age of the passenger; SibSp: Number of siblings and spouses on the ship; Parch: Number of parents / children on the ship; Ticket: Number of the ticket; Fare: The fare of the ticket; Cabin: Number of the cabin; Embarked: Port of embarkation (C = Cherbourg, Q = Queenstown, S = Southhampton). When applying any predictive algorithm, we can never use it immediately without having done any pre-processing of the data. This step is extremely important, and can never be overlooked. For this data set, we perform the following pre-processing steps: 1. Drop features that do not seem to add any value to our model titanic.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], axis=1, inplace=True) Here, we drop the PassengerId, Name, Ticket and Cabin features from the data set. The reason for this, is that these do not supply any predictive power to our model. 2. Create categorical dummies for the embarkment ports ports = pd.get_dummies(titanic.Embarked, prefix='Embarked')ports.head() We created three binary features from the categorical Embarked feature, since the model cannot handle the string names in the original categorical variable. titanic = titanic.join(ports)titanic.drop(['Embarked'], axis=1, inplace=True) 3. Transform gender names to binaries titanic.Sex = titanic.Sex.map({'male': 0, 'female': 1}) Transform the ‘male’ and ‘female’ names to binaries (0 and 1) through a mapping. 4. Replace missing values titanic[pd.isnull(titanic).any(axis=1)] Note that all the missing values (NaNs) appear to be in the Age feature. To solve for these missing values, let us fill the missing values with the average age in the data. titanic.Age.fillna(titanic.Age.mean(), inplace=True) Now that we have pre-processed the data, we can extract the explanatory variables in X and the target variable in y: y = titanic.Survived.copy()X = titanic.drop(['Survived'], axis=1) Next, we split the data in a training and test set. The training set is used to train the logistic regression model. The model learns from the features included in the training set. The test set is used to validate the performance of the logistic regression model. For each observation in the test set, we predict whether the person survived or not, and compare the predictions with the true values. We split the data so that the training set consists of 75% of the data, and the test set consists of 25% of the data. We make use of the train_test_split module of the scikit-learn package. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=123) By making use of the LogisticRegression module in the scikit-learn package, we can fit a logistic regression model, using the features included in X_train, to the training data. model = LogisticRegression()model.fit(X_train, y_train) Next, now that we have trained the logistic regression model on the training data, we are able to use the model to predict whether the persons included in the test set survived the shipwreck: y_pred = pd.Series(model.predict(X_test))y_test = y_test.reset_index(drop=True)z = pd.concat([y_test, y_pred], axis=1)z.columns = ['True', 'Prediction']z.head() Here, we see that for the first five observations of the test set, the logistic regression model predicted 4 out of 5 correctly. To evaluate the entire test set, we can use the metrics module from the scikit-learn package. print("Accuracy:", metrics.accuracy_score(y_test, y_pred))print("Precision:", metrics.precision_score(y_test, y_pred))print("Recall:", metrics.recall_score(y_test, y_pred)) Output: Accuracy: 0.8026905829596412Precision: 0.7631578947368421Recall: 0.6904761904761905 That is, the logistic regression model results in 80.3% accuracy. Definitely not bad for such a simple model! Of course, the model performance could be further improved by e.g. conducting further pre-processing, feature selection and feature extraction. However, this model forms a solid baseline. A nice way to visualize the results of the model is by making use of a confusion matrix. Here, we use matplotlib and seaborn to create a nice confusion matrix figure. cnf_matrix = metrics.confusion_matrix(y_test, y_pred)labels = [0, 1]fig, ax = plt.subplots()tick_marks = np.arange(len(labels))plt.xticks(tick_marks, labels)plt.yticks(tick_marks, labels)# create heatmapsns.heatmap(pd.DataFrame(cnf_matrix), annot=True, cmap="YlGnBu", fmt='g')ax.xaxis.set_label_position("top")plt.title('Confusion matrix', y=1.1)plt.ylabel('True')plt.xlabel('Predicted') In the confusion matrix, we see that 121 persons that did not survive the shipwreck were correctly predicted as not surviving, 18 persons that did not survive the shipwreck were incorrectly predicted as surviving the shipwreck, 26 persons that survived the shipwreck were incorrectly predicted as not surviving the shipwreck and lastly, 58 persons that survived the shipwreck were correctly predicted. Pros: Does not require high computation power; Easy to implement; Straightforward interpretability. Cons: Vulnerable to overfitting; Cannot solve non-linear problems; Not able to handle a large number of categorical features. Hopefully, after reading this article, you are now able to utilize the logistic regression technique yourself by making use of the scikit-learn package within Python. Good luck on using it within your own projects!
[ { "code": null, "e": 447, "s": 172, "text": "The process of differentiating categorical data using predictive techniques is called classification. One of the most widely used classification techniques is the logistic regression. For the theoretical foundation of the logistic regression, please see my previous article." }, { "code": null, "e": 641, "s": 447, "text": "In this article, we are going to apply the logistic regression to a binary classification problem, making use of the scikit-learn (sklearn) package available in the Python programming language." }, { "code": null, "e": 916, "s": 641, "text": "We will use the Titanic dataset (available on Kaggle), where the goal is to predict survival on the Titanic. That is, on the basis of the features (explanatory variables) included in the dataset, we want to predict whether a particular person survived the Titanic shipwreck." }, { "code": null, "e": 994, "s": 916, "text": "We start by importing the required packages and loading the titanic data set." }, { "code": null, "e": 1274, "s": 994, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn import metricsfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splittitanic = pd.read_csv(\".../Titanic/train.csv\")titanic.head()" }, { "code": null, "e": 1376, "s": 1274, "text": "Here, we see the different variables included in the data set. Let us briefly describe each variable:" }, { "code": null, "e": 1414, "s": 1376, "text": "PassengerId: The ID of the passenger;" }, { "code": null, "e": 1529, "s": 1414, "text": "Survived: The target variable; whether the person survived the shipwreck (1) or did not survive the shipwreck (0);" }, { "code": null, "e": 1593, "s": 1529, "text": "Pclass: The class the passenger was in on the ship (1, 2 or 3);" }, { "code": null, "e": 1626, "s": 1593, "text": "Name: The name of the passenger;" }, { "code": null, "e": 1660, "s": 1626, "text": "Sex: The gender of the passenger;" }, { "code": null, "e": 1691, "s": 1660, "text": "Age: The age of the passenger;" }, { "code": null, "e": 1742, "s": 1691, "text": "SibSp: Number of siblings and spouses on the ship;" }, { "code": null, "e": 1791, "s": 1742, "text": "Parch: Number of parents / children on the ship;" }, { "code": null, "e": 1821, "s": 1791, "text": "Ticket: Number of the ticket;" }, { "code": null, "e": 1851, "s": 1821, "text": "Fare: The fare of the ticket;" }, { "code": null, "e": 1879, "s": 1851, "text": "Cabin: Number of the cabin;" }, { "code": null, "e": 1960, "s": 1879, "text": "Embarked: Port of embarkation (C = Cherbourg, Q = Queenstown, S = Southhampton)." }, { "code": null, "e": 2213, "s": 1960, "text": "When applying any predictive algorithm, we can never use it immediately without having done any pre-processing of the data. This step is extremely important, and can never be overlooked. For this data set, we perform the following pre-processing steps:" }, { "code": null, "e": 2277, "s": 2213, "text": "1. Drop features that do not seem to add any value to our model" }, { "code": null, "e": 2356, "s": 2277, "text": "titanic.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], axis=1, inplace=True)" }, { "code": null, "e": 2522, "s": 2356, "text": "Here, we drop the PassengerId, Name, Ticket and Cabin features from the data set. The reason for this, is that these do not supply any predictive power to our model." }, { "code": null, "e": 2577, "s": 2522, "text": "2. Create categorical dummies for the embarkment ports" }, { "code": null, "e": 2649, "s": 2577, "text": "ports = pd.get_dummies(titanic.Embarked, prefix='Embarked')ports.head()" }, { "code": null, "e": 2806, "s": 2649, "text": "We created three binary features from the categorical Embarked feature, since the model cannot handle the string names in the original categorical variable." }, { "code": null, "e": 2884, "s": 2806, "text": "titanic = titanic.join(ports)titanic.drop(['Embarked'], axis=1, inplace=True)" }, { "code": null, "e": 2922, "s": 2884, "text": "3. Transform gender names to binaries" }, { "code": null, "e": 2978, "s": 2922, "text": "titanic.Sex = titanic.Sex.map({'male': 0, 'female': 1})" }, { "code": null, "e": 3059, "s": 2978, "text": "Transform the ‘male’ and ‘female’ names to binaries (0 and 1) through a mapping." }, { "code": null, "e": 3085, "s": 3059, "text": "4. Replace missing values" }, { "code": null, "e": 3125, "s": 3085, "text": "titanic[pd.isnull(titanic).any(axis=1)]" }, { "code": null, "e": 3298, "s": 3125, "text": "Note that all the missing values (NaNs) appear to be in the Age feature. To solve for these missing values, let us fill the missing values with the average age in the data." }, { "code": null, "e": 3351, "s": 3298, "text": "titanic.Age.fillna(titanic.Age.mean(), inplace=True)" }, { "code": null, "e": 3468, "s": 3351, "text": "Now that we have pre-processed the data, we can extract the explanatory variables in X and the target variable in y:" }, { "code": null, "e": 3534, "s": 3468, "text": "y = titanic.Survived.copy()X = titanic.drop(['Survived'], axis=1)" }, { "code": null, "e": 3934, "s": 3534, "text": "Next, we split the data in a training and test set. The training set is used to train the logistic regression model. The model learns from the features included in the training set. The test set is used to validate the performance of the logistic regression model. For each observation in the test set, we predict whether the person survived or not, and compare the predictions with the true values." }, { "code": null, "e": 4124, "s": 3934, "text": "We split the data so that the training set consists of 75% of the data, and the test set consists of 25% of the data. We make use of the train_test_split module of the scikit-learn package." }, { "code": null, "e": 4216, "s": 4124, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=123)" }, { "code": null, "e": 4394, "s": 4216, "text": "By making use of the LogisticRegression module in the scikit-learn package, we can fit a logistic regression model, using the features included in X_train, to the training data." }, { "code": null, "e": 4450, "s": 4394, "text": "model = LogisticRegression()model.fit(X_train, y_train)" }, { "code": null, "e": 4642, "s": 4450, "text": "Next, now that we have trained the logistic regression model on the training data, we are able to use the model to predict whether the persons included in the test set survived the shipwreck:" }, { "code": null, "e": 4803, "s": 4642, "text": "y_pred = pd.Series(model.predict(X_test))y_test = y_test.reset_index(drop=True)z = pd.concat([y_test, y_pred], axis=1)z.columns = ['True', 'Prediction']z.head()" }, { "code": null, "e": 4932, "s": 4803, "text": "Here, we see that for the first five observations of the test set, the logistic regression model predicted 4 out of 5 correctly." }, { "code": null, "e": 5026, "s": 4932, "text": "To evaluate the entire test set, we can use the metrics module from the scikit-learn package." }, { "code": null, "e": 5199, "s": 5026, "text": "print(\"Accuracy:\", metrics.accuracy_score(y_test, y_pred))print(\"Precision:\", metrics.precision_score(y_test, y_pred))print(\"Recall:\", metrics.recall_score(y_test, y_pred))" }, { "code": null, "e": 5207, "s": 5199, "text": "Output:" }, { "code": null, "e": 5291, "s": 5207, "text": "Accuracy: 0.8026905829596412Precision: 0.7631578947368421Recall: 0.6904761904761905" }, { "code": null, "e": 5401, "s": 5291, "text": "That is, the logistic regression model results in 80.3% accuracy. Definitely not bad for such a simple model!" }, { "code": null, "e": 5589, "s": 5401, "text": "Of course, the model performance could be further improved by e.g. conducting further pre-processing, feature selection and feature extraction. However, this model forms a solid baseline." }, { "code": null, "e": 5756, "s": 5589, "text": "A nice way to visualize the results of the model is by making use of a confusion matrix. Here, we use matplotlib and seaborn to create a nice confusion matrix figure." }, { "code": null, "e": 6144, "s": 5756, "text": "cnf_matrix = metrics.confusion_matrix(y_test, y_pred)labels = [0, 1]fig, ax = plt.subplots()tick_marks = np.arange(len(labels))plt.xticks(tick_marks, labels)plt.yticks(tick_marks, labels)# create heatmapsns.heatmap(pd.DataFrame(cnf_matrix), annot=True, cmap=\"YlGnBu\", fmt='g')ax.xaxis.set_label_position(\"top\")plt.title('Confusion matrix', y=1.1)plt.ylabel('True')plt.xlabel('Predicted')" }, { "code": null, "e": 6546, "s": 6144, "text": "In the confusion matrix, we see that 121 persons that did not survive the shipwreck were correctly predicted as not surviving, 18 persons that did not survive the shipwreck were incorrectly predicted as surviving the shipwreck, 26 persons that survived the shipwreck were incorrectly predicted as not surviving the shipwreck and lastly, 58 persons that survived the shipwreck were correctly predicted." }, { "code": null, "e": 6552, "s": 6546, "text": "Pros:" }, { "code": null, "e": 6593, "s": 6552, "text": "Does not require high computation power;" }, { "code": null, "e": 6612, "s": 6593, "text": "Easy to implement;" }, { "code": null, "e": 6646, "s": 6612, "text": "Straightforward interpretability." }, { "code": null, "e": 6652, "s": 6646, "text": "Cons:" }, { "code": null, "e": 6679, "s": 6652, "text": "Vulnerable to overfitting;" }, { "code": null, "e": 6713, "s": 6679, "text": "Cannot solve non-linear problems;" }, { "code": null, "e": 6772, "s": 6713, "text": "Not able to handle a large number of categorical features." } ]
How to convert list elements into a single string in R?
To convert list elements into a single string, we can use paste function but firstly we would need to unlist the elements. Also, since we want to create a single string double quotes will be required at the end of the output. For example, if we have a list that contains 5 elements say 1, 2, 3, 4, 5 then conversion of these elements into a single string would be "12345". Live Demo List1<−list(1,2,3,2,2,1,2,1,4,2,2,2,2,2,2,3,2,2) List1 [[1]] [1] 1 [[2]] [1] 2 [[3]] [1] 3 [[4]] [1] 2 [[5]] [1] 2 [[6]] [1] 1 [[7]] [1] 2 [[8]] [1] 1 [[9]] [1] 4 [[10]] [1] 2 [[11]] [1] 2 [[12]] [1] 2 [[13]] [1] 2 [[14]] [1] 2 [[15]] [1] 2 [[16]] [1] 3 [[17]] [1] 2 [[18]] [1] 2 Converting List1 elements into a single string element − List1<−paste(unlist(List1),collapse="") List1 [1] "123221214222222322" class(List1) [1] "character" Live Demo List2<−list(x1<−rpois(5,5),x2=rpois(5,2),x3=rpois(5,5),x4=rpois(10,4)) List2 [[1]] [1] 6 2 8 3 5 $x2 [1] 2 4 3 2 5 $x3 [1] 8 1 12 1 4 $x4 [1] 7 5 4 3 6 2 5 3 2 2 Converting List2 elements into a single string element − List2<−paste(unlist(List2),collapse="") List2 [1] "62835243258112147543625322"
[ { "code": null, "e": 1435, "s": 1062, "text": "To convert list elements into a single string, we can use paste function but firstly we would need to unlist the elements. Also, since we want to create a single string double quotes will be required at the end of the output. For example, if we have a list that contains 5 elements say 1, 2, 3, 4, 5 then conversion of these elements into a single string would be \"12345\"." }, { "code": null, "e": 1446, "s": 1435, "text": " Live Demo" }, { "code": null, "e": 1501, "s": 1446, "text": "List1<−list(1,2,3,2,2,1,2,1,4,2,2,2,2,2,2,3,2,2)\nList1" }, { "code": null, "e": 1726, "s": 1501, "text": "[[1]]\n[1] 1\n[[2]]\n[1] 2\n[[3]]\n[1] 3\n[[4]]\n[1] 2\n[[5]]\n[1] 2\n[[6]]\n[1] 1\n[[7]]\n[1] 2\n[[8]]\n[1] 1\n[[9]]\n[1] 4\n[[10]]\n[1] 2\n[[11]]\n[1] 2\n[[12]]\n[1] 2\n[[13]]\n[1] 2\n[[14]]\n[1] 2\n[[15]]\n[1] 2\n[[16]]\n[1] 3\n[[17]]\n[1] 2\n[[18]]\n[1] 2" }, { "code": null, "e": 1783, "s": 1726, "text": "Converting List1 elements into a single string element −" }, { "code": null, "e": 1829, "s": 1783, "text": "List1<−paste(unlist(List1),collapse=\"\")\nList1" }, { "code": null, "e": 1854, "s": 1829, "text": "[1] \"123221214222222322\"" }, { "code": null, "e": 1867, "s": 1854, "text": "class(List1)" }, { "code": null, "e": 1884, "s": 1867, "text": "[1] \"character\"\n" }, { "code": null, "e": 1895, "s": 1884, "text": " Live Demo" }, { "code": null, "e": 1972, "s": 1895, "text": "List2<−list(x1<−rpois(5,5),x2=rpois(5,2),x3=rpois(5,5),x4=rpois(10,4))\nList2" }, { "code": null, "e": 2057, "s": 1972, "text": "[[1]]\n[1] 6 2 8 3 5\n$x2\n[1] 2 4 3 2 5\n$x3\n[1] 8 1 12 1 4\n$x4\n[1] 7 5 4 3 6 2 5 3 2 2" }, { "code": null, "e": 2114, "s": 2057, "text": "Converting List2 elements into a single string element −" }, { "code": null, "e": 2160, "s": 2114, "text": "List2<−paste(unlist(List2),collapse=\"\")\nList2" }, { "code": null, "e": 2193, "s": 2160, "text": "[1] \"62835243258112147543625322\"" } ]
Sync Copy in fs-extra using NodeJS
This method copies files or directories from one location to another location in a sync process. The directory can have sub-directories and files. copySync(src, dest[, options]) src – This is a string paramter which will hold the source location of the file or directory that needs to be copies. If the location is a directory, it will copy everything inside of the directory instead of whole directory. src – This is a string paramter which will hold the source location of the file or directory that needs to be copies. If the location is a directory, it will copy everything inside of the directory instead of whole directory. dest – This will hold the destination location where the files/directories will be copies. If src is a files, dest cannot be a directory. dest – This will hold the destination location where the files/directories will be copies. If src is a files, dest cannot be a directory. overwrite – If set to true, existing files or directories will be overwritten. Default value is set to true. overwrite – If set to true, existing files or directories will be overwritten. Default value is set to true. errorOnExist – It will throw an error if the destination file/folder exists only when overwrite is set to false. errorOnExist – It will throw an error if the destination file/folder exists only when overwrite is set to false. preserveTimestamps – Latest modification and access time will be set to that of the original files if true, else it will be OS dependent. preserveTimestamps – Latest modification and access time will be set to that of the original files if true, else it will be OS dependent. filter – This option will filter copied files. Will include filtered files if set to true. filter – This option will filter copied files. Will include filtered files if set to true. Since it is a sync copy, it will not have a callback. Check that fs-extra is installed before proceeding; if not, install fs-exra. Check that fs-extra is installed before proceeding; if not, install fs-exra. You can use the following command to check whether fs-extra is installed or not. You can use the following command to check whether fs-extra is installed or not. npm ls fs-extra Create a syncCopyExample.js and copy-paste the following code snippet into that file. Create a syncCopyExample.js and copy-paste the following code snippet into that file. Now, run the following command to run the following code snippet. Now, run the following command to run the following code snippet. node syncCopyExample.js Code Snippet − const fs = require('fs-extra') // copying file in sync process fs.copySync('/tmp/myfile', '/tmp/mynewfile') console.log("File copied in Sync") // Copies directory from src to dest fs.copySync('/tmp/mydir', '/tmp/mynewdir') console.log("Directory copied in Sync") C:\Users\tutorialsPoint\> node syncCopyExample.js File copied in Sync Directory copied in Sync const fs = require('fs-extra') // Copying files with .txt or .avi as extension fs.copySync( '/tmp/newFile.txt', '/tmp/myfile2.txt', /.*(.txt|.avi)$/, (err) => { console.log ('An error occured while copying')}) console.log("Successfully copied !") C:\Users\tutorialsPoint\> node syncCopyExample.js Successfully copied!
[ { "code": null, "e": 1209, "s": 1062, "text": "This method copies files or directories from one location to another location in a sync process. The directory can have sub-directories and files." }, { "code": null, "e": 1240, "s": 1209, "text": "copySync(src, dest[, options])" }, { "code": null, "e": 1466, "s": 1240, "text": "src – This is a string paramter which will hold the source location of the file or directory that needs to be copies. If the location is a directory, it will copy everything inside of the directory instead of whole directory." }, { "code": null, "e": 1692, "s": 1466, "text": "src – This is a string paramter which will hold the source location of the file or directory that needs to be copies. If the location is a directory, it will copy everything inside of the directory instead of whole directory." }, { "code": null, "e": 1830, "s": 1692, "text": "dest – This will hold the destination location where the files/directories will be copies. If src is a files, dest cannot be a directory." }, { "code": null, "e": 1968, "s": 1830, "text": "dest – This will hold the destination location where the files/directories will be copies. If src is a files, dest cannot be a directory." }, { "code": null, "e": 2077, "s": 1968, "text": "overwrite – If set to true, existing files or directories will be overwritten. Default value is set to true." }, { "code": null, "e": 2186, "s": 2077, "text": "overwrite – If set to true, existing files or directories will be overwritten. Default value is set to true." }, { "code": null, "e": 2299, "s": 2186, "text": "errorOnExist – It will throw an error if the destination file/folder exists only when overwrite is set to false." }, { "code": null, "e": 2412, "s": 2299, "text": "errorOnExist – It will throw an error if the destination file/folder exists only when overwrite is set to false." }, { "code": null, "e": 2550, "s": 2412, "text": "preserveTimestamps – Latest modification and access time will be set to that of the original files if true, else it will be OS dependent." }, { "code": null, "e": 2688, "s": 2550, "text": "preserveTimestamps – Latest modification and access time will be set to that of the original files if true, else it will be OS dependent." }, { "code": null, "e": 2779, "s": 2688, "text": "filter – This option will filter copied files. Will include filtered files if set to true." }, { "code": null, "e": 2870, "s": 2779, "text": "filter – This option will filter copied files. Will include filtered files if set to true." }, { "code": null, "e": 2924, "s": 2870, "text": "Since it is a sync copy, it will not have a callback." }, { "code": null, "e": 3001, "s": 2924, "text": "Check that fs-extra is installed before proceeding; if not, install fs-exra." }, { "code": null, "e": 3078, "s": 3001, "text": "Check that fs-extra is installed before proceeding; if not, install fs-exra." }, { "code": null, "e": 3159, "s": 3078, "text": "You can use the following command to check whether fs-extra is installed or not." }, { "code": null, "e": 3240, "s": 3159, "text": "You can use the following command to check whether fs-extra is installed or not." }, { "code": null, "e": 3256, "s": 3240, "text": "npm ls fs-extra" }, { "code": null, "e": 3342, "s": 3256, "text": "Create a syncCopyExample.js and copy-paste the following code snippet into that file." }, { "code": null, "e": 3428, "s": 3342, "text": "Create a syncCopyExample.js and copy-paste the following code snippet into that file." }, { "code": null, "e": 3494, "s": 3428, "text": "Now, run the following command to run the following code snippet." }, { "code": null, "e": 3560, "s": 3494, "text": "Now, run the following command to run the following code snippet." }, { "code": null, "e": 3584, "s": 3560, "text": "node syncCopyExample.js" }, { "code": null, "e": 3599, "s": 3584, "text": "Code Snippet −" }, { "code": null, "e": 3864, "s": 3599, "text": "const fs = require('fs-extra')\n\n// copying file in sync process\nfs.copySync('/tmp/myfile', '/tmp/mynewfile')\nconsole.log(\"File copied in Sync\")\n\n// Copies directory from src to dest\nfs.copySync('/tmp/mydir', '/tmp/mynewdir')\nconsole.log(\"Directory copied in Sync\")" }, { "code": null, "e": 3959, "s": 3864, "text": "C:\\Users\\tutorialsPoint\\> node syncCopyExample.js\nFile copied in Sync\nDirectory copied in Sync" }, { "code": null, "e": 4286, "s": 3959, "text": "const fs = require('fs-extra')\n\n// Copying files with .txt or .avi as extension\nfs.copySync(\n '/tmp/newFile.txt', '/tmp/myfile2.txt', /.*(.txt|.avi)$/,\n (err) => { console.log ('An error occured while copying')})\nconsole.log(\"Successfully copied !\")\n\nC:\\Users\\tutorialsPoint\\> node syncCopyExample.js\nSuccessfully copied!" } ]
mlock() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint #include <sys/mman.h> int mlock(const void *addr, size_t len); int munlock(const void *addr, size_t len); int mlockall(int flags); int munlockall(void); int mlock(const void *addr, size_t len); int munlock(const void *addr, size_t len); int mlockall(int flags); int munlockall(void); munlock() unlocks pages in the address range starting at addr and continuing for len bytes. After this call, all pages that contain a part of the specified memory range can be moved to external swap space again by the kernel. The flags argument is constructed as the bitwise OR of one or more of the following constants: munlockall() unlocks all pages mapped into the address space of the calling process. Real-time processes that are using mlockall() to prevent delays on page faults should reserve enough locked stack pages before entering the time-critical section, so that no page fault can be caused by function calls. This can be achieved by calling a function that allocates a sufficiently large automatic variable (an array) and writes to the memory occupied by this array in order to touch these stack pages. This way, enough pages will be mapped for the stack and can be locked into RAM. The dummy writes ensure that not even copy-on-write page faults can occur in the critical section. Memory locks are not inherited by a child created via fork(2) and are automatically removed (unlocked) during an execve(2) or when the process terminates. The memory lock on an address range is automatically removed if the address range is unmapped via munmap(2). Memory locks do not stack, i.e., pages which have been locked several times by calls to mlock() or mlockall() will be unlocked by a single call to munlock() for the corresponding range or by munlockall(). Pages which are mapped to several locations or by several processes stay locked into RAM as long as they are locked at least at one location or by at least one process. Since Linux 2.6.9, no limits are placed on the amount of memory that a privileged process can lock and the RLIMIT_MEMLOCK soft resource limit instead defines a limit on how much memory an unprivileged process may lock. Since kernel 2.6.9, if a privileged process calls mlockall(MCL_FUTURE) and later drops privileges (loses the CAP_IPC_LOCK capability by, for example, setting its effective UID to a non-zero value), then subsequent memory allocations (e.g., mmap(2), brk(2)) will fail if the RLIMIT_MEMLOCK resource limit is encountered. On POSIX systems on which mlockall() and munlockall() are available, _POSIX_MEMLOCK is defined in <unistd.h> to a value greater than 0. (See also sysconf(3).) mmap (2) mmap (2) shmctl (2) shmctl (2) setrlimit (2) setrlimit (2) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2478, "s": 2319, "text": "#include <sys/mman.h> \n\nint mlock(const void *addr, size_t len);\n\nint munlock(const void *addr, size_t len);\n\nint mlockall(int flags);\n\nint munlockall(void);\n" }, { "code": null, "e": 2521, "s": 2478, "text": "\nint mlock(const void *addr, size_t len);\n" }, { "code": null, "e": 2566, "s": 2521, "text": "\nint munlock(const void *addr, size_t len);\n" }, { "code": null, "e": 2593, "s": 2566, "text": "\nint mlockall(int flags);\n" }, { "code": null, "e": 2617, "s": 2593, "text": "\nint munlockall(void);\n" }, { "code": null, "e": 2845, "s": 2617, "text": "\nmunlock() unlocks pages in the address range starting at\naddr and continuing for\nlen bytes.\nAfter this call, all pages that contain a part of the specified\nmemory range can be moved to external swap space again by the kernel.\n" }, { "code": null, "e": 2942, "s": 2845, "text": "\nThe\nflags argument is constructed as the bitwise OR of one or more of the\nfollowing constants:\n" }, { "code": null, "e": 3029, "s": 2942, "text": "\nmunlockall() unlocks all pages mapped into the address space of the\ncalling process.\n" }, { "code": null, "e": 3622, "s": 3029, "text": "\nReal-time processes that are using\nmlockall() to prevent delays on page faults should reserve enough\nlocked stack pages before entering the time-critical section,\nso that no page fault can be caused by function calls.\nThis can be achieved by calling a function that allocates a\nsufficiently large automatic variable (an array) and writes to the\nmemory occupied by this array in order to touch these stack pages.\nThis way, enough pages will be mapped for the stack and can be\nlocked into RAM. The dummy writes ensure that not even copy-on-write\npage faults can occur in the critical section.\n" }, { "code": null, "e": 3779, "s": 3622, "text": "\nMemory locks are not inherited by a child created via\nfork(2)\nand are automatically removed (unlocked) during an\nexecve(2)\nor when the process terminates.\n" }, { "code": null, "e": 3890, "s": 3779, "text": "\nThe memory lock on an address range is automatically removed\nif the address range is unmapped via\nmunmap(2).\n" }, { "code": null, "e": 4266, "s": 3890, "text": "\nMemory locks do not stack, i.e., pages which have been locked several times\nby calls to\nmlock() or\nmlockall() will be unlocked by a single call to\nmunlock() for the corresponding range or by\nmunlockall(). Pages which are mapped to several locations or by several processes stay\nlocked into RAM as long as they are locked at least at one location or by\nat least one process.\n" }, { "code": null, "e": 4487, "s": 4266, "text": "\nSince Linux 2.6.9, no limits are placed on the amount of memory\nthat a privileged process can lock and the\nRLIMIT_MEMLOCK soft resource limit instead defines a limit on how much memory an\nunprivileged process may lock.\n" }, { "code": null, "e": 4809, "s": 4487, "text": "\nSince kernel 2.6.9, if a privileged process calls\nmlockall(MCL_FUTURE) and later drops privileges (loses the\nCAP_IPC_LOCK capability by, for example,\nsetting its effective UID to a non-zero value),\nthen subsequent memory allocations (e.g.,\nmmap(2),\nbrk(2))\nwill fail if the\nRLIMIT_MEMLOCK resource limit is encountered.\n" }, { "code": null, "e": 4970, "s": 4809, "text": "\nOn POSIX systems on which\nmlockall() and\nmunlockall() are available,\n_POSIX_MEMLOCK is defined in <unistd.h> to a value greater than 0. (See also\nsysconf(3).)\n" }, { "code": null, "e": 4979, "s": 4970, "text": "mmap (2)" }, { "code": null, "e": 4988, "s": 4979, "text": "mmap (2)" }, { "code": null, "e": 4999, "s": 4988, "text": "shmctl (2)" }, { "code": null, "e": 5010, "s": 4999, "text": "shmctl (2)" }, { "code": null, "e": 5024, "s": 5010, "text": "setrlimit (2)" }, { "code": null, "e": 5038, "s": 5024, "text": "setrlimit (2)" }, { "code": null, "e": 5055, "s": 5038, "text": "\nAdvertisements\n" }, { "code": null, "e": 5090, "s": 5055, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 5118, "s": 5090, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5152, "s": 5118, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5169, "s": 5152, "text": " Frahaan Hussain" }, { "code": null, "e": 5202, "s": 5169, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 5213, "s": 5202, "text": " Pradeep D" }, { "code": null, "e": 5248, "s": 5213, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5264, "s": 5248, "text": " Musab Zayadneh" }, { "code": null, "e": 5297, "s": 5264, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 5309, "s": 5297, "text": " GUHARAJANM" }, { "code": null, "e": 5341, "s": 5309, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 5349, "s": 5341, "text": " Uplatz" }, { "code": null, "e": 5356, "s": 5349, "text": " Print" }, { "code": null, "e": 5367, "s": 5356, "text": " Add Notes" } ]
MongoDB AND operator ( $and )
05 Jun, 2022 MongoDB provides different types of logical query operators and $and operator is one of them. This operator is used to perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression in the array. You can use this operator in methods like find(), update(), etc. according to your requirements. This operator performs short-circuit evaluation. If the first expression of $and operator evaluates to false, then MongoDB will not evaluate the remaining expressions in the array. You can also use AND operation implicitly with the help of comma(, ). You can use AND operation explicitly (i.e., $and) when the same field or operator specified in multiple expressions. Syntax: { $and: [ { Expression1 }, { Expression2 }, ..., { ExpressionN } ] } or { { Expression1 }, { Expression2 }, ..., { ExpressionN }} Examples: In the following examples, we are working with: Database: GeeksforGeeks Collection: contributor Document: three documents that contain the details of the contributors in the form of field-value pairs. In this example, we are retrieving only those employee’s documents whose branch is CSE and joiningYear is 2018. Python3 db.contributor.find({$and: [{branch: "CSE"}, {joiningYear: 2018}]}).pretty() In this example, we are retrieving only those employee’s documents whose branch is CSE. Python3 db.contributor.find({$and: [{branch: {$eq: "CSE"}}, {branch: {$exists: true}}]}).pretty() or Python3 db.contributor.find({branch: {$eq: "CSE", $exists: true}}).pretty() In this example, we are retrieving only those employee’s documents whose satisfy the given conditions. Python3 db.contributor.find({$and: [{$or: [{branch: "ECE"}, {joiningYear: 2017}]}, {$or: [{"personal.state": "UP"}, {"personal.age": 25}]}]}).pretty() vinayedula MongoDB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Markov Decision Process Basics of API Testing Using Postman Copying Files to and from Docker Containers Getting Started with System Design Principal Component Analysis with Python How to create a REST API using Java Spring Boot Monolithic vs Microservices architecture Fuzzy Logic | Introduction Mounting a Volume Inside Docker Container
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2022" }, { "code": null, "e": 408, "s": 28, "text": "MongoDB provides different types of logical query operators and $and operator is one of them. This operator is used to perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression in the array. You can use this operator in methods like find(), update(), etc. according to your requirements." }, { "code": null, "e": 457, "s": 408, "text": "This operator performs short-circuit evaluation." }, { "code": null, "e": 589, "s": 457, "text": "If the first expression of $and operator evaluates to false, then MongoDB will not evaluate the remaining expressions in the array." }, { "code": null, "e": 659, "s": 589, "text": "You can also use AND operation implicitly with the help of comma(, )." }, { "code": null, "e": 776, "s": 659, "text": "You can use AND operation explicitly (i.e., $and) when the same field or operator specified in multiple expressions." }, { "code": null, "e": 785, "s": 776, "text": "Syntax: " }, { "code": null, "e": 915, "s": 785, "text": "{ $and: [ { Expression1 }, { Expression2 }, ..., { ExpressionN } ] }\nor\n{ { Expression1 }, { Expression2 }, ..., { ExpressionN }}" }, { "code": null, "e": 973, "s": 915, "text": "Examples: In the following examples, we are working with:" }, { "code": null, "e": 1126, "s": 973, "text": "Database: GeeksforGeeks Collection: contributor Document: three documents that contain the details of the contributors in the form of field-value pairs." }, { "code": null, "e": 1239, "s": 1126, "text": "In this example, we are retrieving only those employee’s documents whose branch is CSE and joiningYear is 2018. " }, { "code": null, "e": 1247, "s": 1239, "text": "Python3" }, { "code": "db.contributor.find({$and: [{branch: \"CSE\"}, {joiningYear: 2018}]}).pretty()", "e": 1351, "s": 1247, "text": null }, { "code": null, "e": 1440, "s": 1351, "text": "In this example, we are retrieving only those employee’s documents whose branch is CSE. " }, { "code": null, "e": 1448, "s": 1440, "text": "Python3" }, { "code": "db.contributor.find({$and: [{branch: {$eq: \"CSE\"}}, {branch: {$exists: true}}]}).pretty()", "e": 1565, "s": 1448, "text": null }, { "code": null, "e": 1569, "s": 1565, "text": "or " }, { "code": null, "e": 1577, "s": 1569, "text": "Python3" }, { "code": "db.contributor.find({branch: {$eq: \"CSE\", $exists: true}}).pretty()", "e": 1645, "s": 1577, "text": null }, { "code": null, "e": 1749, "s": 1645, "text": "In this example, we are retrieving only those employee’s documents whose satisfy the given conditions. " }, { "code": null, "e": 1757, "s": 1749, "text": "Python3" }, { "code": "db.contributor.find({$and: [{$or: [{branch: \"ECE\"}, {joiningYear: 2017}]}, {$or: [{\"personal.state\": \"UP\"}, {\"personal.age\": 25}]}]}).pretty()", "e": 1961, "s": 1757, "text": null }, { "code": null, "e": 1972, "s": 1961, "text": "vinayedula" }, { "code": null, "e": 1980, "s": 1972, "text": "MongoDB" }, { "code": null, "e": 2006, "s": 1980, "text": "Advanced Computer Subject" }, { "code": null, "e": 2104, "s": 2006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2140, "s": 2104, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 2164, "s": 2140, "text": "Markov Decision Process" }, { "code": null, "e": 2200, "s": 2164, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 2244, "s": 2200, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 2279, "s": 2244, "text": "Getting Started with System Design" }, { "code": null, "e": 2320, "s": 2279, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 2368, "s": 2320, "text": "How to create a REST API using Java Spring Boot" }, { "code": null, "e": 2409, "s": 2368, "text": "Monolithic vs Microservices architecture" }, { "code": null, "e": 2436, "s": 2409, "text": "Fuzzy Logic | Introduction" } ]
How to get attribute of element from Selenium?
We can get the attribute of element in Selenium webdriver. The getAttribute() method is used to obtain the value of an attribute in an html document. In an html code, attribute and its value appear as a key value pair. Some of the commonly known html attributes are disabled, alt, id, href, style, title and src. The value of the attribute that we want to fetch is passed as an argument to the method. Let us consider an html code, for which we shall obtain the src attribute. The value of the src attribute should be /about/images/logo.png. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class GetSrcAttribute{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String u = "https://www.tutorialspoint.com/about/about_careers.htm"driver.get(u); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // identify element WebElement t=driver.findElement(By.xpath("//img[@class='tp-logo']")); // get src attribute with getAttribute() System.out.println("Src attribute is : " + t.getAttribute("src")); driver.close(); } } Output
[ { "code": null, "e": 1406, "s": 1187, "text": "We can get the attribute of element in Selenium webdriver. The getAttribute() method is used to obtain the value of an attribute in an html document. In an html code, attribute and its value appear as a key value pair." }, { "code": null, "e": 1589, "s": 1406, "text": "Some of the commonly known html attributes are disabled, alt, id, href, style, title and src. The value of the attribute that we want to fetch is passed as an argument to the method." }, { "code": null, "e": 1729, "s": 1589, "text": "Let us consider an html code, for which we shall obtain the src attribute. The value of the src attribute should be /about/images/logo.png." }, { "code": null, "e": 2561, "s": 1729, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\n\npublic class GetSrcAttribute{\n public static void main(String[] args) {\nSystem.setProperty(\"webdriver.chrome.driver\",\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String u = \"https://www.tutorialspoint.com/about/about_careers.htm\"driver.get(u);\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify element\n WebElement t=driver.findElement(By.xpath(\"//img[@class='tp-logo']\"));\n // get src attribute with getAttribute()\n System.out.println(\"Src attribute is : \" + t.getAttribute(\"src\"));\n driver.close();\n }\n}\nOutput\n" } ]
Flexbox - Flex-Direction
The flex-direction property is used to specify the direction in which the elements of flex container (flex-items) are needed to be placed. usage − flex-direction: row | row-reverse | column | column-reverse This property accepts four values − row − Arranges the elements of the container horizontally from left to right. row − Arranges the elements of the container horizontally from left to right. row-reverse − Arranges the elements of the container horizontally from right to left. row-reverse − Arranges the elements of the container horizontally from right to left. column − Arranges the elements of the container vertically from left to right. column − Arranges the elements of the container vertically from left to right. column-reverse − Arranges the elements of the container vertically from right to left. column-reverse − Arranges the elements of the container vertically from right to left. Now, we will take a few examples to demonstrate the use of the direction property. On passing this value to the direction property, the elements of the container are arranged horizontally from left to right as shown below. The following example demonstrates the result of passing the value row to the flex-direction property. Here, we are creating six boxes with different colors with the flex-direction value row. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:inline-flex; border:3px solid black; flex-direction:row; } </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 − On passing this value to the direction property, the elements of the container are arranged horizontally from right to left as shown below. The following example demonstrates the result of passing the value row-reverse to the flex-direction property. Here, we are creating six boxes with different colors with the flex-direction value row-reverse. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:inline-flex; border:3px solid black; flex-direction:row-reverse; } </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 − On passing this value to the direction property, the elements of the container are arranged vertically from top to bottom as shown below. The following example demonstrates the result of passing the value column to the flex-direction property. Here, we are creating six boxes with different colors with the flex-direction value column. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:inline-flex; border:3px solid black; flex-direction:column; } </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 − On passing this value to the direction property, the elements of the container are arranged vertically from bottom to top as shown below. The following example demonstrates the result of passing the value column-reverse to the flex-direction property. Here, we are creating six boxes with different colors with the flex-direction value column-reverse. <!doctype html> <html lang = "en"> <style> .box1{background:green;} .box2{background:blue;} .box3{background:red;} .box4{background:magenta;} .box5{background:yellow;} .box6{background:pink;} .box{ font-size:35px; padding:15px; } .container{ display:inline-flex; border:3px solid black; flex-direction:column-reverse; } </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 −
[ { "code": null, "e": 2084, "s": 1945, "text": "The flex-direction property is used to specify the direction in which the elements of flex container (flex-items) are needed to be placed." }, { "code": null, "e": 2092, "s": 2084, "text": "usage −" }, { "code": null, "e": 2153, "s": 2092, "text": "flex-direction: row | row-reverse | column | column-reverse\n" }, { "code": null, "e": 2189, "s": 2153, "text": "This property accepts four values −" }, { "code": null, "e": 2267, "s": 2189, "text": "row − Arranges the elements of the container horizontally from left to right." }, { "code": null, "e": 2345, "s": 2267, "text": "row − Arranges the elements of the container horizontally from left to right." }, { "code": null, "e": 2431, "s": 2345, "text": "row-reverse − Arranges the elements of the container horizontally from right to left." }, { "code": null, "e": 2517, "s": 2431, "text": "row-reverse − Arranges the elements of the container horizontally from right to left." }, { "code": null, "e": 2596, "s": 2517, "text": "column − Arranges the elements of the container vertically from left to right." }, { "code": null, "e": 2675, "s": 2596, "text": "column − Arranges the elements of the container vertically from left to right." }, { "code": null, "e": 2762, "s": 2675, "text": "column-reverse − Arranges the elements of the container vertically from right to left." }, { "code": null, "e": 2849, "s": 2762, "text": "column-reverse − Arranges the elements of the container vertically from right to left." }, { "code": null, "e": 2932, "s": 2849, "text": "Now, we will take a few examples to demonstrate the use of the direction property." }, { "code": null, "e": 3072, "s": 2932, "text": "On passing this value to the direction property, the elements of the container are arranged horizontally from left to right as shown below." }, { "code": null, "e": 3264, "s": 3072, "text": "The following example demonstrates the result of passing the value row to the flex-direction property. Here, we are creating six boxes with different colors with the flex-direction value row." }, { "code": null, "e": 4040, "s": 3264, "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 .box{\n font-size:35px;\n padding:15px;\n }\n .container{\n display:inline-flex;\n border:3px solid black;\n flex-direction:row;\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": 4079, "s": 4040, "text": "It will produce the following result −" }, { "code": null, "e": 4219, "s": 4079, "text": "On passing this value to the direction property, the elements of the container are arranged horizontally from right to left as shown below." }, { "code": null, "e": 4427, "s": 4219, "text": "The following example demonstrates the result of passing the value row-reverse to the flex-direction property. Here, we are creating six boxes with different colors with the flex-direction value row-reverse." }, { "code": null, "e": 5211, "s": 4427, "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 .box{\n font-size:35px;\n padding:15px;\n }\n .container{\n display:inline-flex;\n border:3px solid black;\n flex-direction:row-reverse;\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": 5250, "s": 5211, "text": "It will produce the following result −" }, { "code": null, "e": 5388, "s": 5250, "text": "On passing this value to the direction property, the elements of the container are arranged vertically from top to bottom as shown below." }, { "code": null, "e": 5586, "s": 5388, "text": "The following example demonstrates the result of passing the value column to the flex-direction property. Here, we are creating six boxes with different colors with the flex-direction value column." }, { "code": null, "e": 6361, "s": 5586, "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 .box{\n font-size:35px;\n padding:15px;\n }\n .container{\n display:inline-flex;\n border:3px solid black;\n flex-direction:column;\n }\n </style>\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": 6400, "s": 6361, "text": "It will produce the following result −" }, { "code": null, "e": 6538, "s": 6400, "text": "On passing this value to the direction property, the elements of the container are arranged vertically from bottom to top as shown below." }, { "code": null, "e": 6752, "s": 6538, "text": "The following example demonstrates the result of passing the value column-reverse to the flex-direction property. Here, we are creating six boxes with different colors with the flex-direction value column-reverse." }, { "code": null, "e": 7539, "s": 6752, "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 .box{\n font-size:35px;\n padding:15px;\n }\n .container{\n display:inline-flex;\n border:3px solid black;\n flex-direction:column-reverse;\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>" } ]
Downloading PDFs with Python using Requests and BeautifulSoup
13 Apr, 2021 BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a whole. For most purposes, you can treat it as a Tag object. Requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scrapping, requests must be learned for proceeding further with these technologies. When one makes a request to a URI, it returns a response. Python requests provide inbuilt functionalities for managing both the request and response. This article deals with downloading PDFs using BeautifulSoup and requests libraries in python. Beautifulsoup and requests are useful to extract the required information from the webpage. Approach: To find PDF and download it, we have to follow the following steps: Import beautifulsoup and requests library. Request the URL and get the response object. Find all the hyperlinks present on the webpage. Check for the PDF file link in those links. Get a PDF file using the response object. Implementation: Python3 # Import librariesimport requestsfrom bs4 import BeautifulSoup # URL from which pdfs to be downloadedurl = "https://www.geeksforgeeks.org/how-to-extract-pdf-tables-in-python/" # Requests URL and get response objectresponse = requests.get(url) # Parse text obtainedsoup = BeautifulSoup(response.text, 'html.parser') # Find all hyperlinks present on webpagelinks = soup.find_all('a') i = 0 # From all links check for pdf link and# if present download filefor link in links: if ('.pdf' in link.get('href', [])): i += 1 print("Downloading file: ", i) # Get response object for link response = requests.get(link.get('href')) # Write content in pdf file pdf = open("pdf"+str(i)+".pdf", 'wb') pdf.write(response.content) pdf.close() print("File ", i, " downloaded") print("All PDF files downloaded") Output: Downloading file: 1 File 1 downloaded All PDF files downloaded The above program downloads the PDF files from the provided URL with names pdf1, pdf2, pdf3 and so on respectively. Picked Python BeautifulSoup Python-requests Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2021" }, { "code": null, "e": 360, "s": 28, "text": "BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a whole. For most purposes, you can treat it as a Tag object." }, { "code": null, "e": 717, "s": 360, "text": "Requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scrapping, requests must be learned for proceeding further with these technologies. When one makes a request to a URI, it returns a response. Python requests provide inbuilt functionalities for managing both the request and response." }, { "code": null, "e": 904, "s": 717, "text": "This article deals with downloading PDFs using BeautifulSoup and requests libraries in python. Beautifulsoup and requests are useful to extract the required information from the webpage." }, { "code": null, "e": 914, "s": 904, "text": "Approach:" }, { "code": null, "e": 982, "s": 914, "text": "To find PDF and download it, we have to follow the following steps:" }, { "code": null, "e": 1025, "s": 982, "text": "Import beautifulsoup and requests library." }, { "code": null, "e": 1070, "s": 1025, "text": "Request the URL and get the response object." }, { "code": null, "e": 1118, "s": 1070, "text": "Find all the hyperlinks present on the webpage." }, { "code": null, "e": 1162, "s": 1118, "text": "Check for the PDF file link in those links." }, { "code": null, "e": 1204, "s": 1162, "text": "Get a PDF file using the response object." }, { "code": null, "e": 1220, "s": 1204, "text": "Implementation:" }, { "code": null, "e": 1228, "s": 1220, "text": "Python3" }, { "code": "# Import librariesimport requestsfrom bs4 import BeautifulSoup # URL from which pdfs to be downloadedurl = \"https://www.geeksforgeeks.org/how-to-extract-pdf-tables-in-python/\" # Requests URL and get response objectresponse = requests.get(url) # Parse text obtainedsoup = BeautifulSoup(response.text, 'html.parser') # Find all hyperlinks present on webpagelinks = soup.find_all('a') i = 0 # From all links check for pdf link and# if present download filefor link in links: if ('.pdf' in link.get('href', [])): i += 1 print(\"Downloading file: \", i) # Get response object for link response = requests.get(link.get('href')) # Write content in pdf file pdf = open(\"pdf\"+str(i)+\".pdf\", 'wb') pdf.write(response.content) pdf.close() print(\"File \", i, \" downloaded\") print(\"All PDF files downloaded\")", "e": 2098, "s": 1228, "text": null }, { "code": null, "e": 2106, "s": 2098, "text": "Output:" }, { "code": null, "e": 2172, "s": 2106, "text": "Downloading file: 1\nFile 1 downloaded\nAll PDF files downloaded" }, { "code": null, "e": 2288, "s": 2172, "text": "The above program downloads the PDF files from the provided URL with names pdf1, pdf2, pdf3 and so on respectively." }, { "code": null, "e": 2295, "s": 2288, "text": "Picked" }, { "code": null, "e": 2316, "s": 2295, "text": "Python BeautifulSoup" }, { "code": null, "e": 2332, "s": 2316, "text": "Python-requests" }, { "code": null, "e": 2345, "s": 2332, "text": "Web-scraping" }, { "code": null, "e": 2352, "s": 2345, "text": "Python" }, { "code": null, "e": 2450, "s": 2352, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2482, "s": 2450, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2509, "s": 2482, "text": "Python Classes and Objects" }, { "code": null, "e": 2540, "s": 2509, "text": "Python | os.path.join() method" }, { "code": null, "e": 2563, "s": 2540, "text": "Introduction To PYTHON" }, { "code": null, "e": 2584, "s": 2563, "text": "Python OOPs Concepts" }, { "code": null, "e": 2640, "s": 2584, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2682, "s": 2640, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2724, "s": 2682, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2763, "s": 2724, "text": "Python | Get unique values from a list" } ]
Neo4j Drop Index
27 Aug, 2019 In neo4j you can drop index for both property and nodes. Indexing is data structure that helps faster performance on retrieval operation on database. There is special features in neo4j indexing once you create indexing that index will manage itself and keep it up to date whenever changes made on the database. Similarly DROP INDEX ON statement will provide the indexing.Syntax: DROP INDEX ON:label(node) Example: In the below example we drop index on the Tag property of all nodes with the GeeksforGeeks label. $ DROP INDEX ON:GeeksforGeeks(Tag) Output: $ DROP INDEX ON:GeeksforGeeks(Tag) Output: View Schema: You can use the :schema command to see applicable index is removed from the schema. :schemaOutput: :schema Output: Note: If there is others indexing available then it will show those, basically this command will show all the schema. Remember few things to remove anything fast off all remove the relationship first after try the DELETE clause or REMOVE clause it is a good practice. To remove any node you have to remove the relationships, but in case of indexing that is not required. Indexing is the different things that does not effect on database it just increase the accessibility of your database. by removing the index you lost the fast accessing capability. DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Introduction of DBMS (Database Management System) | Set 1 SQL Trigger | Student Database SQL Interview Questions Introduction of ER Model Data Preprocessing in Data Mining SQL | Views Difference between DELETE, DROP and TRUNCATE Difference between SQL and NoSQL Indexing in Databases | Set 1
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Aug, 2019" }, { "code": null, "e": 407, "s": 28, "text": "In neo4j you can drop index for both property and nodes. Indexing is data structure that helps faster performance on retrieval operation on database. There is special features in neo4j indexing once you create indexing that index will manage itself and keep it up to date whenever changes made on the database. Similarly DROP INDEX ON statement will provide the indexing.Syntax:" }, { "code": null, "e": 433, "s": 407, "text": "DROP INDEX ON:label(node)" }, { "code": null, "e": 540, "s": 433, "text": "Example: In the below example we drop index on the Tag property of all nodes with the GeeksforGeeks label." }, { "code": null, "e": 583, "s": 540, "text": "$ DROP INDEX ON:GeeksforGeeks(Tag)\nOutput:" }, { "code": null, "e": 619, "s": 583, "text": "$ DROP INDEX ON:GeeksforGeeks(Tag)\n" }, { "code": null, "e": 627, "s": 619, "text": "Output:" }, { "code": null, "e": 724, "s": 627, "text": "View Schema: You can use the :schema command to see applicable index is removed from the schema." }, { "code": null, "e": 739, "s": 724, "text": ":schemaOutput:" }, { "code": null, "e": 747, "s": 739, "text": ":schema" }, { "code": null, "e": 755, "s": 747, "text": "Output:" }, { "code": null, "e": 873, "s": 755, "text": "Note: If there is others indexing available then it will show those, basically this command will show all the schema." }, { "code": null, "e": 1307, "s": 873, "text": "Remember few things to remove anything fast off all remove the relationship first after try the DELETE clause or REMOVE clause it is a good practice. To remove any node you have to remove the relationships, but in case of indexing that is not required. Indexing is the different things that does not effect on database it just increase the accessibility of your database. by removing the index you lost the fast accessing capability." }, { "code": null, "e": 1312, "s": 1307, "text": "DBMS" }, { "code": null, "e": 1317, "s": 1312, "text": "DBMS" }, { "code": null, "e": 1415, "s": 1317, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1426, "s": 1415, "text": "CTE in SQL" }, { "code": null, "e": 1484, "s": 1426, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 1515, "s": 1484, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 1539, "s": 1515, "text": "SQL Interview Questions" }, { "code": null, "e": 1564, "s": 1539, "text": "Introduction of ER Model" }, { "code": null, "e": 1598, "s": 1564, "text": "Data Preprocessing in Data Mining" }, { "code": null, "e": 1610, "s": 1598, "text": "SQL | Views" }, { "code": null, "e": 1655, "s": 1610, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1688, "s": 1655, "text": "Difference between SQL and NoSQL" } ]
MySQL - Select Query
The SQL SELECT command is used to fetch data from the MySQL database. You can use this command at mysql> prompt as well as in any script like PHP. Here is generic SQL syntax of SELECT command to fetch data from the MySQL table − SELECT field1, field2,...fieldN FROM table_name1, table_name2... [WHERE Clause] [OFFSET M ][LIMIT N] You can use one or more tables separated by comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command. You can use one or more tables separated by comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command. You can fetch one or more fields in a single SELECT command. You can fetch one or more fields in a single SELECT command. You can specify star (*) in place of fields. In this case, SELECT will return all the fields. You can specify star (*) in place of fields. In this case, SELECT will return all the fields. You can specify any condition using the WHERE clause. You can specify any condition using the WHERE clause. You can specify an offset using OFFSET from where SELECT will start returning records. By default, the offset starts at zero. You can specify an offset using OFFSET from where SELECT will start returning records. By default, the offset starts at zero. You can limit the number of returns using the LIMIT attribute. You can limit the number of returns using the LIMIT attribute. This will use SQL SELECT command to fetch data from the MySQL table tutorials_tbl. The following example will return all the records from the tutorials_tbl table − root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT * from tutorials_tbl +-------------+----------------+-----------------+-----------------+ | tutorial_id | tutorial_title | tutorial_author | submission_date | +-------------+----------------+-----------------+-----------------+ | 1 | Learn PHP | John Poul | 2007-05-21 | | 2 | Learn MySQL | Abdul S | 2007-05-21 | | 3 | JAVA Tutorial | Sanjay | 2007-05-21 | +-------------+----------------+-----------------+-----------------+ 3 rows in set (0.01 sec) mysql> PHP uses mysqli query() or mysql_query() function to select records from a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure. $mysqli->query($sql,$resultmode) $sql Required - SQL query to select records from a MySQL table. $resultmode Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used. Try the following example to select a record from a table − Copy and paste the following example as mysql_example.php − <html> <head> <title>Creating MySQL Table</title> </head> <body> <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'root@123'; $dbname = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if($mysqli->connect_errno ) { printf("Connect failed: %s<br />", $mysqli->connect_error); exit(); } printf('Connected successfully.<br />'); $sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl"; $result = $mysqli->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { printf("Id: %s, Title: %s, Author: %s, Date: %d <br />", $row["tutorial_id"], $row["tutorial_title"], $row["tutorial_author"], $row["submission_date"]); } } else { printf('No record found.<br />'); } mysqli_free_result($result); $mysqli->close(); ?> </body> </html> Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script. Connected successfully. Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021 Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021 Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021 Id: 4, Title: Java Tutorial, Author: Mahesh, Date: 2021 Id: 5, Title: Apache Tutorial, Author: Suresh, Date: 2021
[ { "code": null, "e": 2588, "s": 2441, "text": "The SQL SELECT command is used to fetch data from the MySQL database. You can use this command at mysql> prompt as well as in any script like PHP." }, { "code": null, "e": 2670, "s": 2588, "text": "Here is generic SQL syntax of SELECT command to fetch data from the MySQL table −" }, { "code": null, "e": 2773, "s": 2670, "text": "SELECT field1, field2,...fieldN \nFROM table_name1, table_name2...\n[WHERE Clause]\n[OFFSET M ][LIMIT N]\n" }, { "code": null, "e": 2939, "s": 2773, "text": "You can use one or more tables separated by comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command." }, { "code": null, "e": 3105, "s": 2939, "text": "You can use one or more tables separated by comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command." }, { "code": null, "e": 3166, "s": 3105, "text": "You can fetch one or more fields in a single SELECT command." }, { "code": null, "e": 3227, "s": 3166, "text": "You can fetch one or more fields in a single SELECT command." }, { "code": null, "e": 3321, "s": 3227, "text": "You can specify star (*) in place of fields. In this case, SELECT will return all the fields." }, { "code": null, "e": 3415, "s": 3321, "text": "You can specify star (*) in place of fields. In this case, SELECT will return all the fields." }, { "code": null, "e": 3469, "s": 3415, "text": "You can specify any condition using the WHERE clause." }, { "code": null, "e": 3523, "s": 3469, "text": "You can specify any condition using the WHERE clause." }, { "code": null, "e": 3649, "s": 3523, "text": "You can specify an offset using OFFSET from where SELECT will start returning records. By default, the offset starts at zero." }, { "code": null, "e": 3775, "s": 3649, "text": "You can specify an offset using OFFSET from where SELECT will start returning records. By default, the offset starts at zero." }, { "code": null, "e": 3838, "s": 3775, "text": "You can limit the number of returns using the LIMIT attribute." }, { "code": null, "e": 3901, "s": 3838, "text": "You can limit the number of returns using the LIMIT attribute." }, { "code": null, "e": 3984, "s": 3901, "text": "This will use SQL SELECT command to fetch data from the MySQL table tutorials_tbl." }, { "code": null, "e": 4065, "s": 3984, "text": "The following example will return all the records from the tutorials_tbl table −" }, { "code": null, "e": 4717, "s": 4065, "text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\nmysql> SELECT * from tutorials_tbl \n+-------------+----------------+-----------------+-----------------+\n| tutorial_id | tutorial_title | tutorial_author | submission_date |\n+-------------+----------------+-----------------+-----------------+\n| 1 | Learn PHP | John Poul | 2007-05-21 |\n| 2 | Learn MySQL | Abdul S | 2007-05-21 |\n| 3 | JAVA Tutorial | Sanjay | 2007-05-21 |\n+-------------+----------------+-----------------+-----------------+\n3 rows in set (0.01 sec)\n\nmysql>" }, { "code": null, "e": 4889, "s": 4717, "text": "PHP uses mysqli query() or mysql_query() function to select records from a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure." }, { "code": null, "e": 4923, "s": 4889, "text": "$mysqli->query($sql,$resultmode)\n" }, { "code": null, "e": 4928, "s": 4923, "text": "$sql" }, { "code": null, "e": 4987, "s": 4928, "text": "Required - SQL query to select records from a MySQL table." }, { "code": null, "e": 4999, "s": 4987, "text": "$resultmode" }, { "code": null, "e": 5147, "s": 4999, "text": "Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used." }, { "code": null, "e": 5208, "s": 5147, "text": "Try the following example to select a record from a table −" }, { "code": null, "e": 5268, "s": 5208, "text": "Copy and paste the following example as mysql_example.php −" }, { "code": null, "e": 6444, "s": 5268, "text": "<html>\n <head>\n <title>Creating MySQL Table</title>\n </head>\n <body>\n <?php\n $dbhost = 'localhost';\n $dbuser = 'root';\n $dbpass = 'root@123';\n $dbname = 'TUTORIALS';\n $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);\n \n if($mysqli->connect_errno ) {\n printf(\"Connect failed: %s<br />\", $mysqli->connect_error);\n exit();\n }\n printf('Connected successfully.<br />');\n $sql = \"SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl\";\n\t\t \n $result = $mysqli->query($sql);\n \n if ($result->num_rows > 0) {\n while($row = $result->fetch_assoc()) {\n printf(\"Id: %s, Title: %s, Author: %s, Date: %d <br />\", \n $row[\"tutorial_id\"], \n $row[\"tutorial_title\"], \n $row[\"tutorial_author\"],\n $row[\"submission_date\"]); \n }\n } else {\n printf('No record found.<br />');\n }\n mysqli_free_result($result);\n $mysqli->close();\n ?>\n </body>\n</html>" }, { "code": null, "e": 6609, "s": 6444, "text": "Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script." } ]
Convert Text File to CSV using Python Pandas
02 Sep, 2020 Let’s see how to Convert Text File to CSV using Python Pandas. Python will read data from a text file and will create a dataframe with rows equal to number of lines present in the text file and columns equal to the number of fields present in a single line. See below example for better understanding. Original Text File Dataframe created from upper text file will look as follows: CSV File formed from given text file Note: The first column in dataframe is indexing which is by default when a text file is read. Once the dataframe is created, we will store this dataframe into a CSV file format using Dataframe.to_csv() Method. Syntax: Dataframe.to_csv(parameters) Return: None Let’s see examples: Example 1: Python3 # importing panda libraryimport pandas as pd # readinag given csv file# and creating dataframedataframe1 = pd.read_csv("GeeksforGeeks.txt") # storing this dataframe in a csv filedataframe1.to_csv('GeeksforGeeks.csv', index = None) Output: CSV File formed from given text file The text file read is same as above. After successful run of above code, a file named “GeeksforGeeks.csv” will be created in the same directory. Example 2: Suppose the column heading are not given and the text file looks like: Text File without headers Then while writing the code you can specify headers. Python3 # importing pandas libraryimport pandas as pd # reading given csv file # and creating dataframewebsites = pd.read_csv("GeeksforGeeks.txt" ,header = None) # adding column headingswebsites.columns = ['Name', 'Type', 'Website'] # store dataframe into csv filewebsites.to_csv('GeeksforGeeks.csv', index = None) Output: CSV file with headers We see that headers have been added successfully and file has been converted from ‘.txt’ format to ‘.csv’ format. Example 3: In this example, the fields in the text file are separated by user defined delimiter “/”. ‘/’ Delimited Text File Python3 # importing pandas libraryimport pandas as pd # reading the given csv file # and creating dataframeaccount = pd.read_csv("GeeksforGeeks.txt", delimiter = '/') # store dataframe into csv fileaccount.to_csv('GeeksforGeeks.csv', index = None) Output: CSV File While reading data we specify that data should be tokenized using specified delimiter. In this case ‘/’. Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Sep, 2020" }, { "code": null, "e": 354, "s": 52, "text": "Let’s see how to Convert Text File to CSV using Python Pandas. Python will read data from a text file and will create a dataframe with rows equal to number of lines present in the text file and columns equal to the number of fields present in a single line. See below example for better understanding." }, { "code": null, "e": 373, "s": 354, "text": "Original Text File" }, { "code": null, "e": 435, "s": 373, "text": "Dataframe created from upper text file will look as follows: " }, { "code": null, "e": 472, "s": 435, "text": "CSV File formed from given text file" }, { "code": null, "e": 566, "s": 472, "text": "Note: The first column in dataframe is indexing which is by default when a text file is read." }, { "code": null, "e": 682, "s": 566, "text": "Once the dataframe is created, we will store this dataframe into a CSV file format using Dataframe.to_csv() Method." }, { "code": null, "e": 719, "s": 682, "text": "Syntax: Dataframe.to_csv(parameters)" }, { "code": null, "e": 732, "s": 719, "text": "Return: None" }, { "code": null, "e": 752, "s": 732, "text": "Let’s see examples:" }, { "code": null, "e": 763, "s": 752, "text": "Example 1:" }, { "code": null, "e": 771, "s": 763, "text": "Python3" }, { "code": "# importing panda libraryimport pandas as pd # readinag given csv file# and creating dataframedataframe1 = pd.read_csv(\"GeeksforGeeks.txt\") # storing this dataframe in a csv filedataframe1.to_csv('GeeksforGeeks.csv', index = None)", "e": 1022, "s": 771, "text": null }, { "code": null, "e": 1030, "s": 1022, "text": "Output:" }, { "code": null, "e": 1067, "s": 1030, "text": "CSV File formed from given text file" }, { "code": null, "e": 1213, "s": 1067, "text": "The text file read is same as above. After successful run of above code, a file named “GeeksforGeeks.csv” will be created in the same directory. " }, { "code": null, "e": 1295, "s": 1213, "text": "Example 2: Suppose the column heading are not given and the text file looks like:" }, { "code": null, "e": 1321, "s": 1295, "text": "Text File without headers" }, { "code": null, "e": 1375, "s": 1321, "text": "Then while writing the code you can specify headers. " }, { "code": null, "e": 1383, "s": 1375, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # reading given csv file # and creating dataframewebsites = pd.read_csv(\"GeeksforGeeks.txt\" ,header = None) # adding column headingswebsites.columns = ['Name', 'Type', 'Website'] # store dataframe into csv filewebsites.to_csv('GeeksforGeeks.csv', index = None)", "e": 1731, "s": 1383, "text": null }, { "code": null, "e": 1740, "s": 1731, "text": " Output:" }, { "code": null, "e": 1762, "s": 1740, "text": "CSV file with headers" }, { "code": null, "e": 1876, "s": 1762, "text": "We see that headers have been added successfully and file has been converted from ‘.txt’ format to ‘.csv’ format." }, { "code": null, "e": 1978, "s": 1876, "text": "Example 3: In this example, the fields in the text file are separated by user defined delimiter “/”. " }, { "code": null, "e": 2002, "s": 1978, "text": "‘/’ Delimited Text File" }, { "code": null, "e": 2010, "s": 2002, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # reading the given csv file # and creating dataframeaccount = pd.read_csv(\"GeeksforGeeks.txt\", delimiter = '/') # store dataframe into csv fileaccount.to_csv('GeeksforGeeks.csv', index = None)", "e": 2287, "s": 2010, "text": null }, { "code": null, "e": 2295, "s": 2287, "text": "Output:" }, { "code": null, "e": 2304, "s": 2295, "text": "CSV File" }, { "code": null, "e": 2409, "s": 2304, "text": "While reading data we specify that data should be tokenized using specified delimiter. In this case ‘/’." }, { "code": null, "e": 2423, "s": 2409, "text": "Python-pandas" }, { "code": null, "e": 2430, "s": 2423, "text": "Python" }, { "code": null, "e": 2528, "s": 2430, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2560, "s": 2528, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2587, "s": 2560, "text": "Python Classes and Objects" }, { "code": null, "e": 2608, "s": 2587, "text": "Python OOPs Concepts" }, { "code": null, "e": 2631, "s": 2608, "text": "Introduction To PYTHON" }, { "code": null, "e": 2662, "s": 2631, "text": "Python | os.path.join() method" }, { "code": null, "e": 2718, "s": 2662, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2760, "s": 2718, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2802, "s": 2760, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2841, "s": 2802, "text": "Python | Get unique values from a list" } ]
Point Graph Series in Android
04 Feb, 2021 We have seen using a simple line graph and BarChart implementation in Android to represent data in the graphical format. Another graphical format for representing data is a point graph series. In this article, we will take a look at the implementation of the Point Graph Series in Android. We will be building a simple application in which we will be displaying sample data in a point graph view in Android. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New 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 dependency to build.gradle(Module:app) Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. implementation ‘com.jjoe64:graphview:4.2.2’ After adding the above dependency now sync your project and we will now move towards the implementation of our GraphView. Step 3: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--graph view to display our graph--> <com.jjoe64.graphview.GraphView android:id="@+id/idGraphView" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> Step 4: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import com.jjoe64.graphview.GraphView;import com.jjoe64.graphview.series.DataPoint;import com.jjoe64.graphview.series.PointsGraphSeries; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variable for graph view. GraphView graphView = findViewById(R.id.idGraphView); // on below line we are creating a new data // point series for our point graph series. // we are calling get data point method to add // data point to our point graph series. PointsGraphSeries<DataPoint> series = new PointsGraphSeries<>(getDataPoint()); // below line is to add series // to our graph view. graphView.addSeries(series); // below line is to activate // horizontal scrolling. graphView.getViewport().setScrollable(true); // below line is to activate horizontal // zooming and scrolling. graphView.getViewport().setScalable(true); // below line is to activate vertical and // horizontal zoom with scrolling. graphView.getViewport().setScalableY(true); // below line is to activate vertical scrolling. graphView.getViewport().setScrollableY(true); // below line is to set shape // for the point of graph view. series.setShape(PointsGraphSeries.Shape.TRIANGLE); // below line is to set // the size of our shape. series.setSize(12); // below line is to add color // to our shape of graph view. series.setColor(R.color.purple_200); } private DataPoint[] getDataPoint() { // creating a variable for data point. DataPoint[] dataPoints = new DataPoint[] { // on below line we are adding a new // data point to our Data Point class. new DataPoint(0, 1), new DataPoint(1, 2), new DataPoint(2, 3), new DataPoint(3, 5), new DataPoint(4, 1), new DataPoint(4, 3), new DataPoint(5, 3), new DataPoint(6, 2) }; // at last we are returning // the data point class. return dataPoints; }} Now run your app and see the output of the app. android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android 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": 28, "s": 0, "text": "\n04 Feb, 2021" }, { "code": null, "e": 319, "s": 28, "text": "We have seen using a simple line graph and BarChart implementation in Android to represent data in the graphical format. Another graphical format for representing data is a point graph series. In this article, we will take a look at the implementation of the Point Graph Series in Android. " }, { "code": null, "e": 604, "s": 319, "text": "We will be building a simple application in which we will be displaying sample data in a point graph view in Android. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 633, "s": 604, "text": "Step 1: Create a New Project" }, { "code": null, "e": 795, "s": 633, "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": 846, "s": 795, "text": "Step 2: Add dependency to build.gradle(Module:app)" }, { "code": null, "e": 966, "s": 846, "text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. " }, { "code": null, "e": 1010, "s": 966, "text": "implementation ‘com.jjoe64:graphview:4.2.2’" }, { "code": null, "e": 1134, "s": 1010, "text": "After adding the above dependency now sync your project and we will now move towards the implementation of our GraphView. " }, { "code": null, "e": 1182, "s": 1134, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 1325, "s": 1182, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 1329, "s": 1325, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--graph view to display our graph--> <com.jjoe64.graphview.GraphView android:id=\"@+id/idGraphView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </LinearLayout>", "e": 1868, "s": 1329, "text": null }, { "code": null, "e": 1916, "s": 1868, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 2106, "s": 1916, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 2111, "s": 2106, "text": "Java" }, { "code": "import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import com.jjoe64.graphview.GraphView;import com.jjoe64.graphview.series.DataPoint;import com.jjoe64.graphview.series.PointsGraphSeries; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variable for graph view. GraphView graphView = findViewById(R.id.idGraphView); // on below line we are creating a new data // point series for our point graph series. // we are calling get data point method to add // data point to our point graph series. PointsGraphSeries<DataPoint> series = new PointsGraphSeries<>(getDataPoint()); // below line is to add series // to our graph view. graphView.addSeries(series); // below line is to activate // horizontal scrolling. graphView.getViewport().setScrollable(true); // below line is to activate horizontal // zooming and scrolling. graphView.getViewport().setScalable(true); // below line is to activate vertical and // horizontal zoom with scrolling. graphView.getViewport().setScalableY(true); // below line is to activate vertical scrolling. graphView.getViewport().setScrollableY(true); // below line is to set shape // for the point of graph view. series.setShape(PointsGraphSeries.Shape.TRIANGLE); // below line is to set // the size of our shape. series.setSize(12); // below line is to add color // to our shape of graph view. series.setColor(R.color.purple_200); } private DataPoint[] getDataPoint() { // creating a variable for data point. DataPoint[] dataPoints = new DataPoint[] { // on below line we are adding a new // data point to our Data Point class. new DataPoint(0, 1), new DataPoint(1, 2), new DataPoint(2, 3), new DataPoint(3, 5), new DataPoint(4, 1), new DataPoint(4, 3), new DataPoint(5, 3), new DataPoint(6, 2) }; // at last we are returning // the data point class. return dataPoints; }}", "e": 4744, "s": 2111, "text": null }, { "code": null, "e": 4792, "s": 4744, "text": "Now run your app and see the output of the app." }, { "code": null, "e": 4800, "s": 4792, "text": "android" }, { "code": null, "e": 4824, "s": 4800, "text": "Technical Scripter 2020" }, { "code": null, "e": 4832, "s": 4824, "text": "Android" }, { "code": null, "e": 4837, "s": 4832, "text": "Java" }, { "code": null, "e": 4856, "s": 4837, "text": "Technical Scripter" }, { "code": null, "e": 4861, "s": 4856, "text": "Java" }, { "code": null, "e": 4869, "s": 4861, "text": "Android" }, { "code": null, "e": 4967, "s": 4869, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5036, "s": 4967, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 5068, "s": 5036, "text": "Android SDK and it's Components" }, { "code": null, "e": 5107, "s": 5068, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 5156, "s": 5107, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 5198, "s": 5156, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 5213, "s": 5198, "text": "Arrays in Java" }, { "code": null, "e": 5249, "s": 5213, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 5293, "s": 5249, "text": "Split() String method in Java with examples" }, { "code": null, "e": 5318, "s": 5293, "text": "Reverse a string in Java" } ]
Working with zcat, zmore and zless Command in Linux
10 Oct, 2021 Compression means to keep files together in an archive and to reduce the size of files. Gzip a.k.a. Gunzip is a command in Linux which is used to compress and decompress the files. So in case, you compressed a very large file with gzip and you just want to see what are the contents of the file. As in this case decompression of the file is going to take a lot of time, so in order to save time and view files without decompressing them “zcat” command is used. 1. To display contents of a Gzipped file. $zcat filename.gz This will print all the contents of the compressed file. Note: In this case the, name of file is filename.gz. 2. To display contents of multiple compressed files. $zcat file1.gz file2.gz It display contents of multiple files together. Note: In this case the, name of file is file1.gz and file2.gz. 3. To read compressed data even from a terminal and even it is compressed or not. $zcat -f filename.gz This displays the content of the file even if the content is binary or is in an encrypted form. Note: In this case the, name of file is filename.gz. 4. To paginate the output. $zless filename.gz $zmore filename.gz These are the commands used for paginating the output. Note: In this case the, name of file is filename.gz. 5. To get the properties of the compressed file. $zcat -l filename.gz This will display the properties of files like compressed and uncompressed ratio and uncompressed name etc. Note: In this case the, name of file is filename.gz. 6. To suppress all warnings. $zcat -q filename.gz This will suppress all the warnings that will occur in between the execution of the command. surindertarika1234 sooda367 linux-command Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples nohup Command in Linux with Examples chmod command in Linux with examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Oct, 2021" }, { "code": null, "e": 490, "s": 28, "text": "Compression means to keep files together in an archive and to reduce the size of files. Gzip a.k.a. Gunzip is a command in Linux which is used to compress and decompress the files. So in case, you compressed a very large file with gzip and you just want to see what are the contents of the file. As in this case decompression of the file is going to take a lot of time, so in order to save time and view files without decompressing them “zcat” command is used. " }, { "code": null, "e": 535, "s": 492, "text": "1. To display contents of a Gzipped file. " }, { "code": null, "e": 553, "s": 535, "text": "$zcat filename.gz" }, { "code": null, "e": 611, "s": 553, "text": "This will print all the contents of the compressed file. " }, { "code": null, "e": 665, "s": 611, "text": "Note: In this case the, name of file is filename.gz. " }, { "code": null, "e": 719, "s": 665, "text": "2. To display contents of multiple compressed files. " }, { "code": null, "e": 743, "s": 719, "text": "$zcat file1.gz file2.gz" }, { "code": null, "e": 792, "s": 743, "text": "It display contents of multiple files together. " }, { "code": null, "e": 856, "s": 792, "text": "Note: In this case the, name of file is file1.gz and file2.gz. " }, { "code": null, "e": 939, "s": 856, "text": "3. To read compressed data even from a terminal and even it is compressed or not. " }, { "code": null, "e": 960, "s": 939, "text": "$zcat -f filename.gz" }, { "code": null, "e": 1057, "s": 960, "text": "This displays the content of the file even if the content is binary or is in an encrypted form. " }, { "code": null, "e": 1111, "s": 1057, "text": "Note: In this case the, name of file is filename.gz. " }, { "code": null, "e": 1139, "s": 1111, "text": "4. To paginate the output. " }, { "code": null, "e": 1158, "s": 1139, "text": "$zless filename.gz" }, { "code": null, "e": 1177, "s": 1158, "text": "$zmore filename.gz" }, { "code": null, "e": 1233, "s": 1177, "text": "These are the commands used for paginating the output. " }, { "code": null, "e": 1287, "s": 1233, "text": "Note: In this case the, name of file is filename.gz. " }, { "code": null, "e": 1338, "s": 1287, "text": "5. To get the properties of the compressed file. " }, { "code": null, "e": 1359, "s": 1338, "text": "$zcat -l filename.gz" }, { "code": null, "e": 1468, "s": 1359, "text": "This will display the properties of files like compressed and uncompressed ratio and uncompressed name etc. " }, { "code": null, "e": 1522, "s": 1468, "text": "Note: In this case the, name of file is filename.gz. " }, { "code": null, "e": 1553, "s": 1522, "text": "6. To suppress all warnings. " }, { "code": null, "e": 1574, "s": 1553, "text": "$zcat -q filename.gz" }, { "code": null, "e": 1667, "s": 1574, "text": "This will suppress all the warnings that will occur in between the execution of the command." }, { "code": null, "e": 1686, "s": 1667, "text": "surindertarika1234" }, { "code": null, "e": 1695, "s": 1686, "text": "sooda367" }, { "code": null, "e": 1709, "s": 1695, "text": "linux-command" }, { "code": null, "e": 1720, "s": 1709, "text": "Linux-Unix" }, { "code": null, "e": 1818, "s": 1720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1844, "s": 1818, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1879, "s": 1844, "text": "scp command in Linux with Examples" }, { "code": null, "e": 1916, "s": 1879, "text": "chown command in Linux with Examples" }, { "code": null, "e": 1945, "s": 1916, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 1979, "s": 1945, "text": "mv command in Linux with examples" }, { "code": null, "e": 2016, "s": 1979, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 2053, "s": 2016, "text": "chmod command in Linux with examples" }, { "code": null, "e": 2092, "s": 2053, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 2132, "s": 2092, "text": "Array Basics in Shell Scripting | Set 1" } ]
How to catch IndentationError Exception in python?
A IndentationError occurs any time the parser finds source code that does not follow indentation rules. We can catch it when importing a module, since the module will be compiled on first import. You can't catch it in the same module that contains the try/except block, because with this exception, Python won't be able to finish compiling the module, and no code in the module will be run. We rewrite the given code as follows to handle the exception try: def f(): z=['foo','bar'] for i in z: if i == 'foo': except IndentationError as e: print e "C:/Users/TutorialsPoint1/~.py", line 5 if i == 'foo': ^ IndentationError: expected an indented block
[ { "code": null, "e": 1578, "s": 1187, "text": "A IndentationError occurs any time the parser finds source code that does not follow indentation rules. We can catch it when importing a module, since the module will be compiled on first import. You can't catch it in the same module that contains the try/except block, because with this exception, Python won't be able to finish compiling the module, and no code in the module will be run." }, { "code": null, "e": 1639, "s": 1578, "text": "We rewrite the given code as follows to handle the exception" }, { "code": null, "e": 1734, "s": 1639, "text": "try:\ndef f():\nz=['foo','bar']\nfor i in z:\nif i == 'foo':\nexcept IndentationError as e:\nprint e" }, { "code": null, "e": 1836, "s": 1734, "text": "\"C:/Users/TutorialsPoint1/~.py\", line 5\nif i == 'foo':\n^\nIndentationError: expected an indented block" } ]
Convert given Matrix into a Symmetric Matrix by replacing elements at (i, j) and (j, i) with their mean
07 Mar, 2022 Given an integer N and a N x N matrix, the task is to convert the given matrix into a symmetric matrix by replacing (i, j)th and (j, i)th element with their arithmetic mean. Examples: Input: arr[] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}Output: 1 3 53 5 75 7 9Explanation: The diagonal elements are same. The element at index (0, 1) = 2 and (1, 0) = 4 is replaced by their arithmetic mean i.e, (2 + 4) / 2 = 3. Similarly, the elements at index (2, 0) and (0, 2), (2, 1) and (1, 2) are also replaced by their arithmetic mean and the resulting output matrix is a symmetric matrix. Input: arr[] = {{12, 43, 65}, {23, 75, 13}, {51, 37, 81}}Output:12 33 5833 75 2558 25 81 Approach: The given problem is an implementation-based problem. The idea is to traverse the lower triangular matrix and replace the elements and their respective transpose indices with their arithmetic mean. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program of the above approach#include <iostream>using namespace std;const int N = 3; // Function to convert the given matrix// into a symmetric matrix by replacing// transpose elements with their meanvoid makeSymmetric(int mat[][N]){ // Loop to traverse lower triangular // elements of the given matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (j < i) { mat[i][j] = mat[j][i] = (mat[i][j] + mat[j][i]) / 2; } } }} // Function to print the given matrixvoid showMatrix(int mat[][N]){ // Loop to traverse the // given matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Print current index cout << mat[i][j] << " "; } cout << "\n"; }} // Driver Codeint main(){ int arr[][N] = { { 12, 43, 65 }, { 23, 75, 13 }, { 51, 37, 81 } }; makeSymmetric(arr); showMatrix(arr); return 0;} // Java program of the above approachimport java.util.*; class GFG{ static int N = 3; // Function to convert the given matrix// into a symmetric matrix by replacing// transpose elements with their meanstatic void makeSymmetric(int mat[][]){ // Loop to traverse lower triangular // elements of the given matrix for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { if (j < i) { mat[i][j] = mat[j][i] = (mat[i][j] + mat[j][i]) / 2; } } }} // Function to print the given matrixstatic void showMatrix(int mat[][]){ // Loop to traverse the // given matrix for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { // Print current index System.out.print(mat[i][j] + " "); } System.out.println(); }} // Driver Codepublic static void main(String args[]){ int arr[][] = { { 12, 43, 65 }, { 23, 75, 13 }, { 51, 37, 81 } }; makeSymmetric(arr); showMatrix(arr);}} // This code is contributed by sanjoy_62 # python3 program of the above approachN = 3 # Function to convert the given matrix# into a symmetric matrix by replacing# transpose elements with their meandef makeSymmetric(mat): # Loop to traverse lower triangular # elements of the given matrix for i in range(0, N): for j in range(0, N): if (j < i): mat[i][j] = mat[j][i] = (mat[i][j] + mat[j][i]) // 2 # Function to print the given matrixdef showMatrix(mat): # Loop to traverse the # given matrix for i in range(0, N): for j in range(0, N): # Print current index print(mat[i][j], end=" ") print() # Driver Codeif __name__ == "__main__": arr = [[12, 43, 65], [23, 75, 13], [51, 37, 81]] makeSymmetric(arr) showMatrix(arr) # This code is contributed by rakeshsahni // C# program of the above approachusing System;public class GFG{ static int N = 3; // Function to convert the given matrix // into a symmetric matrix by replacing // transpose elements with their mean static void makeSymmetric(int [,]mat) { // Loop to traverse lower triangular // elements of the given matrix for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { if (j < i) { mat[i,j] = mat[j,i] = (mat[i,j] + mat[j,i]) / 2; } } } } // Function to print the given matrix static void showMatrix(int [,]mat) { // Loop to traverse the // given matrix for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { // Print current index Console.Write(mat[i, j] + " "); } Console.WriteLine(); } } // Driver Code public static void Main(String []args) { int [,]arr = { { 12, 43, 65 }, { 23, 75, 13 }, { 51, 37, 81 } }; makeSymmetric(arr); showMatrix(arr); }}// This code is contributed by 29AjayKumar <script> // JavaScript code for the above approach let N = 3; // Function to convert the given matrix // into a symmetric matrix by replacing // transpose elements with their mean function makeSymmetric(mat) { // Loop to traverse lower triangular // elements of the given matrix for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { if (j < i) { mat[i][j] = mat[j][i] = Math.floor((mat[i][j] + mat[j][i]) / 2); } } } } // Function to print the given matrix function showMatrix(mat) { // Loop to traverse the // given matrix for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { // Print current index document.write(mat[i][j] + " "); } document.write('<br>') } } // Driver Code let arr = [[12, 43, 65], [23, 75, 13], [51, 37, 81]]; makeSymmetric(arr); showMatrix(arr); // This code is contributed by Potta Lokesh </script> 12 33 58 33 75 25 58 25 81 Time complexity: O(N2)Space complexity: O(1) sanjoy_62 lokeshpotta20 shikhasingrajput rakeshsahni nikhatkhan11 Algo-Geek 2021 maths-mean Algo Geek Mathematical Matrix Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Mar, 2022" }, { "code": null, "e": 228, "s": 54, "text": "Given an integer N and a N x N matrix, the task is to convert the given matrix into a symmetric matrix by replacing (i, j)th and (j, i)th element with their arithmetic mean." }, { "code": null, "e": 238, "s": 228, "text": "Examples:" }, { "code": null, "e": 674, "s": 238, "text": "Input: arr[] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}Output: 1 3 53 5 75 7 9Explanation: The diagonal elements are same. The element at index (0, 1) = 2 and (1, 0) = 4 is replaced by their arithmetic mean i.e, (2 + 4) / 2 = 3. Similarly, the elements at index (2, 0) and (0, 2), (2, 1) and (1, 2) are also replaced by their arithmetic mean and the resulting output matrix is a symmetric matrix." }, { "code": null, "e": 809, "s": 674, "text": "Input: arr[] = {{12, 43, 65}, {23, 75, 13}, {51, 37, 81}}Output:12 33 5833 75 2558 25 81" }, { "code": null, "e": 1018, "s": 809, "text": "Approach: The given problem is an implementation-based problem. The idea is to traverse the lower triangular matrix and replace the elements and their respective transpose indices with their arithmetic mean. " }, { "code": null, "e": 1069, "s": 1018, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1073, "s": 1069, "text": "C++" }, { "code": null, "e": 1078, "s": 1073, "text": "Java" }, { "code": null, "e": 1086, "s": 1078, "text": "Python3" }, { "code": null, "e": 1089, "s": 1086, "text": "C#" }, { "code": null, "e": 1100, "s": 1089, "text": "Javascript" }, { "code": "// C++ program of the above approach#include <iostream>using namespace std;const int N = 3; // Function to convert the given matrix// into a symmetric matrix by replacing// transpose elements with their meanvoid makeSymmetric(int mat[][N]){ // Loop to traverse lower triangular // elements of the given matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (j < i) { mat[i][j] = mat[j][i] = (mat[i][j] + mat[j][i]) / 2; } } }} // Function to print the given matrixvoid showMatrix(int mat[][N]){ // Loop to traverse the // given matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Print current index cout << mat[i][j] << \" \"; } cout << \"\\n\"; }} // Driver Codeint main(){ int arr[][N] = { { 12, 43, 65 }, { 23, 75, 13 }, { 51, 37, 81 } }; makeSymmetric(arr); showMatrix(arr); return 0;}", "e": 2123, "s": 1100, "text": null }, { "code": "// Java program of the above approachimport java.util.*; class GFG{ static int N = 3; // Function to convert the given matrix// into a symmetric matrix by replacing// transpose elements with their meanstatic void makeSymmetric(int mat[][]){ // Loop to traverse lower triangular // elements of the given matrix for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { if (j < i) { mat[i][j] = mat[j][i] = (mat[i][j] + mat[j][i]) / 2; } } }} // Function to print the given matrixstatic void showMatrix(int mat[][]){ // Loop to traverse the // given matrix for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { // Print current index System.out.print(mat[i][j] + \" \"); } System.out.println(); }} // Driver Codepublic static void main(String args[]){ int arr[][] = { { 12, 43, 65 }, { 23, 75, 13 }, { 51, 37, 81 } }; makeSymmetric(arr); showMatrix(arr);}} // This code is contributed by sanjoy_62", "e": 3281, "s": 2123, "text": null }, { "code": "# python3 program of the above approachN = 3 # Function to convert the given matrix# into a symmetric matrix by replacing# transpose elements with their meandef makeSymmetric(mat): # Loop to traverse lower triangular # elements of the given matrix for i in range(0, N): for j in range(0, N): if (j < i): mat[i][j] = mat[j][i] = (mat[i][j] + mat[j][i]) // 2 # Function to print the given matrixdef showMatrix(mat): # Loop to traverse the # given matrix for i in range(0, N): for j in range(0, N): # Print current index print(mat[i][j], end=\" \") print() # Driver Codeif __name__ == \"__main__\": arr = [[12, 43, 65], [23, 75, 13], [51, 37, 81]] makeSymmetric(arr) showMatrix(arr) # This code is contributed by rakeshsahni", "e": 4161, "s": 3281, "text": null }, { "code": "// C# program of the above approachusing System;public class GFG{ static int N = 3; // Function to convert the given matrix // into a symmetric matrix by replacing // transpose elements with their mean static void makeSymmetric(int [,]mat) { // Loop to traverse lower triangular // elements of the given matrix for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { if (j < i) { mat[i,j] = mat[j,i] = (mat[i,j] + mat[j,i]) / 2; } } } } // Function to print the given matrix static void showMatrix(int [,]mat) { // Loop to traverse the // given matrix for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { // Print current index Console.Write(mat[i, j] + \" \"); } Console.WriteLine(); } } // Driver Code public static void Main(String []args) { int [,]arr = { { 12, 43, 65 }, { 23, 75, 13 }, { 51, 37, 81 } }; makeSymmetric(arr); showMatrix(arr); }}// This code is contributed by 29AjayKumar", "e": 5265, "s": 4161, "text": null }, { "code": " <script> // JavaScript code for the above approach let N = 3; // Function to convert the given matrix // into a symmetric matrix by replacing // transpose elements with their mean function makeSymmetric(mat) { // Loop to traverse lower triangular // elements of the given matrix for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { if (j < i) { mat[i][j] = mat[j][i] = Math.floor((mat[i][j] + mat[j][i]) / 2); } } } } // Function to print the given matrix function showMatrix(mat) { // Loop to traverse the // given matrix for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { // Print current index document.write(mat[i][j] + \" \"); } document.write('<br>') } } // Driver Code let arr = [[12, 43, 65], [23, 75, 13], [51, 37, 81]]; makeSymmetric(arr); showMatrix(arr); // This code is contributed by Potta Lokesh </script>", "e": 6506, "s": 5265, "text": null }, { "code": null, "e": 6536, "s": 6506, "text": "12 33 58 \n33 75 25 \n58 25 81 " }, { "code": null, "e": 6581, "s": 6536, "text": "Time complexity: O(N2)Space complexity: O(1)" }, { "code": null, "e": 6593, "s": 6583, "text": "sanjoy_62" }, { "code": null, "e": 6607, "s": 6593, "text": "lokeshpotta20" }, { "code": null, "e": 6624, "s": 6607, "text": "shikhasingrajput" }, { "code": null, "e": 6636, "s": 6624, "text": "rakeshsahni" }, { "code": null, "e": 6649, "s": 6636, "text": "nikhatkhan11" }, { "code": null, "e": 6664, "s": 6649, "text": "Algo-Geek 2021" }, { "code": null, "e": 6675, "s": 6664, "text": "maths-mean" }, { "code": null, "e": 6685, "s": 6675, "text": "Algo Geek" }, { "code": null, "e": 6698, "s": 6685, "text": "Mathematical" }, { "code": null, "e": 6705, "s": 6698, "text": "Matrix" }, { "code": null, "e": 6718, "s": 6705, "text": "Mathematical" }, { "code": null, "e": 6725, "s": 6718, "text": "Matrix" } ]
Major Applications of Data Science
12 Mar, 2021 Data Science is the deep study of a large quantity of data, which involves extracting some meaningful from the raw, structured, and unstructured data. The extracting out meaningful data from large amounts use processing of data and this processing can be done using statistical techniques and algorithm, scientific techniques, different technologies, etc. It uses various tools and techniques to extract meaningful data from raw data. Data Science is also known as the Future of Artificial Intelligence. For Example, Jagroop loves books to read but every time when he wants to buy some books he was always confused that which book he should buy as there are plenty of choices in front of him. This Data Science Technique will useful. When he opens Amazon he will get product recommendations on the basis of his previous data. When he chooses one of them he also gets a recommendation to buy these books with this one as this set is mostly bought. So all Recommendation of Products and Showing set of books purchased collectively is one of the examples of Data Science. The most useful application of Data Science is Search Engines. As we know when we want to search for something on the internet, we mostly used Search engines like Google, Yahoo, Safari, Firefox, etc. So Data Science is used to get Searches faster. For Example, When we search something suppose “Data Structure and algorithm courses ” then at that time on the Internet Explorer we get the first link of GeeksforGeeks Courses. This happens because the GeeksforGeeks website is visited most in order to get information regarding Data Structure courses and Computer related subjects. So this analysis is Done using Data Science, and we get the Topmost visited Web Links. Data Science also entered into the Transport field like Driverless Cars. With the help of Driverless Cars, it is easy to reduce the number of Accidents. For Example, In Driverless Cars the training data is fed into the algorithm and with the help of Data Science techniques, the Data is analyzed like what is the speed limit in Highway, Busy Streets, Narrow Roads, etc. And how to handle different situations while driving etc. Data Science plays a key role in Financial Industries. Financial Industries always have an issue of fraud and risk of losses. Thus, Financial Industries needs to automate risk of loss analysis in order to carry out strategic decisions for the company. Also, Financial Industries uses Data Science Analytics tools in order to predict the future. It allows the companies to predict customer lifetime value and their stock market moves. For Example, In Stock Market, Data Science is the main part. In the Stock Market, Data Science is used to examine past behavior with past data and their goal is to examine the future outcome. Data is analyzed in such a way that it makes it possible to predict future stock prices over a set timetable. E-Commerce Websites like Amazon, Flipkart, etc. uses data Science to make a better user experience with personalized recommendations. For Example, When we search for something on the E-commerce websites we get suggestions similar to choices according to our past data and also we get recommendations according to most buy the product, most rated, most searched, etc. This is all done with the help of Data Science. In the Healthcare Industry data science act as a boon. Data Science is used for: Detecting Tumor. Drug discoveries. Medical Image Analysis. Virtual Medical Bots. Genetics and Genomics. Predictive Modeling for Diagnosis etc. Currently, Data Science is also used in Image Recognition. For Example, When we upload our image with our friend on Facebook, Facebook gives suggestions Tagging who is in the picture. This is done with the help of machine learning and Data Science. When an Image is Recognized, the data analysis is done on one’s Facebook friends and after analysis, if the faces which are present in the picture matched with someone else profile then Facebook suggests us auto-tagging. Targeting Recommendation is the most important application of Data Science. Whatever the user searches on the Internet, he/she will see numerous posts everywhere. This can be explained properly with an example: Suppose I want a mobile phone, so I just Google search it and after that, I changed my mind to buy offline. Data Science helps those companies who are paying for Advertisements for their mobile. So everywhere on the internet in the social media, in the websites, in the apps everywhere I will see the recommendation of that mobile phone which I searched for. So this will force me to buy online. With the help of Data Science, Airline Sector is also growing like with the help of it, it becomes easy to predict flight delays. It also helps to decide whether to directly land into the destination or take a halt in between like a flight can have a direct route from Delhi to the U.S.A or it can halt in between after that reach at the destination. In most of the games where a user will play with an opponent i.e. a Computer Opponent, data science concepts are used with machine learning where with the help of past data the Computer will improve its performance. There are many games like Chess, EA Sports, etc. will use Data Science concepts. The process of creating medicine is very difficult and time-consuming and has to be done with full disciplined because it is a matter of Someone’s life. Without Data Science, it takes lots of time, resources, and finance or developing new Medicine or drug but with the help of Data Science, it becomes easy because the prediction of success rate can be easily determined based on biological data or factors. The algorithms based on data science will forecast how this will react to the human body without lab experiments. Various Logistics companies like DHL, FedEx, etc. make use of Data Science. Data Science helps these companies to find the best route for the Shipment of their Products, the best time suited for delivery, the best mode of transport to reach the destination, etc. AutoComplete feature is an important part of Data Science where the user will get the facility to just type a few letters or words, and he will get the feature of auto-completing the line. In Google Mail, when we are writing formal mail to someone so at that time data science concept of Autocomplete feature is used where he/she is an efficient choice to auto-complete the whole line. Also in Search Engines in social media, in various apps, AutoComplete feature is widely used. data-science Technical Scripter 2020 GBlog Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge What is Hashing | A Complete Tutorial GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa How to Learn Data Science in 10 weeks? Roadmap to Learn JavaScript For Beginners What is Data Structure: Types, Classifications and Applications How To Switch From A Service-Based To A Product-Based Company? Axios in React: A Guide for Beginners
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Mar, 2021" }, { "code": null, "e": 532, "s": 28, "text": "Data Science is the deep study of a large quantity of data, which involves extracting some meaningful from the raw, structured, and unstructured data. The extracting out meaningful data from large amounts use processing of data and this processing can be done using statistical techniques and algorithm, scientific techniques, different technologies, etc. It uses various tools and techniques to extract meaningful data from raw data. Data Science is also known as the Future of Artificial Intelligence." }, { "code": null, "e": 1097, "s": 532, "text": "For Example, Jagroop loves books to read but every time when he wants to buy some books he was always confused that which book he should buy as there are plenty of choices in front of him. This Data Science Technique will useful. When he opens Amazon he will get product recommendations on the basis of his previous data. When he chooses one of them he also gets a recommendation to buy these books with this one as this set is mostly bought. So all Recommendation of Products and Showing set of books purchased collectively is one of the examples of Data Science." }, { "code": null, "e": 1345, "s": 1097, "text": "The most useful application of Data Science is Search Engines. As we know when we want to search for something on the internet, we mostly used Search engines like Google, Yahoo, Safari, Firefox, etc. So Data Science is used to get Searches faster." }, { "code": null, "e": 1764, "s": 1345, "text": "For Example, When we search something suppose “Data Structure and algorithm courses ” then at that time on the Internet Explorer we get the first link of GeeksforGeeks Courses. This happens because the GeeksforGeeks website is visited most in order to get information regarding Data Structure courses and Computer related subjects. So this analysis is Done using Data Science, and we get the Topmost visited Web Links." }, { "code": null, "e": 1917, "s": 1764, "text": "Data Science also entered into the Transport field like Driverless Cars. With the help of Driverless Cars, it is easy to reduce the number of Accidents." }, { "code": null, "e": 2192, "s": 1917, "text": "For Example, In Driverless Cars the training data is fed into the algorithm and with the help of Data Science techniques, the Data is analyzed like what is the speed limit in Highway, Busy Streets, Narrow Roads, etc. And how to handle different situations while driving etc." }, { "code": null, "e": 2627, "s": 2192, "text": "Data Science plays a key role in Financial Industries. Financial Industries always have an issue of fraud and risk of losses. Thus, Financial Industries needs to automate risk of loss analysis in order to carry out strategic decisions for the company. Also, Financial Industries uses Data Science Analytics tools in order to predict the future. It allows the companies to predict customer lifetime value and their stock market moves. " }, { "code": null, "e": 2929, "s": 2627, "text": "For Example, In Stock Market, Data Science is the main part. In the Stock Market, Data Science is used to examine past behavior with past data and their goal is to examine the future outcome. Data is analyzed in such a way that it makes it possible to predict future stock prices over a set timetable." }, { "code": null, "e": 3063, "s": 2929, "text": "E-Commerce Websites like Amazon, Flipkart, etc. uses data Science to make a better user experience with personalized recommendations." }, { "code": null, "e": 3344, "s": 3063, "text": "For Example, When we search for something on the E-commerce websites we get suggestions similar to choices according to our past data and also we get recommendations according to most buy the product, most rated, most searched, etc. This is all done with the help of Data Science." }, { "code": null, "e": 3425, "s": 3344, "text": "In the Healthcare Industry data science act as a boon. Data Science is used for:" }, { "code": null, "e": 3442, "s": 3425, "text": "Detecting Tumor." }, { "code": null, "e": 3460, "s": 3442, "text": "Drug discoveries." }, { "code": null, "e": 3484, "s": 3460, "text": "Medical Image Analysis." }, { "code": null, "e": 3506, "s": 3484, "text": "Virtual Medical Bots." }, { "code": null, "e": 3529, "s": 3506, "text": "Genetics and Genomics." }, { "code": null, "e": 3568, "s": 3529, "text": "Predictive Modeling for Diagnosis etc." }, { "code": null, "e": 4040, "s": 3568, "text": "Currently, Data Science is also used in Image Recognition. For Example, When we upload our image with our friend on Facebook, Facebook gives suggestions Tagging who is in the picture. This is done with the help of machine learning and Data Science. When an Image is Recognized, the data analysis is done on one’s Facebook friends and after analysis, if the faces which are present in the picture matched with someone else profile then Facebook suggests us auto-tagging. " }, { "code": null, "e": 4647, "s": 4040, "text": "Targeting Recommendation is the most important application of Data Science. Whatever the user searches on the Internet, he/she will see numerous posts everywhere. This can be explained properly with an example: Suppose I want a mobile phone, so I just Google search it and after that, I changed my mind to buy offline. Data Science helps those companies who are paying for Advertisements for their mobile. So everywhere on the internet in the social media, in the websites, in the apps everywhere I will see the recommendation of that mobile phone which I searched for. So this will force me to buy online." }, { "code": null, "e": 4998, "s": 4647, "text": "With the help of Data Science, Airline Sector is also growing like with the help of it, it becomes easy to predict flight delays. It also helps to decide whether to directly land into the destination or take a halt in between like a flight can have a direct route from Delhi to the U.S.A or it can halt in between after that reach at the destination." }, { "code": null, "e": 5295, "s": 4998, "text": "In most of the games where a user will play with an opponent i.e. a Computer Opponent, data science concepts are used with machine learning where with the help of past data the Computer will improve its performance. There are many games like Chess, EA Sports, etc. will use Data Science concepts." }, { "code": null, "e": 5817, "s": 5295, "text": "The process of creating medicine is very difficult and time-consuming and has to be done with full disciplined because it is a matter of Someone’s life. Without Data Science, it takes lots of time, resources, and finance or developing new Medicine or drug but with the help of Data Science, it becomes easy because the prediction of success rate can be easily determined based on biological data or factors. The algorithms based on data science will forecast how this will react to the human body without lab experiments." }, { "code": null, "e": 6080, "s": 5817, "text": "Various Logistics companies like DHL, FedEx, etc. make use of Data Science. Data Science helps these companies to find the best route for the Shipment of their Products, the best time suited for delivery, the best mode of transport to reach the destination, etc." }, { "code": null, "e": 6561, "s": 6080, "text": "AutoComplete feature is an important part of Data Science where the user will get the facility to just type a few letters or words, and he will get the feature of auto-completing the line. In Google Mail, when we are writing formal mail to someone so at that time data science concept of Autocomplete feature is used where he/she is an efficient choice to auto-complete the whole line. Also in Search Engines in social media, in various apps, AutoComplete feature is widely used." }, { "code": null, "e": 6574, "s": 6561, "text": "data-science" }, { "code": null, "e": 6598, "s": 6574, "text": "Technical Scripter 2020" }, { "code": null, "e": 6604, "s": 6598, "text": "GBlog" }, { "code": null, "e": 6623, "s": 6604, "text": "Technical Scripter" }, { "code": null, "e": 6721, "s": 6623, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6776, "s": 6721, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 6813, "s": 6776, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 6851, "s": 6813, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 6917, "s": 6851, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 6988, "s": 6917, "text": "GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa" }, { "code": null, "e": 7027, "s": 6988, "text": "How to Learn Data Science in 10 weeks?" }, { "code": null, "e": 7069, "s": 7027, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 7133, "s": 7069, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7196, "s": 7133, "text": "How To Switch From A Service-Based To A Product-Based Company?" } ]
How Bitcoin Transaction Works?
21 Sep, 2021 Bitcoin is basically a digital currency that is currently used as a form of payment. Bitcoin is a cryptocurrency and the transactions related to bitcoins take place in the blockchain network. Every bitcoin is stored in a virtual wallet and transaction involves the transfer of bitcoin from one wallet to another. Bitcoins can be sent from peer to peer irrespective of geographical location without any intermediator in between(for example bank per se). it works in a decentralized way, meaning nobody can interfere with your digital money, only you are responsible for your bitcoins. Bitcoin transaction means sending bitcoin from one person to the other in the secured blockchain network. These are messages that are digitally signed using cryptography and are verified by the miners that are present in the blockchain network. The miner is the person who solves mathematical puzzles(also called proof of work) to validate the transaction. Anyone with mining hardware and high processing power can take part in this. Numerous miners take part simultaneously to solve the complex mathematical puzzle, the one who solves it first, wins 12.5 bitcoin as a reward. miner verifies the transactions(after solving the puzzle) and then adds the block to the blockchain when confirmed. The transaction input is the bitcoin address from which the money was sent, and the transaction output is the bitcoin address to which the money was sent. Generally, a bitcoin transaction takes 10 to 20 minutes to confirm any transactions. if network congestion takes place, then time might take even 60 minutes. Example: Suppose Hari wants to send 5 BTC(bitcoins) to Senorita. Input- It consists of the bitcoin address from which hari got his bitcoins previously. Amount- This deals the specific amount of money that hari wishes to send to senorita, in this case, its 5BTC. Output- This is the bitcoin address of senorita which hari needs to know in order to transfer the bitcoins to her wallet. Bitcoin address of senorita is also known as public key. The transaction rate or speed is dependent on the amount the user pays for it. If a user pays a small amount, the transaction rate will be slow, the transaction will take more time to happen, vice versa is applicable here. Due to limited space, only a limited number of transactions are possible at one point in time.Consider a case where heavy network traffic occurs, then the miners prioritize those transactions that have the highest fees so that even in the hectic congestion, the highest-paid transaction gets executed.Many bitcoin wallets allow users to set transaction fees manually. The fees are directly sent to the miners. When the bitcoin hits a bull run, the transaction fees shoot up to an all-time high. there is no such minimum transaction fee a user must pay, but the highest transaction fees mainly lie between $24 to $31. as the highest-paid transaction gets confirmed first, therefore the fees tend to fluctuate based on the demand of the user. Time is taken for transaction confirmation mainly depends on two factors: Transaction fees: As discussed above, if the user pays minimal transaction fees, then the time taken for confirmation of a particular transaction would take a longer time. the mining process needs significant technology and efforts, therefore the importance of transaction fees comes into play. Network load: Every transaction gets stored temporarily in the memory pool till the miners confirm it. When the transaction activities reach a certain high threshold, the memory pool gets jammed thereby slowing the confirmation time of the transaction even more. Due to this, all the subsequent transactions become susceptible to delay. Sending or exchanging bitcoins undergoes lots of procedures underneath. The bitcoin wallet and the network ensures that the digital currency reaches the receiver properly. There are two basic terminologies related to this- Public key: Also known as a bitcoin address, these are publicly known to all like your username in social media handles. In order to receive bitcoins, the user must share his public key with the other user. Private key: These are kept secret and must not be shared with anyone, similar to the user’s password of social media accounts. Private keys are the most important thing in the whole cryptocurrency concept. The private key allows the user to have access to bitcoins, if the user forgets the private keys, there’s no way to recover the bitcoins or the private key. Therefore, it is advised to make a proper backup of the private key in a safe place. Transaction input is nothing but the address of the sender which gets registered in the network and remains in an encrypted and inaccessible state. Transaction output is the receiver’s address which is registered on the bitcoin network. In the previous example, Hari opens his bitcoin account and signs a transaction detail with his private key, and then broadcasted to a bitcoin network called blockchain, where miners compete with each other to find a hash value called nonce which solves the mathematical puzzle thereby verifying the transaction. The miners create new blocks by abiding by the fact that the transaction volume must be less than 21 million. 21 million is the total number of bitcoins that can be generated. The verified transaction gets a unique identification code and is linked with the previous verified transaction. In the bitcoin network, every transaction is traceable via linked blocks. Anyone can understand who sent it to who at any point in time. thus, bitcoin works in a transparent manner There are mainly three types of bitcoin addresses: P2PKH addresses: These addresses start with number 1. For example 1WX23.P2SH addresses: These addresses start with number 2. For example 2WX23.Bech32 addresses: These addresses start with bc1. For example bc12WX23. P2PKH addresses: These addresses start with number 1. For example 1WX23. P2SH addresses: These addresses start with number 2. For example 2WX23. Bech32 addresses: These addresses start with bc1. For example bc12WX23. An internal transaction is a transaction that doesn’t come under any external third party.it works inside the internal function of business thereby doesn’t exchange any sort of resources. Internal transaction doesn’t have any impact on the cash flow as it deals only with interdepartmental transactions. An External transaction is a transaction that comes under any external third party.it basically is an exchange medium between an internal organization and a third party. Since it involves exchange with third parties, it has a huge impact on the cash flow. In order to send or receive bitcoins, one must possess a bitcoin wallet application. After installing the bitcoin wallet app, select the type of currency you want to send. For example ethereum, bitcoin, etc. Write in the receiver’s address. Type the amount of bitcoin you wish to send. Pay the required transaction fee. Press the “send bitcoin” button and the cryptocurrency will be transferred. In order to receive bitcoins, do the following steps: Open the wallet and click receive. Share the public key address. It can be a QR code or a combination of numbers and letters. Anyone with a public address can send the cryptocurrency. pradiptamukherjee Picked Blockchain Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect ReactJS with MetaMask ? Solidity - While, Do-While, and For Loop Solidity - Libraries Solidity - Variables Hyperledger Fabric in Blockchain Solidity - Functions How to Setup Your Own Private Ethereum Network? Solidity - Error Handling Blockchain - Hyperledger vs Ethereum Difference between Public and Private blockchain
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Sep, 2021" }, { "code": null, "e": 612, "s": 28, "text": "Bitcoin is basically a digital currency that is currently used as a form of payment. Bitcoin is a cryptocurrency and the transactions related to bitcoins take place in the blockchain network. Every bitcoin is stored in a virtual wallet and transaction involves the transfer of bitcoin from one wallet to another. Bitcoins can be sent from peer to peer irrespective of geographical location without any intermediator in between(for example bank per se). it works in a decentralized way, meaning nobody can interfere with your digital money, only you are responsible for your bitcoins." }, { "code": null, "e": 1619, "s": 612, "text": "Bitcoin transaction means sending bitcoin from one person to the other in the secured blockchain network. These are messages that are digitally signed using cryptography and are verified by the miners that are present in the blockchain network. The miner is the person who solves mathematical puzzles(also called proof of work) to validate the transaction. Anyone with mining hardware and high processing power can take part in this. Numerous miners take part simultaneously to solve the complex mathematical puzzle, the one who solves it first, wins 12.5 bitcoin as a reward. miner verifies the transactions(after solving the puzzle) and then adds the block to the blockchain when confirmed. The transaction input is the bitcoin address from which the money was sent, and the transaction output is the bitcoin address to which the money was sent. Generally, a bitcoin transaction takes 10 to 20 minutes to confirm any transactions. if network congestion takes place, then time might take even 60 minutes." }, { "code": null, "e": 1684, "s": 1619, "text": "Example: Suppose Hari wants to send 5 BTC(bitcoins) to Senorita." }, { "code": null, "e": 2098, "s": 1684, "text": "Input- It consists of the bitcoin address from which hari got his bitcoins previously.\n\nAmount- This deals the specific amount of money that hari wishes to send to senorita, \n in this case, its 5BTC.\n \nOutput- This is the bitcoin address of senorita which hari needs to know in order to \n transfer the bitcoins to her wallet. Bitcoin address of senorita is also known\n as public key." }, { "code": null, "e": 3062, "s": 2098, "text": "The transaction rate or speed is dependent on the amount the user pays for it. If a user pays a small amount, the transaction rate will be slow, the transaction will take more time to happen, vice versa is applicable here. Due to limited space, only a limited number of transactions are possible at one point in time.Consider a case where heavy network traffic occurs, then the miners prioritize those transactions that have the highest fees so that even in the hectic congestion, the highest-paid transaction gets executed.Many bitcoin wallets allow users to set transaction fees manually. The fees are directly sent to the miners. When the bitcoin hits a bull run, the transaction fees shoot up to an all-time high. there is no such minimum transaction fee a user must pay, but the highest transaction fees mainly lie between $24 to $31. as the highest-paid transaction gets confirmed first, therefore the fees tend to fluctuate based on the demand of the user." }, { "code": null, "e": 3136, "s": 3062, "text": "Time is taken for transaction confirmation mainly depends on two factors:" }, { "code": null, "e": 3431, "s": 3136, "text": "Transaction fees: As discussed above, if the user pays minimal transaction fees, then the time taken for confirmation of a particular transaction would take a longer time. the mining process needs significant technology and efforts, therefore the importance of transaction fees comes into play." }, { "code": null, "e": 3768, "s": 3431, "text": "Network load: Every transaction gets stored temporarily in the memory pool till the miners confirm it. When the transaction activities reach a certain high threshold, the memory pool gets jammed thereby slowing the confirmation time of the transaction even more. Due to this, all the subsequent transactions become susceptible to delay." }, { "code": null, "e": 3991, "s": 3768, "text": "Sending or exchanging bitcoins undergoes lots of procedures underneath. The bitcoin wallet and the network ensures that the digital currency reaches the receiver properly. There are two basic terminologies related to this-" }, { "code": null, "e": 4198, "s": 3991, "text": "Public key: Also known as a bitcoin address, these are publicly known to all like your username in social media handles. In order to receive bitcoins, the user must share his public key with the other user." }, { "code": null, "e": 4647, "s": 4198, "text": "Private key: These are kept secret and must not be shared with anyone, similar to the user’s password of social media accounts. Private keys are the most important thing in the whole cryptocurrency concept. The private key allows the user to have access to bitcoins, if the user forgets the private keys, there’s no way to recover the bitcoins or the private key. Therefore, it is advised to make a proper backup of the private key in a safe place." }, { "code": null, "e": 5486, "s": 4647, "text": "Transaction input is nothing but the address of the sender which gets registered in the network and remains in an encrypted and inaccessible state. Transaction output is the receiver’s address which is registered on the bitcoin network. In the previous example, Hari opens his bitcoin account and signs a transaction detail with his private key, and then broadcasted to a bitcoin network called blockchain, where miners compete with each other to find a hash value called nonce which solves the mathematical puzzle thereby verifying the transaction. The miners create new blocks by abiding by the fact that the transaction volume must be less than 21 million. 21 million is the total number of bitcoins that can be generated. The verified transaction gets a unique identification code and is linked with the previous verified transaction." }, { "code": null, "e": 5667, "s": 5486, "text": "In the bitcoin network, every transaction is traceable via linked blocks. Anyone can understand who sent it to who at any point in time. thus, bitcoin works in a transparent manner" }, { "code": null, "e": 5718, "s": 5667, "text": "There are mainly three types of bitcoin addresses:" }, { "code": null, "e": 5934, "s": 5718, "text": "P2PKH addresses: These addresses start with number 1. For example 1WX23.P2SH addresses: These addresses start with number 2. For example 2WX23.Bech32 addresses: These addresses start with bc1. For example bc12WX23." }, { "code": null, "e": 6007, "s": 5934, "text": "P2PKH addresses: These addresses start with number 1. For example 1WX23." }, { "code": null, "e": 6079, "s": 6007, "text": "P2SH addresses: These addresses start with number 2. For example 2WX23." }, { "code": null, "e": 6152, "s": 6079, "text": "Bech32 addresses: These addresses start with bc1. For example bc12WX23." }, { "code": null, "e": 6456, "s": 6152, "text": "An internal transaction is a transaction that doesn’t come under any external third party.it works inside the internal function of business thereby doesn’t exchange any sort of resources. Internal transaction doesn’t have any impact on the cash flow as it deals only with interdepartmental transactions." }, { "code": null, "e": 6712, "s": 6456, "text": "An External transaction is a transaction that comes under any external third party.it basically is an exchange medium between an internal organization and a third party. Since it involves exchange with third parties, it has a huge impact on the cash flow." }, { "code": null, "e": 6797, "s": 6712, "text": "In order to send or receive bitcoins, one must possess a bitcoin wallet application." }, { "code": null, "e": 6920, "s": 6797, "text": "After installing the bitcoin wallet app, select the type of currency you want to send. For example ethereum, bitcoin, etc." }, { "code": null, "e": 6953, "s": 6920, "text": "Write in the receiver’s address." }, { "code": null, "e": 6998, "s": 6953, "text": "Type the amount of bitcoin you wish to send." }, { "code": null, "e": 7032, "s": 6998, "text": "Pay the required transaction fee." }, { "code": null, "e": 7108, "s": 7032, "text": "Press the “send bitcoin” button and the cryptocurrency will be transferred." }, { "code": null, "e": 7162, "s": 7108, "text": "In order to receive bitcoins, do the following steps:" }, { "code": null, "e": 7197, "s": 7162, "text": "Open the wallet and click receive." }, { "code": null, "e": 7288, "s": 7197, "text": "Share the public key address. It can be a QR code or a combination of numbers and letters." }, { "code": null, "e": 7346, "s": 7288, "text": "Anyone with a public address can send the cryptocurrency." }, { "code": null, "e": 7364, "s": 7346, "text": "pradiptamukherjee" }, { "code": null, "e": 7371, "s": 7364, "text": "Picked" }, { "code": null, "e": 7382, "s": 7371, "text": "Blockchain" }, { "code": null, "e": 7480, "s": 7382, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7519, "s": 7480, "text": "How to connect ReactJS with MetaMask ?" }, { "code": null, "e": 7560, "s": 7519, "text": "Solidity - While, Do-While, and For Loop" }, { "code": null, "e": 7581, "s": 7560, "text": "Solidity - Libraries" }, { "code": null, "e": 7602, "s": 7581, "text": "Solidity - Variables" }, { "code": null, "e": 7635, "s": 7602, "text": "Hyperledger Fabric in Blockchain" }, { "code": null, "e": 7656, "s": 7635, "text": "Solidity - Functions" }, { "code": null, "e": 7704, "s": 7656, "text": "How to Setup Your Own Private Ethereum Network?" }, { "code": null, "e": 7730, "s": 7704, "text": "Solidity - Error Handling" }, { "code": null, "e": 7767, "s": 7730, "text": "Blockchain - Hyperledger vs Ethereum" } ]
Python | Real time weather detection using Tkinter
10 Jun, 2021 Prerequisites : Introduction to tkinter | Find current weather of any cityPython offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Now, it’s upto the imagination or necessity of developer, what he/she want to develop using this toolkit.To create a tkinter : Importing the module – tkinter Create the main window (container) Add any number of widgets to the main window. Apply the event Trigger on the widgets. Let’s create a GUI based simple Real-time Weather detection application which can give Weather details of any cities.Modules required: tkinter requests json Below is the implementation : Python3 # import all functions from the tkinter from tkinter import * from tkinter import messagebox # function to find weather details# of any city using openweathermap apidef tell_weather() : # import required modules import requests, json # enter your api key here api_key = "Your_API_key" # base_url variable to store url base_url = "http://api.openweathermap.org/data/2.5/weather?" # take a city name from city_field entry box city_name = city_field.get() # complete_url variable to store complete url address complete_url = base_url + "appid =" + api_key + "&q =" + city_name # get method of requests module # return response object response = requests.get(complete_url) # json method of response object convert # json format data into python format data x = response.json() # now x contains list of nested dictionaries # we know dictionary contains key value pair # check the value of "cod" key is equal to "404" # or not if not that means city is found # otherwise city is not found if x["cod"] != "404" : # store the value of "main" key in variable y y = x["main"] # store the value corresponding to the "temp" key of y current_temperature = y["temp"] # store the value corresponding to the "pressure" key of y current_pressure = y["pressure"] # store the value corresponding to the "humidity" key of y current_humidity = y["humidity"] # store the value of "weather" key in variable z z = x["weather"] # store the value corresponding to the "description" key # at the 0th index of z weather_description = z[0]["description"] # insert method inserting the # value in the text entry box. temp_field.insert(15, str(current_temperature) + " Kelvin") atm_field.insert(10, str(current_pressure) + " hPa") humid_field.insert(15, str(current_humidiy) + " %") desc_field.insert(10, str(weather_description) ) # if city is not found else : # message dialog box appear which # shows given Error message messagebox.showerror("Error", "City Not Found \n" "Please enter valid city name") # clear the content of city_field entry box city_field.delete(0, END) # Function for clearing the# contents of all text entry boxes def clear_all() : city_field.delete(0, END) temp_field.delete(0, END) atm_field.delete(0, END) humid_field.delete(0, END) desc_field.delete(0, END) # set focus on the city_field entry box city_field.focus_set() # Driver codeif __name__ == "__main__" : # Create a GUI window root = Tk() # set the name of tkinter GUI window root.title("Gui Application") # Set the background colour of GUI window root.configure(background = "light green") # Set the configuration of GUI window root.geometry("425x175") # Create a Weather Gui Application label headlabel = Label(root, text = "Weather Gui Application", fg = 'black', bg = 'red') # Create a City name : label label1 = Label(root, text = "City name : ", fg = 'black', bg = 'dark green') # Create a City name : label label2 = Label(root, text = "Temperature :", fg = 'black', bg = 'dark green') # Create a atm pressure : label label3 = Label(root, text = "atm pressure :", fg = 'black', bg = 'dark green') # Create a humidity : label label4 = Label(root, text = "humidity :", fg = 'black', bg = 'dark green') # Create a description :label label5 = Label(root, text = "description :", fg = 'black', bg = 'dark green') # grid method is used for placing # the widgets at respective positions # in table like structure . headlabel.grid(row = 0, column = 1) label1.grid(row = 1, column = 0, sticky ="E") label2.grid(row = 3, column = 0, sticky ="E") label3.grid(row = 4, column = 0, sticky ="E") label4.grid(row = 5, column = 0, sticky ="E") label5.grid(row = 6, column = 0, sticky ="E") # Create a text entry box # for filling or typing the information. city_field = Entry(root) temp_field = Entry(root) atm_field = Entry(root) humid_field = Entry(root) desc_field = Entry(root) # grid method is used for placing # the widgets at respective positions # in table like structure . # ipadx keyword argument set width of entry space . city_field.grid(row = 1, column = 1, ipadx ="100") temp_field.grid(row = 3, column = 1, ipadx ="100") atm_field.grid(row = 4, column = 1, ipadx ="100") humid_field.grid(row = 5, column = 1, ipadx ="100") desc_field.grid(row = 6, column = 1, ipadx ="100") # Create a Submit Button and attached # to tell_weather function button1 = Button(root, text = "Submit", bg = "red", fg = "black", command = tell_weather) # Create a Clear Button and attached # to clear_all function button2 = Button(root, text = "Clear", bg = "red", fg = "black", command = clear_all) # grid method is used for placing # the widgets at respective positions # in table like structure . button1.grid(row = 2, column = 1) button2.grid(row = 7, column = 1) # Start the GUI root.mainloop() Output : simmytarika5 surinderdawra388 python-utility Technical Scripter 2018 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Jun, 2021" }, { "code": null, "e": 568, "s": 52, "text": "Prerequisites : Introduction to tkinter | Find current weather of any cityPython offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Now, it’s upto the imagination or necessity of developer, what he/she want to develop using this toolkit.To create a tkinter : " }, { "code": null, "e": 599, "s": 568, "text": "Importing the module – tkinter" }, { "code": null, "e": 634, "s": 599, "text": "Create the main window (container)" }, { "code": null, "e": 680, "s": 634, "text": "Add any number of widgets to the main window." }, { "code": null, "e": 720, "s": 680, "text": "Apply the event Trigger on the widgets." }, { "code": null, "e": 857, "s": 720, "text": "Let’s create a GUI based simple Real-time Weather detection application which can give Weather details of any cities.Modules required: " }, { "code": null, "e": 879, "s": 857, "text": "tkinter\nrequests\njson" }, { "code": null, "e": 911, "s": 879, "text": "Below is the implementation : " }, { "code": null, "e": 919, "s": 911, "text": "Python3" }, { "code": "# import all functions from the tkinter from tkinter import * from tkinter import messagebox # function to find weather details# of any city using openweathermap apidef tell_weather() : # import required modules import requests, json # enter your api key here api_key = \"Your_API_key\" # base_url variable to store url base_url = \"http://api.openweathermap.org/data/2.5/weather?\" # take a city name from city_field entry box city_name = city_field.get() # complete_url variable to store complete url address complete_url = base_url + \"appid =\" + api_key + \"&q =\" + city_name # get method of requests module # return response object response = requests.get(complete_url) # json method of response object convert # json format data into python format data x = response.json() # now x contains list of nested dictionaries # we know dictionary contains key value pair # check the value of \"cod\" key is equal to \"404\" # or not if not that means city is found # otherwise city is not found if x[\"cod\"] != \"404\" : # store the value of \"main\" key in variable y y = x[\"main\"] # store the value corresponding to the \"temp\" key of y current_temperature = y[\"temp\"] # store the value corresponding to the \"pressure\" key of y current_pressure = y[\"pressure\"] # store the value corresponding to the \"humidity\" key of y current_humidity = y[\"humidity\"] # store the value of \"weather\" key in variable z z = x[\"weather\"] # store the value corresponding to the \"description\" key # at the 0th index of z weather_description = z[0][\"description\"] # insert method inserting the # value in the text entry box. temp_field.insert(15, str(current_temperature) + \" Kelvin\") atm_field.insert(10, str(current_pressure) + \" hPa\") humid_field.insert(15, str(current_humidiy) + \" %\") desc_field.insert(10, str(weather_description) ) # if city is not found else : # message dialog box appear which # shows given Error message messagebox.showerror(\"Error\", \"City Not Found \\n\" \"Please enter valid city name\") # clear the content of city_field entry box city_field.delete(0, END) # Function for clearing the# contents of all text entry boxes def clear_all() : city_field.delete(0, END) temp_field.delete(0, END) atm_field.delete(0, END) humid_field.delete(0, END) desc_field.delete(0, END) # set focus on the city_field entry box city_field.focus_set() # Driver codeif __name__ == \"__main__\" : # Create a GUI window root = Tk() # set the name of tkinter GUI window root.title(\"Gui Application\") # Set the background colour of GUI window root.configure(background = \"light green\") # Set the configuration of GUI window root.geometry(\"425x175\") # Create a Weather Gui Application label headlabel = Label(root, text = \"Weather Gui Application\", fg = 'black', bg = 'red') # Create a City name : label label1 = Label(root, text = \"City name : \", fg = 'black', bg = 'dark green') # Create a City name : label label2 = Label(root, text = \"Temperature :\", fg = 'black', bg = 'dark green') # Create a atm pressure : label label3 = Label(root, text = \"atm pressure :\", fg = 'black', bg = 'dark green') # Create a humidity : label label4 = Label(root, text = \"humidity :\", fg = 'black', bg = 'dark green') # Create a description :label label5 = Label(root, text = \"description :\", fg = 'black', bg = 'dark green') # grid method is used for placing # the widgets at respective positions # in table like structure . headlabel.grid(row = 0, column = 1) label1.grid(row = 1, column = 0, sticky =\"E\") label2.grid(row = 3, column = 0, sticky =\"E\") label3.grid(row = 4, column = 0, sticky =\"E\") label4.grid(row = 5, column = 0, sticky =\"E\") label5.grid(row = 6, column = 0, sticky =\"E\") # Create a text entry box # for filling or typing the information. city_field = Entry(root) temp_field = Entry(root) atm_field = Entry(root) humid_field = Entry(root) desc_field = Entry(root) # grid method is used for placing # the widgets at respective positions # in table like structure . # ipadx keyword argument set width of entry space . city_field.grid(row = 1, column = 1, ipadx =\"100\") temp_field.grid(row = 3, column = 1, ipadx =\"100\") atm_field.grid(row = 4, column = 1, ipadx =\"100\") humid_field.grid(row = 5, column = 1, ipadx =\"100\") desc_field.grid(row = 6, column = 1, ipadx =\"100\") # Create a Submit Button and attached # to tell_weather function button1 = Button(root, text = \"Submit\", bg = \"red\", fg = \"black\", command = tell_weather) # Create a Clear Button and attached # to clear_all function button2 = Button(root, text = \"Clear\", bg = \"red\", fg = \"black\", command = clear_all) # grid method is used for placing # the widgets at respective positions # in table like structure . button1.grid(row = 2, column = 1) button2.grid(row = 7, column = 1) # Start the GUI root.mainloop()", "e": 6375, "s": 919, "text": null }, { "code": null, "e": 6386, "s": 6375, "text": "Output : " }, { "code": null, "e": 6403, "s": 6390, "text": "simmytarika5" }, { "code": null, "e": 6420, "s": 6403, "text": "surinderdawra388" }, { "code": null, "e": 6435, "s": 6420, "text": "python-utility" }, { "code": null, "e": 6459, "s": 6435, "text": "Technical Scripter 2018" }, { "code": null, "e": 6466, "s": 6459, "text": "Python" }, { "code": null, "e": 6564, "s": 6466, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6582, "s": 6564, "text": "Python Dictionary" }, { "code": null, "e": 6624, "s": 6582, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 6646, "s": 6624, "text": "Enumerate() in Python" }, { "code": null, "e": 6681, "s": 6646, "text": "Read a file line by line in Python" }, { "code": null, "e": 6707, "s": 6681, "text": "Python String | replace()" }, { "code": null, "e": 6739, "s": 6707, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6768, "s": 6739, "text": "*args and **kwargs in Python" }, { "code": null, "e": 6795, "s": 6768, "text": "Python Classes and Objects" }, { "code": null, "e": 6825, "s": 6795, "text": "Iterate over a list in Python" } ]
Priority Queue of Sets in C++ with Examples
18 Jan, 2022 Priority Queues Priority queues are a type of container adapters, specifically designed such that the first element of the queue is the greatest of all elements in the queue and elements are in nonincreasing order (hence we can see that each element of the queue has a priority {fixed order}). Functions used with Priority Queues: empty(): Returns whether the queue is empty. size(): Returns the size of the queue. top(): Returns a reference to the topmost element of the queue. pop(): Deletes the first element of the queue. Sets Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. Functions used with Sets: size(): Returns the number of elements in the set. insert(const x): Adds a new element ‘x’ to the set. Priority queue of sets can be quite useful for designing complex data structures. Syntax : priority_queue<set<data_type>> priorityQueue This stores set as an element in the max-heap priority queue Below is the implementation of the max-heap priority queue of set: C++ // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print priority// queue contentsvoid print(priority_queue<set<int> > priorityQueue){ while (!priorityQueue.empty()) { // Each element of the priority // queue is a set itself set<int> st = priorityQueue.top(); cout << "[ "; // Print the set elements for (auto element : st) cout << element << ' '; cout << ']'; cout << '\n'; // Pop out the topmost set priorityQueue.pop(); }} // Driver codeint main(){ // Declaring a max-heap priority // queue priority_queue<set<int> > priorityQueue; // Declaring a set of integers set<int> set1; // Inserting into the set set1.insert(10); set1.insert(1); set1.insert(2); set1.insert(5); // Push the set into priority // queue priorityQueue.push(set1); // Declaring another set set<int> set2; // Inserting into the set set2.insert(2); set2.insert(7); set2.insert(12); set2.insert(1); // Push the set into priority queue priorityQueue.push(set2); // Declaring another set set<int> set3; // Inserting into the set set3.insert(4); set3.insert(7); set3.insert(12); set3.insert(13); // Push the set into priority queue priorityQueue.push(set3); // Print the priority queue print(priorityQueue); return 0;} [ 4 7 12 13 ] [ 1 2 7 12 ] [ 1 2 5 10 ] By default priority queue is a max-heap, therefore internally for two sets inside the priority queue, the set having a greater first element is the topmost element. If the first element is equal then the second value of sets is compared and so on. Syntax: priority_queue<set<data_type>, vector<set<data_type>>, greater<set<data_type>>> priorityQueue This stores set as an element in the min-heap priority queue Below is the implementation of the min-heap priority queue of set: C++ // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print priority// queue contentsvoid print(priority_queue<set<int>, vector<set<int> >, greater<set<int> > > priorityQueue){ while (!priorityQueue.empty()) { // Each element of the priority // queue is a set itself set<int> st = priorityQueue.top(); cout << "[ "; // Print the set elements for (auto element : st) cout << element << ' '; cout << ']'; cout << '\n'; // Pop out the topmost set priorityQueue.pop(); }} // Driver codeint main(){ // Declaring a min-heap // priority queue priority_queue<set<int>, vector<set<int> >, greater<set<int> > > priorityQueue; // Declaring a set of integers set<int> set1; // Inserting into the set set1.insert(10); set1.insert(1); set1.insert(2); set1.insert(5); // Push the set into priority // queue priorityQueue.push(set1); // Declaring another set set<int> set2; // Inserting into the set set2.insert(2); set2.insert(7); set2.insert(12); set2.insert(1); // Push the set into priority // queue priorityQueue.push(set2); // Declaring another set set<int> set3; // Inserting into the set set3.insert(4); set3.insert(7); set3.insert(12); set3.insert(13); // Push the set into priority // queue priorityQueue.push(set3); // Print the priority queue print(priorityQueue); return 0;} [ 1 2 5 10 ] [ 1 2 7 12 ] [ 4 7 12 13 ] Internally for two sets inside the min-heap priority queue, the set having the smaller first element is the topmost element. If the first element is equal then the second value of sets is compared and so on. clintra cpp-priority-queue cpp-set STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Pair in C++ Standard Template Library (STL) Friend class and function in C++ std::string class in C++ Queue in C++ Standard Template Library (STL) std::find in C++ Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) vector insert() function in C++ STL
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Jan, 2022" }, { "code": null, "e": 70, "s": 54, "text": "Priority Queues" }, { "code": null, "e": 348, "s": 70, "text": "Priority queues are a type of container adapters, specifically designed such that the first element of the queue is the greatest of all elements in the queue and elements are in nonincreasing order (hence we can see that each element of the queue has a priority {fixed order})." }, { "code": null, "e": 385, "s": 348, "text": "Functions used with Priority Queues:" }, { "code": null, "e": 430, "s": 385, "text": "empty(): Returns whether the queue is empty." }, { "code": null, "e": 469, "s": 430, "text": "size(): Returns the size of the queue." }, { "code": null, "e": 533, "s": 469, "text": "top(): Returns a reference to the topmost element of the queue." }, { "code": null, "e": 580, "s": 533, "text": "pop(): Deletes the first element of the queue." }, { "code": null, "e": 585, "s": 580, "text": "Sets" }, { "code": null, "e": 863, "s": 585, "text": "Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. " }, { "code": null, "e": 889, "s": 863, "text": "Functions used with Sets:" }, { "code": null, "e": 940, "s": 889, "text": "size(): Returns the number of elements in the set." }, { "code": null, "e": 992, "s": 940, "text": "insert(const x): Adds a new element ‘x’ to the set." }, { "code": null, "e": 1074, "s": 992, "text": "Priority queue of sets can be quite useful for designing complex data structures." }, { "code": null, "e": 1083, "s": 1074, "text": "Syntax :" }, { "code": null, "e": 1190, "s": 1083, "text": "priority_queue<set<data_type>> priorityQueue \nThis stores set as an element in the max-heap priority queue" }, { "code": null, "e": 1257, "s": 1190, "text": "Below is the implementation of the max-heap priority queue of set:" }, { "code": null, "e": 1261, "s": 1257, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print priority// queue contentsvoid print(priority_queue<set<int> > priorityQueue){ while (!priorityQueue.empty()) { // Each element of the priority // queue is a set itself set<int> st = priorityQueue.top(); cout << \"[ \"; // Print the set elements for (auto element : st) cout << element << ' '; cout << ']'; cout << '\\n'; // Pop out the topmost set priorityQueue.pop(); }} // Driver codeint main(){ // Declaring a max-heap priority // queue priority_queue<set<int> > priorityQueue; // Declaring a set of integers set<int> set1; // Inserting into the set set1.insert(10); set1.insert(1); set1.insert(2); set1.insert(5); // Push the set into priority // queue priorityQueue.push(set1); // Declaring another set set<int> set2; // Inserting into the set set2.insert(2); set2.insert(7); set2.insert(12); set2.insert(1); // Push the set into priority queue priorityQueue.push(set2); // Declaring another set set<int> set3; // Inserting into the set set3.insert(4); set3.insert(7); set3.insert(12); set3.insert(13); // Push the set into priority queue priorityQueue.push(set3); // Print the priority queue print(priorityQueue); return 0;}", "e": 2706, "s": 1261, "text": null }, { "code": null, "e": 2749, "s": 2709, "text": "[ 4 7 12 13 ]\n[ 1 2 7 12 ]\n[ 1 2 5 10 ]" }, { "code": null, "e": 2999, "s": 2751, "text": "By default priority queue is a max-heap, therefore internally for two sets inside the priority queue, the set having a greater first element is the topmost element. If the first element is equal then the second value of sets is compared and so on." }, { "code": null, "e": 3009, "s": 3001, "text": "Syntax:" }, { "code": null, "e": 3167, "s": 3011, "text": "priority_queue<set<data_type>, vector<set<data_type>>, greater<set<data_type>>> priorityQueue \nThis stores set as an element in the min-heap priority queue" }, { "code": null, "e": 3236, "s": 3169, "text": "Below is the implementation of the min-heap priority queue of set:" }, { "code": null, "e": 3242, "s": 3238, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print priority// queue contentsvoid print(priority_queue<set<int>, vector<set<int> >, greater<set<int> > > priorityQueue){ while (!priorityQueue.empty()) { // Each element of the priority // queue is a set itself set<int> st = priorityQueue.top(); cout << \"[ \"; // Print the set elements for (auto element : st) cout << element << ' '; cout << ']'; cout << '\\n'; // Pop out the topmost set priorityQueue.pop(); }} // Driver codeint main(){ // Declaring a min-heap // priority queue priority_queue<set<int>, vector<set<int> >, greater<set<int> > > priorityQueue; // Declaring a set of integers set<int> set1; // Inserting into the set set1.insert(10); set1.insert(1); set1.insert(2); set1.insert(5); // Push the set into priority // queue priorityQueue.push(set1); // Declaring another set set<int> set2; // Inserting into the set set2.insert(2); set2.insert(7); set2.insert(12); set2.insert(1); // Push the set into priority // queue priorityQueue.push(set2); // Declaring another set set<int> set3; // Inserting into the set set3.insert(4); set3.insert(7); set3.insert(12); set3.insert(13); // Push the set into priority // queue priorityQueue.push(set3); // Print the priority queue print(priorityQueue); return 0;}", "e": 4885, "s": 3242, "text": null }, { "code": null, "e": 4928, "s": 4888, "text": "[ 1 2 5 10 ]\n[ 1 2 7 12 ]\n[ 4 7 12 13 ]" }, { "code": null, "e": 5138, "s": 4930, "text": "Internally for two sets inside the min-heap priority queue, the set having the smaller first element is the topmost element. If the first element is equal then the second value of sets is compared and so on." }, { "code": null, "e": 5148, "s": 5140, "text": "clintra" }, { "code": null, "e": 5167, "s": 5148, "text": "cpp-priority-queue" }, { "code": null, "e": 5175, "s": 5167, "text": "cpp-set" }, { "code": null, "e": 5179, "s": 5175, "text": "STL" }, { "code": null, "e": 5183, "s": 5179, "text": "C++" }, { "code": null, "e": 5187, "s": 5183, "text": "STL" }, { "code": null, "e": 5191, "s": 5187, "text": "CPP" }, { "code": null, "e": 5289, "s": 5191, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5313, "s": 5289, "text": "Sorting a vector in C++" }, { "code": null, "e": 5333, "s": 5313, "text": "Polymorphism in C++" }, { "code": null, "e": 5377, "s": 5333, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 5410, "s": 5377, "text": "Friend class and function in C++" }, { "code": null, "e": 5435, "s": 5410, "text": "std::string class in C++" }, { "code": null, "e": 5480, "s": 5435, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 5497, "s": 5480, "text": "std::find in C++" }, { "code": null, "e": 5545, "s": 5497, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 5589, "s": 5545, "text": "List in C++ Standard Template Library (STL)" } ]
Run Multiple Services In Single Docker Container Using Supervisor | by Aakash Rathor | Towards Data Science
Have you ever faced this scenario where you want to run two or more lightweight services within the same container? Although Docker provides a Docker-compose tool for building and running multi-services applications in multiple containers. Docker-compose requires a YAML file to configure your multiple services. But sometimes we want to run two or more lightweight services inside the same container. In this article I will explain how we can start multiple services in the same docker container using the “Supervisor” tool. So what is Supervisor? A supervisor is a tool that allows us to manage a number of different processes simultaneously in Linux like operating system. The supervisor tool requires a .conf file where we specify the processes and different options related to that process like the output log location, auto start, auto restart, etc. Sample services that I am going to used I am going to run two different services “Gunicorn server running Django app” and “Redis server” inside the same container. So in the sample project that I have created contains a simple Django REST API for adding and fetching data from the Redis server. In a production setting these two services are used in separate containers with production-grade configuration. For the sake of demonstration, I will run both the services in one docker container. Project Directory structure One of the good practices to start building your project is to have a neat and clear project structure. So considering this we will be using the below directory structure for our codes: multi_service├── django_app│ ├── db.sqlite3│ ├── django_app│ ├── manage.py│ ├── redis_test│ └── requirements.txt├── Dockerfile└── supervisor └── service_script.conf Testing Our Services In Local(Django App and Redis) Before putting out services in docker, first, let’s test them locally. You can download the complete project from GitHub using the below link.URL: https://github.com/aakash-rathore/docker_multi_services.git For testing Redis server just download it using below command: Using apt package installer$ sudo apt-get install redis-server# Use apk add (For alpine linux)# apk add redis Now run the server using below command: $ redis-serve You will see the service running: For testing Django app in local we will use Gunicorn server. Use below command for running app in gunicorn server: $ gunicorn --bind 0.0.0.0:8000 django_app.wsgi The output of this command is below: Supervisor config file Create a file “service_script.conf” as per the directory structure specified above. Add the django and redis services as per the configuration below: ## service_script.conf[supervisord] ## This is the main process for the Supervisor nodaemon=true ## This setting is to specify that we are not running in daemon mode[program:redis_script] ## This is the part where we give the name and add config for our 1st servicecommand=redis-server ## This is the main command to run our 1st serviceautorestart=true ## This setting specifies that the supervisor will restart the service in case of failurestderr_logfile=/dev/stdout ## This setting specifies that the supervisor will log the errors in the standard outputstderr_logfile_maxbytes = 0stdout_logfile=/dev/stdout ## This setting specifies that the supervisor will log the output in the standard outputstdout_logfile_maxbytes = 0## same setting for 2nd service[program:django_service] command=gunicorn --bind 0.0.0.0:8000 django_app.wsgiautostart=trueautorestart=truestderr_logfile=/dev/stdoutstderr_logfile_maxbytes = 0stdout_logfile=/dev/stdoutstdout_logfile_maxbytes = 0 Dockerfile Creation Now we will start making our docker file. The steps of adding layers are given below:Base Image -> Install Required Tools -> Add Source Code -> Add Config File -> Start ServiceFinal Dockerfile is given below: # Base ImageFROM alpine# Installing required toolsRUN apk --update add nano supervisor python3 redis# Adding Django Source code to container ADD /django_app /src/django_app# Adding supervisor configuration file to containerADD /supervisor /src/supervisor# Installing required python modules for appRUN pip3 install -r /src/django_app/requirements.txt# Exposing container port for binding with hostEXPOSE 8000# Using Django app directory as homeWORKDIR /src/django_app# Initializing Redis server and Gunicorn server from supervisordCMD ["supervisord","-c","/src/supervisor/service_script.conf"] Building And Testing Finally, build the docker image using the below command: $ docker build -t multi_service:1 . The output after a successful build operation: Now run the docker container using the above built image: $ docker run -it -p 8000:8000 multi_service:1 Here the docker container is run in non-daemon mode if you want to run it in daemon mode use ‘-d’ option, the output of the above command: Let's test the django app in API testing tool, I am using a lightweight “Advanced REST client too” available in Google Chrome extension store. You can use Postman, Curl, or any other tools for testing: Testing add user Function: Testing fetch user: Conclusion In this article, I explained how we can run multiple services(Django app and Redis server) inside a single docker container. In the end, we also did some tests to check if both the services are running or not. Please leave your comment about this article below and in case you are facing issues in any of the steps specified above you can reach out to me through Instagram and LinkedIn.
[ { "code": null, "e": 288, "s": 172, "text": "Have you ever faced this scenario where you want to run two or more lightweight services within the same container?" }, { "code": null, "e": 574, "s": 288, "text": "Although Docker provides a Docker-compose tool for building and running multi-services applications in multiple containers. Docker-compose requires a YAML file to configure your multiple services. But sometimes we want to run two or more lightweight services inside the same container." }, { "code": null, "e": 698, "s": 574, "text": "In this article I will explain how we can start multiple services in the same docker container using the “Supervisor” tool." }, { "code": null, "e": 721, "s": 698, "text": "So what is Supervisor?" }, { "code": null, "e": 1028, "s": 721, "text": "A supervisor is a tool that allows us to manage a number of different processes simultaneously in Linux like operating system. The supervisor tool requires a .conf file where we specify the processes and different options related to that process like the output log location, auto start, auto restart, etc." }, { "code": null, "e": 1068, "s": 1028, "text": "Sample services that I am going to used" }, { "code": null, "e": 1520, "s": 1068, "text": "I am going to run two different services “Gunicorn server running Django app” and “Redis server” inside the same container. So in the sample project that I have created contains a simple Django REST API for adding and fetching data from the Redis server. In a production setting these two services are used in separate containers with production-grade configuration. For the sake of demonstration, I will run both the services in one docker container." }, { "code": null, "e": 1548, "s": 1520, "text": "Project Directory structure" }, { "code": null, "e": 1734, "s": 1548, "text": "One of the good practices to start building your project is to have a neat and clear project structure. So considering this we will be using the below directory structure for our codes:" }, { "code": null, "e": 1912, "s": 1734, "text": "multi_service├── django_app│ ├── db.sqlite3│ ├── django_app│ ├── manage.py│ ├── redis_test│ └── requirements.txt├── Dockerfile└── supervisor └── service_script.conf" }, { "code": null, "e": 1964, "s": 1912, "text": "Testing Our Services In Local(Django App and Redis)" }, { "code": null, "e": 2171, "s": 1964, "text": "Before putting out services in docker, first, let’s test them locally. You can download the complete project from GitHub using the below link.URL: https://github.com/aakash-rathore/docker_multi_services.git" }, { "code": null, "e": 2234, "s": 2171, "text": "For testing Redis server just download it using below command:" }, { "code": null, "e": 2344, "s": 2234, "text": "Using apt package installer$ sudo apt-get install redis-server# Use apk add (For alpine linux)# apk add redis" }, { "code": null, "e": 2384, "s": 2344, "text": "Now run the server using below command:" }, { "code": null, "e": 2398, "s": 2384, "text": "$ redis-serve" }, { "code": null, "e": 2432, "s": 2398, "text": "You will see the service running:" }, { "code": null, "e": 2547, "s": 2432, "text": "For testing Django app in local we will use Gunicorn server. Use below command for running app in gunicorn server:" }, { "code": null, "e": 2594, "s": 2547, "text": "$ gunicorn --bind 0.0.0.0:8000 django_app.wsgi" }, { "code": null, "e": 2631, "s": 2594, "text": "The output of this command is below:" }, { "code": null, "e": 2654, "s": 2631, "text": "Supervisor config file" }, { "code": null, "e": 2804, "s": 2654, "text": "Create a file “service_script.conf” as per the directory structure specified above. Add the django and redis services as per the configuration below:" }, { "code": null, "e": 3781, "s": 2804, "text": "## service_script.conf[supervisord] ## This is the main process for the Supervisor nodaemon=true ## This setting is to specify that we are not running in daemon mode[program:redis_script] ## This is the part where we give the name and add config for our 1st servicecommand=redis-server ## This is the main command to run our 1st serviceautorestart=true ## This setting specifies that the supervisor will restart the service in case of failurestderr_logfile=/dev/stdout ## This setting specifies that the supervisor will log the errors in the standard outputstderr_logfile_maxbytes = 0stdout_logfile=/dev/stdout ## This setting specifies that the supervisor will log the output in the standard outputstdout_logfile_maxbytes = 0## same setting for 2nd service[program:django_service] command=gunicorn --bind 0.0.0.0:8000 django_app.wsgiautostart=trueautorestart=truestderr_logfile=/dev/stdoutstderr_logfile_maxbytes = 0stdout_logfile=/dev/stdoutstdout_logfile_maxbytes = 0" }, { "code": null, "e": 3801, "s": 3781, "text": "Dockerfile Creation" }, { "code": null, "e": 4010, "s": 3801, "text": "Now we will start making our docker file. The steps of adding layers are given below:Base Image -> Install Required Tools -> Add Source Code -> Add Config File -> Start ServiceFinal Dockerfile is given below:" }, { "code": null, "e": 4604, "s": 4010, "text": "# Base ImageFROM alpine# Installing required toolsRUN apk --update add nano supervisor python3 redis# Adding Django Source code to container ADD /django_app /src/django_app# Adding supervisor configuration file to containerADD /supervisor /src/supervisor# Installing required python modules for appRUN pip3 install -r /src/django_app/requirements.txt# Exposing container port for binding with hostEXPOSE 8000# Using Django app directory as homeWORKDIR /src/django_app# Initializing Redis server and Gunicorn server from supervisordCMD [\"supervisord\",\"-c\",\"/src/supervisor/service_script.conf\"]" }, { "code": null, "e": 4625, "s": 4604, "text": "Building And Testing" }, { "code": null, "e": 4682, "s": 4625, "text": "Finally, build the docker image using the below command:" }, { "code": null, "e": 4718, "s": 4682, "text": "$ docker build -t multi_service:1 ." }, { "code": null, "e": 4765, "s": 4718, "text": "The output after a successful build operation:" }, { "code": null, "e": 4823, "s": 4765, "text": "Now run the docker container using the above built image:" }, { "code": null, "e": 4869, "s": 4823, "text": "$ docker run -it -p 8000:8000 multi_service:1" }, { "code": null, "e": 5008, "s": 4869, "text": "Here the docker container is run in non-daemon mode if you want to run it in daemon mode use ‘-d’ option, the output of the above command:" }, { "code": null, "e": 5210, "s": 5008, "text": "Let's test the django app in API testing tool, I am using a lightweight “Advanced REST client too” available in Google Chrome extension store. You can use Postman, Curl, or any other tools for testing:" }, { "code": null, "e": 5237, "s": 5210, "text": "Testing add user Function:" }, { "code": null, "e": 5257, "s": 5237, "text": "Testing fetch user:" }, { "code": null, "e": 5268, "s": 5257, "text": "Conclusion" }, { "code": null, "e": 5478, "s": 5268, "text": "In this article, I explained how we can run multiple services(Django app and Redis server) inside a single docker container. In the end, we also did some tests to check if both the services are running or not." } ]
Duration minusDays() method in Java
An immutable copy of a duration where some days are removed from it can be obtained using the minusDays() method in the Duration class in Java. This method requires a single parameter i.e. the number of days to be subtracted and it returns the duration with the subtracted days. A program that demonstrates this is given as follows − Live Demo import java.time.Duration; public class Demo { public static void main(String[] args) { Duration d = Duration.ofDays(5); System.out.println("The duration is: " + d); System.out.println("A copy with 2 days removed from the duration is: " + d.minusDays(2)); } } The duration is: PT120H A copy with 2 days removed from the duration is: PT72H Now let us understand the above program. First the duration is displayed. Then an immutable copy of the duration where 2 days are removed is obtained using the minusDays() method and this is displayed. A code snippet that demonstrates this is as follows − Duration d = Duration.ofDays(5); System.out.println("The duration is: " + d); System.out.println("A copy with 2 days removed from the duration is: " + d.minusDays(2));
[ { "code": null, "e": 1341, "s": 1062, "text": "An immutable copy of a duration where some days are removed from it can be obtained using the minusDays() method in the Duration class in Java. This method requires a single parameter i.e. the number of days to be subtracted and it returns the duration with the subtracted days." }, { "code": null, "e": 1396, "s": 1341, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1407, "s": 1396, "text": " Live Demo" }, { "code": null, "e": 1691, "s": 1407, "text": "import java.time.Duration;\npublic class Demo {\n public static void main(String[] args) {\n Duration d = Duration.ofDays(5);\n System.out.println(\"The duration is: \" + d);\n System.out.println(\"A copy with 2 days removed from the duration is: \" + d.minusDays(2));\n }\n}" }, { "code": null, "e": 1770, "s": 1691, "text": "The duration is: PT120H\nA copy with 2 days removed from the duration is: PT72H" }, { "code": null, "e": 1811, "s": 1770, "text": "Now let us understand the above program." }, { "code": null, "e": 2026, "s": 1811, "text": "First the duration is displayed. Then an immutable copy of the duration where 2 days are removed is obtained using the minusDays() method and this is displayed. A code snippet that demonstrates this is as follows −" }, { "code": null, "e": 2194, "s": 2026, "text": "Duration d = Duration.ofDays(5);\nSystem.out.println(\"The duration is: \" + d);\nSystem.out.println(\"A copy with 2 days removed from the duration is: \" + d.minusDays(2));" } ]
Row-wise vs column-wise traversal of matrix - GeeksforGeeks
05 Apr, 2022 Two common ways of traversing a matrix are row-major-order and column-major-order. Row Major Order : When matrix is accessed row by row. Column Major Order : When matrix is accessed column by column.Examples: Input : mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} Output : Row-wise: 1 2 3 4 5 6 7 8 9 Col-wise : 1 4 7 2 5 8 3 6 9 Difference: If we see according to time complexity, both lead to O(n2), but when it comes to cache level one of the orders access will be faster as compare to other one. It depends on the language we are using. Like in C, store matrix in row major form so while accessing the i+1th element after ith, most probably it will lead to a hit, which will further reduce the time of program. Following codes are showing the time difference in row major and column major access. C++ Java Python3 C# // C program showing time difference// in row major and column major access#include <stdio.h>#include <time.h> // taking MAX 10000 so that time difference// can be shown#define MAX 10000 int arr[MAX][MAX] = {0}; void rowMajor() { int i, j; // accessing element row wise for (i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) { arr[i][j]++; } }} void colMajor() { int i, j; // accessing element column wise for (i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) { arr[j][i]++; } }} // driver codeint main() { int i, j; // Time taken by row major order clock_t t = clock(); rowMajor(); t = clock() - t; printf("Row major access time :%f s\n", t / (float)CLOCKS_PER_SEC); // Time taken by column major order t = clock(); colMajor(); t = clock() - t; printf("Column major access time :%f s\n", t / (float)CLOCKS_PER_SEC); return 0;} // Java program showing time difference// in row major and column major accessimport java.time.Duration;import java.time.Instant;import java.util.*; class GFG{ // taking MAX 10000 so that time difference// can be shownstatic int MAX= 10000; static int [][]arr = new int[MAX][MAX]; static void rowMajor(){ int i, j; // accessing element row wise for (i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) { arr[i][j]++; } }} static void colMajor(){ int i, j; // accessing element column wise for (i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) { arr[j][i]++; } }} // Driver codepublic static void main(String[] args){ // Time taken by row major order Instant start = Instant.now(); rowMajor(); Instant end = Instant.now(); System.out.println("Row major access time : "+ Duration.between(start, end)); // Time taken by column major order start = Instant.now(); colMajor(); end = Instant.now(); System.out.printf("Column major access time : "+ Duration.between(start, end));}} // This code is contributed by 29AjayKumar # Python3 program showing time difference# in row major and column major access # taking MAX 10000 so that time difference# can be shownMAX = 1000from time import clock arr = [[ 0 for i in range(MAX)] for i in range(MAX)] def rowMajor(): global arr # accessing element row wise for i in range(MAX): for j in range(MAX): arr[i][j] += 1 def colMajor(): global arr # accessing element column wise for i in range(MAX): for j in range(MAX): arr[j][i] += 1 # Driver codeif __name__ == '__main__': # Time taken by row major order t = clock() rowMajor(); t = clock() - t print("Row major access time :{:.2f} s".format(t)) # Time taken by column major order t = clock() colMajor() t = clock() - t print("Column major access time :{:.2f} s".format(t)) # This code is contributed by mohit kumar 29 // C# program showing time difference// in row major and column major accessusing System;using static System.DateTime;public class GFG{ // taking MAX 10000 so that time difference // can be shown public static int MAX = 1000; public static int[,] arr = new int[GFG.MAX,GFG.MAX]; public static void rowMajor() { int i; int j; // accessing element row wise for ( i = 0; i < GFG.MAX; i++) { for ( j = 0; j < GFG.MAX; j++) { GFG.arr[i,j]++; } } } public static void colMajor() { int i; int j; // accessing element column wise for ( i = 0; i < GFG.MAX; i++) { for ( j = 0; j < GFG.MAX; j++) { GFG.arr[j,i]++; } } } // Driver code public static void Main(String[] args) { // Time taken by row major order var start = DateTime.UtcNow; GFG.rowMajor(); var end = DateTime.UtcNow; TimeSpan spanR = end.Subtract( start ); Console.WriteLine("Row major access time : " + spanR.TotalMinutes + " min"); // Time taken by column major order start = DateTime.UtcNow; GFG.colMajor(); end = DateTime.UtcNow; TimeSpan spanC = end.Subtract( start ); Console.WriteLine("Column major access time : " + spanC.TotalMinutes + " min"); }} // This code is contributed by yoursthek2002 Row major access time :0.492000 s Column major access time :1.621000 s 29AjayKumar mohit kumar 29 yoursthek2002 Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Program to multiply two matrices Count all possible paths from top left to bottom right of a mXn matrix Printing all solutions in N-Queen Problem Min Cost Path | DP-6 Python program to multiply two matrices The Celebrity Problem Multiplication of two Matrices in Single line using Numpy in Python Gold Mine Problem
[ { "code": null, "e": 24714, "s": 24686, "text": "\n05 Apr, 2022" }, { "code": null, "e": 24925, "s": 24714, "text": "Two common ways of traversing a matrix are row-major-order and column-major-order. Row Major Order : When matrix is accessed row by row. Column Major Order : When matrix is accessed column by column.Examples: " }, { "code": null, "e": 25090, "s": 24925, "text": "Input : mat[][] = {{1, 2, 3}, \n {4, 5, 6}, \n {7, 8, 9}}\nOutput : Row-wise: 1 2 3 4 5 6 7 8 9\n Col-wise : 1 4 7 2 5 8 3 6 9" }, { "code": null, "e": 25565, "s": 25092, "text": "Difference: If we see according to time complexity, both lead to O(n2), but when it comes to cache level one of the orders access will be faster as compare to other one. It depends on the language we are using. Like in C, store matrix in row major form so while accessing the i+1th element after ith, most probably it will lead to a hit, which will further reduce the time of program. Following codes are showing the time difference in row major and column major access. " }, { "code": null, "e": 25569, "s": 25565, "text": "C++" }, { "code": null, "e": 25574, "s": 25569, "text": "Java" }, { "code": null, "e": 25582, "s": 25574, "text": "Python3" }, { "code": null, "e": 25585, "s": 25582, "text": "C#" }, { "code": "// C program showing time difference// in row major and column major access#include <stdio.h>#include <time.h> // taking MAX 10000 so that time difference// can be shown#define MAX 10000 int arr[MAX][MAX] = {0}; void rowMajor() { int i, j; // accessing element row wise for (i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) { arr[i][j]++; } }} void colMajor() { int i, j; // accessing element column wise for (i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) { arr[j][i]++; } }} // driver codeint main() { int i, j; // Time taken by row major order clock_t t = clock(); rowMajor(); t = clock() - t; printf(\"Row major access time :%f s\\n\", t / (float)CLOCKS_PER_SEC); // Time taken by column major order t = clock(); colMajor(); t = clock() - t; printf(\"Column major access time :%f s\\n\", t / (float)CLOCKS_PER_SEC); return 0;}", "e": 26489, "s": 25585, "text": null }, { "code": "// Java program showing time difference// in row major and column major accessimport java.time.Duration;import java.time.Instant;import java.util.*; class GFG{ // taking MAX 10000 so that time difference// can be shownstatic int MAX= 10000; static int [][]arr = new int[MAX][MAX]; static void rowMajor(){ int i, j; // accessing element row wise for (i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) { arr[i][j]++; } }} static void colMajor(){ int i, j; // accessing element column wise for (i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) { arr[j][i]++; } }} // Driver codepublic static void main(String[] args){ // Time taken by row major order Instant start = Instant.now(); rowMajor(); Instant end = Instant.now(); System.out.println(\"Row major access time : \"+ Duration.between(start, end)); // Time taken by column major order start = Instant.now(); colMajor(); end = Instant.now(); System.out.printf(\"Column major access time : \"+ Duration.between(start, end));}} // This code is contributed by 29AjayKumar", "e": 27679, "s": 26489, "text": null }, { "code": "# Python3 program showing time difference# in row major and column major access # taking MAX 10000 so that time difference# can be shownMAX = 1000from time import clock arr = [[ 0 for i in range(MAX)] for i in range(MAX)] def rowMajor(): global arr # accessing element row wise for i in range(MAX): for j in range(MAX): arr[i][j] += 1 def colMajor(): global arr # accessing element column wise for i in range(MAX): for j in range(MAX): arr[j][i] += 1 # Driver codeif __name__ == '__main__': # Time taken by row major order t = clock() rowMajor(); t = clock() - t print(\"Row major access time :{:.2f} s\".format(t)) # Time taken by column major order t = clock() colMajor() t = clock() - t print(\"Column major access time :{:.2f} s\".format(t)) # This code is contributed by mohit kumar 29", "e": 28558, "s": 27679, "text": null }, { "code": "// C# program showing time difference// in row major and column major accessusing System;using static System.DateTime;public class GFG{ // taking MAX 10000 so that time difference // can be shown public static int MAX = 1000; public static int[,] arr = new int[GFG.MAX,GFG.MAX]; public static void rowMajor() { int i; int j; // accessing element row wise for ( i = 0; i < GFG.MAX; i++) { for ( j = 0; j < GFG.MAX; j++) { GFG.arr[i,j]++; } } } public static void colMajor() { int i; int j; // accessing element column wise for ( i = 0; i < GFG.MAX; i++) { for ( j = 0; j < GFG.MAX; j++) { GFG.arr[j,i]++; } } } // Driver code public static void Main(String[] args) { // Time taken by row major order var start = DateTime.UtcNow; GFG.rowMajor(); var end = DateTime.UtcNow; TimeSpan spanR = end.Subtract( start ); Console.WriteLine(\"Row major access time : \" + spanR.TotalMinutes + \" min\"); // Time taken by column major order start = DateTime.UtcNow; GFG.colMajor(); end = DateTime.UtcNow; TimeSpan spanC = end.Subtract( start ); Console.WriteLine(\"Column major access time : \" + spanC.TotalMinutes + \" min\"); }} // This code is contributed by yoursthek2002", "e": 29873, "s": 28558, "text": null }, { "code": null, "e": 29944, "s": 29873, "text": "Row major access time :0.492000 s\nColumn major access time :1.621000 s" }, { "code": null, "e": 29958, "s": 29946, "text": "29AjayKumar" }, { "code": null, "e": 29973, "s": 29958, "text": "mohit kumar 29" }, { "code": null, "e": 29987, "s": 29973, "text": "yoursthek2002" }, { "code": null, "e": 29994, "s": 29987, "text": "Matrix" }, { "code": null, "e": 30001, "s": 29994, "text": "Matrix" }, { "code": null, "e": 30099, "s": 30001, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30108, "s": 30099, "text": "Comments" }, { "code": null, "e": 30121, "s": 30108, "text": "Old Comments" }, { "code": null, "e": 30145, "s": 30121, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 30207, "s": 30145, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 30240, "s": 30207, "text": "Program to multiply two matrices" }, { "code": null, "e": 30311, "s": 30240, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 30353, "s": 30311, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 30374, "s": 30353, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 30414, "s": 30374, "text": "Python program to multiply two matrices" }, { "code": null, "e": 30436, "s": 30414, "text": "The Celebrity Problem" }, { "code": null, "e": 30504, "s": 30436, "text": "Multiplication of two Matrices in Single line using Numpy in Python" } ]
ReactJS – getDerivedStateFromError() Method
In this article, we are going to see how to execute a function if some error occurs in the component. This method is called when a component encounters some error during the React Component Lifecycle. This method allows us to handle the error boundaries of the application. To avoid performance issues, don’t set up any side-effects in this method. static getDerivedStateFromError(error) It accepts the error as a parameter that was thrown as a component. In this example, we will build a React application that displays the contained Comp1 component if no error occurs; otherwise it displays some text. But here, in Comp1 component, error is defined to occur, as the state is not defined which fires the getDerivedStateFromError in the parent component. App.jsx import React, { Component } from 'react'; class App extends Component { constructor(){ super(); this.state = { err: false }; } static getDerivedStateFromError(error) { // Changing the state if some error occurs return { err: true, }; } render() { return ( <div> {this.state.err ? <div>Some Error Occurred</div> : <Comp1 />} </div> ); } } class Comp1 extends Component { render() { return <h1>{this.state.data}</h1>; } } export default App; This will produce the following result.
[ { "code": null, "e": 1164, "s": 1062, "text": "In this article, we are going to see how to execute a function if some error occurs in the component." }, { "code": null, "e": 1411, "s": 1164, "text": "This method is called when a component encounters some error during the React Component Lifecycle. This method allows us to handle the error boundaries of the application. To avoid performance issues, don’t set up any side-effects in this method." }, { "code": null, "e": 1450, "s": 1411, "text": "static getDerivedStateFromError(error)" }, { "code": null, "e": 1518, "s": 1450, "text": "It accepts the error as a parameter that was thrown as a component." }, { "code": null, "e": 1817, "s": 1518, "text": "In this example, we will build a React application that displays the contained Comp1 component if no error occurs; otherwise it displays some text. But here, in Comp1 component, error is defined to occur, as the state is not defined which fires the getDerivedStateFromError in the parent component." }, { "code": null, "e": 1825, "s": 1817, "text": "App.jsx" }, { "code": null, "e": 2392, "s": 1825, "text": "import React, { Component } from 'react';\n\nclass App extends Component {\n constructor(){\n super();\n this.state = {\n err: false\n };\n }\n static getDerivedStateFromError(error) {\n // Changing the state if some error occurs\n return {\n err: true,\n };\n }\n render() {\n return (\n <div>\n {this.state.err ? <div>Some Error Occurred</div> : <Comp1 />}\n </div>\n );\n }\n}\nclass Comp1 extends Component {\n render() {\n return <h1>{this.state.data}</h1>;\n }\n}\nexport default App;" }, { "code": null, "e": 2432, "s": 2392, "text": "This will produce the following result." } ]
Blob object in JavaScript
The blob object is used for representing a blob object which is immutable and is used for representing raw data. The blob has a size and mime type property just like a file has. File is a derivation of blob and blob can be used in places where the file is used. Following is the code showing blob object in JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result{ font-size: 18px; font-weight: 500; color: rebeccapurple; } </style> </head> <body> <h1>Blob object in JavaScript</h1> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to create and display a blob object</h3> <script> let resEle = document.querySelector(".result"); document.querySelector(".Btn").addEventListener("click", () => { let blob = new Blob(["This is a sample blob"], { type: "text/plain" }); resEle.innerHTML = "blob.type = " + blob.type + "<br>"; resEle.innerHTML += "blob.size = " + blob.size; }); </script> </body> </html> The above code will produce the following output − On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1324, "s": 1062, "text": "The blob object is used for representing a blob object which is immutable and is used for representing raw data. The blob has a size and mime type property just like a file has. File is a derivation of blob and blob can be used in places where the file is used." }, { "code": null, "e": 1382, "s": 1324, "text": "Following is the code showing blob object in JavaScript −" }, { "code": null, "e": 1393, "s": 1382, "text": " Live Demo" }, { "code": null, "e": 2290, "s": 1393, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result{\n font-size: 18px;\n font-weight: 500;\n color: rebeccapurple;\n }\n</style>\n</head>\n<body>\n<h1>Blob object in JavaScript</h1>\n<div class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to create and display a blob object</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n let blob = new Blob([\"This is a sample blob\"], { type: \"text/plain\" });\n resEle.innerHTML = \"blob.type = \" + blob.type + \"<br>\";\n resEle.innerHTML += \"blob.size = \" + blob.size;\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2341, "s": 2290, "text": "The above code will produce the following output −" }, { "code": null, "e": 2379, "s": 2341, "text": "On clicking the ‘CLICK HERE’ button −" } ]
Generate all N digit numbers having absolute difference as K between adjacent digits - GeeksforGeeks
29 May, 2021 Given two integers N and K, the task is to generate all positive integers with length N having an absolute difference of adjacent digits equal to K. Examples: Input: N = 4, K = 8Output: 1919, 8080, 9191Explanation:The absolute difference between every consecutive digit of each number is 8.For Example: 8080 (abs(8-0) = 8, abs(0-8) = 8) Input: N = 2, K = 2Output: 13, 24, 20, 35, 31, 46, 42, 57, 53, 68, 64, 79, 75, 86, 97Explanation:The absolute difference between every consecutive digit of each number is 1. Approach: The idea is to use Backtracking. Iterate over digits [1, 9] and for each digit from the N-digit number having a difference of absolute digit as K using recursion. Below are the steps: 1. Create a vector ans[] to store all the resulting numbers and recursively iterate from 1 to 9 to generate numbers starting from each digit. Below are the cases: Base Case: For all integers of a single length, that is, N = 1, add them to ans[]. Recursive Call: If adding digit K to the numbers to one’s digit doesn’t exceed 9, then recursively call by decreasing the N and update num to (10*num + num%10 + K) as shown below: if(num % 10 + K ≤ 9) { recursive_function(10 * num + (num % 10 + K), K, N – 1, and); } If the value of K is non-zero after all the recursive call and if num % 10 >= K, then again recursively call by decreasing the N and update num to (10*num + num%10 – K) as: recursive_function(10 * num + num % 10 – K, K, N – 1, ans); 2. After all the above steps print the numbers stored in ans[]. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that recursively finds the// possible numbers and append into ansvoid checkUntil(int num, int K, int N, vector<int>& ans){ // Base Case if (N == 1) { ans.push_back(num); return; } // Check the sum of last digit and k // less than or equal to 9 or not if ((num % 10 + K) <= 9) checkUntil(10 * num + (num % 10 + K), K, N - 1, ans); // If k==0, then subtraction and // addition does not make any // difference // Hence, subtraction is skipped if (K) { if ((num % 10 - K) >= 0) checkUntil(10 * num + num % 10 - K, K, N - 1, ans); }} // Function to call checkUntil function// for every integer from 1 to 9void check(int K, int N, vector<int>& ans){ // check_util function recursively // store all numbers starting from i for (int i = 1; i <= 9; i++) { checkUntil(i, K, N, ans); }} // Function to print the all numbers// which satisfy the conditionsvoid print(vector<int>& ans){ for (int i = 0; i < ans.size(); i++) { cout << ans[i] << ", "; }} // Driver Codeint main(){ // Given N and K int N = 4, K = 8; // To store the result vector<int> ans; // Function Call check(K, N, ans); // Print Resultant Numbers print(ans); return 0;} // Java program for// the above approachimport java.util.*;class GFG{ // Function that recursively finds the // possible numbers and append into ans static void checkUntil(int num, int K, int N, Vector<Integer> ans) { // Base Case if (N == 1) { ans.add(num); return; } // Check the sum of last digit and k // less than or equal to 9 or not if ((num % 10 + K) <= 9) checkUntil(10 * num + (num % 10 + K), K, N - 1, ans); // If k==0, then subtraction and // addition does not make any // difference // Hence, subtraction is skipped if (K > 0) { if ((num % 10 - K) >= 0) checkUntil(10 * num + num % 10 - K, K, N - 1, ans); } } // Function to call checkUntil function // for every integer from 1 to 9 static void check(int K, int N, Vector<Integer> ans) { // check_util function recursively // store all numbers starting from i for (int i = 1; i <= 9; i++) { checkUntil(i, K, N, ans); } } // Function to print the all numbers // which satisfy the conditions static void print(Vector<Integer> ans) { for (int i = 0; i < ans.size(); i++) { System.out.print(ans.get(i) + ", "); } } // Driver Code public static void main(String[] args) { // Given N and K int N = 4, K = 8; // To store the result Vector<Integer> ans = new Vector<Integer>();; // Function Call check(K, N, ans); // Print Resultant Numbers print(ans); }} // This code is contributed by Amit Katiyar # Python3 program for the above approach # Function that recursively finds the# possible numbers and append into ansdef checkUntil(num, K, N, ans): # Base Case if (N == 1): ans.append(num) return # Check the sum of last digit and k # less than or equal to 9 or not if ((num % 10 + K) <= 9): checkUntil(10 * num + (num % 10 + K), K, N - 1, ans) # If k==0, then subtraction and # addition does not make any # difference # Hence, subtraction is skipped if (K): if ((num % 10 - K) >= 0): checkUntil(10 * num + num % 10 - K, K, N - 1, ans) # Function to call checkUntil function# for every integer from 1 to 9def check(K, N, ans): # check_util function recursively # store all numbers starting from i for i in range(1, 10): checkUntil(i, K, N, ans) # Function to print the all numbers# which satisfy the conditionsdef print_list(ans): for i in range(len(ans)): print(ans[i], end = ", ") # Driver Codeif __name__ == "__main__": # Given N and K N = 4 K = 8; # To store the result ans = [] # Function call check(K, N, ans) # Print resultant numbers print_list(ans) # This code is contributed by chitranayal // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function that recursively finds the// possible numbers and append into ansstatic void checkUntil(int num, int K, int N, List<int> ans){ // Base Case if (N == 1) { ans.Add(num); return; } // Check the sum of last digit and k // less than or equal to 9 or not if ((num % 10 + K) <= 9) checkUntil(10 * num + (num % 10 + K), K, N - 1, ans); // If k==0, then subtraction and // addition does not make any // difference // Hence, subtraction is skipped if (K > 0) { if ((num % 10 - K) >= 0) checkUntil(10 * num + num % 10 - K, K, N - 1, ans); }} // Function to call checkUntil function// for every integer from 1 to 9static void check(int K, int N, List<int> ans){ // check_util function recursively // store all numbers starting from i for(int i = 1; i <= 9; i++) { checkUntil(i, K, N, ans); }} // Function to print the all numbers// which satisfy the conditionsstatic void print(List<int> ans){ for(int i = 0; i < ans.Count; i++) { Console.Write(ans[i] + ", "); }} // Driver Codepublic static void Main(String[] args){ // Given N and K int N = 4, K = 8; // To store the result List<int> ans = new List<int>();; // Function call check(K, N, ans); // Print Resultant Numbers print(ans);}} // This code is contributed by Amit Katiyar <script> // Javascript program to implement// the above approach // Function that recursively finds the // possible numbers and append into ans function checkUntil(num, K, N, ans) { // Base Case if (N == 1) { ans.push(num); return; } // Check the sum of last digit and k // less than or equal to 9 or not if ((num % 10 + K) <= 9) checkUntil(10 * num + (num % 10 + K), K, N - 1, ans); // If k==0, then subtraction and // addition does not make any // difference // Hence, subtraction is skipped if (K > 0) { if ((num % 10 - K) >= 0) checkUntil(10 * num + num % 10 - K, K, N - 1, ans); } } // Function to call checkUntil function // for every integer from 1 to 9 function check(K, N, ans) { // check_util function recursively // store all numbers starting from i for (let i = 1; i <= 9; i++) { checkUntil(i, K, N, ans); } } // Function to print the all numbers // which satisfy the conditions function print( ans) { for (let i = 0; i < ans.length; i++) { document.write(ans[i] + ", "); } } // Driver Code // Given N and K let N = 4, K = 8; // To store the result let ans = [] // Function Call check(K, N, ans); // Print Resultant Numbers print(ans); </script> 1919, 8080, 9191, Time Complexity: O(2N)Auxiliary Space: O(N) ukasp amit143katiyar chinmoy1997pal ankita_saini number-digits subsequence Backtracking Mathematical Recursion Mathematical Recursion Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Tug of War Difference between Backtracking and Branch-N-Bound technique Perfect Sum Problem N-Queen Problem | Local Search using Hill climbing with random neighbour Find shortest safe route in a path with landmines Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 24567, "s": 24539, "text": "\n29 May, 2021" }, { "code": null, "e": 24716, "s": 24567, "text": "Given two integers N and K, the task is to generate all positive integers with length N having an absolute difference of adjacent digits equal to K." }, { "code": null, "e": 24726, "s": 24716, "text": "Examples:" }, { "code": null, "e": 24904, "s": 24726, "text": "Input: N = 4, K = 8Output: 1919, 8080, 9191Explanation:The absolute difference between every consecutive digit of each number is 8.For Example: 8080 (abs(8-0) = 8, abs(0-8) = 8)" }, { "code": null, "e": 25079, "s": 24904, "text": "Input: N = 2, K = 2Output: 13, 24, 20, 35, 31, 46, 42, 57, 53, 68, 64, 79, 75, 86, 97Explanation:The absolute difference between every consecutive digit of each number is 1. " }, { "code": null, "e": 25273, "s": 25079, "text": "Approach: The idea is to use Backtracking. Iterate over digits [1, 9] and for each digit from the N-digit number having a difference of absolute digit as K using recursion. Below are the steps:" }, { "code": null, "e": 25438, "s": 25273, "text": "1. Create a vector ans[] to store all the resulting numbers and recursively iterate from 1 to 9 to generate numbers starting from each digit. Below are the cases: " }, { "code": null, "e": 25521, "s": 25438, "text": "Base Case: For all integers of a single length, that is, N = 1, add them to ans[]." }, { "code": null, "e": 25701, "s": 25521, "text": "Recursive Call: If adding digit K to the numbers to one’s digit doesn’t exceed 9, then recursively call by decreasing the N and update num to (10*num + num%10 + K) as shown below:" }, { "code": null, "e": 25791, "s": 25701, "text": "if(num % 10 + K ≤ 9) { recursive_function(10 * num + (num % 10 + K), K, N – 1, and); }" }, { "code": null, "e": 25964, "s": 25791, "text": "If the value of K is non-zero after all the recursive call and if num % 10 >= K, then again recursively call by decreasing the N and update num to (10*num + num%10 – K) as:" }, { "code": null, "e": 26024, "s": 25964, "text": "recursive_function(10 * num + num % 10 – K, K, N – 1, ans);" }, { "code": null, "e": 26088, "s": 26024, "text": "2. After all the above steps print the numbers stored in ans[]." }, { "code": null, "e": 26139, "s": 26088, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26143, "s": 26139, "text": "C++" }, { "code": null, "e": 26148, "s": 26143, "text": "Java" }, { "code": null, "e": 26156, "s": 26148, "text": "Python3" }, { "code": null, "e": 26159, "s": 26156, "text": "C#" }, { "code": null, "e": 26170, "s": 26159, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that recursively finds the// possible numbers and append into ansvoid checkUntil(int num, int K, int N, vector<int>& ans){ // Base Case if (N == 1) { ans.push_back(num); return; } // Check the sum of last digit and k // less than or equal to 9 or not if ((num % 10 + K) <= 9) checkUntil(10 * num + (num % 10 + K), K, N - 1, ans); // If k==0, then subtraction and // addition does not make any // difference // Hence, subtraction is skipped if (K) { if ((num % 10 - K) >= 0) checkUntil(10 * num + num % 10 - K, K, N - 1, ans); }} // Function to call checkUntil function// for every integer from 1 to 9void check(int K, int N, vector<int>& ans){ // check_util function recursively // store all numbers starting from i for (int i = 1; i <= 9; i++) { checkUntil(i, K, N, ans); }} // Function to print the all numbers// which satisfy the conditionsvoid print(vector<int>& ans){ for (int i = 0; i < ans.size(); i++) { cout << ans[i] << \", \"; }} // Driver Codeint main(){ // Given N and K int N = 4, K = 8; // To store the result vector<int> ans; // Function Call check(K, N, ans); // Print Resultant Numbers print(ans); return 0;}", "e": 27660, "s": 26170, "text": null }, { "code": "// Java program for// the above approachimport java.util.*;class GFG{ // Function that recursively finds the // possible numbers and append into ans static void checkUntil(int num, int K, int N, Vector<Integer> ans) { // Base Case if (N == 1) { ans.add(num); return; } // Check the sum of last digit and k // less than or equal to 9 or not if ((num % 10 + K) <= 9) checkUntil(10 * num + (num % 10 + K), K, N - 1, ans); // If k==0, then subtraction and // addition does not make any // difference // Hence, subtraction is skipped if (K > 0) { if ((num % 10 - K) >= 0) checkUntil(10 * num + num % 10 - K, K, N - 1, ans); } } // Function to call checkUntil function // for every integer from 1 to 9 static void check(int K, int N, Vector<Integer> ans) { // check_util function recursively // store all numbers starting from i for (int i = 1; i <= 9; i++) { checkUntil(i, K, N, ans); } } // Function to print the all numbers // which satisfy the conditions static void print(Vector<Integer> ans) { for (int i = 0; i < ans.size(); i++) { System.out.print(ans.get(i) + \", \"); } } // Driver Code public static void main(String[] args) { // Given N and K int N = 4, K = 8; // To store the result Vector<Integer> ans = new Vector<Integer>();; // Function Call check(K, N, ans); // Print Resultant Numbers print(ans); }} // This code is contributed by Amit Katiyar", "e": 29461, "s": 27660, "text": null }, { "code": "# Python3 program for the above approach # Function that recursively finds the# possible numbers and append into ansdef checkUntil(num, K, N, ans): # Base Case if (N == 1): ans.append(num) return # Check the sum of last digit and k # less than or equal to 9 or not if ((num % 10 + K) <= 9): checkUntil(10 * num + (num % 10 + K), K, N - 1, ans) # If k==0, then subtraction and # addition does not make any # difference # Hence, subtraction is skipped if (K): if ((num % 10 - K) >= 0): checkUntil(10 * num + num % 10 - K, K, N - 1, ans) # Function to call checkUntil function# for every integer from 1 to 9def check(K, N, ans): # check_util function recursively # store all numbers starting from i for i in range(1, 10): checkUntil(i, K, N, ans) # Function to print the all numbers# which satisfy the conditionsdef print_list(ans): for i in range(len(ans)): print(ans[i], end = \", \") # Driver Codeif __name__ == \"__main__\": # Given N and K N = 4 K = 8; # To store the result ans = [] # Function call check(K, N, ans) # Print resultant numbers print_list(ans) # This code is contributed by chitranayal", "e": 30780, "s": 29461, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function that recursively finds the// possible numbers and append into ansstatic void checkUntil(int num, int K, int N, List<int> ans){ // Base Case if (N == 1) { ans.Add(num); return; } // Check the sum of last digit and k // less than or equal to 9 or not if ((num % 10 + K) <= 9) checkUntil(10 * num + (num % 10 + K), K, N - 1, ans); // If k==0, then subtraction and // addition does not make any // difference // Hence, subtraction is skipped if (K > 0) { if ((num % 10 - K) >= 0) checkUntil(10 * num + num % 10 - K, K, N - 1, ans); }} // Function to call checkUntil function// for every integer from 1 to 9static void check(int K, int N, List<int> ans){ // check_util function recursively // store all numbers starting from i for(int i = 1; i <= 9; i++) { checkUntil(i, K, N, ans); }} // Function to print the all numbers// which satisfy the conditionsstatic void print(List<int> ans){ for(int i = 0; i < ans.Count; i++) { Console.Write(ans[i] + \", \"); }} // Driver Codepublic static void Main(String[] args){ // Given N and K int N = 4, K = 8; // To store the result List<int> ans = new List<int>();; // Function call check(K, N, ans); // Print Resultant Numbers print(ans);}} // This code is contributed by Amit Katiyar", "e": 32317, "s": 30780, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function that recursively finds the // possible numbers and append into ans function checkUntil(num, K, N, ans) { // Base Case if (N == 1) { ans.push(num); return; } // Check the sum of last digit and k // less than or equal to 9 or not if ((num % 10 + K) <= 9) checkUntil(10 * num + (num % 10 + K), K, N - 1, ans); // If k==0, then subtraction and // addition does not make any // difference // Hence, subtraction is skipped if (K > 0) { if ((num % 10 - K) >= 0) checkUntil(10 * num + num % 10 - K, K, N - 1, ans); } } // Function to call checkUntil function // for every integer from 1 to 9 function check(K, N, ans) { // check_util function recursively // store all numbers starting from i for (let i = 1; i <= 9; i++) { checkUntil(i, K, N, ans); } } // Function to print the all numbers // which satisfy the conditions function print( ans) { for (let i = 0; i < ans.length; i++) { document.write(ans[i] + \", \"); } } // Driver Code // Given N and K let N = 4, K = 8; // To store the result let ans = [] // Function Call check(K, N, ans); // Print Resultant Numbers print(ans); </script>", "e": 33927, "s": 32317, "text": null }, { "code": null, "e": 33945, "s": 33927, "text": "1919, 8080, 9191," }, { "code": null, "e": 33989, "s": 33945, "text": "Time Complexity: O(2N)Auxiliary Space: O(N)" }, { "code": null, "e": 33995, "s": 33989, "text": "ukasp" }, { "code": null, "e": 34010, "s": 33995, "text": "amit143katiyar" }, { "code": null, "e": 34025, "s": 34010, "text": "chinmoy1997pal" }, { "code": null, "e": 34038, "s": 34025, "text": "ankita_saini" }, { "code": null, "e": 34052, "s": 34038, "text": "number-digits" }, { "code": null, "e": 34064, "s": 34052, "text": "subsequence" }, { "code": null, "e": 34077, "s": 34064, "text": "Backtracking" }, { "code": null, "e": 34090, "s": 34077, "text": "Mathematical" }, { "code": null, "e": 34100, "s": 34090, "text": "Recursion" }, { "code": null, "e": 34113, "s": 34100, "text": "Mathematical" }, { "code": null, "e": 34123, "s": 34113, "text": "Recursion" }, { "code": null, "e": 34136, "s": 34123, "text": "Backtracking" }, { "code": null, "e": 34234, "s": 34136, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34243, "s": 34234, "text": "Comments" }, { "code": null, "e": 34256, "s": 34243, "text": "Old Comments" }, { "code": null, "e": 34267, "s": 34256, "text": "Tug of War" }, { "code": null, "e": 34328, "s": 34267, "text": "Difference between Backtracking and Branch-N-Bound technique" }, { "code": null, "e": 34348, "s": 34328, "text": "Perfect Sum Problem" }, { "code": null, "e": 34421, "s": 34348, "text": "N-Queen Problem | Local Search using Hill climbing with random neighbour" }, { "code": null, "e": 34471, "s": 34421, "text": "Find shortest safe route in a path with landmines" }, { "code": null, "e": 34501, "s": 34471, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34516, "s": 34501, "text": "C++ Data Types" }, { "code": null, "e": 34559, "s": 34516, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 34578, "s": 34559, "text": "Coin Change | DP-7" } ]
Splitting a dataset. Here I explain how to split your data... | by Nischal Madiraju | Towards Data Science
To train any machine learning model irrespective what type of dataset is being used you have to split the dataset into training data and testing data. So, let us look into how it can be done? Here I am going to use the iris dataset and split it using the ‘train_test_split’ library from sklearn from sklearn.model_selection import train_test_splitfrom sklearn.datasets import load_iris Then I load the iris dataset into a variable. iris = load_iris() Which I then use to store the data and target value into two separate variables. x, y = iris.data, iris.target Here I have used the ‘train_test_split’ to split the data in 80:20 ratio i.e. 80% of the data will be used for training the model while 20% will be used for testing the model that is built out of it. x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=123) As you can see here I have passed the following parameters in ‘train_test_split’: x and y that we had previously definedtest_size: This is set 0.2 thus defining the test size will be 20% of the datasetrandom_state: it controls the shuffling applied to the data before applying the split. Setting random_state a fixed value will guarantee that the same sequence of random numbers are generated each time you run the code. x and y that we had previously defined test_size: This is set 0.2 thus defining the test size will be 20% of the dataset random_state: it controls the shuffling applied to the data before applying the split. Setting random_state a fixed value will guarantee that the same sequence of random numbers are generated each time you run the code. When splitting a dataset there are two competing concerns:-If you have less training data, your parameter estimates have greater variance.-And if you have less testing data, your performance statistic will have greater variance.The data should be divided in such a way that neither of them is too high, which is more dependent on the amount of data you have. If your data is too small then no split will give you satisfactory variance so you will have to do cross-validation but if your data is huge then it doesn’t really matter whether you choose an 80:20 split or a 90:10 split (indeed you may choose to use less training data as otherwise, it might be more computationally intensive).
[ { "code": null, "e": 364, "s": 172, "text": "To train any machine learning model irrespective what type of dataset is being used you have to split the dataset into training data and testing data. So, let us look into how it can be done?" }, { "code": null, "e": 467, "s": 364, "text": "Here I am going to use the iris dataset and split it using the ‘train_test_split’ library from sklearn" }, { "code": null, "e": 558, "s": 467, "text": "from sklearn.model_selection import train_test_splitfrom sklearn.datasets import load_iris" }, { "code": null, "e": 604, "s": 558, "text": "Then I load the iris dataset into a variable." }, { "code": null, "e": 623, "s": 604, "text": "iris = load_iris()" }, { "code": null, "e": 704, "s": 623, "text": "Which I then use to store the data and target value into two separate variables." }, { "code": null, "e": 734, "s": 704, "text": "x, y = iris.data, iris.target" }, { "code": null, "e": 934, "s": 734, "text": "Here I have used the ‘train_test_split’ to split the data in 80:20 ratio i.e. 80% of the data will be used for training the model while 20% will be used for testing the model that is built out of it." }, { "code": null, "e": 1017, "s": 934, "text": "x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=123)" }, { "code": null, "e": 1099, "s": 1017, "text": "As you can see here I have passed the following parameters in ‘train_test_split’:" }, { "code": null, "e": 1438, "s": 1099, "text": "x and y that we had previously definedtest_size: This is set 0.2 thus defining the test size will be 20% of the datasetrandom_state: it controls the shuffling applied to the data before applying the split. Setting random_state a fixed value will guarantee that the same sequence of random numbers are generated each time you run the code." }, { "code": null, "e": 1477, "s": 1438, "text": "x and y that we had previously defined" }, { "code": null, "e": 1559, "s": 1477, "text": "test_size: This is set 0.2 thus defining the test size will be 20% of the dataset" }, { "code": null, "e": 1779, "s": 1559, "text": "random_state: it controls the shuffling applied to the data before applying the split. Setting random_state a fixed value will guarantee that the same sequence of random numbers are generated each time you run the code." } ]
How do you copy a Lua table by value?
Copying a table means that we want all the values or pairs that are present in one table in another table. In Lua, there’s no standard library function that we can use to create such a table but we can create our own function to do so. Let’s create a function in Lua that will take a table as an argument and will create a new table that will be the exact copy of the table passed as an argument to the function. Consider the example shown below as reference − Live Demo a = {} a["name"] = "mukul" a["age"] = 23 a["isWorking"] = true function table.table_copy(t) local t2 = {} for k,v in pairs(t) do t2[k] = v end return t2 end copy = table.table_copy(a) for _,v in pairs(a) do print(v) end for _,v in pairs(copy) do print(v) end In the above example, we have a table named a which we later pass as an argument to the function named table.table_copy() and that function returns us a copy of the same table that we passed and finally I printed the values inside these tables to check whether the copied table is accurate or not. mukul true 23 mukul true 23
[ { "code": null, "e": 1298, "s": 1062, "text": "Copying a table means that we want all the values or pairs that are present in one table in another table. In Lua, there’s no standard library function that we can use to create such a table but we can create our own function to do so." }, { "code": null, "e": 1475, "s": 1298, "text": "Let’s create a function in Lua that will take a table as an argument and will create a new table that will be the exact copy of the table passed as an argument to the function." }, { "code": null, "e": 1523, "s": 1475, "text": "Consider the example shown below as reference −" }, { "code": null, "e": 1534, "s": 1523, "text": " Live Demo" }, { "code": null, "e": 1811, "s": 1534, "text": "a = {}\na[\"name\"] = \"mukul\"\na[\"age\"] = 23\na[\"isWorking\"] = true\nfunction table.table_copy(t)\n local t2 = {}\n for k,v in pairs(t) do\n t2[k] = v\n end\n return t2\nend\ncopy = table.table_copy(a)\nfor _,v in pairs(a) do print(v) end\nfor _,v in pairs(copy) do print(v) end" }, { "code": null, "e": 2109, "s": 1811, "text": "In the above example, we have a table named a which we later pass as an argument to the function named table.table_copy() and that function returns us a copy of the same table that we passed and finally I printed the values inside these tables to check whether the copied table is accurate or not." }, { "code": null, "e": 2137, "s": 2109, "text": "mukul\ntrue\n23\nmukul\ntrue\n23" } ]
Count digit groupings of a number with given constraints - GeeksforGeeks
06 May, 2021 We are given a string consisting of digits, we may group these digits into sub-groups (but maintaining their original order). The task is to count the number of groupings such that for every sub-group except the last one, the sum of digits in a sub-group is less than or equal to the sum of the digits in the sub-group immediately on its right. For example, a valid grouping of digits of number 1119 is (1-11-9). Sum of digits in first subgroup is 1, next subgroup is 2, and last subgroup is 9. Sum of every subgroup is less than or equal to its immediate right. Examples : Input : "1119" Output: 7 Sub-groups: [1-119], [1-1-19], [1-11-9], [1-1-1-9], [11-19] and [111-9]. Note : Here we have included [1119] in the group and the sum of digits is 12 and this group has no immediate right. Input : "1234" Output: 6 Sub-groups : [1234], [1-234], [12-34], [1-2-3-4], [12-3-4] and [1-2-34] Let “length” be the length of the input number. A recursive solution is to consider every position from 0 length-1. For every position, recursively count all possible subgroups after it. Below is C++ implementation of the naive recursive solution. C++ Java Python3 C# PHP Javascript // C++ program to count number of// ways to group digits of a number// such that sum of digits in every// subgroup is less than or equal to// its immediate right subgroup.#include<bits/stdc++.h>using namespace std; // Function to find the subgroupsint countGroups(int position, int previous_sum, int length, char *num){ // Terminating Condition if (position == length) return 1; int res = 0; // sum of digits int sum = 0; // Traverse all digits from // current position to rest // of the length of string for (int i = position; i < length; i++) { sum += (num[i] - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } // Total number of subgroups // till current position return res;} // Driver Codeint main(){ char num[] = "1119"; int len = strlen(num); cout << countGroups(0, 0, len, num); return 0;} // Java program to count number// of ways to group digits of // a number such that sum of // digits in every subgroup is// less than or equal to its// immediate right subgroup.import java.io.*; class GFG{ // Function to find// the subgroupsstatic int countGroups(int position, int previous_sum, int length, String num){ // Terminating Condition if (position == length) return 1; int res = 0; // sum of digits int sum = 0; // Traverse all digits from // current position to rest // of the length of string for (int i = position; i < length; i++) { sum += (num.charAt(i) - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } // Total number of subgroups // till current position return res;} // Driver Codepublic static void main (String[] args){ String num = "1119"; int len =num .length(); System.out.println(countGroups(0, 0, len, num));}} // This code is contributed by anuj_67. # Python3 program to count# number of ways to group digits# of a number such that sum of# digits in every subgroup# is less than or equal to its immediate# right subgroup. # Function to find the subgroupsdef countGroups(position, previous_sum, length, num): # Terminating Condition if(position == length): return 1 res = 0 # sum of digits sum = 0 # Traverse all digits from # current position to rest # of the length of string for i in range(position, length): sum = sum + int(num[i]) # If forward_sum is greater # than the previous sum, # then call the method again if (sum >= previous_sum): # Note : We pass current # sum as previous sum res = res + countGroups(i + 1, sum, length, num) # Total number of subgroups # till the current position return res # Driver Codeif __name__=='__main__': num = "1119" len = len(num) print(countGroups(0, 0, len, num)) # This code is contributed by# Sanjit_Prasad // C# program to count number// of ways to group digits of// a number such that sum of// digits in every subgroup is// less than or equal to its// immediate right subgroup.using System; class GFG{ // Function to find// the subgroupsstatic int countGroups(int position, int previous_sum, int length, String num){ // Terminating Condition if (position == length) return 1; int res = 0; // sum of digits int sum = 0; // Traverse all digits from // current position to rest // of the length of string for (int i = position; i < length; i++) { sum += (num[i] - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } // Total number of subgroups // till current position return res;} // Driver Codepublic static void Main (){ String num = "1119"; int len = num.Length; Console.Write(countGroups(0, 0, len, num));}} // This code is contributed by 29AjayKumar <?php// PHP program to count number of// ways to group digits of a number// such that sum of digits in every// subgroup is less than or equal// to its immediate right subgroup. // Function to find the subgroupsfunction countGroups($position, $previous_sum, $length,$num){ // Terminating Condition if ($position == $length) return 1; $res = 0; // sum of digits $sum = 0; // Traverse all digits from // current position to rest // of the length of string for ($i = $position; $i < $length; $i++) { $sum += ($num[$i] - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if ($sum >= $previous_sum) // Note : We pass current // sum as previous sum $res += countGroups($i + 1, $sum, $length, $num); } // Total number of subgroups // till current position return $res;} // Driver Code$num = "1119";$len = strlen($num);echo countGroups(0, 0, $len, $num); // This code is contributed by ajit?> <script> // Javascript program to count number // of ways to group digits of // a number such that sum of // digits in every subgroup is // less than or equal to its // immediate right subgroup. // Function to find // the subgroups function countGroups(position, previous_sum, length, num) { // Terminating Condition if (position == length) return 1; let res = 0; // sum of digits let sum = 0; // Traverse all digits from // current position to rest // of the length of string for (let i = position; i < length; i++) { sum += (num[i].charCodeAt() - '0'.charCodeAt()); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } // Total number of subgroups // till current position return res; } let num = "1119"; let len = num.length; document.write(countGroups(0, 0, len, num)); </script> Output : 7 If we take a closer look at the above recursive solution, we notice that there may be overlapping subproblems. For example, if the input number is 12345, then for position = 3 and previous_sum = 3, we recur two times. Similarly, for position 4 and previous_sum = 7, we recur two times. Therefore the above solution can be optimized using Dynamic Programming. Below is a Dynamic Programming based solution for this problem. The maximum sum of digits can be 9*length where ‘length’ is length of input num.Create a 2D array int dp[MAX][9*MAX] where MAX is maximum possible length of input number. A value dp[position][previous] is going to store result for ‘position’ and ‘previous_sum’. If current subproblem has been evaluated i.e; dp[position][previous_sum] != -1, then use this result, else recursively compute its value. If by including the current position digit in sum i.e; sum = sum + num[position]-‘0’, sum becomes greater than equal to previous sum, then increment the result and call the problem for next position in the num.If position == length, then we have been traversed current subgroup successfully and we return 1; The maximum sum of digits can be 9*length where ‘length’ is length of input num. Create a 2D array int dp[MAX][9*MAX] where MAX is maximum possible length of input number. A value dp[position][previous] is going to store result for ‘position’ and ‘previous_sum’. If current subproblem has been evaluated i.e; dp[position][previous_sum] != -1, then use this result, else recursively compute its value. If by including the current position digit in sum i.e; sum = sum + num[position]-‘0’, sum becomes greater than equal to previous sum, then increment the result and call the problem for next position in the num. If position == length, then we have been traversed current subgroup successfully and we return 1; Below is the implementation of the above algorithm. C++ Java Python3 C# Javascript // C++ program to count number of// ways to group digits of a number// such that sum of digits in every// subgroup is less than or equal// to its immediate right subgroup.#include<bits/stdc++.h>using namespace std; // Maximum length of// input number stringconst int MAX = 40; // A memoization table to store// results of subproblems length// of string is 40 and maximum// sum will be 9 * 40 = 360.int dp[MAX][9*MAX + 1]; // Function to find the count// of splits with given conditionint countGroups(int position, int previous_sum, int length, char *num){ // Terminating Condition if (position == length) return 1; // If already evaluated for // a given sub problem then // return the value if (dp[position][previous_sum] != -1) return dp[position][previous_sum]; // countGroups for current // sub-group is 0 dp[position][previous_sum] = 0; int res = 0; // sum of digits int sum = 0; // Traverse all digits from // current position to rest // of the length of string for (int i = position; i < length; i++) { sum += (num[i] - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } dp[position][previous_sum] = res; // total number of subgroups // till current position return res;} // Driver Codeint main(){ char num[] = "1119"; int len = strlen(num); // Initialize dp table memset(dp, -1, sizeof(dp)); cout << countGroups(0, 0, len, num); return 0;} // Java program to count the number of// ways to group digits of a number// such that sum of digits in every// subgroup is less than or equal// to its immediate right subgroup.class GFG{ // Maximum length of// input number stringstatic int MAX = 40; // A memoization table to store// results of subproblems length// of string is 40 and maximum// sum will be 9 * 40 = 360.static int dp[][] = new int[MAX][9 * MAX + 1]; // Function to find the count// of splits with given conditionstatic int countGroups(int position, int previous_sum, int length, char []num){ // Terminating Condition if (position == length) return 1; // If already evaluated for // a given sub problem then // return the value if (dp[position][previous_sum] != -1) return dp[position][previous_sum]; // countGroups for current // sub-group is 0 dp[position][previous_sum] = 0; int res = 0; // sum of digits int sum = 0; // Traverse all digits from // current position to rest // of the length of string for (int i = position; i < length; i++) { sum += (num[i] - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } dp[position][previous_sum] = res; // total number of subgroups // till current position return res;} // Driver Codepublic static void main(String[] args){ char num[] = "1119".toCharArray(); int len = num.length; // Initialize dp table for(int i = 0; i < dp.length; i++) { for(int j = 0;j < 9 * MAX + 1; j++){ dp[i][j] = -1; } } System.out.println(countGroups(0, 0, len, num)); }} // This code is contributed by PrinciRaj1992 # Python3 program to count the number of# ways to group digits of a number# such that sum of digits in every# subgroup is less than or equal# to its immediate right subgroup. # Maximum length of# input number stringMAX = 40 # A memoization table to store# results of subproblems length# of string is 40 and maximum# sum will be 9 * 40 = 360.dp = [[ -1 for i in range(9 * MAX + 1)] for i in range(MAX)] # Function to find the count# of splits with given conditiondef countGroups(position, previous_sum, length, num): # Terminating Condition if (position == length): return 1 # If already evaluated for # a given sub problem then # return the value if (dp[position][previous_sum] != -1): return dp[position][previous_sum] # countGroups for current # sub-group is 0 dp[position][previous_sum] = 0 res = 0 # sum of digits sum = 0 # Traverse all digits from # current position to rest # of the length of string for i in range(position,length): sum += (ord(num[i]) - ord('0')) # If forward_sum is greater # than the previous sum, # then call the method again if (sum >= previous_sum): # Note : We pass current # sum as previous sum res += countGroups(i + 1, sum, length, num) dp[position][previous_sum] = res # total number of subgroups # till the current position return res # Driver Codenum = "1119"len = len(num) print(countGroups(0, 0, len, num)) # This code is contributed by Mohit Kumar // C# program to count number of// ways to group digits of a number// such that sum of digits in every// subgroup is less than or equal// to its immediate right subgroup.using System; class GFG{ // Maximum length of // input number string static int MAX = 40; // A memoization table to store // results of subproblems length // of string is 40 and maximum // sum will be 9 * 40 = 360. static int[,] dp = new int[MAX, 9 * MAX + 1]; // Function to find the count // of splits with given condition static int countGroups(int position, int previous_sum, int length, char[] num) { // Terminating Condition if (position == length) return 1; // If already evaluated for // a given sub problem then // return the value if (dp[position,previous_sum] != -1) return dp[position,previous_sum]; // countGroups for current // sub-group is 0 dp[position,previous_sum] = 0; int res = 0; // sum of digits int sum = 0; // Traverse all digits from // current position to rest // of the length of string for (int i = position; i < length; i++) { sum += (num[i] - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } dp[position,previous_sum] = res; // total number of subgroups // till current position return res; } // Driver Code static void Main() { char[] num = {'1', '1', '1', '9'}; int len = num.Length; // Initialize dp table for(int i = 0; i < MAX; i++) for(int j = 0; j < 9 * MAX + 1; j++) dp[i, j] = -1; Console.Write(countGroups(0, 0, len, num)); }} // This code is contributed by DrRoot_ <script> // Javascript program to count the number of// ways to group digits of a number// such that sum of digits in every// subgroup is less than or equal// to its immediate right subgroup. // Maximum length of // input number string let MAX = 40; // A memoization table to store // results of subproblems length // of string is 40 and maximum // sum will be 9 * 40 = 360. let dp=new Array(MAX); // Function to find the count // of splits with given condition function countGroups( position,previous_sum,length,num) { // Terminating Condition if (position == length) return 1; // If already evaluated for // a given sub problem then // return the value if (dp[position][previous_sum] != -1) return dp[position][previous_sum]; // countGroups for current // sub-group is 0 dp[position][previous_sum] = 0; let res = 0; // sum of digits let sum = 0; // Traverse all digits from // current position to rest // of the length of string for (let i = position; i < length; i++) { sum += (num[i] - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } dp[position][previous_sum] = res; // total number of subgroups // till current position return res; } // Driver Code let num = "1119".split(""); let len = num.length; // Initialize dp table for(let i = 0; i < dp.length; i++) { dp[i]=new Array(9 * MAX + 1) for(let j = 0;j < 9 * MAX + 1; j++){ dp[i][j] = -1; } } document.write(countGroups(0, 0, len, num)); // This code is contributed by unknown2108</script> Output : 7 This article is contributed by Shashank Mishra ( Gullu ). This article is reviewed by team GeeksForGeeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t vt_m Sanjit_Prasad 29AjayKumar princiraj1992 DrRoot_ mohit kumar 29 ujjwalmittal divyeshrabadiya07 unknown2108 number-digits Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Subset Sum Problem | DP-25 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Longest Palindromic Substring | Set 1 Coin Change | DP-7 Sieve of Eratosthenes Overlapping Subproblems Property in Dynamic Programming | DP-1 Edit Distance | DP-5
[ { "code": null, "e": 25116, "s": 25088, "text": "\n06 May, 2021" }, { "code": null, "e": 25692, "s": 25116, "text": "We are given a string consisting of digits, we may group these digits into sub-groups (but maintaining their original order). The task is to count the number of groupings such that for every sub-group except the last one, the sum of digits in a sub-group is less than or equal to the sum of the digits in the sub-group immediately on its right. For example, a valid grouping of digits of number 1119 is (1-11-9). Sum of digits in first subgroup is 1, next subgroup is 2, and last subgroup is 9. Sum of every subgroup is less than or equal to its immediate right. Examples : " }, { "code": null, "e": 26044, "s": 25692, "text": "Input : \"1119\"\nOutput: 7\nSub-groups: [1-119], [1-1-19], [1-11-9], [1-1-1-9],\n [11-19] and [111-9].\nNote : Here we have included [1119] in the group and\n the sum of digits is 12 and this group has no \n immediate right.\n\nInput : \"1234\"\nOutput: 6\nSub-groups : [1234], [1-234], [12-34], [1-2-3-4],\n [12-3-4] and [1-2-34]" }, { "code": null, "e": 26295, "s": 26046, "text": "Let “length” be the length of the input number. A recursive solution is to consider every position from 0 length-1. For every position, recursively count all possible subgroups after it. Below is C++ implementation of the naive recursive solution. " }, { "code": null, "e": 26299, "s": 26295, "text": "C++" }, { "code": null, "e": 26304, "s": 26299, "text": "Java" }, { "code": null, "e": 26312, "s": 26304, "text": "Python3" }, { "code": null, "e": 26315, "s": 26312, "text": "C#" }, { "code": null, "e": 26319, "s": 26315, "text": "PHP" }, { "code": null, "e": 26330, "s": 26319, "text": "Javascript" }, { "code": "// C++ program to count number of// ways to group digits of a number// such that sum of digits in every// subgroup is less than or equal to// its immediate right subgroup.#include<bits/stdc++.h>using namespace std; // Function to find the subgroupsint countGroups(int position, int previous_sum, int length, char *num){ // Terminating Condition if (position == length) return 1; int res = 0; // sum of digits int sum = 0; // Traverse all digits from // current position to rest // of the length of string for (int i = position; i < length; i++) { sum += (num[i] - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } // Total number of subgroups // till current position return res;} // Driver Codeint main(){ char num[] = \"1119\"; int len = strlen(num); cout << countGroups(0, 0, len, num); return 0;}", "e": 27474, "s": 26330, "text": null }, { "code": "// Java program to count number// of ways to group digits of // a number such that sum of // digits in every subgroup is// less than or equal to its// immediate right subgroup.import java.io.*; class GFG{ // Function to find// the subgroupsstatic int countGroups(int position, int previous_sum, int length, String num){ // Terminating Condition if (position == length) return 1; int res = 0; // sum of digits int sum = 0; // Traverse all digits from // current position to rest // of the length of string for (int i = position; i < length; i++) { sum += (num.charAt(i) - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } // Total number of subgroups // till current position return res;} // Driver Codepublic static void main (String[] args){ String num = \"1119\"; int len =num .length(); System.out.println(countGroups(0, 0, len, num));}} // This code is contributed by anuj_67.", "e": 28763, "s": 27474, "text": null }, { "code": "# Python3 program to count# number of ways to group digits# of a number such that sum of# digits in every subgroup# is less than or equal to its immediate# right subgroup. # Function to find the subgroupsdef countGroups(position, previous_sum, length, num): # Terminating Condition if(position == length): return 1 res = 0 # sum of digits sum = 0 # Traverse all digits from # current position to rest # of the length of string for i in range(position, length): sum = sum + int(num[i]) # If forward_sum is greater # than the previous sum, # then call the method again if (sum >= previous_sum): # Note : We pass current # sum as previous sum res = res + countGroups(i + 1, sum, length, num) # Total number of subgroups # till the current position return res # Driver Codeif __name__=='__main__': num = \"1119\" len = len(num) print(countGroups(0, 0, len, num)) # This code is contributed by# Sanjit_Prasad", "e": 29804, "s": 28763, "text": null }, { "code": "// C# program to count number// of ways to group digits of// a number such that sum of// digits in every subgroup is// less than or equal to its// immediate right subgroup.using System; class GFG{ // Function to find// the subgroupsstatic int countGroups(int position, int previous_sum, int length, String num){ // Terminating Condition if (position == length) return 1; int res = 0; // sum of digits int sum = 0; // Traverse all digits from // current position to rest // of the length of string for (int i = position; i < length; i++) { sum += (num[i] - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } // Total number of subgroups // till current position return res;} // Driver Codepublic static void Main (){ String num = \"1119\"; int len = num.Length; Console.Write(countGroups(0, 0, len, num));}} // This code is contributed by 29AjayKumar", "e": 31045, "s": 29804, "text": null }, { "code": "<?php// PHP program to count number of// ways to group digits of a number// such that sum of digits in every// subgroup is less than or equal// to its immediate right subgroup. // Function to find the subgroupsfunction countGroups($position, $previous_sum, $length,$num){ // Terminating Condition if ($position == $length) return 1; $res = 0; // sum of digits $sum = 0; // Traverse all digits from // current position to rest // of the length of string for ($i = $position; $i < $length; $i++) { $sum += ($num[$i] - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if ($sum >= $previous_sum) // Note : We pass current // sum as previous sum $res += countGroups($i + 1, $sum, $length, $num); } // Total number of subgroups // till current position return $res;} // Driver Code$num = \"1119\";$len = strlen($num);echo countGroups(0, 0, $len, $num); // This code is contributed by ajit?>", "e": 32152, "s": 31045, "text": null }, { "code": "<script> // Javascript program to count number // of ways to group digits of // a number such that sum of // digits in every subgroup is // less than or equal to its // immediate right subgroup. // Function to find // the subgroups function countGroups(position, previous_sum, length, num) { // Terminating Condition if (position == length) return 1; let res = 0; // sum of digits let sum = 0; // Traverse all digits from // current position to rest // of the length of string for (let i = position; i < length; i++) { sum += (num[i].charCodeAt() - '0'.charCodeAt()); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } // Total number of subgroups // till current position return res; } let num = \"1119\"; let len = num.length; document.write(countGroups(0, 0, len, num)); </script>", "e": 33386, "s": 32152, "text": null }, { "code": null, "e": 33396, "s": 33386, "text": "Output : " }, { "code": null, "e": 33398, "s": 33396, "text": "7" }, { "code": null, "e": 33822, "s": 33398, "text": "If we take a closer look at the above recursive solution, we notice that there may be overlapping subproblems. For example, if the input number is 12345, then for position = 3 and previous_sum = 3, we recur two times. Similarly, for position 4 and previous_sum = 7, we recur two times. Therefore the above solution can be optimized using Dynamic Programming. Below is a Dynamic Programming based solution for this problem. " }, { "code": null, "e": 34532, "s": 33822, "text": "The maximum sum of digits can be 9*length where ‘length’ is length of input num.Create a 2D array int dp[MAX][9*MAX] where MAX is maximum possible length of input number. A value dp[position][previous] is going to store result for ‘position’ and ‘previous_sum’. If current subproblem has been evaluated i.e; dp[position][previous_sum] != -1, then use this result, else recursively compute its value. If by including the current position digit in sum i.e; sum = sum + num[position]-‘0’, sum becomes greater than equal to previous sum, then increment the result and call the problem for next position in the num.If position == length, then we have been traversed current subgroup successfully and we return 1;" }, { "code": null, "e": 34613, "s": 34532, "text": "The maximum sum of digits can be 9*length where ‘length’ is length of input num." }, { "code": null, "e": 34797, "s": 34613, "text": "Create a 2D array int dp[MAX][9*MAX] where MAX is maximum possible length of input number. A value dp[position][previous] is going to store result for ‘position’ and ‘previous_sum’. " }, { "code": null, "e": 34937, "s": 34797, "text": "If current subproblem has been evaluated i.e; dp[position][previous_sum] != -1, then use this result, else recursively compute its value. " }, { "code": null, "e": 35148, "s": 34937, "text": "If by including the current position digit in sum i.e; sum = sum + num[position]-‘0’, sum becomes greater than equal to previous sum, then increment the result and call the problem for next position in the num." }, { "code": null, "e": 35246, "s": 35148, "text": "If position == length, then we have been traversed current subgroup successfully and we return 1;" }, { "code": null, "e": 35299, "s": 35246, "text": "Below is the implementation of the above algorithm. " }, { "code": null, "e": 35303, "s": 35299, "text": "C++" }, { "code": null, "e": 35308, "s": 35303, "text": "Java" }, { "code": null, "e": 35316, "s": 35308, "text": "Python3" }, { "code": null, "e": 35319, "s": 35316, "text": "C#" }, { "code": null, "e": 35330, "s": 35319, "text": "Javascript" }, { "code": "// C++ program to count number of// ways to group digits of a number// such that sum of digits in every// subgroup is less than or equal// to its immediate right subgroup.#include<bits/stdc++.h>using namespace std; // Maximum length of// input number stringconst int MAX = 40; // A memoization table to store// results of subproblems length// of string is 40 and maximum// sum will be 9 * 40 = 360.int dp[MAX][9*MAX + 1]; // Function to find the count// of splits with given conditionint countGroups(int position, int previous_sum, int length, char *num){ // Terminating Condition if (position == length) return 1; // If already evaluated for // a given sub problem then // return the value if (dp[position][previous_sum] != -1) return dp[position][previous_sum]; // countGroups for current // sub-group is 0 dp[position][previous_sum] = 0; int res = 0; // sum of digits int sum = 0; // Traverse all digits from // current position to rest // of the length of string for (int i = position; i < length; i++) { sum += (num[i] - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } dp[position][previous_sum] = res; // total number of subgroups // till current position return res;} // Driver Codeint main(){ char num[] = \"1119\"; int len = strlen(num); // Initialize dp table memset(dp, -1, sizeof(dp)); cout << countGroups(0, 0, len, num); return 0;}", "e": 37063, "s": 35330, "text": null }, { "code": " // Java program to count the number of// ways to group digits of a number// such that sum of digits in every// subgroup is less than or equal// to its immediate right subgroup.class GFG{ // Maximum length of// input number stringstatic int MAX = 40; // A memoization table to store// results of subproblems length// of string is 40 and maximum// sum will be 9 * 40 = 360.static int dp[][] = new int[MAX][9 * MAX + 1]; // Function to find the count// of splits with given conditionstatic int countGroups(int position, int previous_sum, int length, char []num){ // Terminating Condition if (position == length) return 1; // If already evaluated for // a given sub problem then // return the value if (dp[position][previous_sum] != -1) return dp[position][previous_sum]; // countGroups for current // sub-group is 0 dp[position][previous_sum] = 0; int res = 0; // sum of digits int sum = 0; // Traverse all digits from // current position to rest // of the length of string for (int i = position; i < length; i++) { sum += (num[i] - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } dp[position][previous_sum] = res; // total number of subgroups // till current position return res;} // Driver Codepublic static void main(String[] args){ char num[] = \"1119\".toCharArray(); int len = num.length; // Initialize dp table for(int i = 0; i < dp.length; i++) { for(int j = 0;j < 9 * MAX + 1; j++){ dp[i][j] = -1; } } System.out.println(countGroups(0, 0, len, num)); }} // This code is contributed by PrinciRaj1992", "e": 38987, "s": 37063, "text": null }, { "code": "# Python3 program to count the number of# ways to group digits of a number# such that sum of digits in every# subgroup is less than or equal# to its immediate right subgroup. # Maximum length of# input number stringMAX = 40 # A memoization table to store# results of subproblems length# of string is 40 and maximum# sum will be 9 * 40 = 360.dp = [[ -1 for i in range(9 * MAX + 1)] for i in range(MAX)] # Function to find the count# of splits with given conditiondef countGroups(position, previous_sum, length, num): # Terminating Condition if (position == length): return 1 # If already evaluated for # a given sub problem then # return the value if (dp[position][previous_sum] != -1): return dp[position][previous_sum] # countGroups for current # sub-group is 0 dp[position][previous_sum] = 0 res = 0 # sum of digits sum = 0 # Traverse all digits from # current position to rest # of the length of string for i in range(position,length): sum += (ord(num[i]) - ord('0')) # If forward_sum is greater # than the previous sum, # then call the method again if (sum >= previous_sum): # Note : We pass current # sum as previous sum res += countGroups(i + 1, sum, length, num) dp[position][previous_sum] = res # total number of subgroups # till the current position return res # Driver Codenum = \"1119\"len = len(num) print(countGroups(0, 0, len, num)) # This code is contributed by Mohit Kumar", "e": 40596, "s": 38987, "text": null }, { "code": "// C# program to count number of// ways to group digits of a number// such that sum of digits in every// subgroup is less than or equal// to its immediate right subgroup.using System; class GFG{ // Maximum length of // input number string static int MAX = 40; // A memoization table to store // results of subproblems length // of string is 40 and maximum // sum will be 9 * 40 = 360. static int[,] dp = new int[MAX, 9 * MAX + 1]; // Function to find the count // of splits with given condition static int countGroups(int position, int previous_sum, int length, char[] num) { // Terminating Condition if (position == length) return 1; // If already evaluated for // a given sub problem then // return the value if (dp[position,previous_sum] != -1) return dp[position,previous_sum]; // countGroups for current // sub-group is 0 dp[position,previous_sum] = 0; int res = 0; // sum of digits int sum = 0; // Traverse all digits from // current position to rest // of the length of string for (int i = position; i < length; i++) { sum += (num[i] - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } dp[position,previous_sum] = res; // total number of subgroups // till current position return res; } // Driver Code static void Main() { char[] num = {'1', '1', '1', '9'}; int len = num.Length; // Initialize dp table for(int i = 0; i < MAX; i++) for(int j = 0; j < 9 * MAX + 1; j++) dp[i, j] = -1; Console.Write(countGroups(0, 0, len, num)); }} // This code is contributed by DrRoot_", "e": 42766, "s": 40596, "text": null }, { "code": "<script> // Javascript program to count the number of// ways to group digits of a number// such that sum of digits in every// subgroup is less than or equal// to its immediate right subgroup. // Maximum length of // input number string let MAX = 40; // A memoization table to store // results of subproblems length // of string is 40 and maximum // sum will be 9 * 40 = 360. let dp=new Array(MAX); // Function to find the count // of splits with given condition function countGroups( position,previous_sum,length,num) { // Terminating Condition if (position == length) return 1; // If already evaluated for // a given sub problem then // return the value if (dp[position][previous_sum] != -1) return dp[position][previous_sum]; // countGroups for current // sub-group is 0 dp[position][previous_sum] = 0; let res = 0; // sum of digits let sum = 0; // Traverse all digits from // current position to rest // of the length of string for (let i = position; i < length; i++) { sum += (num[i] - '0'); // If forward_sum is greater // than the previous sum, // then call the method again if (sum >= previous_sum) // Note : We pass current // sum as previous sum res += countGroups(i + 1, sum, length, num); } dp[position][previous_sum] = res; // total number of subgroups // till current position return res; } // Driver Code let num = \"1119\".split(\"\"); let len = num.length; // Initialize dp table for(let i = 0; i < dp.length; i++) { dp[i]=new Array(9 * MAX + 1) for(let j = 0;j < 9 * MAX + 1; j++){ dp[i][j] = -1; } } document.write(countGroups(0, 0, len, num)); // This code is contributed by unknown2108</script>", "e": 44699, "s": 42766, "text": null }, { "code": null, "e": 44710, "s": 44699, "text": "Output : " }, { "code": null, "e": 44713, "s": 44710, "text": " 7" }, { "code": null, "e": 44945, "s": 44713, "text": "This article is contributed by Shashank Mishra ( Gullu ). This article is reviewed by team GeeksForGeeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 44951, "s": 44945, "text": "jit_t" }, { "code": null, "e": 44956, "s": 44951, "text": "vt_m" }, { "code": null, "e": 44970, "s": 44956, "text": "Sanjit_Prasad" }, { "code": null, "e": 44982, "s": 44970, "text": "29AjayKumar" }, { "code": null, "e": 44996, "s": 44982, "text": "princiraj1992" }, { "code": null, "e": 45004, "s": 44996, "text": "DrRoot_" }, { "code": null, "e": 45019, "s": 45004, "text": "mohit kumar 29" }, { "code": null, "e": 45032, "s": 45019, "text": "ujjwalmittal" }, { "code": null, "e": 45050, "s": 45032, "text": "divyeshrabadiya07" }, { "code": null, "e": 45062, "s": 45050, "text": "unknown2108" }, { "code": null, "e": 45076, "s": 45062, "text": "number-digits" }, { "code": null, "e": 45096, "s": 45076, "text": "Dynamic Programming" }, { "code": null, "e": 45116, "s": 45096, "text": "Dynamic Programming" }, { "code": null, "e": 45214, "s": 45116, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45245, "s": 45214, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 45278, "s": 45245, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 45313, "s": 45278, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 45340, "s": 45313, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 45408, "s": 45340, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 45446, "s": 45408, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 45465, "s": 45446, "text": "Coin Change | DP-7" }, { "code": null, "e": 45487, "s": 45465, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 45550, "s": 45487, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" } ]
How to use multiple for and while loops together in Python?
You can create nested loops in python fairly easily. You can even nest a for loop inside a while loop or the other way around. For example, for i in range(5): j = i while j != 0: print(j, end=', ') j -= 1 print("") This will give the output 1, 2, 1, 3, 2, 1, 4, 3, 2, 1, You can take this nesting to as many levels as you like.
[ { "code": null, "e": 1202, "s": 1062, "text": "You can create nested loops in python fairly easily. You can even nest a for loop inside a while loop or the other way around. For example," }, { "code": null, "e": 1298, "s": 1202, "text": "for i in range(5):\n j = i\n while j != 0:\n print(j, end=', ')\n j -= 1\n print(\"\")" }, { "code": null, "e": 1324, "s": 1298, "text": "This will give the output" }, { "code": null, "e": 1354, "s": 1324, "text": "1,\n2, 1,\n3, 2, 1,\n4, 3, 2, 1," }, { "code": null, "e": 1411, "s": 1354, "text": "You can take this nesting to as many levels as you like." } ]
C Program to print hollow pyramid and diamond pattern
Here we will see how to generate hollow pyramid and diamond patterns using C. We can generate solid Pyramid patterns very easily. To make it hollow, we have to add some few tricks. For the pyramid at the first line it will print one star, and at the last line it will print n number of stars. For other lines it will print exactly two stars at the start and end of the line, and there will be some blank spaces between these two starts. #include <stdio.h> int main() { int n, i, j; printf("Enter number of lines: "); scanf("%d", &n); for(i = 1; i<=n; i++) { for(j = 1; j<=(n-i); j++){ //print the blank spaces before star printf(" "); } if(i == 1 || i == n){ //for the first and last line, print the stars continuously for(j = 1; j<=i; j++) { printf("* "); } } else { printf("*"); //in each line star at start and end position for(j = 1; j<=2*i-3; j++) { //print space to make hollow printf(" "); } printf("*"); } printf("\n"); } } Enter number of lines: 20 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * For the diamond at the first line and at the last line it will print one star. For other lines it will print exactly two stars at the start and end of the line, and there will be some blank spaces between these two starts. Diamond has two parts. The upper half and the lower half. At the upper half we have to increase the space count, and for the lower half, we have to decrease the space count. Here the line numbers can be divided into two parts by using another variable called mid. #include <stdio.h> int main() { int n, i, j, mid; printf("Enter number of lines: "); scanf("%d", &n); if(n %2 == 1) { //when n is odd, increase it by 1 to make it even n++; } mid = (n/2); for(i = 1; i<= mid; i++) { for(j = 1; j<=(mid-i); j++){ //print the blank spaces before star printf(" "); } if(i == 1) { printf("*"); } else { printf("*"); //in each line star at start and end position for(j = 1; j<=2*i-3; j++){ //print space to make hollow printf(" "); } printf("*"); } printf("\n"); } for(i = mid+1; i<n; i++) { for(j = 1; j<=i-mid; j++) { //print the blank spaces before star printf(" "); } if(i == n-1) { printf("*"); } else { printf("*"); //in each line star at start and end position for(j = 1; j<=2*(n - i)-3; j++) { //print space to make hollow printf(" "); } printf("*"); } printf("\n"); } Enter number of lines: 15 * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[ { "code": null, "e": 1243, "s": 1062, "text": "Here we will see how to generate hollow pyramid and diamond patterns using C. We can generate solid Pyramid patterns very easily. To make it hollow, we have to add some few tricks." }, { "code": null, "e": 1499, "s": 1243, "text": "For the pyramid at the first line it will print one star, and at the last line it will print n number of stars. For other lines it will print exactly two stars at the start and end of the line, and there will be some blank spaces between these two starts." }, { "code": null, "e": 2150, "s": 1499, "text": "#include <stdio.h>\nint main() {\n int n, i, j;\n printf(\"Enter number of lines: \");\n scanf(\"%d\", &n);\n for(i = 1; i<=n; i++) {\n for(j = 1; j<=(n-i); j++){ //print the blank spaces before star\n printf(\" \");\n }\n if(i == 1 || i == n){ //for the first and last line, print the\n stars continuously\n for(j = 1; j<=i; j++) {\n printf(\"* \");\n }\n } else {\n printf(\"*\"); //in each line star at start and end\n position\n for(j = 1; j<=2*i-3; j++) { //print space to make hollow\n printf(\" \");\n }\n printf(\"*\");\n }\n printf(\"\\n\");\n }\n}" }, { "code": null, "e": 3246, "s": 2150, "text": "Enter number of lines: 20\n *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * * * * * * * * * * * * * * * * * * * * " }, { "code": null, "e": 3733, "s": 3246, "text": "For the diamond at the first line and at the last line it will print one star. For other lines it will print exactly two stars at the start and end of the line, and there will be some blank spaces between these two starts. Diamond has two parts. The upper half and the lower half. At the upper half we have to increase the space count, and for the lower half, we have to decrease the space count. Here the line numbers can be divided into two parts by using another variable called mid." }, { "code": null, "e": 4707, "s": 3733, "text": "#include <stdio.h>\nint main() {\n int n, i, j, mid;\n printf(\"Enter number of lines: \");\n scanf(\"%d\", &n);\n if(n %2 == 1) { //when n is odd, increase it by 1 to make it even\n n++;\n}\nmid = (n/2);\nfor(i = 1; i<= mid; i++) {\n for(j = 1; j<=(mid-i); j++){ //print the blank spaces before star\n printf(\" \");\n }\n if(i == 1) {\n printf(\"*\");\n } else {\n printf(\"*\"); //in each line star at start and end\n position\n for(j = 1; j<=2*i-3; j++){ //print space to make hollow\n printf(\" \");\n }\n printf(\"*\");\n }\n printf(\"\\n\");\n}\nfor(i = mid+1; i<n; i++) {\n for(j = 1; j<=i-mid; j++) { //print the blank spaces before star\n printf(\" \");\n }\n if(i == n-1) {\n printf(\"*\");\n } else {\n printf(\"*\"); //in each line star at start and end\n position\n for(j = 1; j<=2*(n - i)-3; j++) { //print space to make\n hollow\n printf(\" \");\n }\n printf(\"*\");\n }\n printf(\"\\n\");\n}" }, { "code": null, "e": 5165, "s": 4707, "text": "Enter number of lines: 15\n *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n * *\n *" } ]
React Events
Just like HTML DOM events, React can perform actions based on user events. React has the same events as HTML: click, change, mouseover etc. React events are written in camelCase syntax: onClick instead of onclick. React event handlers are written inside curly braces: onClick={shoot} instead of onClick="shoot()". <button onClick={shoot}>Take the Shot!</button> <button onclick="shoot()">Take the Shot!</button> Put the shoot function inside the Football component: function Football() { const shoot = () => { alert("Great Shot!"); } return ( <button onClick={shoot}>Take the shot!</button> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Football />); Run Example » To pass an argument to an event handler, use an arrow function. Send "Goal!" as a parameter to the shoot function, using arrow function: function Football() { const shoot = (a) => { alert(a); } return ( <button onClick={() => shoot("Goal!")}>Take the shot!</button> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Football />); Run Example » Event handlers have access to the React event that triggered the function. In our example the event is the "click" event. Arrow Function: Sending the event object manually: function Football() { const shoot = (a, b) => { alert(b.type); /* 'b' represents the React event that triggered the function, in this case the 'click' event */ } return ( <button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Football />); Run Example » This will come in handy when we look at Form in a later chapter. Complete this statement to include a click event handler. <button ={clicked()}>Click Me!</button> Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 75, "s": 0, "text": "Just like HTML DOM events, React can perform actions based on user events." }, { "code": null, "e": 140, "s": 75, "text": "React has the same events as HTML: click, change, mouseover etc." }, { "code": null, "e": 186, "s": 140, "text": "React events are written in camelCase syntax:" }, { "code": null, "e": 214, "s": 186, "text": "onClick\ninstead of onclick." }, { "code": null, "e": 269, "s": 214, "text": "React event handlers are written inside curly \nbraces:" }, { "code": null, "e": 317, "s": 269, "text": "onClick={shoot} instead of\nonClick=\"shoot()\". " }, { "code": null, "e": 366, "s": 317, "text": "<button onClick={shoot}>Take the Shot!</button>\n" }, { "code": null, "e": 417, "s": 366, "text": "<button onclick=\"shoot()\">Take the Shot!</button>\n" }, { "code": null, "e": 473, "s": 417, "text": "Put the shoot function inside the\n Football component:" }, { "code": null, "e": 716, "s": 473, "text": "function Football() {\n const shoot = () => {\n alert(\"Great Shot!\");\n }\n\n return (\n <button onClick={shoot}>Take the shot!</button>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Football />);\n" }, { "code": null, "e": 733, "s": 716, "text": "\nRun \nExample »\n" }, { "code": null, "e": 797, "s": 733, "text": "To pass an argument to an event handler, use an arrow function." }, { "code": null, "e": 876, "s": 797, "text": "Send \"Goal!\" as a parameter to the shoot \n function, using arrow \n function:" }, { "code": null, "e": 1123, "s": 876, "text": "function Football() {\n const shoot = (a) => {\n alert(a);\n }\n\n return (\n <button onClick={() => shoot(\"Goal!\")}>Take the shot!</button>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Football />);\n" }, { "code": null, "e": 1140, "s": 1123, "text": "\nRun \nExample »\n" }, { "code": null, "e": 1215, "s": 1140, "text": "Event handlers have access to the React event that triggered the function." }, { "code": null, "e": 1262, "s": 1215, "text": "In our example the event is the \"click\" event." }, { "code": null, "e": 1313, "s": 1262, "text": "Arrow Function: Sending the event object manually:" }, { "code": null, "e": 1695, "s": 1313, "text": "function Football() {\n const shoot = (a, b) => {\n alert(b.type);\n /*\n 'b' represents the React event that triggered the function,\n in this case the 'click' event\n */\n }\n\n return (\n <button onClick={(event) => shoot(\"Goal!\", event)}>Take the shot!</button>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Football />);\n \n" }, { "code": null, "e": 1712, "s": 1695, "text": "\nRun \nExample »\n" }, { "code": null, "e": 1778, "s": 1712, "text": "This will come in handy when we look at Form in \na later chapter." }, { "code": null, "e": 1836, "s": 1778, "text": "Complete this statement to include a click event handler." }, { "code": null, "e": 1877, "s": 1836, "text": "<button ={clicked()}>Click Me!</button>\n" }, { "code": null, "e": 1896, "s": 1877, "text": "Start the Exercise" }, { "code": null, "e": 1929, "s": 1896, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1971, "s": 1929, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2078, "s": 1971, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2097, "s": 2078, "text": "help@w3schools.com" } ]
How To Organize Data Science Project Notebooks With Extensions | Towards Data Science
While working on a Data Science project notebook, I create code and markdown cells every minute, print variables, get results, visualize data, try tens of visualizations to find the best looking ones... If I don’t keep well organized during all this process, I can’t manage to come to the end of the project until the deadline. In this article, I am going to share the Jupyter notebook extensions I use everyday while working on a project. In the terminal: pip install jupyter_contrib_nbextensions In Jupyter notebook: ! pip install jupyter_contrib_nbextensions After installing notebook extensions, click on the Home tab, then click Nbextensions. Select Collapsible Headings, Codefolding, Table of Contents(2), Autopep8, and ExecuteTime. After opening your notebook you will see the following toolbar. Time to discover these 5 extensions: This extension is going to keep you organized in your technical presentations. Here is all your project: Only one line! It is very easy to navigate through these collapsible headings. This is kind of a collapsible heading in code cells. If you use this extension, your code is going to look shorter. Long code cells are hidden. The little blue left-right arrow shows that you can open this line. This is the icon for the table of contents extension in the notebook. When you click it, a window pops up on the left. You can change settings by clicking the settings button. The best thing in this extension is, you do nothing. The table of contents is prepared automatically. You just put headings to markdown cells, and it automatically gives numbers to your headings. Love it! What is PEP-8 style? PEP-8 is a guideline on how to write easy-to-read and consistent code. It is written by Guido van Rossum, Barry Warsaw, and Nick Coghlan in 2001. How to install autopep8? python3 -m pip install autopep8 This code installs the autopep8 to Python3 How to use autopep8? Go to the cell you want to fit the pep8 standards. Just click this icon at the toolbar. It will change your code from something like this, into something like that. Cool! Execution time is important if you are working with a huge amount of data. You try to decrease computing costs and make your code run faster. Instead of using the %timeit or %time commands, you can measure running time and timestamps for all cells. Jupyter notebook has around 60 extensions. I shared only 5 of them that make my life easier. Discover the other extensions by just clicking on them. Any suggestions to seymatas@gmail.com will be very appreciated!
[ { "code": null, "e": 500, "s": 172, "text": "While working on a Data Science project notebook, I create code and markdown cells every minute, print variables, get results, visualize data, try tens of visualizations to find the best looking ones... If I don’t keep well organized during all this process, I can’t manage to come to the end of the project until the deadline." }, { "code": null, "e": 612, "s": 500, "text": "In this article, I am going to share the Jupyter notebook extensions I use everyday while working on a project." }, { "code": null, "e": 629, "s": 612, "text": "In the terminal:" }, { "code": null, "e": 670, "s": 629, "text": "pip install jupyter_contrib_nbextensions" }, { "code": null, "e": 691, "s": 670, "text": "In Jupyter notebook:" }, { "code": null, "e": 734, "s": 691, "text": "! pip install jupyter_contrib_nbextensions" }, { "code": null, "e": 820, "s": 734, "text": "After installing notebook extensions, click on the Home tab, then click Nbextensions." }, { "code": null, "e": 911, "s": 820, "text": "Select Collapsible Headings, Codefolding, Table of Contents(2), Autopep8, and ExecuteTime." }, { "code": null, "e": 975, "s": 911, "text": "After opening your notebook you will see the following toolbar." }, { "code": null, "e": 1012, "s": 975, "text": "Time to discover these 5 extensions:" }, { "code": null, "e": 1091, "s": 1012, "text": "This extension is going to keep you organized in your technical presentations." }, { "code": null, "e": 1132, "s": 1091, "text": "Here is all your project: Only one line!" }, { "code": null, "e": 1196, "s": 1132, "text": "It is very easy to navigate through these collapsible headings." }, { "code": null, "e": 1408, "s": 1196, "text": "This is kind of a collapsible heading in code cells. If you use this extension, your code is going to look shorter. Long code cells are hidden. The little blue left-right arrow shows that you can open this line." }, { "code": null, "e": 1478, "s": 1408, "text": "This is the icon for the table of contents extension in the notebook." }, { "code": null, "e": 1527, "s": 1478, "text": "When you click it, a window pops up on the left." }, { "code": null, "e": 1584, "s": 1527, "text": "You can change settings by clicking the settings button." }, { "code": null, "e": 1789, "s": 1584, "text": "The best thing in this extension is, you do nothing. The table of contents is prepared automatically. You just put headings to markdown cells, and it automatically gives numbers to your headings. Love it!" }, { "code": null, "e": 1810, "s": 1789, "text": "What is PEP-8 style?" }, { "code": null, "e": 1956, "s": 1810, "text": "PEP-8 is a guideline on how to write easy-to-read and consistent code. It is written by Guido van Rossum, Barry Warsaw, and Nick Coghlan in 2001." }, { "code": null, "e": 1981, "s": 1956, "text": "How to install autopep8?" }, { "code": null, "e": 2013, "s": 1981, "text": "python3 -m pip install autopep8" }, { "code": null, "e": 2056, "s": 2013, "text": "This code installs the autopep8 to Python3" }, { "code": null, "e": 2077, "s": 2056, "text": "How to use autopep8?" }, { "code": null, "e": 2165, "s": 2077, "text": "Go to the cell you want to fit the pep8 standards. Just click this icon at the toolbar." }, { "code": null, "e": 2216, "s": 2165, "text": "It will change your code from something like this," }, { "code": null, "e": 2242, "s": 2216, "text": "into something like that." }, { "code": null, "e": 2248, "s": 2242, "text": "Cool!" }, { "code": null, "e": 2497, "s": 2248, "text": "Execution time is important if you are working with a huge amount of data. You try to decrease computing costs and make your code run faster. Instead of using the %timeit or %time commands, you can measure running time and timestamps for all cells." }, { "code": null, "e": 2646, "s": 2497, "text": "Jupyter notebook has around 60 extensions. I shared only 5 of them that make my life easier. Discover the other extensions by just clicking on them." } ]
Python interface for SQLite databases
SQLite is an open source database and is serverless that needs no configuration. Entire database is a single disk file that can be placed anywhere in operating system's file system. SQLite commands are similar to standard SQL. SQLite is extensively used by applications such as browsers for internal data storage. It is also convenient data storage for embedded devices. Standard Python library has in built support for SQLite database connectivity. It contains sqlite3 module which is a DB-API V2 compliant module written by Gerhad Haring. It adheres to DB-API 2.0. The DB-API has been defined in accordance with PEP-249 to ensure similarity between the Python modules that are used to access different databases products. First step in database handling process is to obtain a connection object representing the database. Next using the connection, obtain a cursor object. A cursor object is similar to the concept of iterator. It is used to process individual rows returned by database queries. A cursor can be viewed as a pointer to one row in a set of rows. The cursor object helps in executing SQL queries for performing CRUD operations on the underlying database. This function in sqlite3 module returns connection object representing an existing database on disk , or opens a new database if it doesn't exist already. import sqlite3 conn=sqlite3.connect('mydb.sqlite3') SQLite supports creation of in-memory database. Use a special name ':memory:' for that purpose conn=sqlite3.connect(':memory:') Following methods are defined in Connection class cursor() This method returns cursor object. cur=conn.cursor() commit() − This method persistently commits transactions to the disk. rollback() − This method rolls back transactions to restore database state to last call to commit(). This method ensures data consistency in case of exceptions in SQL transactions. try: conn.commit() except: conn.rollback() execute() − Implicitly creates cursor and calls its execute() method executemany() − This method implicitly creates cursor and calls its executemany() method create_function() − This method creates a user-defined function that you can later use from within SQL statements. create_aggregate() − This method creates an aggregate function. iterdump() − This method creates a dump of database in SQL text format. import sqlite3 con = sqlite3.connect('mydb.sqlite3') f = dump.sql', 'w') for line in con.iterdump(): f.write('%s\n' % line) backup() − This method creates a backup of SQLite database even while it is being accessed. source = sqlite3.connect('mydb.sqlite3') dest = sqlite3.connect(':memory:') source.backup(dest) Cursor obtained from connection object facilitates performing various SQL operations on the database using execute() method. For instance, following statement creates a table in the current database cur = conn.cursor() cur.execute("CREATE TABLE guests ( ID INTEGER PRIMARY KEY, name TEXT (20) NOT NULL, address TEXT (40), city TEXT (20) );" Following inserts a record in the table cur.execute('''INSERT INTO GUESTS VALUES(1,'RAJU','ABIDS', 'HYDERABAD');''') Use executemany() method to perform bulk addition operation addreses=[(2,'KISHAN', 'TILAK ROAD', 'PUNE'), (3, 'LATA', 'GAANDHI NAGAR', 'AURANGABAD')] sql='INSERT INTO GUESTS VALUES (:ID, :NAME, :ADD, :CITY)' cur.executemany(sql, addreses) SELECT query forms a result set containing all records returned as a response to query. The execute() method uses a string representing SELECT query statement. There are two methods in DB-API to retrieve rows in the cursor representing the result set. fetchone() − Fetches next available record from the result set in the form a tuple consisting of values of each column of the fetched record. fetchall() − Fetches all remaining records in the form of list of tuples. Each tuple corresponds to one row and contains values of each column in the table. Following code uses fetchone() method to list all records in guests table sql = "SELECT * from guests;" cur = db.cursor() cur.execute(sql) while True: record=cur.fetchone() if record==None: break print (record) Use of fetchall() method is demonstrated by following statement sql = "SELECT * from guests;" cur = db.cursor() cur.execute(sql) set = cur.fetchall() for record in set: print (record) SQLite data types are by default mapped to equivalent Python data types as per following table The DB-API defines following exceptions with respect to SQL operations with a SQLite database −
[ { "code": null, "e": 1433, "s": 1062, "text": "SQLite is an open source database and is serverless that needs no configuration. Entire database is a single disk file that can be placed anywhere in operating system's file system. SQLite commands are similar to standard SQL. SQLite is extensively used by applications such as browsers for internal data storage. It is also convenient data storage for embedded devices." }, { "code": null, "e": 1629, "s": 1433, "text": "Standard Python library has in built support for SQLite database connectivity. It contains sqlite3 module which is a DB-API V2 compliant module written by Gerhad Haring. It adheres to DB-API 2.0." }, { "code": null, "e": 1786, "s": 1629, "text": "The DB-API has been defined in accordance with PEP-249 to ensure similarity between the Python modules that are used to access different databases products." }, { "code": null, "e": 2125, "s": 1786, "text": "First step in database handling process is to obtain a connection object representing the database. Next using the connection, obtain a cursor object. A cursor object is similar to the concept of iterator. It is used to process individual rows returned by database queries. A cursor can be viewed as a pointer to one row in a set of rows." }, { "code": null, "e": 2233, "s": 2125, "text": "The cursor object helps in executing SQL queries for performing CRUD operations on the underlying database." }, { "code": null, "e": 2388, "s": 2233, "text": "This function in sqlite3 module returns connection object representing an existing database on disk , or opens a new database if it doesn't exist already." }, { "code": null, "e": 2440, "s": 2388, "text": "import sqlite3\nconn=sqlite3.connect('mydb.sqlite3')" }, { "code": null, "e": 2535, "s": 2440, "text": "SQLite supports creation of in-memory database. Use a special name ':memory:' for that purpose" }, { "code": null, "e": 2568, "s": 2535, "text": "conn=sqlite3.connect(':memory:')" }, { "code": null, "e": 2618, "s": 2568, "text": "Following methods are defined in Connection class" }, { "code": null, "e": 2662, "s": 2618, "text": "cursor() This method returns cursor object." }, { "code": null, "e": 2680, "s": 2662, "text": "cur=conn.cursor()" }, { "code": null, "e": 2750, "s": 2680, "text": "commit() − This method persistently commits transactions to the disk." }, { "code": null, "e": 2931, "s": 2750, "text": "rollback() − This method rolls back transactions to restore database state to last call to commit(). This method ensures data consistency in case of exceptions in SQL transactions." }, { "code": null, "e": 2974, "s": 2931, "text": "try:\nconn.commit()\nexcept:\nconn.rollback()" }, { "code": null, "e": 3043, "s": 2974, "text": "execute() − Implicitly creates cursor and calls its execute() method" }, { "code": null, "e": 3132, "s": 3043, "text": "executemany() − This method implicitly creates cursor and calls its executemany() method" }, { "code": null, "e": 3247, "s": 3132, "text": "create_function() − This method creates a user-defined function that you can later use from within SQL statements." }, { "code": null, "e": 3311, "s": 3247, "text": "create_aggregate() − This method creates an aggregate function." }, { "code": null, "e": 3383, "s": 3311, "text": "iterdump() − This method creates a dump of database in SQL text format." }, { "code": null, "e": 3507, "s": 3383, "text": "import sqlite3\ncon = sqlite3.connect('mydb.sqlite3')\nf = dump.sql', 'w')\nfor line in con.iterdump():\nf.write('%s\\n' % line)" }, { "code": null, "e": 3599, "s": 3507, "text": "backup() − This method creates a backup of SQLite database even while it is being accessed." }, { "code": null, "e": 3695, "s": 3599, "text": "source = sqlite3.connect('mydb.sqlite3')\ndest = sqlite3.connect(':memory:')\nsource.backup(dest)" }, { "code": null, "e": 3894, "s": 3695, "text": "Cursor obtained from connection object facilitates performing various SQL operations on the database using execute() method. For instance, following statement creates a table in the current database" }, { "code": null, "e": 4048, "s": 3894, "text": "cur = conn.cursor()\ncur.execute(\"CREATE TABLE guests (\n ID INTEGER PRIMARY KEY,\n name TEXT (20) NOT NULL,\n address TEXT (40),\n city TEXT (20)\n);\"" }, { "code": null, "e": 4088, "s": 4048, "text": "Following inserts a record in the table" }, { "code": null, "e": 4165, "s": 4088, "text": "cur.execute('''INSERT INTO GUESTS VALUES(1,'RAJU','ABIDS', 'HYDERABAD');''')" }, { "code": null, "e": 4225, "s": 4165, "text": "Use executemany() method to perform bulk addition operation" }, { "code": null, "e": 4404, "s": 4225, "text": "addreses=[(2,'KISHAN', 'TILAK ROAD', 'PUNE'), (3, 'LATA', 'GAANDHI NAGAR', 'AURANGABAD')]\nsql='INSERT INTO GUESTS VALUES (:ID, :NAME, :ADD, :CITY)'\ncur.executemany(sql, addreses)" }, { "code": null, "e": 4656, "s": 4404, "text": "SELECT query forms a result set containing all records returned as a response to query. The execute() method uses a string representing SELECT query statement. There are two methods in DB-API to retrieve rows in the cursor representing the result set." }, { "code": null, "e": 4798, "s": 4656, "text": "fetchone() − Fetches next available record from the result set in the form a tuple consisting of values of each column of the fetched record." }, { "code": null, "e": 4955, "s": 4798, "text": "fetchall() − Fetches all remaining records in the form of list of tuples. Each tuple corresponds to one row and contains values of each column in the table." }, { "code": null, "e": 5029, "s": 4955, "text": "Following code uses fetchone() method to list all records in guests table" }, { "code": null, "e": 5166, "s": 5029, "text": "sql = \"SELECT * from guests;\"\ncur = db.cursor()\ncur.execute(sql)\nwhile True:\nrecord=cur.fetchone()\nif record==None:\nbreak\nprint (record)" }, { "code": null, "e": 5230, "s": 5166, "text": "Use of fetchall() method is demonstrated by following statement" }, { "code": null, "e": 5350, "s": 5230, "text": "sql = \"SELECT * from guests;\"\ncur = db.cursor()\ncur.execute(sql)\nset = cur.fetchall()\nfor record in set:\nprint (record)" }, { "code": null, "e": 5445, "s": 5350, "text": "SQLite data types are by default mapped to equivalent Python data types as per following table" }, { "code": null, "e": 5541, "s": 5445, "text": "The DB-API defines following exceptions with respect to SQL operations with a SQLite database −" } ]
Lambda Functions with Example and Error Handling | by Wie Kiang H. | Towards Data Science
Before going through this, you need to be familiar with defining your own function in Python; otherwise, you will get lost in the middle. The articles below will give you more information on how to define your own function. towardsdatascience.com towardsdatascience.com towardsdatascience.com There is a more agile way to write functions on the fly, and these are called lambda functions. It is because we use the keyword lambda. For example, we write a function called raise_number_to_power as a lambda function. After the keyword lambda, we specify the names of the arguments, which is x and y. Then, we use a colon, followed by the expression that defines what we wish the function to return. Lambda functions allow you to write immediate functions in dirty ways, so I wouldn’t recommend you to use them all the time, but there are situations when they can come in very helpful. For example, the map function, which takes two arguments. A function and a sequence such as a list, and the function over all elements of the sequence. We can carry lambda functions to map without even naming them, and in this case, we refer to them as anonymous functions. For instance, we use a map on a lambda function that squares all elements of a list, and you will store the result in a square variable. While printing the square variable, it reveals that it is a map object. To see what it contains, we use the function list to turn it into a list and print the results. As expected, it’s a list containing the squares of the elements in the original list. When you misuse a function, it should throw you an error. For example, check out the function float that returns a floating-point from a number or string. When you pass the function float an integer value, the corresponding float is returned. Similarly, if you give it the string 8.7 it will return the float value. However, if you pass it the string hello, Python will throw an error showing you that it couldn’t convert the string to float. In this case, it threw a ValueError, and there are many types of errors. When we write our functions, we may wish to discover particular problems and write specific error messages. Let’s check out the user-defined function that computes the square root of a number. It works as expected with integers. What are the results if we pass it a string such as hello? It will throw you an error corresponding to a line of code within the function definition. This error says it was some TypeError, but the message may not be particularly helpful to a user of our function, so we should attempt to provide useful error messages for the functions we write. The primary method to catch such exceptions is the try-except clause, in which Python tries to run the code following a try, and if it can, all is well. If it cannot work due to an exception, it runs the exception code. Let’s now rewrite our square_root function, but this time catch any exceptions raised. In the example, we try to execute x to the power of 0.5. Using except, in the case of an exception, we print x must be an int or float. We see that the resulting function works well for ints and floats and prints out what we wanted it to for a string. We may also wish only to catch TypeError and let other errors pass through, in which case we would use except TypeError. Many different types of exceptions can be detected, and you can have a look at them in the Python documentation available online. Instead of slightly printing an error message, you will want to raise an error by using the keyword raise. For example, the square_root function does something we may not want when applied to negative numbers. It returns a complex number that we may not want. Let’s say that we don’t wish our function to work for negative numbers. Using an if clause, we can raise a ValueError for cases in which the user passes the function a negative number. If we give our new function a negative number, see it returns the prescribed ValueError. Other Interesting Articles#1 Function Arguments: Default, Keyword, and Arbitrary#2 Scope of Variable and LEGB Rule#3 Writing Your Own Functions#4 Python: Procedural or Object-Oriented Programming?#5 Data Science with Python: How to Use NumPy Library#6 Do you have the Software Engineer and Data Scientist skills? Wie Kiang is a researcher who is responsible for collecting, organizing, and analyzing opinions and data to solve problems, explore issues, and predict trends. He is working in almost every sector of Machine Learning and Deep Learning. He is carrying out experiments and investigations in a range of areas, including Convolutional Neural Networks, Natural Language Processing, and Recurrent Neural Networks. Connect on LinkedIn
[ { "code": null, "e": 396, "s": 172, "text": "Before going through this, you need to be familiar with defining your own function in Python; otherwise, you will get lost in the middle. The articles below will give you more information on how to define your own function." }, { "code": null, "e": 419, "s": 396, "text": "towardsdatascience.com" }, { "code": null, "e": 442, "s": 419, "text": "towardsdatascience.com" }, { "code": null, "e": 465, "s": 442, "text": "towardsdatascience.com" }, { "code": null, "e": 868, "s": 465, "text": "There is a more agile way to write functions on the fly, and these are called lambda functions. It is because we use the keyword lambda. For example, we write a function called raise_number_to_power as a lambda function. After the keyword lambda, we specify the names of the arguments, which is x and y. Then, we use a colon, followed by the expression that defines what we wish the function to return." }, { "code": null, "e": 1206, "s": 868, "text": "Lambda functions allow you to write immediate functions in dirty ways, so I wouldn’t recommend you to use them all the time, but there are situations when they can come in very helpful. For example, the map function, which takes two arguments. A function and a sequence such as a list, and the function over all elements of the sequence." }, { "code": null, "e": 1719, "s": 1206, "text": "We can carry lambda functions to map without even naming them, and in this case, we refer to them as anonymous functions. For instance, we use a map on a lambda function that squares all elements of a list, and you will store the result in a square variable. While printing the square variable, it reveals that it is a map object. To see what it contains, we use the function list to turn it into a list and print the results. As expected, it’s a list containing the squares of the elements in the original list." }, { "code": null, "e": 2035, "s": 1719, "text": "When you misuse a function, it should throw you an error. For example, check out the function float that returns a floating-point from a number or string. When you pass the function float an integer value, the corresponding float is returned. Similarly, if you give it the string 8.7 it will return the float value." }, { "code": null, "e": 2614, "s": 2035, "text": "However, if you pass it the string hello, Python will throw an error showing you that it couldn’t convert the string to float. In this case, it threw a ValueError, and there are many types of errors. When we write our functions, we may wish to discover particular problems and write specific error messages. Let’s check out the user-defined function that computes the square root of a number. It works as expected with integers. What are the results if we pass it a string such as hello? It will throw you an error corresponding to a line of code within the function definition." }, { "code": null, "e": 2810, "s": 2614, "text": "This error says it was some TypeError, but the message may not be particularly helpful to a user of our function, so we should attempt to provide useful error messages for the functions we write." }, { "code": null, "e": 3369, "s": 2810, "text": "The primary method to catch such exceptions is the try-except clause, in which Python tries to run the code following a try, and if it can, all is well. If it cannot work due to an exception, it runs the exception code. Let’s now rewrite our square_root function, but this time catch any exceptions raised. In the example, we try to execute x to the power of 0.5. Using except, in the case of an exception, we print x must be an int or float. We see that the resulting function works well for ints and floats and prints out what we wanted it to for a string." }, { "code": null, "e": 3727, "s": 3369, "text": "We may also wish only to catch TypeError and let other errors pass through, in which case we would use except TypeError. Many different types of exceptions can be detected, and you can have a look at them in the Python documentation available online. Instead of slightly printing an error message, you will want to raise an error by using the keyword raise." }, { "code": null, "e": 4154, "s": 3727, "text": "For example, the square_root function does something we may not want when applied to negative numbers. It returns a complex number that we may not want. Let’s say that we don’t wish our function to work for negative numbers. Using an if clause, we can raise a ValueError for cases in which the user passes the function a negative number. If we give our new function a negative number, see it returns the prescribed ValueError." }, { "code": null, "e": 4467, "s": 4154, "text": "Other Interesting Articles#1 Function Arguments: Default, Keyword, and Arbitrary#2 Scope of Variable and LEGB Rule#3 Writing Your Own Functions#4 Python: Procedural or Object-Oriented Programming?#5 Data Science with Python: How to Use NumPy Library#6 Do you have the Software Engineer and Data Scientist skills?" }, { "code": null, "e": 4627, "s": 4467, "text": "Wie Kiang is a researcher who is responsible for collecting, organizing, and analyzing opinions and data to solve problems, explore issues, and predict trends." }, { "code": null, "e": 4875, "s": 4627, "text": "He is working in almost every sector of Machine Learning and Deep Learning. He is carrying out experiments and investigations in a range of areas, including Convolutional Neural Networks, Natural Language Processing, and Recurrent Neural Networks." } ]
Simple File Upload Script in PHP
Theory of Computation In this tutorial, you will learn a simple script to upload a file on a remote server using a simple HTML form and store it in a directory. It is easy to upload a file to the server using PHP. This can be used to upload any type of file, like PDF, doc, image, video, zip files and other file types. We can also strict by specifying file type, set the limited file size and much more. To create a File Uploader, first create a form and add a file type input field. The file type input shows the "Browse" button on the web page. If a form contains any file type input field, then we want to make sure to add a form attribute 'encrypt' with a value 'multipart/form-data'. The encrypt attribute specifies the content-type to be uploaded. First, make sure that PHP is configured to allow the file upload. For this, open the 'php.ini' file and look for 'file_uploads' directive and set it on. file_uploads = On <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data"> <div class="form-group"> <label class="col-md-3 control-label">Upload a file (PDF, DOC, DOCX)</label> <div class="col-md-6"> <input type="file" name="attachment" class="form-control-file" /> </div> </div> <div class="form-group"> <div class="col-md-9 col-md-offset-3"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> PHP has a global array $_FILES, to handle the file upload. This array returns the following data of the uploaded files. Suppose the name of the input field to upload file is 'attachment', then we will get the following array after uploading the file - $_FILES['attachment']['name'] $_FILES['attachment']['type'] $_FILES['attachment']['size'] $_FILES['attachment']['tmp_name'] $_FILES['attachment']['error'] When a file is uploaded, it first saves in a temporary directory on the server. In the given code, the is_uploaded_file() function is used to check the file whether it is successfully uploaded or not. <?php // check the file is uploaded or not if (is_uploaded_file($_FILES['attachment']['tmp_name'])) { $errors= array(); // Determine the file location $newname = dirname(__FILE__) . '/' .basename($_FILES['attachment']['name']); } ?> Now, we want to check the size of the uploaded file. If the file is larger than 2MB, an error message is displayed. The other file extension raises an error message. if($_FILES['attachment']['size'] > 2097152) { $errors[]='File size must be excately 2 MB'; } The code below only allows the users to upload PDF, DOC, DOCX files. // Check Allowed File Types $file_ext=strtolower(end(explode('.',$_FILES['attachment']['name']))); $extensions= array("pdf","doc","docx"); if(in_array($file_ext,$extensions)=== false){ $errors[]="File extension not allowed, please choose a PDF, DOC, DOCX file."; } PHP predefined function move_uploaded_file() is used to move the uploaded file from the temporary location to a specified location. // Move the file from temporary location to specified location if (!(move_uploaded_file($_FILES['attachment']['tmp_name'], $newname))) { print_r($errors); } else { echo "<p>The file saved as: {$newname}</p>\n"; } Here, we have merged the above code and got the full script to upload a file. <html> <head> <title>Simple File Upload Script in PHP</title> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <?php // check the file is uploaded or not if (is_uploaded_file($_FILES['attachment']['tmp_name'])) { // Determine the file location $newname = dirname(__FILE__) . '/' .basename($_FILES['attachment']['name']); if($_FILES['attachment']['size'] > 2097152) { $errors[]='File size must be excately 2 MB'; } // Check Allowed File Types $file_ext=strtolower(end(explode('.',$_FILES['attachment']['name']))); $extensions= array("pdf","doc","docx"); if(in_array($file_ext,$extensions)=== false){ $errors[]="File extension not allowed, please choose a PDF, DOC, DOCX file."; } if(empty($errors)==true){ // Move the file from temporary location to determined location if (!(move_uploaded_file($_FILES['attachment']['tmp_name'], $newname))) { echo "<p>ERROR: A problem occurred during file upload!</p>\n"; } else { echo "<p>The file has been saved as: {$newname}</p>\n"; } } else{ print_r($errors); } } ?> <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data"> <div class="form-group"> <label class="col-md-3 control-label">Upload a file (PDF, DOC, DOCX)</label> <div class="col-md-6"> <input type="file" name="attachment" class="form-control-file" /> </div> </div> <div class="form-group"> <div class="col-md-9 col-md-offset-3"> <button type="submit" class="btn btn-primary">Submit</button>
[ { "code": null, "e": 112, "s": 90, "text": "Theory of Computation" }, { "code": null, "e": 495, "s": 112, "text": "In this tutorial, you will learn a simple script to upload a file on a remote server using a simple HTML form and store it in a directory. It is easy to upload a file to the server using PHP. This can be used to upload any type of file, like PDF, doc, image, video, zip files and other file types. We can also strict by specifying file type, set the limited file size and much more." }, { "code": null, "e": 845, "s": 495, "text": "To create a File Uploader, first create a form and add a file type input field. The file type input shows the \"Browse\" button on the web page. If a form contains any file type input field, then we want to make sure to add a form attribute 'encrypt' with a value 'multipart/form-data'. The encrypt attribute specifies the content-type to be uploaded." }, { "code": null, "e": 999, "s": 845, "text": "First, make sure that PHP is configured to allow the file upload. For this, open the 'php.ini' file and look for \n'file_uploads' directive and set it on." }, { "code": null, "e": 1017, "s": 999, "text": "file_uploads = On" }, { "code": null, "e": 1472, "s": 1017, "text": "<form action=\"<?php echo $_SERVER['PHP_SELF'] ?>\" method=\"post\" enctype=\"multipart/form-data\">\n<div class=\"form-group\">\n\t<label class=\"col-md-3 control-label\">Upload a file (PDF, DOC, DOCX)</label>\n\t<div class=\"col-md-6\">\n\t<input type=\"file\" name=\"attachment\" class=\"form-control-file\" />\n\t</div>\n</div>\n<div class=\"form-group\">\n\t<div class=\"col-md-9 col-md-offset-3\">\n\t<button type=\"submit\" class=\"btn btn-primary\">Submit</button>\n\t</div>\n</div>\n</form>" }, { "code": null, "e": 1724, "s": 1472, "text": "PHP has a global array $_FILES, to handle the file upload. This array returns the following data of the uploaded files. Suppose the name of the input field to upload file is 'attachment', then we will get the following array after uploading the file -" }, { "code": null, "e": 1883, "s": 1724, "text": "$_FILES['attachment']['name']\n\n$_FILES['attachment']['type']\n\n$_FILES['attachment']['size']\n\n$_FILES['attachment']['tmp_name']\n\n$_FILES['attachment']['error']" }, { "code": null, "e": 2084, "s": 1883, "text": "When a file is uploaded, it first saves in a temporary directory on the server. In the given code, the is_uploaded_file() function is used to check the file whether it is successfully uploaded or not." }, { "code": null, "e": 2334, "s": 2084, "text": "<?php \n\n// check the file is uploaded or not\nif (is_uploaded_file($_FILES['attachment']['tmp_name'])) { \n $errors= array();\n\n\t// Determine the file location\n\t$newname = dirname(__FILE__) . '/' .basename($_FILES['attachment']['name']);\n}\n?>" }, { "code": null, "e": 2500, "s": 2334, "text": "Now, we want to check the size of the uploaded file. If the file is larger than 2MB, an error message is displayed. The other file extension raises an error message." }, { "code": null, "e": 2603, "s": 2500, "text": "if($_FILES['attachment']['size'] > 2097152) {\n $errors[]='File size must be excately 2 MB';\n}\n" }, { "code": null, "e": 2673, "s": 2603, "text": "The code below only allows the users to upload PDF, DOC, DOCX files. " }, { "code": null, "e": 2943, "s": 2673, "text": "// Check Allowed File Types\n\t$file_ext=strtolower(end(explode('.',$_FILES['attachment']['name'])));\n\t$extensions= array(\"pdf\",\"doc\",\"docx\");\n\tif(in_array($file_ext,$extensions)=== false){\n\t\t$errors[]=\"File extension not allowed, please choose a PDF, DOC, DOCX file.\";\n}" }, { "code": null, "e": 3075, "s": 2943, "text": "PHP predefined function move_uploaded_file() is used to move the uploaded file from the temporary location to a specified location." }, { "code": null, "e": 3295, "s": 3075, "text": "// Move the file from temporary location to specified location\n\tif (!(move_uploaded_file($_FILES['attachment']['tmp_name'], $newname))) {\n\t\tprint_r($errors);\n\t} else {\n\t\techo \"<p>The file saved as: {$newname}</p>\\n\";\n\t}" }, { "code": null, "e": 3373, "s": 3295, "text": "Here, we have merged the above code and got the full script to upload a file." } ]
Compute the Negative Binomial Density in R Programming - dnbinom() Function - GeeksforGeeks
25 Jun, 2020 dnbinom() function in R Language is used to compute the value of negative binomial density. It also creates a plot of the negative binomial density. Syntax: dnbinom(vec, size, prob) Parameters:vec: x-values for binomial densitysize: Number of trialsprob: Probability Example 1: # R program to compute# Negative Binomial Density # Vector of x-valuesx <- seq(0, 10, by = 1) # Calling dnbinom() Functiony <- dnbinom(x, size = 10, prob = 0.5)y Output: [1] 0.0009765625 0.0048828125 0.0134277344 0.0268554688 0.0436401367 [6] 0.0610961914 0.0763702393 0.0872802734 0.0927352905 0.0927352905 [11] 0.0880985260 Example 2: # R program to compute# Negative Binomial Density # Vector of x-valuesx <- seq(0, 100, by = 1) # Calling dnbinom() Functiony <- dnbinom(x, size = 10, prob = 0.5) # Plot a graphplot(y) Output: R Statistics-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Printing Output of an R Program How to Change Axis Scales in R Plots? Group by function in R using Dplyr K-Means Clustering in R Programming Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 25316, "s": 25288, "text": "\n25 Jun, 2020" }, { "code": null, "e": 25465, "s": 25316, "text": "dnbinom() function in R Language is used to compute the value of negative binomial density. It also creates a plot of the negative binomial density." }, { "code": null, "e": 25498, "s": 25465, "text": "Syntax: dnbinom(vec, size, prob)" }, { "code": null, "e": 25583, "s": 25498, "text": "Parameters:vec: x-values for binomial densitysize: Number of trialsprob: Probability" }, { "code": null, "e": 25594, "s": 25583, "text": "Example 1:" }, { "code": "# R program to compute# Negative Binomial Density # Vector of x-valuesx <- seq(0, 10, by = 1) # Calling dnbinom() Functiony <- dnbinom(x, size = 10, prob = 0.5)y", "e": 25758, "s": 25594, "text": null }, { "code": null, "e": 25766, "s": 25758, "text": "Output:" }, { "code": null, "e": 25925, "s": 25766, "text": " [1] 0.0009765625 0.0048828125 0.0134277344 0.0268554688 0.0436401367\n [6] 0.0610961914 0.0763702393 0.0872802734 0.0927352905 0.0927352905\n[11] 0.0880985260\n" }, { "code": null, "e": 25936, "s": 25925, "text": "Example 2:" }, { "code": "# R program to compute# Negative Binomial Density # Vector of x-valuesx <- seq(0, 100, by = 1) # Calling dnbinom() Functiony <- dnbinom(x, size = 10, prob = 0.5) # Plot a graphplot(y)", "e": 26123, "s": 25936, "text": null }, { "code": null, "e": 26131, "s": 26123, "text": "Output:" }, { "code": null, "e": 26153, "s": 26131, "text": "R Statistics-Function" }, { "code": null, "e": 26164, "s": 26153, "text": "R Language" }, { "code": null, "e": 26262, "s": 26164, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26320, "s": 26262, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 26372, "s": 26320, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 26404, "s": 26372, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 26456, "s": 26404, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26500, "s": 26456, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 26532, "s": 26500, "text": "Printing Output of an R Program" }, { "code": null, "e": 26570, "s": 26532, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26605, "s": 26570, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26641, "s": 26605, "text": "K-Means Clustering in R Programming" } ]
Recursive and Recursive Enumerable Languages in TOC
29 Nov, 2021 Recursive Enumerable (RE) or Type -0 Language RE languages or type-0 languages are generated by type-0 grammars. An RE language can be accepted or recognized by Turing machine which means it will enter into final state for the strings of language and may or may not enter into rejecting state for the strings which are not part of the language. It means TM can loop forever for the strings which are not a part of the language. RE languages are also called as Turing recognizable languages. Recursive Language (REC) A recursive language (subset of RE) can be decided by Turing machine which means it will enter into final state for the strings of language and rejecting state for the strings which are not part of the language. e.g.; L= {anbncn|n>=1} is recursive because we can construct a turing machine which will move to final state if the string is of the form anbncn else move to non-final state. So the TM will always halt in this case. REC languages are also called as Turing decidable languages. The relationship between RE and REC languages can be shown in Figure 1. Closure Properties of Recursive Languages Union: If L1 and If L2 are two recursive languages, their union L1∪L2 will also be recursive because if TM halts for L1 and halts for L2, it will also halt for L1∪L2. Concatenation: If L1 and If L2 are two recursive languages, their concatenation L1.L2 will also be recursive. For Example: L1= {anbncn|n>=0} L2= {dmemfm|m>=0} L3= L1.L2 = {anbncndm emfm|m>=0 and n>=0} is also recursive. L1 says n no. of a’s followed by n no. of b’s followed by n no. of c’s. L2 says m no. of d’s followed by m no. of e’s followed by m no. of f’s. Their concatenation first matches no. of a’s, b’s and c’s and then matches no. of d’s, e’s and f’s. So it can be decided by TM. Kleene Closure: If L1is recursive, its kleene closure L1* will also be recursive. For Example: L1= {anbncn|n>=0} L1*= { anbncn||n>=0}* is also recursive. Intersection and complement: If L1 and If L2 are two recursive languages, their intersection L1 ∩ L2 will also be recursive. For Example: L1= {anbncndm|n>=0 and m>=0} L2= {anbncndn|n>=0 and m>=0} L3=L1 ∩ L2 = { anbncndn |n>=0} will be recursive. L1 says n no. of a’s followed by n no. of b’s followed by n no. of c’s and then any no. of d’s. L2 says any no. of a’s followed by n no. of b’s followed by n no. of c’s followed by n no. of d’s. Their intersection says n no. of a’s followed by n no. of b’s followed by n no. of c’s followed by n no. of d’s. So it can be decided by turing machine, hence recursive. Similarly, complement of recursive language L1 which is ∑*-L1, will also be recursive. Note: As opposed to REC languages, RE languages are not closed under complementation which means complement of RE language need not be RE. GATE Questions Question 1: Which of the following statements is/are FALSE? 1.For every non-deterministic TM, there exists an equivalent deterministic TM. 2.Turing recognizable languages are closed under union and complementation. 3.Turing decidable languages are closed under intersection and complementation. 4.Turing recognizable languages are closed under union and intersection. A.1 and 4 B.1 and 3 C.2 D.3 Solution: Statement 1 is true as we can convert every non-deterministic TM to deterministic TM. Statement 2 is false as Turing recognizable languages (RE languages) are not closed under complementation. Statement 3 is true as Turing decidable languages (REC languages) are closed under intersection and complementation. Statement 4 is true as Turing recognizable languages (RE languages) are closed under union and intersection. Question 2 : Let L be a language and L’ be its complement. Which one of the following is NOT a viable possibility? A.Neither L nor L’ is RE. B.One of L and L’ is RE but not recursive; the other is not RE. C.Both L and L’ are RE but not recursive. D.Both L and L’ are recursive. Solution: Option A is correct because if L is not RE, its complementation will not be RE. Option B is correct because if L is RE, L’ need not be RE or vice versa because RE languages are not closed under complementation. Option C is false because if L is RE, L’ will not be RE. But if L is recursive, L’ will also be recursive and both will be RE as well because REC languages are subset of RE. As they have mentioned not to be REC, so option is false. Option D is correct because if L is recursive L’ will also be recursive. Question 3: Let L1 be a recursive language, and let L2 be a recursively enumerable but not a recursive language. Which one of the following is TRUE? A.L1′ is recursive and L2′ is recursively enumerable B.L1′ is recursive and L2′ is not recursively enumerable C.L1′ and L2′ are recursively enumerable D.L1′ is recursively enumerable and L2′ is recursive Solution: Option A is False as L2’ can’t be recursive enumerable (L2 is RE and RE are not closed under complementation). Option B is correct as L1’ is REC (REC languages are closed under complementation) and L2’ is not recursive enumerable (RE languages are not closed under complementation). Option C is False as L2’ can’t be recursive enumerable (L2 is RE and RE are not closed under complementation). Option D is False as L2’ can’t be recursive enumerable (L2 is RE and RE languages are not closed under complementation). As REC languages are subset of RE, L2’ can’t be REC as well. This article is contributed by Sonal Tuteja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Karthiik kk9826225 Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Nov, 2021" }, { "code": null, "e": 98, "s": 52, "text": "Recursive Enumerable (RE) or Type -0 Language" }, { "code": null, "e": 543, "s": 98, "text": "RE languages or type-0 languages are generated by type-0 grammars. An RE language can be accepted or recognized by Turing machine which means it will enter into final state for the strings of language and may or may not enter into rejecting state for the strings which are not part of the language. It means TM can loop forever for the strings which are not a part of the language. RE languages are also called as Turing recognizable languages." }, { "code": null, "e": 568, "s": 543, "text": "Recursive Language (REC)" }, { "code": null, "e": 1131, "s": 568, "text": "A recursive language (subset of RE) can be decided by Turing machine which means it will enter into final state for the strings of language and rejecting state for the strings which are not part of the language. e.g.; L= {anbncn|n>=1} is recursive because we can construct a turing machine which will move to final state if the string is of the form anbncn else move to non-final state. So the TM will always halt in this case. REC languages are also called as Turing decidable languages. The relationship between RE and REC languages can be shown in Figure 1. " }, { "code": null, "e": 1175, "s": 1133, "text": "Closure Properties of Recursive Languages" }, { "code": null, "e": 1342, "s": 1175, "text": "Union: If L1 and If L2 are two recursive languages, their union L1∪L2 will also be recursive because if TM halts for L1 and halts for L2, it will also halt for L1∪L2." }, { "code": null, "e": 1466, "s": 1342, "text": "Concatenation: If L1 and If L2 are two recursive languages, their concatenation L1.L2 will also be recursive. For Example: " }, { "code": null, "e": 1580, "s": 1466, "text": " L1= {anbncn|n>=0} \n L2= {dmemfm|m>=0}\n L3= L1.L2\n = {anbncndm emfm|m>=0 and n>=0} is also recursive." }, { "code": null, "e": 1852, "s": 1580, "text": "L1 says n no. of a’s followed by n no. of b’s followed by n no. of c’s. L2 says m no. of d’s followed by m no. of e’s followed by m no. of f’s. Their concatenation first matches no. of a’s, b’s and c’s and then matches no. of d’s, e’s and f’s. So it can be decided by TM." }, { "code": null, "e": 1947, "s": 1852, "text": "Kleene Closure: If L1is recursive, its kleene closure L1* will also be recursive. For Example:" }, { "code": null, "e": 2024, "s": 1947, "text": " L1= {anbncn|n>=0}\n L1*= { anbncn||n>=0}* is also recursive." }, { "code": null, "e": 2163, "s": 2024, "text": "Intersection and complement: If L1 and If L2 are two recursive languages, their intersection L1 ∩ L2 will also be recursive. For Example: " }, { "code": null, "e": 2288, "s": 2163, "text": " L1= {anbncndm|n>=0 and m>=0} \n L2= {anbncndn|n>=0 and m>=0}\n L3=L1 ∩ L2\n = { anbncndn |n>=0} will be recursive." }, { "code": null, "e": 2742, "s": 2290, "text": "L1 says n no. of a’s followed by n no. of b’s followed by n no. of c’s and then any no. of d’s. L2 says any no. of a’s followed by n no. of b’s followed by n no. of c’s followed by n no. of d’s. Their intersection says n no. of a’s followed by n no. of b’s followed by n no. of c’s followed by n no. of d’s. So it can be decided by turing machine, hence recursive. Similarly, complement of recursive language L1 which is ∑*-L1, will also be recursive." }, { "code": null, "e": 2881, "s": 2742, "text": "Note: As opposed to REC languages, RE languages are not closed under complementation which means complement of RE language need not be RE." }, { "code": null, "e": 2897, "s": 2881, "text": "GATE Questions " }, { "code": null, "e": 3265, "s": 2897, "text": "Question 1: Which of the following statements is/are FALSE? 1.For every non-deterministic TM, there exists an equivalent deterministic TM. 2.Turing recognizable languages are closed under union and complementation. 3.Turing decidable languages are closed under intersection and complementation. 4.Turing recognizable languages are closed under union and intersection." }, { "code": null, "e": 3293, "s": 3265, "text": "A.1 and 4 B.1 and 3 C.2 D.3" }, { "code": null, "e": 3303, "s": 3293, "text": "Solution:" }, { "code": null, "e": 3722, "s": 3303, "text": "Statement 1 is true as we can convert every non-deterministic TM to deterministic TM. Statement 2 is false as Turing recognizable languages (RE languages) are not closed under complementation. Statement 3 is true as Turing decidable languages (REC languages) are closed under intersection and complementation. Statement 4 is true as Turing recognizable languages (RE languages) are closed under union and intersection." }, { "code": null, "e": 4000, "s": 3722, "text": "Question 2 : Let L be a language and L’ be its complement. Which one of the following is NOT a viable possibility? A.Neither L nor L’ is RE. B.One of L and L’ is RE but not recursive; the other is not RE. C.Both L and L’ are RE but not recursive. D.Both L and L’ are recursive." }, { "code": null, "e": 4010, "s": 4000, "text": "Solution:" }, { "code": null, "e": 4526, "s": 4010, "text": "Option A is correct because if L is not RE, its complementation will not be RE. Option B is correct because if L is RE, L’ need not be RE or vice versa because RE languages are not closed under complementation. Option C is false because if L is RE, L’ will not be RE. But if L is recursive, L’ will also be recursive and both will be RE as well because REC languages are subset of RE. As they have mentioned not to be REC, so option is false. Option D is correct because if L is recursive L’ will also be recursive." }, { "code": null, "e": 4675, "s": 4526, "text": "Question 3: Let L1 be a recursive language, and let L2 be a recursively enumerable but not a recursive language. Which one of the following is TRUE?" }, { "code": null, "e": 4889, "s": 4675, "text": "A.L1′ is recursive and L2′ is recursively enumerable B.L1′ is recursive and L2′ is not recursively enumerable C.L1′ and L2′ are recursively enumerable D.L1′ is recursively enumerable and L2′ is recursive Solution:" }, { "code": null, "e": 5465, "s": 4889, "text": "Option A is False as L2’ can’t be recursive enumerable (L2 is RE and RE are not closed under complementation). Option B is correct as L1’ is REC (REC languages are closed under complementation) and L2’ is not recursive enumerable (RE languages are not closed under complementation). Option C is False as L2’ can’t be recursive enumerable (L2 is RE and RE are not closed under complementation). Option D is False as L2’ can’t be recursive enumerable (L2 is RE and RE languages are not closed under complementation). As REC languages are subset of RE, L2’ can’t be REC as well." }, { "code": null, "e": 5634, "s": 5465, "text": "This article is contributed by Sonal Tuteja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 5643, "s": 5634, "text": "Karthiik" }, { "code": null, "e": 5653, "s": 5643, "text": "kk9826225" }, { "code": null, "e": 5686, "s": 5653, "text": "Theory of Computation & Automata" } ]
Flutter – BoxConstraints Widget
09 Aug, 2021 BoxConstraints is a built-in widget in flutter SDK. Its functionality is to add sized constraints on its child widget. It is usually taken as the object of constraints property in ConstrainedBox widget. It comes packed with many properties for customization. Below we will see all its properties with and an example, It paints a box with the mentioned constraints. const BoxConstraints( {double minWidth: 0.0, double maxWidth: double.infinity, double minHeight: 0.0, double maxHeight: double.infinity} ) It paints a box which expands to fill its parent BoxConstriants widget. const BoxConstraints.expand( {double? width, double? height} ) It created a box which does not grow beyond the mentioned size. BoxConstraints.loose( Size size ) It will create a box which does not change its size. BoxConstraints.tight( Size size ) It will paint a box on the screen with by just mentioning its height and width. const BoxConstraints.tightFor( {double? width, double? height} ) Here we get a box whose height and width is set to infinity if not mentioned. const BoxConstraints.tightForFinite( {double width: double.infinity, double height: double.infinity} ) biggest: This property takes in Size class as the object to specify the biggest the box can get. flipped: The flipped property takes in BoxConstriants class as the object to flip the height and width properties of the widget. hasBoundedHeight: This property takes in a boolean as the object to specify whether the maxHeight had an upper limit. hasBoundedWidth: This property takes in a boolean as the object to specify whether the maxWidth had an upper limit. hasInfiniteHeight: This property also takes in a boolean as the object to determine whether the box has infinite height. hasInfiniteWidth: This property also takes in a boolean as the object to determine whether the box has infinite width. hasTightHeight: This property determines whether the box height will be fixed to only one value or not by taking in a boolean as the object. hasTightWidth: This property determines whether the box width will be fixed to only one value or not by taking in a boolean as the object isNormalized: It also takes in a boolean value as the object to specify if the maximum and minimum height and width will be same ort not. isTight: The isTight property also takes in a boolean as the object to determine whether the box constraints will be fixed to only one height and width or not. maxHeight: This property takes in a double value as the object to control the maximum height the box can get to. maxWith: This property takes in a double value as the object to control the maximum width box will get to. minHeight: This property takes in a double value as the object to control the minimum height box will get to. minWidth: This property takes in a double value as the object to control the minimum width box will get to. smallest: This property controls the smallest size the box can achieve by taking in Size class as the object. Example 1: Dart import 'package:flutter/material.dart'; //Material design libraryvoid main() { runApp( //widget tree starts here MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], centerTitle: true, ), //AppBar body: Center( child: Container( color: Colors.green, padding: EdgeInsets.all(20), child: Text( 'GfG', style: TextStyle(color: Colors.white, fontSize: 20), ), //Text /** BoxConstraints Widget **/ constraints: BoxConstraints( minHeight: 50, minWidth: 50, maxHeight: 80, maxWidth: 80), //BoxConstraints ), //container ), //Center ), //Scaffold ), //MaterialApp );} Output: Explanation: Inside the Container widget which is a child of Center widget (Parent widget in the body) the constraints property is holding BoxConstraints widget. Inside that the minHeight and minWidth are set to 50 px and maxHeight and maxWidth is set to 80 px. The Container is green colored and is holding white colored text. The constraints that are set will not allow the container to have a height and width greater than 80 px and less than 50 px. Example 2: Dart import 'package:flutter/material.dart'; //Material design libraryvoid main() { runApp( //widget tree starts here MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], centerTitle: true, ), //AppBar body: Center( child: Container( color: Colors.green, padding: EdgeInsets.all(20), /** BoxConstraints Widget **/ constraints: BoxConstraints( minHeight: 50, minWidth: 50, maxHeight: 80, maxWidth: 80), //BoxConstraints child: Container( color: Colors.greenAccent[400], child: Text( 'GfG', style: TextStyle(color: Colors.white, fontSize: 20), ), //Text constraints: BoxConstraints.expand(height: 50, width: 50), )), //container ), //Center ), //Scaffold ), //MaterialApp );} Output: Explanation: This flutter app is similar to the previous one, except the fact the child widget in the Container which was a Text is replaced by another Container widget. The second container is assigned a color of greenAccent[400], and the child is a Text widget. The constraints property in the second container is taking BoxConstraints.expand as the object, with its height and width property set to 50 px each. The BoxConstraints.expands is expanding in its parent BoxConstraints to a height and width of 50 px. And because of the fact it expands, it always starts from the center. sagartomar9927 Flutter-widgets Android Dart Flutter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Custom Bottom Navigation Bar Splash Screen in Flutter Flutter - Asset Image
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Aug, 2021" }, { "code": null, "e": 369, "s": 52, "text": "BoxConstraints is a built-in widget in flutter SDK. Its functionality is to add sized constraints on its child widget. It is usually taken as the object of constraints property in ConstrainedBox widget. It comes packed with many properties for customization. Below we will see all its properties with and an example," }, { "code": null, "e": 418, "s": 369, "text": " It paints a box with the mentioned constraints." }, { "code": null, "e": 557, "s": 418, "text": "const BoxConstraints(\n{double minWidth: 0.0,\ndouble maxWidth: double.infinity,\ndouble minHeight: 0.0,\ndouble maxHeight: double.infinity}\n)" }, { "code": null, "e": 629, "s": 557, "text": "It paints a box which expands to fill its parent BoxConstriants widget." }, { "code": null, "e": 692, "s": 629, "text": "const BoxConstraints.expand(\n{double? width,\ndouble? height}\n)" }, { "code": null, "e": 757, "s": 692, "text": "It created a box which does not grow beyond the mentioned size. " }, { "code": null, "e": 791, "s": 757, "text": "BoxConstraints.loose(\nSize size\n)" }, { "code": null, "e": 845, "s": 791, "text": " It will create a box which does not change its size." }, { "code": null, "e": 879, "s": 845, "text": "BoxConstraints.tight(\nSize size\n)" }, { "code": null, "e": 960, "s": 879, "text": " It will paint a box on the screen with by just mentioning its height and width." }, { "code": null, "e": 1025, "s": 960, "text": "const BoxConstraints.tightFor(\n{double? width,\ndouble? height}\n)" }, { "code": null, "e": 1104, "s": 1025, "text": " Here we get a box whose height and width is set to infinity if not mentioned." }, { "code": null, "e": 1207, "s": 1104, "text": "const BoxConstraints.tightForFinite(\n{double width: double.infinity,\ndouble height: double.infinity}\n)" }, { "code": null, "e": 1304, "s": 1207, "text": "biggest: This property takes in Size class as the object to specify the biggest the box can get." }, { "code": null, "e": 1433, "s": 1304, "text": "flipped: The flipped property takes in BoxConstriants class as the object to flip the height and width properties of the widget." }, { "code": null, "e": 1551, "s": 1433, "text": "hasBoundedHeight: This property takes in a boolean as the object to specify whether the maxHeight had an upper limit." }, { "code": null, "e": 1667, "s": 1551, "text": "hasBoundedWidth: This property takes in a boolean as the object to specify whether the maxWidth had an upper limit." }, { "code": null, "e": 1788, "s": 1667, "text": "hasInfiniteHeight: This property also takes in a boolean as the object to determine whether the box has infinite height." }, { "code": null, "e": 1907, "s": 1788, "text": "hasInfiniteWidth: This property also takes in a boolean as the object to determine whether the box has infinite width." }, { "code": null, "e": 2048, "s": 1907, "text": "hasTightHeight: This property determines whether the box height will be fixed to only one value or not by taking in a boolean as the object." }, { "code": null, "e": 2186, "s": 2048, "text": "hasTightWidth: This property determines whether the box width will be fixed to only one value or not by taking in a boolean as the object" }, { "code": null, "e": 2324, "s": 2186, "text": "isNormalized: It also takes in a boolean value as the object to specify if the maximum and minimum height and width will be same ort not." }, { "code": null, "e": 2484, "s": 2324, "text": "isTight: The isTight property also takes in a boolean as the object to determine whether the box constraints will be fixed to only one height and width or not." }, { "code": null, "e": 2597, "s": 2484, "text": "maxHeight: This property takes in a double value as the object to control the maximum height the box can get to." }, { "code": null, "e": 2704, "s": 2597, "text": "maxWith: This property takes in a double value as the object to control the maximum width box will get to." }, { "code": null, "e": 2814, "s": 2704, "text": "minHeight: This property takes in a double value as the object to control the minimum height box will get to." }, { "code": null, "e": 2922, "s": 2814, "text": "minWidth: This property takes in a double value as the object to control the minimum width box will get to." }, { "code": null, "e": 3032, "s": 2922, "text": "smallest: This property controls the smallest size the box can achieve by taking in Size class as the object." }, { "code": null, "e": 3043, "s": 3032, "text": "Example 1:" }, { "code": null, "e": 3048, "s": 3043, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; //Material design libraryvoid main() { runApp( //widget tree starts here MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], centerTitle: true, ), //AppBar body: Center( child: Container( color: Colors.green, padding: EdgeInsets.all(20), child: Text( 'GfG', style: TextStyle(color: Colors.white, fontSize: 20), ), //Text /** BoxConstraints Widget **/ constraints: BoxConstraints( minHeight: 50, minWidth: 50, maxHeight: 80, maxWidth: 80), //BoxConstraints ), //container ), //Center ), //Scaffold ), //MaterialApp );}", "e": 3918, "s": 3048, "text": null }, { "code": null, "e": 3926, "s": 3918, "text": "Output:" }, { "code": null, "e": 4379, "s": 3926, "text": "Explanation: Inside the Container widget which is a child of Center widget (Parent widget in the body) the constraints property is holding BoxConstraints widget. Inside that the minHeight and minWidth are set to 50 px and maxHeight and maxWidth is set to 80 px. The Container is green colored and is holding white colored text. The constraints that are set will not allow the container to have a height and width greater than 80 px and less than 50 px." }, { "code": null, "e": 4392, "s": 4381, "text": "Example 2:" }, { "code": null, "e": 4397, "s": 4392, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; //Material design libraryvoid main() { runApp( //widget tree starts here MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], centerTitle: true, ), //AppBar body: Center( child: Container( color: Colors.green, padding: EdgeInsets.all(20), /** BoxConstraints Widget **/ constraints: BoxConstraints( minHeight: 50, minWidth: 50, maxHeight: 80, maxWidth: 80), //BoxConstraints child: Container( color: Colors.greenAccent[400], child: Text( 'GfG', style: TextStyle(color: Colors.white, fontSize: 20), ), //Text constraints: BoxConstraints.expand(height: 50, width: 50), )), //container ), //Center ), //Scaffold ), //MaterialApp );}", "e": 5456, "s": 4397, "text": null }, { "code": null, "e": 5464, "s": 5456, "text": "Output:" }, { "code": null, "e": 6049, "s": 5464, "text": "Explanation: This flutter app is similar to the previous one, except the fact the child widget in the Container which was a Text is replaced by another Container widget. The second container is assigned a color of greenAccent[400], and the child is a Text widget. The constraints property in the second container is taking BoxConstraints.expand as the object, with its height and width property set to 50 px each. The BoxConstraints.expands is expanding in its parent BoxConstraints to a height and width of 50 px. And because of the fact it expands, it always starts from the center." }, { "code": null, "e": 6064, "s": 6049, "text": "sagartomar9927" }, { "code": null, "e": 6080, "s": 6064, "text": "Flutter-widgets" }, { "code": null, "e": 6088, "s": 6080, "text": "Android" }, { "code": null, "e": 6093, "s": 6088, "text": "Dart" }, { "code": null, "e": 6101, "s": 6093, "text": "Flutter" }, { "code": null, "e": 6109, "s": 6101, "text": "Android" }, { "code": null, "e": 6207, "s": 6109, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6276, "s": 6207, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 6308, "s": 6276, "text": "Android SDK and it's Components" }, { "code": null, "e": 6347, "s": 6308, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 6396, "s": 6347, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 6438, "s": 6396, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 6470, "s": 6438, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 6498, "s": 6470, "text": "Listview.builder in Flutter" }, { "code": null, "e": 6537, "s": 6498, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 6562, "s": 6537, "text": "Splash Screen in Flutter" } ]
A Peterson Graph Problem
06 Jun, 2022 The following graph G is called a Petersen graph and its vertices have been numbered from 0 to 9. Some letters have also been assigned to vertices of G, as can be seen from the following picture: Let’s consider a walk W in graph G, which consists of L vertices W1, W2, ..., WL. A string S of L letters ‘A’ – ‘E’ is realized by walk W if the sequence of letters written along W is equal to S. Vertices can be visited multiple times while walking along W.For example, S = ‘ABBECCD’ is realized by W = (0, 1, 6, 9, 7, 2, 3). Determine whether there is a walk W which realizes a given string S in graph G, and if so then find the lexicographically least such walk. The only line of input contains one string S. If there is no walk W which realizes S, then output -1 otherwise, you should output the least lexicographical walk W which realizes S. Examples: Input : s = 'ABB' Output: 016 Explanation: As we can see in the graph the path from ABB is 016. Input : s = 'AABE' Output :-1 Explanation: As there is no path that exists, hence output is -1. We apply breadth first search to visit each vertex of the graph. C++ Java Python3 C# Javascript // C++ program to find the// path in Peterson graph#include <bits/stdc++.h>using namespace std; // path to be checkedchar S[100005]; // adjacency matrix.bool adj[10][10]; // resulted path - waychar result[100005]; // we are applying breadth first search// herebool findthepath(char* S, int v){ result[0] = v + '0'; for (int i = 1; S[i]; i++) { // first traverse the outer graph if (adj[v][S[i] - 'A'] || adj[S[i] - 'A'][v]) { v = S[i] - 'A'; } // then traverse the inner graph else if (adj[v][S[i] - 'A' + 5] || adj[S[i] - 'A' + 5][v]) { v = S[i] - 'A' + 5; } // if the condition failed to satisfy // return false else return false; result[i] = v + '0'; } return true;} // driver codeint main(){ // here we have used adjacency matrix to make // connections between the connected nodes adj[0][1] = adj[1][2] = adj[2][3] = adj[3][4] = adj[4][0] = adj[0][5] = adj[1][6] = adj[2][7] = adj[3][8] = adj[4][9] = adj[5][7] = adj[7][9] = adj[9][6] = adj[6][8] = adj[8][5] = true; // path to be checked char S[] = "ABB"; if (findthepath(S, S[0] - 'A') || findthepath(S, S[0] - 'A' + 5)) { cout << result; } else { cout << "-1"; } return 0;} // Java program to find the// path in Peterson graphclass GFG{ // path to be checked static char []S = new char[100005]; // adjacency matrix. static boolean [][]adj = new boolean[10][10]; // resulted path - way static char[] result = new char[100005]; // we are applying breadth first search // here static boolean findthepath(char[] S, int v) { result[0] = (char) (v + '0'); for (int i = 1; i<(int)S.length; i++) { // first traverse the outer graph if (adj[v][S[i] - 'A'] || adj[S[i] - 'A'][v]) { v = S[i] - 'A'; } // then traverse the inner graph else if (adj[v][S[i] - 'A' + 5] || adj[S[i] - 'A' + 5][v]) { v = S[i] - 'A' + 5; } // if the condition failed to satisfy // return false else return false; result[i] = (char) (v + '0'); } return true; } // Driver code public static void main(String[] args) { // here we have used adjacency matrix to make // connections between the connected nodes adj[0][1] = adj[1][2] = adj[2][3] = adj[3][4] = adj[4][0] = adj[0][5] = adj[1][6] = adj[2][7] = adj[3][8] = adj[4][9] = adj[5][7] = adj[7][9] = adj[9][6] = adj[6][8] = adj[8][5] = true; // path to be checked char S[] = "ABB".toCharArray(); if (findthepath(S, S[0] - 'A') || findthepath(S, S[0] - 'A' + 5)) { System.out.print(result); } else { System.out.print("-1"); } }} // This code is contributed by Rajput-Ji # Python3 program to find the# path in Peterson graph# path to be checked # adjacency matrix.adj = [[False for i in range(10)] for j in range(10)] # resulted path - wayresult = [0] # we are applying breadth first search# heredef findthepath(S, v): result[0] = v for i in range(1, len(S)): # first traverse the outer graph if (adj[v][ord(S[i]) - ord('A')] or adj[ord(S[i]) - ord('A')][v]): v = ord(S[i]) - ord('A') # then traverse the inner graph else if (adj[v][ord(S[i]) - ord('A') + 5] or adj[ord(S[i]) - ord('A') + 5][v]): v = ord(S[i]) - ord('A') + 5 # if the condition failed to satisfy # return false else: return False result.append(v) return True # driver code# here we have used adjacency matrix to make# connections between the connected nodesadj[0][1] = adj[1][2] = adj[2][3] = \adj[3][4] = adj[4][0] = adj[0][5] = \adj[1][6] = adj[2][7] = adj[3][8] = \adj[4][9] = adj[5][7] = adj[7][9] = \adj[9][6] = adj[6][8] = adj[8][5] = True # path to be checkedS= "ABB"S=list(S)if (findthepath(S, ord(S[0]) - ord('A')) or findthepath(S, ord(S[0]) - ord('A') + 5)): print(*result, sep = "")else: print("-1") # This code is contributed by SHUBHAMSINGH10 // C# program to find the// path in Peterson graphusing System;public class GFG{ // adjacency matrix. static bool [,]adj = new bool[10, 10]; // resulted path - way static char[] result = new char[100005]; // we are applying breadth first search // here static bool findthepath(String S, int v) { result[0] = (char) (v + '0'); for (int i = 1; i < S.Length; i++) { // first traverse the outer graph if (adj[v,S[i] - 'A'] || adj[S[i] - 'A',v]) { v = S[i] - 'A'; } // then traverse the inner graph else if (adj[v,S[i] - 'A' + 5] || adj[S[i] - 'A' + 5,v]) { v = S[i] - 'A' + 5; } // if the condition failed to satisfy // return false else return false; result[i] = (char) (v + '0'); } return true; } // Driver code public static void Main(String[] args) { // here we have used adjacency matrix to make // connections between the connected nodes adj[0,1] = adj[1,2] = adj[2,3] = adj[3,4] = adj[4,0] = adj[0,5] = adj[1,6] = adj[2,7] = adj[3,8] = adj[4,9] = adj[5,7] = adj[7,9] = adj[9,6] = adj[6,8] = adj[8,5] = true; // path to be checked String S = "ABB"; if (findthepath(S, S[0] - 'A') || findthepath(S, S[0] - 'A' + 5)) { Console.WriteLine(result); } else { Console.Write("-1"); } }} // This code is contributed by aashish1995 <script> // Javascript program to find the// path in Peterson graph // adjacency matrix.let adj = new Array(10).fill(0).map(() => new Array(10).fill(false)) // resulted path - waylet result = new Array(100005) // we are applying breadth first search// herefunction findthepath(S, v) { result[0] = v for (let i = 1; i < S.length; i++) { // first traverse the outer graph if (adj[v][S[i].charCodeAt(0) - 'A'.charCodeAt(0)] || adj[S[i].charCodeAt(0) - 'A'.charCodeAt(0)][v]) { v = S[i].charCodeAt(0) - 'A'.charCodeAt(0); } // then traverse the inner graph else if (adj[v][S[i].charCodeAt(0) - 'A'.charCodeAt(0) + 5] || adj[S[i].charCodeAt(0) - 'A'.charCodeAt(0) + 5][v]) { v = S[i].charCodeAt(0) - 'A'.charCodeAt(0) + 5; } // if the condition failed to satisfy // return false else return false; result[i] = String.fromCharCode(v + '0'.charCodeAt(0)); } return true;} // Driver code // here we have used adjacency matrix to make// connections between the connected nodesadj[0][1] = adj[1][2] = adj[2][3] = adj[3][4] = adj[4][0] = adj[0][5] = adj[1][6] = adj[2][7] = adj[3][8] = adj[4][9] = adj[5][7] = adj[7][9] = adj[9][6] = adj[6][8] = adj[8][5] = true; // path to be checkedlet S = "ABB";S = S.split("")if (findthepath(S, S[0].charCodeAt(0) - 'A'.charCodeAt(0)) || findthepath(S, S[0].charCodeAt(0) - 'A'.charCodeAt(0) + 5)) { document.write(result.join(""));}else { document.write("-1");} // This code is contributed by Saurabh Jaiswal </script> Output: 016 This article is contributed by Sunidhi Chaudhary. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Rajput-Ji SHUBHAMSINGH10 aashish1995 simmytarika5 _saurabh_jaiswal Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Detect Cycle in a Directed Graph Find if there is a path between two vertices in a directed graph Introduction to Data Structures Floyd Warshall Algorithm | DP-16 Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) What is Data Structure: Types, Classifications and Applications Bellman–Ford Algorithm | DP-23 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jun, 2022" }, { "code": null, "e": 898, "s": 54, "text": "The following graph G is called a Petersen graph and its vertices have been numbered from 0 to 9. Some letters have also been assigned to vertices of G, as can be seen from the following picture: Let’s consider a walk W in graph G, which consists of L vertices W1, W2, ..., WL. A string S of L letters ‘A’ – ‘E’ is realized by walk W if the sequence of letters written along W is equal to S. Vertices can be visited multiple times while walking along W.For example, S = ‘ABBECCD’ is realized by W = (0, 1, 6, 9, 7, 2, 3). Determine whether there is a walk W which realizes a given string S in graph G, and if so then find the lexicographically least such walk. The only line of input contains one string S. If there is no walk W which realizes S, then output -1 otherwise, you should output the least lexicographical walk W which realizes S. " }, { "code": null, "e": 910, "s": 898, "text": "Examples: " }, { "code": null, "e": 1128, "s": 910, "text": "Input : s = 'ABB'\nOutput: 016\nExplanation: As we can see in the graph\n the path from ABB is 016.\nInput : s = 'AABE'\nOutput :-1\nExplanation: As there is no path that\n exists, hence output is -1." }, { "code": null, "e": 1197, "s": 1130, "text": "We apply breadth first search to visit each vertex of the graph. " }, { "code": null, "e": 1201, "s": 1197, "text": "C++" }, { "code": null, "e": 1206, "s": 1201, "text": "Java" }, { "code": null, "e": 1214, "s": 1206, "text": "Python3" }, { "code": null, "e": 1217, "s": 1214, "text": "C#" }, { "code": null, "e": 1228, "s": 1217, "text": "Javascript" }, { "code": "// C++ program to find the// path in Peterson graph#include <bits/stdc++.h>using namespace std; // path to be checkedchar S[100005]; // adjacency matrix.bool adj[10][10]; // resulted path - waychar result[100005]; // we are applying breadth first search// herebool findthepath(char* S, int v){ result[0] = v + '0'; for (int i = 1; S[i]; i++) { // first traverse the outer graph if (adj[v][S[i] - 'A'] || adj[S[i] - 'A'][v]) { v = S[i] - 'A'; } // then traverse the inner graph else if (adj[v][S[i] - 'A' + 5] || adj[S[i] - 'A' + 5][v]) { v = S[i] - 'A' + 5; } // if the condition failed to satisfy // return false else return false; result[i] = v + '0'; } return true;} // driver codeint main(){ // here we have used adjacency matrix to make // connections between the connected nodes adj[0][1] = adj[1][2] = adj[2][3] = adj[3][4] = adj[4][0] = adj[0][5] = adj[1][6] = adj[2][7] = adj[3][8] = adj[4][9] = adj[5][7] = adj[7][9] = adj[9][6] = adj[6][8] = adj[8][5] = true; // path to be checked char S[] = \"ABB\"; if (findthepath(S, S[0] - 'A') || findthepath(S, S[0] - 'A' + 5)) { cout << result; } else { cout << \"-1\"; } return 0;}", "e": 2599, "s": 1228, "text": null }, { "code": "// Java program to find the// path in Peterson graphclass GFG{ // path to be checked static char []S = new char[100005]; // adjacency matrix. static boolean [][]adj = new boolean[10][10]; // resulted path - way static char[] result = new char[100005]; // we are applying breadth first search // here static boolean findthepath(char[] S, int v) { result[0] = (char) (v + '0'); for (int i = 1; i<(int)S.length; i++) { // first traverse the outer graph if (adj[v][S[i] - 'A'] || adj[S[i] - 'A'][v]) { v = S[i] - 'A'; } // then traverse the inner graph else if (adj[v][S[i] - 'A' + 5] || adj[S[i] - 'A' + 5][v]) { v = S[i] - 'A' + 5; } // if the condition failed to satisfy // return false else return false; result[i] = (char) (v + '0'); } return true; } // Driver code public static void main(String[] args) { // here we have used adjacency matrix to make // connections between the connected nodes adj[0][1] = adj[1][2] = adj[2][3] = adj[3][4] = adj[4][0] = adj[0][5] = adj[1][6] = adj[2][7] = adj[3][8] = adj[4][9] = adj[5][7] = adj[7][9] = adj[9][6] = adj[6][8] = adj[8][5] = true; // path to be checked char S[] = \"ABB\".toCharArray(); if (findthepath(S, S[0] - 'A') || findthepath(S, S[0] - 'A' + 5)) { System.out.print(result); } else { System.out.print(\"-1\"); } }} // This code is contributed by Rajput-Ji", "e": 4394, "s": 2599, "text": null }, { "code": "# Python3 program to find the# path in Peterson graph# path to be checked # adjacency matrix.adj = [[False for i in range(10)] for j in range(10)] # resulted path - wayresult = [0] # we are applying breadth first search# heredef findthepath(S, v): result[0] = v for i in range(1, len(S)): # first traverse the outer graph if (adj[v][ord(S[i]) - ord('A')] or adj[ord(S[i]) - ord('A')][v]): v = ord(S[i]) - ord('A') # then traverse the inner graph else if (adj[v][ord(S[i]) - ord('A') + 5] or adj[ord(S[i]) - ord('A') + 5][v]): v = ord(S[i]) - ord('A') + 5 # if the condition failed to satisfy # return false else: return False result.append(v) return True # driver code# here we have used adjacency matrix to make# connections between the connected nodesadj[0][1] = adj[1][2] = adj[2][3] = \\adj[3][4] = adj[4][0] = adj[0][5] = \\adj[1][6] = adj[2][7] = adj[3][8] = \\adj[4][9] = adj[5][7] = adj[7][9] = \\adj[9][6] = adj[6][8] = adj[8][5] = True # path to be checkedS= \"ABB\"S=list(S)if (findthepath(S, ord(S[0]) - ord('A')) or findthepath(S, ord(S[0]) - ord('A') + 5)): print(*result, sep = \"\")else: print(\"-1\") # This code is contributed by SHUBHAMSINGH10", "e": 5732, "s": 4394, "text": null }, { "code": "// C# program to find the// path in Peterson graphusing System;public class GFG{ // adjacency matrix. static bool [,]adj = new bool[10, 10]; // resulted path - way static char[] result = new char[100005]; // we are applying breadth first search // here static bool findthepath(String S, int v) { result[0] = (char) (v + '0'); for (int i = 1; i < S.Length; i++) { // first traverse the outer graph if (adj[v,S[i] - 'A'] || adj[S[i] - 'A',v]) { v = S[i] - 'A'; } // then traverse the inner graph else if (adj[v,S[i] - 'A' + 5] || adj[S[i] - 'A' + 5,v]) { v = S[i] - 'A' + 5; } // if the condition failed to satisfy // return false else return false; result[i] = (char) (v + '0'); } return true; } // Driver code public static void Main(String[] args) { // here we have used adjacency matrix to make // connections between the connected nodes adj[0,1] = adj[1,2] = adj[2,3] = adj[3,4] = adj[4,0] = adj[0,5] = adj[1,6] = adj[2,7] = adj[3,8] = adj[4,9] = adj[5,7] = adj[7,9] = adj[9,6] = adj[6,8] = adj[8,5] = true; // path to be checked String S = \"ABB\"; if (findthepath(S, S[0] - 'A') || findthepath(S, S[0] - 'A' + 5)) { Console.WriteLine(result); } else { Console.Write(\"-1\"); } }} // This code is contributed by aashish1995", "e": 7157, "s": 5732, "text": null }, { "code": "<script> // Javascript program to find the// path in Peterson graph // adjacency matrix.let adj = new Array(10).fill(0).map(() => new Array(10).fill(false)) // resulted path - waylet result = new Array(100005) // we are applying breadth first search// herefunction findthepath(S, v) { result[0] = v for (let i = 1; i < S.length; i++) { // first traverse the outer graph if (adj[v][S[i].charCodeAt(0) - 'A'.charCodeAt(0)] || adj[S[i].charCodeAt(0) - 'A'.charCodeAt(0)][v]) { v = S[i].charCodeAt(0) - 'A'.charCodeAt(0); } // then traverse the inner graph else if (adj[v][S[i].charCodeAt(0) - 'A'.charCodeAt(0) + 5] || adj[S[i].charCodeAt(0) - 'A'.charCodeAt(0) + 5][v]) { v = S[i].charCodeAt(0) - 'A'.charCodeAt(0) + 5; } // if the condition failed to satisfy // return false else return false; result[i] = String.fromCharCode(v + '0'.charCodeAt(0)); } return true;} // Driver code // here we have used adjacency matrix to make// connections between the connected nodesadj[0][1] = adj[1][2] = adj[2][3] = adj[3][4] = adj[4][0] = adj[0][5] = adj[1][6] = adj[2][7] = adj[3][8] = adj[4][9] = adj[5][7] = adj[7][9] = adj[9][6] = adj[6][8] = adj[8][5] = true; // path to be checkedlet S = \"ABB\";S = S.split(\"\")if (findthepath(S, S[0].charCodeAt(0) - 'A'.charCodeAt(0)) || findthepath(S, S[0].charCodeAt(0) - 'A'.charCodeAt(0) + 5)) { document.write(result.join(\"\"));}else { document.write(\"-1\");} // This code is contributed by Saurabh Jaiswal </script>", "e": 8674, "s": 7157, "text": null }, { "code": null, "e": 8684, "s": 8674, "text": "Output: " }, { "code": null, "e": 8688, "s": 8684, "text": "016" }, { "code": null, "e": 9114, "s": 8688, "text": "This article is contributed by Sunidhi Chaudhary. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9124, "s": 9114, "text": "Rajput-Ji" }, { "code": null, "e": 9139, "s": 9124, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 9151, "s": 9139, "text": "aashish1995" }, { "code": null, "e": 9164, "s": 9151, "text": "simmytarika5" }, { "code": null, "e": 9181, "s": 9164, "text": "_saurabh_jaiswal" }, { "code": null, "e": 9187, "s": 9181, "text": "Graph" }, { "code": null, "e": 9193, "s": 9187, "text": "Graph" }, { "code": null, "e": 9291, "s": 9193, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9311, "s": 9291, "text": "Topological Sorting" }, { "code": null, "e": 9369, "s": 9311, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 9402, "s": 9369, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 9467, "s": 9402, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 9499, "s": 9467, "text": "Introduction to Data Structures" }, { "code": null, "e": 9532, "s": 9499, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 9607, "s": 9532, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 9671, "s": 9607, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 9702, "s": 9671, "text": "Bellman–Ford Algorithm | DP-23" } ]
Flutter - Creating Snackbar Using GetX Library - GeeksforGeeks
14 May, 2021 Sometimes, it’s very useful to show the message when a certain action takes place in our app. Let’s suppose, we have a list of items and we want to delete any item from the list then after deleting those items, some message should be displayed to inform the user that the item has been deleted. If we want to undo the action then we can simply do and show the snackbar with some message. Generally, when we create snackbar, then it uses context for creating snackbar, and also syntax is not so easy. To overcome this problem, we can create Snackbar using GetX with just simple code without using any context. Follow the below steps to create snackbar using GetX: Create a new flutter application with the below command: flutter create APP_NAME Add get package to pubspec.yaml file: Import get package in main.dart file: import 'package:get/get.dart'; For creating an app, use GetMaterialApp instead of MaterialApp because we are using GetX library. After the creation of the app, create a button in the center. After that, create Snackbar using Get.snackbar(title, message); Provide the title and message to the snackbar. We can add some extra beauty to this snackbar like background color, text color, snackbar duration, snackbarPosition, onTap() property, etc. main.dart file: Dart import 'package:flutter/material.dart';import 'package:get/get.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return GetMaterialApp( title: 'Scaffold demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks Scaffold'), centerTitle: true, backgroundColor: Colors.green, ), body: Center( child: ElevatedButton( child: Text('Open Snackbar'), onPressed: (){ Get.snackbar( "GeeksforGeeks", "Hello everyone", icon: Icon(Icons.person, color: Colors.white), snackPosition: SnackPosition.BOTTOM, ); }, ), ), ); }} Output: Get.snackbar( "GeeksforGeeks", "Hello everyone", icon: Icon(Icons.person, color: Colors.white), snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.green, ); If we run our app with the above properties then the output will be: Get.snackbar( "GeeksforGeeks", "Hello everyone", icon: Icon(Icons.person, color: Colors.white), snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.green, borderRadius: 20, margin: EdgeInsets.all(15), colorText: Colors.white, duration: Duration(seconds: 4), isDismissible: true, dismissDirection: SnackDismissDirection.HORIZONTAL, forwardAnimationCurve: Curves.easeOutBack, ); If we run with the above properties, the output will be: Flutter UI-components Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs
[ { "code": null, "e": 25397, "s": 25369, "text": "\n14 May, 2021" }, { "code": null, "e": 26007, "s": 25397, "text": "Sometimes, it’s very useful to show the message when a certain action takes place in our app. Let’s suppose, we have a list of items and we want to delete any item from the list then after deleting those items, some message should be displayed to inform the user that the item has been deleted. If we want to undo the action then we can simply do and show the snackbar with some message. Generally, when we create snackbar, then it uses context for creating snackbar, and also syntax is not so easy. To overcome this problem, we can create Snackbar using GetX with just simple code without using any context. " }, { "code": null, "e": 26061, "s": 26007, "text": "Follow the below steps to create snackbar using GetX:" }, { "code": null, "e": 26118, "s": 26061, "text": "Create a new flutter application with the below command:" }, { "code": null, "e": 26142, "s": 26118, "text": "flutter create APP_NAME" }, { "code": null, "e": 26180, "s": 26142, "text": "Add get package to pubspec.yaml file:" }, { "code": null, "e": 26218, "s": 26180, "text": "Import get package in main.dart file:" }, { "code": null, "e": 26249, "s": 26218, "text": "import 'package:get/get.dart';" }, { "code": null, "e": 26347, "s": 26249, "text": "For creating an app, use GetMaterialApp instead of MaterialApp because we are using GetX library." }, { "code": null, "e": 26409, "s": 26347, "text": "After the creation of the app, create a button in the center." }, { "code": null, "e": 26473, "s": 26409, "text": "After that, create Snackbar using Get.snackbar(title, message);" }, { "code": null, "e": 26520, "s": 26473, "text": "Provide the title and message to the snackbar." }, { "code": null, "e": 26661, "s": 26520, "text": "We can add some extra beauty to this snackbar like background color, text color, snackbar duration, snackbarPosition, onTap() property, etc." }, { "code": null, "e": 26677, "s": 26661, "text": "main.dart file:" }, { "code": null, "e": 26682, "s": 26677, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:get/get.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return GetMaterialApp( title: 'Scaffold demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks Scaffold'), centerTitle: true, backgroundColor: Colors.green, ), body: Center( child: ElevatedButton( child: Text('Open Snackbar'), onPressed: (){ Get.snackbar( \"GeeksforGeeks\", \"Hello everyone\", icon: Icon(Icons.person, color: Colors.white), snackPosition: SnackPosition.BOTTOM, ); }, ), ), ); }}", "e": 27770, "s": 26682, "text": null }, { "code": null, "e": 27778, "s": 27770, "text": "Output:" }, { "code": null, "e": 28034, "s": 27778, "text": "Get.snackbar(\n \"GeeksforGeeks\",\n \"Hello everyone\",\n icon: Icon(Icons.person, color: Colors.white),\n snackPosition: SnackPosition.BOTTOM,\n backgroundColor: Colors.green,\n );" }, { "code": null, "e": 28103, "s": 28034, "text": "If we run our app with the above properties then the output will be:" }, { "code": null, "e": 28684, "s": 28103, "text": "Get.snackbar(\n \"GeeksforGeeks\",\n \"Hello everyone\",\n icon: Icon(Icons.person, color: Colors.white),\n snackPosition: SnackPosition.BOTTOM,\n backgroundColor: Colors.green,\n borderRadius: 20,\n margin: EdgeInsets.all(15),\n colorText: Colors.white,\n duration: Duration(seconds: 4),\n isDismissible: true,\n dismissDirection: SnackDismissDirection.HORIZONTAL,\n forwardAnimationCurve: Curves.easeOutBack,\n\n );" }, { "code": null, "e": 28741, "s": 28684, "text": "If we run with the above properties, the output will be:" }, { "code": null, "e": 28763, "s": 28741, "text": "Flutter UI-components" }, { "code": null, "e": 28768, "s": 28763, "text": "Dart" }, { "code": null, "e": 28776, "s": 28768, "text": "Flutter" }, { "code": null, "e": 28874, "s": 28776, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28913, "s": 28874, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 28939, "s": 28913, "text": "ListView Class in Flutter" }, { "code": null, "e": 28965, "s": 28939, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 28988, "s": 28965, "text": "Flutter - Stack Widget" }, { "code": null, "e": 29006, "s": 28988, "text": "Flutter - Dialogs" }, { "code": null, "e": 29045, "s": 29006, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29062, "s": 29045, "text": "Flutter Tutorial" }, { "code": null, "e": 29088, "s": 29062, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 29111, "s": 29088, "text": "Flutter - Stack Widget" } ]
What characters are valid for JavaScript variable names?
To check the valid characters for JavaScript variable names, you should follow the below given naming conventions, which discuss about other rules to name a variable − Name can begin with $ and _ characters, for example, _result. You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid. JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one. JavaScript variable names are case-sensitive. For example, Name and name are two different variables. Here are the correct forms of a variable name in JavaScrip − result _result The following is an incorrect form for a variable name − 2result
[ { "code": null, "e": 1230, "s": 1062, "text": "To check the valid characters for JavaScript variable names, you should follow the below given naming conventions, which discuss about other rules to name a variable −" }, { "code": null, "e": 1292, "s": 1230, "text": "Name can begin with $ and _ characters, for example, _result." }, { "code": null, "e": 1481, "s": 1292, "text": "You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid." }, { "code": null, "e": 1682, "s": 1481, "text": "JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one." }, { "code": null, "e": 1784, "s": 1682, "text": "JavaScript variable names are case-sensitive. For example, Name and name are two different variables." }, { "code": null, "e": 1845, "s": 1784, "text": "Here are the correct forms of a variable name in JavaScrip −" }, { "code": null, "e": 1861, "s": 1845, "text": "result\n _result" }, { "code": null, "e": 1918, "s": 1861, "text": "The following is an incorrect form for a variable name −" }, { "code": null, "e": 1926, "s": 1918, "text": "2result" } ]
Linear Regression Simulation to Understand Slope Sensitivity | by Robert Wood | Towards Data Science
Over the next few minutes, I’ll send you on your way to leveraging linear regression for a bit more than explanation or prediction, rather you’ll utilize them to for the sake of inference. We will leverage simulation for inference in three ways: Understanding model sensitivity p-value confidence intervals In this post, we’ll mostly be exploring the first one. It will be foundational to my next posts of using simulation to determine p-value and confidence intervals. If you’re not familiar with how linear regression works in general, jump over to this post. You can jump over here to find various posts on different variations on linear regression, from creating them, to understanding and explaining them. Traditionally we use linear regression to make an assessment between a variety of variables. On top of that assessment, what we are going to learn here is how you can adjust the inputs of various regression models to drive deeper understanding of the sensitivity or variability of the relationship between your explanatory & response variables. So how might we go about determining the variability of the relationship of two variables? Think about it like this... What is the key output of a linear regression? If you guessed a line, then you’ve got it right! The regression output is effectively the equation of a line, and the slope of that equation serves as the indication of relationship of X & Y. When seeking to understand the variation of our the relationship between response & explanatory variable... it's the slope that we're after. Let's say you ran your linear regression over different samples... the question we would have, is does our slope vary? Or how much does it vary? Is it positive sometimes and negative others? etc. We’ve done a bit of exposition to get to the punch line here, but hopefully this serves to give you a solid foundational footing to really understand and use this is practice. To sum up our introduction, it comes down to this: We want to understand the variability and sensitivity to variability of the relationship between two variables when we vary the sample driving the model The dataset we’re working with is a Seattle home prices dataset. I’ve used this dataset many times before and find it particularly flexible for demonstration. The record level of the dataset is by home and details price, square footage, # of beds, # of baths, and so forth. Through the course of this post, we’ll be trying to explain price through a function of other square footage. There is certainly a lot of exploratory data analysis (EDA) you’d want to engage in before you jumped right into this section. There are also certain data pre-requisites that you’d confirm, but for the sake of this illustration, let’s dive in. fit <- lm(price_log ~ sqft_living_log data = housing)summary(fit) Perfect! We’ve got ourselves a linear model, let’s go ahead and visualize that. Also keep in mind that I have taken the log of both variables to clean up standardize their distributions. housing %>% mutate(sqft_living_log = log(sqft_living), price_log = log(price))%>%ggplot(aes(x = sqft_living_log, y = price_log)) + geom_point() + geom_smooth(method = "lm", se = FALSE) In this dataset, we’re just working with a sample of 4600 homes. This is not an exhaustive population. As such, we are going to use a certain sampling technique to generate many “perspectives”. Said perspectives will drive how we go about understanding the sensitivity of our response and explanatory variables. Sampling variability creates difficulty when trying to draw conclusions about an underlying population. These many perspectives or samples of the data we have are how we eliminate the potentially adverse effects of sampling variability. So above we have one line... but what we need is many lines, for many situations. What we’re going to do next is sample our housing data in smaller groups in give each their own regression model. First things first, we are going to use the rep_sample_n function to randomly select a group of 100 homes... we'll repeat that process a total of 100 times. samples <- housing %>% rep_sample_n(size = 100, reps = 100) Now that we have our samples dataset, let’s visualize them very similar to how we did it before. Only in this case, we are going to group our visualization by replicate. The reason this is pertinent is so that we can distinguish point to point; which replicate they pertain to. As you can see in the above code, there will be 100 replicates of 100 records each. ggplot(samples, aes(x = sqft_living_log, y = price_log, group = replicate)) + geom_point() + geom_smooth(method = 'lm', se = FALSE) What you’ll see above are the various regression lines fit to each of the disparate samples of 100. As you can see there are cases where slopes are greater or lower. This is the foundation of us being able to understand a range of ‘slope’ that applies to the underlying population. As you’d imagine interacting with our samples is going to vary the amount of variation in slope. Below I’ve run the same code, but am only drawing 10 random samples for each replicate. So here you have the visualization, but you don’t yet have the actual details of the linear regression itself. We’re going to need to run a separate regression for each replicate. Since we already have our generated simulated dataset, we just need to group by replicate, in this case it’s not for the sake of aggregation, rather it’s to model at the group level. Once we declare our group_by, we are going to leverage the do function to indicate our group action. For the group action, we want to run separate models for each of them. Now what we have is 100 regression outputs. While there are many relevant pieces of the output, we are targeting the term for our explanatory variable. Take a look at the code below! coefs <- samples %>% group_by(replicate) %>% do(lm(price_log ~ sqft_living_log, data = .) %>% tidy()) %>% filter(term == 'sqft_living_log') We now have a dataframe with each replicate and the corresponding coefficient for our term of interest. Let’s take a peek at our distribution of slopes. ggplot(coefs, aes(x = estimate)) + geom_histogram() We can see a mostly normal distribution. In the case that we ran it with more replicates, it would look smoother. One thing for you to keep in mind. I’m not suggesting that every time you run a linear regression, you need to arbitrarily run 100 of them for various samples of your data. For many business applications, your data may be representative of the entire population. But even in cases when you don’t have the entire population, the purposes to either approach are different. Here we are leveraging simulation and many linear regression models to eventually make inferential claims about the underlying population. It still makes sense to leverage linear regression in different formats for things like modeling for explanation/description, or prediction. As we seek to understand the distribution of slope coefficients, it can be very helpful to vary the data that eventually supports said distribution. As displayed above, altering the sample size of each replicate is going to lend greater understanding to the reduction in slope variation with different samples. Another thing that will drive greater variation in our slope would be a reduction in variation on our explanatory variables. It may come as a bit of surprise, but with a broader range of explanatory datapoints, the our model has more information upon which to explain a relationship. We have done a lot in such a short amount of time. It’s easy to get lost when dissecting statistics concepts like inference. My hope is that having a strong foundational understanding of the need and corresponding execution of simulation to better understand the relationship between our response and explanatory variables. If this was helpful, feel free to check out my other posts at datasciencelessons.com. Happy Data Science-ing!
[ { "code": null, "e": 361, "s": 172, "text": "Over the next few minutes, I’ll send you on your way to leveraging linear regression for a bit more than explanation or prediction, rather you’ll utilize them to for the sake of inference." }, { "code": null, "e": 418, "s": 361, "text": "We will leverage simulation for inference in three ways:" }, { "code": null, "e": 450, "s": 418, "text": "Understanding model sensitivity" }, { "code": null, "e": 458, "s": 450, "text": "p-value" }, { "code": null, "e": 479, "s": 458, "text": "confidence intervals" }, { "code": null, "e": 642, "s": 479, "text": "In this post, we’ll mostly be exploring the first one. It will be foundational to my next posts of using simulation to determine p-value and confidence intervals." }, { "code": null, "e": 734, "s": 642, "text": "If you’re not familiar with how linear regression works in general, jump over to this post." }, { "code": null, "e": 883, "s": 734, "text": "You can jump over here to find various posts on different variations on linear regression, from creating them, to understanding and explaining them." }, { "code": null, "e": 1228, "s": 883, "text": "Traditionally we use linear regression to make an assessment between a variety of variables. On top of that assessment, what we are going to learn here is how you can adjust the inputs of various regression models to drive deeper understanding of the sensitivity or variability of the relationship between your explanatory & response variables." }, { "code": null, "e": 1319, "s": 1228, "text": "So how might we go about determining the variability of the relationship of two variables?" }, { "code": null, "e": 1347, "s": 1319, "text": "Think about it like this..." }, { "code": null, "e": 1923, "s": 1347, "text": "What is the key output of a linear regression? If you guessed a line, then you’ve got it right! The regression output is effectively the equation of a line, and the slope of that equation serves as the indication of relationship of X & Y. When seeking to understand the variation of our the relationship between response & explanatory variable... it's the slope that we're after. Let's say you ran your linear regression over different samples... the question we would have, is does our slope vary? Or how much does it vary? Is it positive sometimes and negative others? etc." }, { "code": null, "e": 2099, "s": 1923, "text": "We’ve done a bit of exposition to get to the punch line here, but hopefully this serves to give you a solid foundational footing to really understand and use this is practice." }, { "code": null, "e": 2150, "s": 2099, "text": "To sum up our introduction, it comes down to this:" }, { "code": null, "e": 2303, "s": 2150, "text": "We want to understand the variability and sensitivity to variability of the relationship between two variables when we vary the sample driving the model" }, { "code": null, "e": 2577, "s": 2303, "text": "The dataset we’re working with is a Seattle home prices dataset. I’ve used this dataset many times before and find it particularly flexible for demonstration. The record level of the dataset is by home and details price, square footage, # of beds, # of baths, and so forth." }, { "code": null, "e": 2687, "s": 2577, "text": "Through the course of this post, we’ll be trying to explain price through a function of other square footage." }, { "code": null, "e": 2931, "s": 2687, "text": "There is certainly a lot of exploratory data analysis (EDA) you’d want to engage in before you jumped right into this section. There are also certain data pre-requisites that you’d confirm, but for the sake of this illustration, let’s dive in." }, { "code": null, "e": 3006, "s": 2931, "text": "fit <- lm(price_log ~ sqft_living_log data = housing)summary(fit)" }, { "code": null, "e": 3193, "s": 3006, "text": "Perfect! We’ve got ourselves a linear model, let’s go ahead and visualize that. Also keep in mind that I have taken the log of both variables to clean up standardize their distributions." }, { "code": null, "e": 3391, "s": 3193, "text": "housing %>% mutate(sqft_living_log = log(sqft_living), price_log = log(price))%>%ggplot(aes(x = sqft_living_log, y = price_log)) + geom_point() + geom_smooth(method = \"lm\", se = FALSE)" }, { "code": null, "e": 3703, "s": 3391, "text": "In this dataset, we’re just working with a sample of 4600 homes. This is not an exhaustive population. As such, we are going to use a certain sampling technique to generate many “perspectives”. Said perspectives will drive how we go about understanding the sensitivity of our response and explanatory variables." }, { "code": null, "e": 3940, "s": 3703, "text": "Sampling variability creates difficulty when trying to draw conclusions about an underlying population. These many perspectives or samples of the data we have are how we eliminate the potentially adverse effects of sampling variability." }, { "code": null, "e": 4022, "s": 3940, "text": "So above we have one line... but what we need is many lines, for many situations." }, { "code": null, "e": 4136, "s": 4022, "text": "What we’re going to do next is sample our housing data in smaller groups in give each their own regression model." }, { "code": null, "e": 4293, "s": 4136, "text": "First things first, we are going to use the rep_sample_n function to randomly select a group of 100 homes... we'll repeat that process a total of 100 times." }, { "code": null, "e": 4354, "s": 4293, "text": "samples <- housing %>% rep_sample_n(size = 100, reps = 100)" }, { "code": null, "e": 4716, "s": 4354, "text": "Now that we have our samples dataset, let’s visualize them very similar to how we did it before. Only in this case, we are going to group our visualization by replicate. The reason this is pertinent is so that we can distinguish point to point; which replicate they pertain to. As you can see in the above code, there will be 100 replicates of 100 records each." }, { "code": null, "e": 4852, "s": 4716, "text": "ggplot(samples, aes(x = sqft_living_log, y = price_log, group = replicate)) + geom_point() + geom_smooth(method = 'lm', se = FALSE)" }, { "code": null, "e": 5134, "s": 4852, "text": "What you’ll see above are the various regression lines fit to each of the disparate samples of 100. As you can see there are cases where slopes are greater or lower. This is the foundation of us being able to understand a range of ‘slope’ that applies to the underlying population." }, { "code": null, "e": 5319, "s": 5134, "text": "As you’d imagine interacting with our samples is going to vary the amount of variation in slope. Below I’ve run the same code, but am only drawing 10 random samples for each replicate." }, { "code": null, "e": 5430, "s": 5319, "text": "So here you have the visualization, but you don’t yet have the actual details of the linear regression itself." }, { "code": null, "e": 5499, "s": 5430, "text": "We’re going to need to run a separate regression for each replicate." }, { "code": null, "e": 5854, "s": 5499, "text": "Since we already have our generated simulated dataset, we just need to group by replicate, in this case it’s not for the sake of aggregation, rather it’s to model at the group level. Once we declare our group_by, we are going to leverage the do function to indicate our group action. For the group action, we want to run separate models for each of them." }, { "code": null, "e": 5898, "s": 5854, "text": "Now what we have is 100 regression outputs." }, { "code": null, "e": 6006, "s": 5898, "text": "While there are many relevant pieces of the output, we are targeting the term for our explanatory variable." }, { "code": null, "e": 6037, "s": 6006, "text": "Take a look at the code below!" }, { "code": null, "e": 6188, "s": 6037, "text": "coefs <- samples %>% group_by(replicate) %>% do(lm(price_log ~ sqft_living_log, data = .) %>% tidy()) %>% filter(term == 'sqft_living_log')" }, { "code": null, "e": 6292, "s": 6188, "text": "We now have a dataframe with each replicate and the corresponding coefficient for our term of interest." }, { "code": null, "e": 6341, "s": 6292, "text": "Let’s take a peek at our distribution of slopes." }, { "code": null, "e": 6394, "s": 6341, "text": "ggplot(coefs, aes(x = estimate)) + geom_histogram()" }, { "code": null, "e": 6508, "s": 6394, "text": "We can see a mostly normal distribution. In the case that we ran it with more replicates, it would look smoother." }, { "code": null, "e": 7159, "s": 6508, "text": "One thing for you to keep in mind. I’m not suggesting that every time you run a linear regression, you need to arbitrarily run 100 of them for various samples of your data. For many business applications, your data may be representative of the entire population. But even in cases when you don’t have the entire population, the purposes to either approach are different. Here we are leveraging simulation and many linear regression models to eventually make inferential claims about the underlying population. It still makes sense to leverage linear regression in different formats for things like modeling for explanation/description, or prediction." }, { "code": null, "e": 7470, "s": 7159, "text": "As we seek to understand the distribution of slope coefficients, it can be very helpful to vary the data that eventually supports said distribution. As displayed above, altering the sample size of each replicate is going to lend greater understanding to the reduction in slope variation with different samples." }, { "code": null, "e": 7754, "s": 7470, "text": "Another thing that will drive greater variation in our slope would be a reduction in variation on our explanatory variables. It may come as a bit of surprise, but with a broader range of explanatory datapoints, the our model has more information upon which to explain a relationship." }, { "code": null, "e": 8078, "s": 7754, "text": "We have done a lot in such a short amount of time. It’s easy to get lost when dissecting statistics concepts like inference. My hope is that having a strong foundational understanding of the need and corresponding execution of simulation to better understand the relationship between our response and explanatory variables." } ]
Java SQL Timestamp setTime() function with examples - GeeksforGeeks
25 Oct, 2019 The setTime() function is a part of Timestamp class of Java SQL.The function is used to set the time of the Timestamp object. The function takes time in milliseconds which represents the time in milliseconds after 1st January, 1970. Function Signature: public void setTime(long t) Syntax: ts1.setTime(l); Parameters: The function accepts a long value l as parameter which is to be set as the time. Return value: The function does not return any value. Exception: The function does not throw any exceptions. Below programs illustrates the use of setTime() function Example 1: Create a timestamp and use the setTime() to change the time of timestamp object. // Java program to demonstrate the// use of setTime() function import java.sql.*; public class solution { public static void main(String args[]) { // Create two timestamp objects Timestamp ts = new Timestamp(10000); // Display the timestamp object System.out.println("Timestamp time: " + ts.toString()); // Set the value of timestamp object // using setTime function ts.setTime(1000000000); // Display the new timestamp object System.out.println("New Timestamp time: " + ts.toString()); }} Timestamp time: 1970-01-01 00:00:10.0 New Timestamp time: 1970-01-12 13:46:40.0 Example 2: Create a timestamp and use the setTime() to change the time of timestamp object by passing negative long value as parameter. Giving negative long value represents the time before 1st January 1970 // Java program to demonstrate the// use of setTime() function import java.sql.*; public class solution { public static void main(String args[]) { // Create two timestamp objects Timestamp ts = new Timestamp(10000); // Display the timestamp object System.out.println("Timestamp time: " + ts.toString()); // Set the value of timestamp object // using setTime function ts.setTime(-1000000000); // Display the new timestamp object System.out.println("New Timestamp time: " + ts.toString()); }} Timestamp time: 1970-01-01 00:00:10.0 New Timestamp time: 1969-12-20 10:13:20.0 Reference: https://docs.oracle.com/javase/9/docs/api/java/sql/Timestamp.html#setTime-long- shubham_singh Java-Functions Java-Sql package Java-TimeStamp Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples PriorityQueue in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 25237, "s": 25209, "text": "\n25 Oct, 2019" }, { "code": null, "e": 25470, "s": 25237, "text": "The setTime() function is a part of Timestamp class of Java SQL.The function is used to set the time of the Timestamp object. The function takes time in milliseconds which represents the time in milliseconds after 1st January, 1970." }, { "code": null, "e": 25490, "s": 25470, "text": "Function Signature:" }, { "code": null, "e": 25518, "s": 25490, "text": "public void setTime(long t)" }, { "code": null, "e": 25526, "s": 25518, "text": "Syntax:" }, { "code": null, "e": 25542, "s": 25526, "text": "ts1.setTime(l);" }, { "code": null, "e": 25635, "s": 25542, "text": "Parameters: The function accepts a long value l as parameter which is to be set as the time." }, { "code": null, "e": 25689, "s": 25635, "text": "Return value: The function does not return any value." }, { "code": null, "e": 25744, "s": 25689, "text": "Exception: The function does not throw any exceptions." }, { "code": null, "e": 25801, "s": 25744, "text": "Below programs illustrates the use of setTime() function" }, { "code": null, "e": 25893, "s": 25801, "text": "Example 1: Create a timestamp and use the setTime() to change the time of timestamp object." }, { "code": "// Java program to demonstrate the// use of setTime() function import java.sql.*; public class solution { public static void main(String args[]) { // Create two timestamp objects Timestamp ts = new Timestamp(10000); // Display the timestamp object System.out.println(\"Timestamp time: \" + ts.toString()); // Set the value of timestamp object // using setTime function ts.setTime(1000000000); // Display the new timestamp object System.out.println(\"New Timestamp time: \" + ts.toString()); }}", "e": 26515, "s": 25893, "text": null }, { "code": null, "e": 26596, "s": 26515, "text": "Timestamp time: 1970-01-01 00:00:10.0\nNew Timestamp time: 1970-01-12 13:46:40.0\n" }, { "code": null, "e": 26803, "s": 26596, "text": "Example 2: Create a timestamp and use the setTime() to change the time of timestamp object by passing negative long value as parameter. Giving negative long value represents the time before 1st January 1970" }, { "code": "// Java program to demonstrate the// use of setTime() function import java.sql.*; public class solution { public static void main(String args[]) { // Create two timestamp objects Timestamp ts = new Timestamp(10000); // Display the timestamp object System.out.println(\"Timestamp time: \" + ts.toString()); // Set the value of timestamp object // using setTime function ts.setTime(-1000000000); // Display the new timestamp object System.out.println(\"New Timestamp time: \" + ts.toString()); }}", "e": 27426, "s": 26803, "text": null }, { "code": null, "e": 27507, "s": 27426, "text": "Timestamp time: 1970-01-01 00:00:10.0\nNew Timestamp time: 1969-12-20 10:13:20.0\n" }, { "code": null, "e": 27598, "s": 27507, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/sql/Timestamp.html#setTime-long-" }, { "code": null, "e": 27612, "s": 27598, "text": "shubham_singh" }, { "code": null, "e": 27627, "s": 27612, "text": "Java-Functions" }, { "code": null, "e": 27644, "s": 27627, "text": "Java-Sql package" }, { "code": null, "e": 27659, "s": 27644, "text": "Java-TimeStamp" }, { "code": null, "e": 27664, "s": 27659, "text": "Java" }, { "code": null, "e": 27669, "s": 27664, "text": "Java" }, { "code": null, "e": 27767, "s": 27669, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27782, "s": 27767, "text": "Stream In Java" }, { "code": null, "e": 27803, "s": 27782, "text": "Constructors in Java" }, { "code": null, "e": 27822, "s": 27803, "text": "Exceptions in Java" }, { "code": null, "e": 27852, "s": 27822, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27898, "s": 27852, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27915, "s": 27898, "text": "Generics in Java" }, { "code": null, "e": 27936, "s": 27915, "text": "Introduction to Java" }, { "code": null, "e": 27979, "s": 27936, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28001, "s": 27979, "text": "PriorityQueue in Java" } ]
C program to write an image in PGM format
The PGM is the Portable Gray Map. If we want to store a 2d array in C as images in PNG, JPEG, or any other image format, we have to do lots of work to encode the data in some specified format before writing into a file. The Netpbm format gives an easy and portable solution. The Netpbm is an open source package of graphics program and it is used basically in linux or Unix platform. It also works under Microsoft Windows systems. Each file starts with a two-byte magic number. This magic number is used to identify the type of the file. The types are PBM, PGM, PPM etc. It also identifies the encoding (ASCII or Binary). The magic number is a capital P followed by a single digit number. The ASCII encoding allows human readability and easy transfer to other platforms; the binary format is more efficient in file size but it may have native byte-order issues. How to write PGM files? Set the magic number P2 Add whitespace (Space, Tabs, CRs, LFs) Add width, formatted as ASCII character in decimal Add Whitespace Add height, formatted as ASCII character in decimal Add Whitespace Put the maximum gray value, again in ASCII decimal Add Whitespace Width x Height gray values, each in ASCII decimal (Range between 0 and maximum value), separated by whitespace from top to bottom. #include <stdio.h> main() { int i, j; int w = 13, h = 13; // This 2D array will be converted into an image The size is 13 x 13 int image[13][13] = { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31}, { 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47}, { 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63}, { 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79}, { 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95 }, { 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111}, { 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127}, { 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143}, { 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159}, { 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175}, { 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191}, { 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207} }; FILE* pgmimg; pgmimg = fopen("my_pgmimg.pgm", "wb"); //write the file in binary mode fprintf(pgmimg, "P2\n"); // Writing Magic Number to the File fprintf(pgmimg, "%d %d\n", w, h); // Writing Width and Height into the file fprintf(pgmimg, "255\n"); // Writing the maximum gray value int count = 0; for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { fprintf(pgmimg, "%d ", image[i][j]); //Copy gray value from array to file } fprintf(pgmimg, "\n"); } fclose(pgmimg); } The PGM image is looking like below
[ { "code": null, "e": 1282, "s": 1062, "text": "The PGM is the Portable Gray Map. If we want to store a 2d array in C as images in PNG, JPEG, or any other image format, we have to do lots of work to encode the data in some specified format before writing into a file." }, { "code": null, "e": 1493, "s": 1282, "text": "The Netpbm format gives an easy and portable solution. The Netpbm is an open source package of graphics program and it is used basically in linux or Unix platform. It also works under Microsoft Windows systems." }, { "code": null, "e": 1751, "s": 1493, "text": "Each file starts with a two-byte magic number. This magic number is used to identify the type of the file. The types are PBM, PGM, PPM etc. It also identifies the encoding (ASCII or Binary). The magic number is a capital P followed by a single digit number." }, { "code": null, "e": 1924, "s": 1751, "text": "The ASCII encoding allows human readability and easy transfer to other platforms; the binary format is more efficient in file size but it may have native byte-order issues." }, { "code": null, "e": 1948, "s": 1924, "text": "How to write PGM files?" }, { "code": null, "e": 1972, "s": 1948, "text": "Set the magic number P2" }, { "code": null, "e": 2011, "s": 1972, "text": "Add whitespace (Space, Tabs, CRs, LFs)" }, { "code": null, "e": 2062, "s": 2011, "text": "Add width, formatted as ASCII character in decimal" }, { "code": null, "e": 2077, "s": 2062, "text": "Add Whitespace" }, { "code": null, "e": 2129, "s": 2077, "text": "Add height, formatted as ASCII character in decimal" }, { "code": null, "e": 2144, "s": 2129, "text": "Add Whitespace" }, { "code": null, "e": 2195, "s": 2144, "text": "Put the maximum gray value, again in ASCII decimal" }, { "code": null, "e": 2210, "s": 2195, "text": "Add Whitespace" }, { "code": null, "e": 2341, "s": 2210, "text": "Width x Height gray values, each in ASCII decimal (Range between 0 and maximum value), separated by whitespace from top to bottom." }, { "code": null, "e": 3927, "s": 2341, "text": "#include <stdio.h>\nmain() {\n int i, j;\n int w = 13, h = 13;\n // This 2D array will be converted into an image The size is 13 x 13\n int image[13][13] = {\n { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 },\n { 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31},\n { 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47},\n { 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63},\n { 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79},\n { 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95 },\n { 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111},\n { 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127},\n { 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143},\n { 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159},\n { 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175},\n { 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191},\n { 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207}\n };\n FILE* pgmimg;\n pgmimg = fopen(\"my_pgmimg.pgm\", \"wb\"); //write the file in binary mode\n fprintf(pgmimg, \"P2\\n\"); // Writing Magic Number to the File\n fprintf(pgmimg, \"%d %d\\n\", w, h); // Writing Width and Height into the\n file\n fprintf(pgmimg, \"255\\n\"); // Writing the maximum gray value\n int count = 0;\n for (i = 0; i < h; i++) {\n for (j = 0; j < w; j++) {\n fprintf(pgmimg, \"%d \", image[i][j]); //Copy gray value from\n array to file\n }\n fprintf(pgmimg, \"\\n\");\n }\n fclose(pgmimg);\n}" }, { "code": null, "e": 3963, "s": 3927, "text": "The PGM image is looking like below" } ]
OpenCV - Drawing a Rectangle
You can draw a rectangle on an image using the method rectangle() of the imgproc class. Following is the syntax of this method − rectangle(img, pt1, pt2, color, thickness) This method accepts the following parameters − mat − A Mat object representing the image on which the rectangle is to be drawn. mat − A Mat object representing the image on which the rectangle is to be drawn. pt1 and pt2 − Two Point objects representing the vertices of the rectangle that is to be drawn. pt1 and pt2 − Two Point objects representing the vertices of the rectangle that is to be drawn. scalar − A Scalar object representing the color of the rectangle. (BGR) scalar − A Scalar object representing the color of the rectangle. (BGR) thickness − An integer representing the thickness of the rectangle; by default, the value of thickness is 1. thickness − An integer representing the thickness of the rectangle; by default, the value of thickness is 1. The following example demonstrates how to draw a rectangle on an image and display it using JavaFX window. import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.InputStream; import javax.imageio.ImageIO; import javafx.application.Application; import javafx.embed.swing.SwingFXUtils; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.stage.Stage; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.core.Point; import org.opencv.core.Scalar; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class DrawingRectangle extends Application { Mat matrix = null; @Override public void start(Stage stage) throws Exception { // Capturing the snapshot from the camera DrawingRectangle obj = new DrawingRectangle(); WritableImage writableImage = obj.LoadImage(); // Setting the image view ImageView imageView = new ImageView(writableImage); // setting the fit height and width of the image view imageView.setFitHeight(600); imageView.setFitWidth(600); // Setting the preserve ratio of the image view imageView.setPreserveRatio(true); // Creating a Group object Group root = new Group(imageView); // Creating a scene object Scene scene = new Scene(root, 600, 400); // Setting title to the Stage stage.setTitle("Drawing Rectangle on the image"); // Adding scene to the stage stage.setScene(scene); // Displaying the contents of the stage stage.show(); } public WritableImage LoadImage() throws Exception { // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Reading the Image from the file and storing it in to a Matrix object String file ="E:/OpenCV/chap8/input.jpg"; Mat matrix = Imgcodecs.imread(file); // Drawing a Rectangle Imgproc.rectangle ( matrix, //Matrix obj of the image new Point(130, 50), //p1 new Point(300, 280), //p2 new Scalar(0, 0, 255), //Scalar object for color 5 //Thickness of the line ); // Encoding the image MatOfByte matOfByte = new MatOfByte(); Imgcodecs.imencode(".jpg", matrix, matOfByte); // Storing the encoded Mat in a byte array byte[] byteArray = matOfByte.toArray(); // Displaying the image InputStream in = new ByteArrayInputStream(byteArray); BufferedImage bufImage = ImageIO.read(in); this.matrix = matrix; // Creating the Writable Image WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null); return writableImage; } public static void main(String args[]) { launch(args); } } On executing the above program, you will get the following output − 70 Lectures 9 hours Abhilash Nelson 41 Lectures 4 hours Abhilash Nelson 20 Lectures 2 hours Spotle Learn 12 Lectures 46 mins Srikanth Guskra 19 Lectures 2 hours Haithem Gasmi 67 Lectures 6.5 hours Gianluca Mottola Print Add Notes Bookmark this page
[ { "code": null, "e": 3133, "s": 3004, "text": "You can draw a rectangle on an image using the method rectangle() of the imgproc class. Following is the syntax of this method −" }, { "code": null, "e": 3177, "s": 3133, "text": "rectangle(img, pt1, pt2, color, thickness)\n" }, { "code": null, "e": 3224, "s": 3177, "text": "This method accepts the following parameters −" }, { "code": null, "e": 3305, "s": 3224, "text": "mat − A Mat object representing the image on which the rectangle is to be drawn." }, { "code": null, "e": 3386, "s": 3305, "text": "mat − A Mat object representing the image on which the rectangle is to be drawn." }, { "code": null, "e": 3482, "s": 3386, "text": "pt1 and pt2 − Two Point objects representing the vertices of the rectangle that is to be drawn." }, { "code": null, "e": 3578, "s": 3482, "text": "pt1 and pt2 − Two Point objects representing the vertices of the rectangle that is to be drawn." }, { "code": null, "e": 3650, "s": 3578, "text": "scalar − A Scalar object representing the color of the rectangle. (BGR)" }, { "code": null, "e": 3722, "s": 3650, "text": "scalar − A Scalar object representing the color of the rectangle. (BGR)" }, { "code": null, "e": 3831, "s": 3722, "text": "thickness − An integer representing the thickness of the rectangle; by default, the value of thickness is 1." }, { "code": null, "e": 3940, "s": 3831, "text": "thickness − An integer representing the thickness of the rectangle; by default, the value of thickness is 1." }, { "code": null, "e": 4047, "s": 3940, "text": "The following example demonstrates how to draw a rectangle on an image and display it using JavaFX window." }, { "code": null, "e": 6911, "s": 4047, "text": "import java.awt.image.BufferedImage;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\nimport javax.imageio.ImageIO;\n\nimport javafx.application.Application;\nimport javafx.embed.swing.SwingFXUtils;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.image.WritableImage;\nimport javafx.stage.Stage;\n\nimport org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.MatOfByte;\nimport org.opencv.core.Point;\nimport org.opencv.core.Scalar;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class DrawingRectangle extends Application {\n Mat matrix = null;\n\n @Override\n public void start(Stage stage) throws Exception {\n // Capturing the snapshot from the camera\n DrawingRectangle obj = new DrawingRectangle();\n WritableImage writableImage = obj.LoadImage();\n\n // Setting the image view\n ImageView imageView = new ImageView(writableImage);\n\n // setting the fit height and width of the image view\n imageView.setFitHeight(600);\n imageView.setFitWidth(600);\n\n // Setting the preserve ratio of the image view\n imageView.setPreserveRatio(true);\n\n // Creating a Group object\n Group root = new Group(imageView);\n\n // Creating a scene object\n Scene scene = new Scene(root, 600, 400);\n\n // Setting title to the Stage\n stage.setTitle(\"Drawing Rectangle on the image\");\n\n // Adding scene to the stage\n stage.setScene(scene);\n\n // Displaying the contents of the stage\n stage.show();\n }\n public WritableImage LoadImage() throws Exception {\n // Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n\n // Reading the Image from the file and storing it in to a Matrix object\n String file =\"E:/OpenCV/chap8/input.jpg\";\n Mat matrix = Imgcodecs.imread(file);\n\n // Drawing a Rectangle\n Imgproc.rectangle (\n matrix, //Matrix obj of the image\n new Point(130, 50), //p1\n new Point(300, 280), //p2\n new Scalar(0, 0, 255), //Scalar object for color\n 5 //Thickness of the line\n );\n \n // Encoding the image\n MatOfByte matOfByte = new MatOfByte();\n Imgcodecs.imencode(\".jpg\", matrix, matOfByte);\n\n // Storing the encoded Mat in a byte array\n byte[] byteArray = matOfByte.toArray();\n\n // Displaying the image\n InputStream in = new ByteArrayInputStream(byteArray);\n BufferedImage bufImage = ImageIO.read(in);\n\n this.matrix = matrix;\n\n // Creating the Writable Image\n WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);\n return writableImage;\n }\n public static void main(String args[]) {\n launch(args);\n }\n}" }, { "code": null, "e": 6979, "s": 6911, "text": "On executing the above program, you will get the following output −" }, { "code": null, "e": 7012, "s": 6979, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 7029, "s": 7012, "text": " Abhilash Nelson" }, { "code": null, "e": 7062, "s": 7029, "text": "\n 41 Lectures \n 4 hours \n" }, { "code": null, "e": 7079, "s": 7062, "text": " Abhilash Nelson" }, { "code": null, "e": 7112, "s": 7079, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 7126, "s": 7112, "text": " Spotle Learn" }, { "code": null, "e": 7158, "s": 7126, "text": "\n 12 Lectures \n 46 mins\n" }, { "code": null, "e": 7175, "s": 7158, "text": " Srikanth Guskra" }, { "code": null, "e": 7208, "s": 7175, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 7223, "s": 7208, "text": " Haithem Gasmi" }, { "code": null, "e": 7258, "s": 7223, "text": "\n 67 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7276, "s": 7258, "text": " Gianluca Mottola" }, { "code": null, "e": 7283, "s": 7276, "text": " Print" }, { "code": null, "e": 7294, "s": 7283, "text": " Add Notes" } ]
Print all possible ways to split an array into K subsets
21 Jul, 2021 Given an array arr[] of size N and an integer K, the task is to print all possible ways to split the given array into K subsets. Examples: Input: arr[] = { 1, 2, 3 }, K = 2Output: { {{ 1, 2 }, { 3 }}, {{ 1, 3 }, { 2 }}, {{ 1 }, { 2, 3 }}}. Input: arr[] = { 1, 2, 3, 4 }, K = 2Output: { {{ 1, 2, 3 }, { 4 }}, {{ 1, 2, 4 }, { 3 }}, {{ 1, 2 }, { 3, 4 }}, {{ 1, 3, 4 }, { 2 }}, {{ 1, 3 }, { 2, 4 }}, {{ 1, 4 }, { 2, 3 }}, {{ 1 }, { 2 3, 4 }} } Approach: The problem can be solved using backtracking to generate and print all the subsets. Follow the steps below to solve the problem: Traverse the array and insert elements into any one of the K subsets using the following recurrence relation: Traverse the array and insert elements into any one of the K subsets using the following recurrence relation: PartitionSub(i, K, N) { for (j = 0; j < K; j++) { sub[j].push_back(arr[i]) PartitionSub(i + 1, K, N) sub[j].pop_back() } } If K is equal to 0 or K > N, then subsets cannot be generated.If count of array elements inserted into K subsets equal to N, then print the elements of the subset. If K is equal to 0 or K > N, then subsets cannot be generated. If count of array elements inserted into K subsets equal to N, then print the elements of the subset. C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // arr: Store input array// i: Stores current index of arr// N: Stores length of arr// K: Stores count of subsets// nos: Stores count of feasible subsets formed// v: Store K subsets of the given array // Utility function to find all possible// ways to split array into K subsetsvoid PartitionSub(int arr[], int i, int N, int K, int nos, vector<vector<int> >& v){ // If count of elements in K subsets // are greater than or equal to N if (i >= N) { // If count of subsets // formed is equal to K if (nos == K) { // Print K subsets by splitting // array into K subsets for (int x = 0; x < v.size(); x++) { cout << "{ "; // Print current subset for (int y = 0; y < v[x].size(); y++) { cout << v[x][y]; // If current element is the last // element of the subset if (y == v[x].size() - 1) { cout << " "; } // Otherwise else { cout << ", "; } } if (x == v.size() - 1) { cout << "}"; } else { cout << "}, "; } } cout << endl; } return; } for (int j = 0; j < K; j++) { // If any subset is occupied, // then push the element // in that first if (v[j].size() > 0) { v[j].push_back(arr[i]); // Recursively do the same // for remaining elements PartitionSub(arr, i + 1, N, K, nos, v); // Backtrack v[j].pop_back(); } // Otherwise, push it in an empty // subset and increase the // subset count by 1 else { v[j].push_back(arr[i]); PartitionSub(arr, i + 1, N, K, nos + 1, v); v[j].pop_back(); // Break to avoid the case of going in // other empty subsets, if available, // and forming the same combination break; } }} // Function to to find all possible ways to// split array into K subsetsvoid partKSubsets(int arr[], int N, int K){ // Stores K subset by splitting array // into K subsets vector<vector<int> > v(K); // Size of each subset must // be less than the number of elements if (K == 0 || K > N) { cout << "Not Possible" << endl; } else { cout << "The Subset Combinations are: " << endl; PartitionSub(arr, 0, N, K, 0, v); }} // Driver Codeint main(){ // Given array int arr[] = { 1, 2, 3, 4 }; // Given K int K = 2; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Prints all possible // splits into subsets partKSubsets(arr, N, K);} // Java program for above approachimport java.util.*;import java.lang.*;class Gfg{ // arr: Store input array // i: Stores current index of arr // N: Stores length of arr // K: Stores count of subsets // nos: Stores count of feasible subsets formed // v: Store K subsets of the given array // Utility function to find all possible // ways to split array into K subsets static void PartitionSub(int arr[], int i, int N, int K, int nos, ArrayList<ArrayList<Integer>> v) { // If count of elements in K subsets // are greater than or equal to N if (i >= N) { // If count of subsets // formed is equal to K if (nos == K) { // Print K subsets by splitting // array into K subsets for (int x = 0; x < v.size(); x++) { System.out.print("{ "); // Print current subset for (int y = 0; y < v.get(x).size(); y++) { System.out.print(v.get(x).get(y)); // If current element is the last // element of the subset if (y == v.get(x).size() - 1) { System.out.print(" "); } // Otherwise else { System.out.print(", "); } } if (x == v.size() - 1) { System.out.print("}"); } else { System.out.print("}, "); } } System.out.println();; } return; } for (int j = 0; j < K; j++) { // If any subset is occupied, // then push the element // in that first if (v.get(j).size() > 0) { v.get(j).add(arr[i]); // Recursively do the same // for remaining elements PartitionSub(arr, i + 1, N, K, nos, v); // Backtrack v.get(j).remove(v.get(j).size()-1); } // Otherwise, push it in an empty // subset and increase the // subset count by 1 else { v.get(j).add(arr[i]); PartitionSub(arr, i + 1, N, K, nos + 1, v); v.get(j).remove(v.get(j).size()-1); // Break to avoid the case of going in // other empty subsets, if available, // and forming the same combination break; } } } // Function to to find all possible ways to // split array into K subsets static void partKSubsets(int arr[], int N, int K) { // Stores K subset by splitting array // into K subsets ArrayList<ArrayList<Integer>> v = new ArrayList<>(); for(int i = 0; i < K; i++) v.add(new ArrayList<>()); // Size of each subset must // be less than the number of elements if (K == 0 || K > N) { System.out.println("Not Possible"); } else { System.out.println("The Subset Combinations are: "); PartitionSub(arr, 0, N, K, 0, v); } } // Driver function public static void main (String[] args) { // Given array int arr[] = { 1, 2, 3, 4 }; // Given K int K = 2; // Size of the array int N = arr.length; // Prints all possible // splits into subsets partKSubsets(arr, N, K); }} // This code is contributed by offbeat # Python 3 program for the above approach # arr: Store input array# i: Stores current index of arr# N: Stores length of arr# K: Stores count of subsets# nos: Stores count of feasible subsets formed# v: Store K subsets of the given array # Utility function to find all possible# ways to split array into K subsetsdef PartitionSub(arr, i, N, K, nos, v): # If count of elements in K subsets # are greater than or equal to N if (i >= N): # If count of subsets # formed is equal to K if (nos == K): # Print K subsets by splitting # array into K subsets for x in range(len(v)): print("{ ", end = "") # Print current subset for y in range(len(v[x])): print(v[x][y], end = "") # If current element is the last # element of the subset if (y == len(v[x]) - 1): print(" ", end = "") # Otherwise else: print(", ", end = "") if (x == len(v) - 1): print("}", end = "") else: print("}, ", end = "") print("\n", end = "") return for j in range(K): # If any subset is occupied, # then push the element # in that first if (len(v[j]) > 0): v[j].append(arr[i]) # Recursively do the same # for remaining elements PartitionSub(arr, i + 1, N, K, nos, v) # Backtrack v[j].remove(v[j][len(v[j]) - 1]) # Otherwise, push it in an empty # subset and increase the # subset count by 1 else: v[j].append(arr[i]) PartitionSub(arr, i + 1, N, K, nos + 1, v) v[j].remove(v[j][len(v[j]) - 1]) # Break to avoid the case of going in # other empty subsets, if available, # and forming the same combination break # Function to to find all possible ways to# split array into K subsetsdef partKSubsets(arr, N, K): # Stores K subset by splitting array # into K subsets v = [[] for i in range(K)] # Size of each subset must # be less than the number of elements if (K == 0 or K > N): print("Not Possible", end = "") else: print("The Subset Combinations are: ") PartitionSub(arr, 0, N, K, 0, v) # Driver Codeif __name__ == '__main__': # Given array arr = [1, 2, 3, 4] # Given K K = 2 # Size of the array N = len(arr) # Prints all possible # splits into subsets partKSubsets(arr, N, K) # This code is contributed by bgangwar59. // C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // arr: Store input array // i: Stores current index of arr // N: Stores length of arr // K: Stores count of subsets // nos: Stores count of feasible subsets formed // v: Store K subsets of the given array // Utility function to find all possible // ways to split array into K subsets static void PartitionSub(int []arr, int i, int N, int K, int nos, List<List<int>>v){ // If count of elements in K subsets // are greater than or equal to N if (i >= N) { // If count of subsets // formed is equal to K if (nos == K) { // Print K subsets by splitting // array into K subsets for (int x = 0; x < v.Count; x++) { Console.Write("{ "); // Print current subset for (int y = 0; y < v[x].Count; y++) { Console.Write(v[x][y]); // If current element is the last // element of the subset if (y == v[x].Count - 1) { Console.Write(" "); } // Otherwise else { Console.Write(", "); } } if (x == v.Count - 1) { Console.Write("}"); } else { Console.Write("}, "); } } Console.Write("\n"); } return; } for (int j = 0; j < K; j++) { // If any subset is occupied, // then push the element // in that first if (v[j].Count > 0) { v[j].Add(arr[i]); // Recursively do the same // for remaining elements PartitionSub(arr, i + 1, N, K, nos, v); // Backtrack v[j].RemoveAt(v[j].Count - 1); } // Otherwise, push it in an empty // subset and increase the // subset count by 1 else { v[j].Add(arr[i]); PartitionSub(arr, i + 1, N, K, nos + 1, v); v[j].RemoveAt(v[j].Count - 1); // Break to avoid the case of going in // other empty subsets, if available, // and forming the same combination break; } }} // Function to to find all possible ways to // split array into K subsets static void partKSubsets(int []arr, int N, int K) { // Stores K subset by splitting array // into K subsets List<List<int> > v = new List<List<int>>(); for(int i=0;i<K;i++) v.Add(new List<int>()); // Size of each subset must // be less than the number of elements if (K == 0 || K > N) { Console.WriteLine("Not Possible"); } else { Console.WriteLine("The Subset Combinations are: "); PartitionSub(arr, 0, N, K, 0, v); } } // Driver Code public static void Main() { // Given array int []arr = {1, 2, 3, 4}; // Given K int K = 2; // Size of the array int N = arr.Length; // Prints all possible // splits into subsets partKSubsets(arr, N, K); }} // This code is contributed by SURENDRA_GANGWAR. <script> // Javascript program for above approach // arr: Store input array // i: Stores current index of arr // N: Stores length of arr // K: Stores count of subsets // nos: Stores count of feasible subsets formed // v: Store K subsets of the given array // Utility function to find all possible // ways to split array into K subsets function PartitionSub(arr, i, N, K, nos, v) { // If count of elements in K subsets // are greater than or equal to N if (i >= N) { // If count of subsets // formed is equal to K if (nos == K) { // Print K subsets by splitting // array into K subsets for (let x = 0; x < v.length; x++) { document.write("{ "); // Print current subset for (let y = 0; y < v[x].length; y++) { document.write(v[x][y]); // If current element is the last // element of the subset if (y == v[x].length - 1) { document.write(" "); } // Otherwise else { document.write(", "); } } if (x == v.length - 1) { document.write("}"); } else { document.write("}, "); } } document.write("</br>"); } return; } for (let j = 0; j < K; j++) { // If any subset is occupied, // then push the element // in that first if (v[j].length > 0) { v[j].push(arr[i]); // Recursively do the same // for remaining elements PartitionSub(arr, i + 1, N, K, nos, v); // Backtrack v[j].pop(); } // Otherwise, push it in an empty // subset and increase the // subset count by 1 else { v[j].push(arr[i]); PartitionSub(arr, i + 1, N, K, nos + 1, v); v[j].pop(); // Break to avoid the case of going in // other empty subsets, if available, // and forming the same combination break; } } } // Function to to find all possible ways to // split array into K subsets function partKSubsets(arr, N, K) { // Stores K subset by splitting array // into K subsets let v = []; for(let i = 0; i < K; i++) v.push([]); // Size of each subset must // be less than the number of elements if (K == 0 || K > N) { document.write("Not Possible" + "</br>"); } else { document.write("The Subset Combinations are: " + "</br>"); PartitionSub(arr, 0, N, K, 0, v); } } // Given array let arr = [ 1, 2, 3, 4 ]; // Given K let K = 2; // Size of the array let N = arr.length; // Prints all possible // splits into subsets partKSubsets(arr, N, K); // This code is contributed by decode2207.</script> The Subset Combinations are: { 1, 2, 3 }, { 4 } { 1, 2, 4 }, { 3 } { 1, 2 }, { 3, 4 } { 1, 3, 4 }, { 2 } { 1, 3 }, { 2, 4 } { 1, 4 }, { 2, 3 } { 1 }, { 2, 3, 4 } bgangwar59 SURENDRA_GANGWAR offbeat gulshankumarar231 decode2207 subset Technical Scripter 2020 Arrays Backtracking Recursion Stack Technical Scripter Arrays Recursion Stack subset Backtracking 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 Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) N Queen Problem | Backtracking-3 The Knight's tour problem | Backtracking-1 Rat in a Maze | Backtracking-2 Backtracking | Introduction
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jul, 2021" }, { "code": null, "e": 183, "s": 54, "text": "Given an array arr[] of size N and an integer K, the task is to print all possible ways to split the given array into K subsets." }, { "code": null, "e": 193, "s": 183, "text": "Examples:" }, { "code": null, "e": 294, "s": 193, "text": "Input: arr[] = { 1, 2, 3 }, K = 2Output: { {{ 1, 2 }, { 3 }}, {{ 1, 3 }, { 2 }}, {{ 1 }, { 2, 3 }}}." }, { "code": null, "e": 494, "s": 294, "text": "Input: arr[] = { 1, 2, 3, 4 }, K = 2Output: { {{ 1, 2, 3 }, { 4 }}, {{ 1, 2, 4 }, { 3 }}, {{ 1, 2 }, { 3, 4 }}, {{ 1, 3, 4 }, { 2 }}, {{ 1, 3 }, { 2, 4 }}, {{ 1, 4 }, { 2, 3 }}, {{ 1 }, { 2 3, 4 }} }" }, { "code": null, "e": 633, "s": 494, "text": "Approach: The problem can be solved using backtracking to generate and print all the subsets. Follow the steps below to solve the problem:" }, { "code": null, "e": 745, "s": 633, "text": "Traverse the array and insert elements into any one of the K subsets using the following recurrence relation: " }, { "code": null, "e": 857, "s": 745, "text": "Traverse the array and insert elements into any one of the K subsets using the following recurrence relation: " }, { "code": null, "e": 879, "s": 857, "text": "PartitionSub(i, K, N)" }, { "code": null, "e": 881, "s": 879, "text": "{" }, { "code": null, "e": 910, "s": 881, "text": " for (j = 0; j < K; j++) {" }, { "code": null, "e": 941, "s": 910, "text": " sub[j].push_back(arr[i])" }, { "code": null, "e": 973, "s": 941, "text": " PartitionSub(i + 1, K, N)" }, { "code": null, "e": 997, "s": 973, "text": " sub[j].pop_back()" }, { "code": null, "e": 1002, "s": 997, "text": " }" }, { "code": null, "e": 1004, "s": 1002, "text": "}" }, { "code": null, "e": 1169, "s": 1004, "text": " If K is equal to 0 or K > N, then subsets cannot be generated.If count of array elements inserted into K subsets equal to N, then print the elements of the subset." }, { "code": null, "e": 1234, "s": 1171, "text": "If K is equal to 0 or K > N, then subsets cannot be generated." }, { "code": null, "e": 1336, "s": 1234, "text": "If count of array elements inserted into K subsets equal to N, then print the elements of the subset." }, { "code": null, "e": 1340, "s": 1336, "text": "C++" }, { "code": null, "e": 1345, "s": 1340, "text": "Java" }, { "code": null, "e": 1353, "s": 1345, "text": "Python3" }, { "code": null, "e": 1356, "s": 1353, "text": "C#" }, { "code": null, "e": 1367, "s": 1356, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // arr: Store input array// i: Stores current index of arr// N: Stores length of arr// K: Stores count of subsets// nos: Stores count of feasible subsets formed// v: Store K subsets of the given array // Utility function to find all possible// ways to split array into K subsetsvoid PartitionSub(int arr[], int i, int N, int K, int nos, vector<vector<int> >& v){ // If count of elements in K subsets // are greater than or equal to N if (i >= N) { // If count of subsets // formed is equal to K if (nos == K) { // Print K subsets by splitting // array into K subsets for (int x = 0; x < v.size(); x++) { cout << \"{ \"; // Print current subset for (int y = 0; y < v[x].size(); y++) { cout << v[x][y]; // If current element is the last // element of the subset if (y == v[x].size() - 1) { cout << \" \"; } // Otherwise else { cout << \", \"; } } if (x == v.size() - 1) { cout << \"}\"; } else { cout << \"}, \"; } } cout << endl; } return; } for (int j = 0; j < K; j++) { // If any subset is occupied, // then push the element // in that first if (v[j].size() > 0) { v[j].push_back(arr[i]); // Recursively do the same // for remaining elements PartitionSub(arr, i + 1, N, K, nos, v); // Backtrack v[j].pop_back(); } // Otherwise, push it in an empty // subset and increase the // subset count by 1 else { v[j].push_back(arr[i]); PartitionSub(arr, i + 1, N, K, nos + 1, v); v[j].pop_back(); // Break to avoid the case of going in // other empty subsets, if available, // and forming the same combination break; } }} // Function to to find all possible ways to// split array into K subsetsvoid partKSubsets(int arr[], int N, int K){ // Stores K subset by splitting array // into K subsets vector<vector<int> > v(K); // Size of each subset must // be less than the number of elements if (K == 0 || K > N) { cout << \"Not Possible\" << endl; } else { cout << \"The Subset Combinations are: \" << endl; PartitionSub(arr, 0, N, K, 0, v); }} // Driver Codeint main(){ // Given array int arr[] = { 1, 2, 3, 4 }; // Given K int K = 2; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Prints all possible // splits into subsets partKSubsets(arr, N, K);}", "e": 4402, "s": 1367, "text": null }, { "code": "// Java program for above approachimport java.util.*;import java.lang.*;class Gfg{ // arr: Store input array // i: Stores current index of arr // N: Stores length of arr // K: Stores count of subsets // nos: Stores count of feasible subsets formed // v: Store K subsets of the given array // Utility function to find all possible // ways to split array into K subsets static void PartitionSub(int arr[], int i, int N, int K, int nos, ArrayList<ArrayList<Integer>> v) { // If count of elements in K subsets // are greater than or equal to N if (i >= N) { // If count of subsets // formed is equal to K if (nos == K) { // Print K subsets by splitting // array into K subsets for (int x = 0; x < v.size(); x++) { System.out.print(\"{ \"); // Print current subset for (int y = 0; y < v.get(x).size(); y++) { System.out.print(v.get(x).get(y)); // If current element is the last // element of the subset if (y == v.get(x).size() - 1) { System.out.print(\" \"); } // Otherwise else { System.out.print(\", \"); } } if (x == v.size() - 1) { System.out.print(\"}\"); } else { System.out.print(\"}, \"); } } System.out.println();; } return; } for (int j = 0; j < K; j++) { // If any subset is occupied, // then push the element // in that first if (v.get(j).size() > 0) { v.get(j).add(arr[i]); // Recursively do the same // for remaining elements PartitionSub(arr, i + 1, N, K, nos, v); // Backtrack v.get(j).remove(v.get(j).size()-1); } // Otherwise, push it in an empty // subset and increase the // subset count by 1 else { v.get(j).add(arr[i]); PartitionSub(arr, i + 1, N, K, nos + 1, v); v.get(j).remove(v.get(j).size()-1); // Break to avoid the case of going in // other empty subsets, if available, // and forming the same combination break; } } } // Function to to find all possible ways to // split array into K subsets static void partKSubsets(int arr[], int N, int K) { // Stores K subset by splitting array // into K subsets ArrayList<ArrayList<Integer>> v = new ArrayList<>(); for(int i = 0; i < K; i++) v.add(new ArrayList<>()); // Size of each subset must // be less than the number of elements if (K == 0 || K > N) { System.out.println(\"Not Possible\"); } else { System.out.println(\"The Subset Combinations are: \"); PartitionSub(arr, 0, N, K, 0, v); } } // Driver function public static void main (String[] args) { // Given array int arr[] = { 1, 2, 3, 4 }; // Given K int K = 2; // Size of the array int N = arr.length; // Prints all possible // splits into subsets partKSubsets(arr, N, K); }} // This code is contributed by offbeat", "e": 7615, "s": 4402, "text": null }, { "code": "# Python 3 program for the above approach # arr: Store input array# i: Stores current index of arr# N: Stores length of arr# K: Stores count of subsets# nos: Stores count of feasible subsets formed# v: Store K subsets of the given array # Utility function to find all possible# ways to split array into K subsetsdef PartitionSub(arr, i, N, K, nos, v): # If count of elements in K subsets # are greater than or equal to N if (i >= N): # If count of subsets # formed is equal to K if (nos == K): # Print K subsets by splitting # array into K subsets for x in range(len(v)): print(\"{ \", end = \"\") # Print current subset for y in range(len(v[x])): print(v[x][y], end = \"\") # If current element is the last # element of the subset if (y == len(v[x]) - 1): print(\" \", end = \"\") # Otherwise else: print(\", \", end = \"\") if (x == len(v) - 1): print(\"}\", end = \"\") else: print(\"}, \", end = \"\") print(\"\\n\", end = \"\") return for j in range(K): # If any subset is occupied, # then push the element # in that first if (len(v[j]) > 0): v[j].append(arr[i]) # Recursively do the same # for remaining elements PartitionSub(arr, i + 1, N, K, nos, v) # Backtrack v[j].remove(v[j][len(v[j]) - 1]) # Otherwise, push it in an empty # subset and increase the # subset count by 1 else: v[j].append(arr[i]) PartitionSub(arr, i + 1, N, K, nos + 1, v) v[j].remove(v[j][len(v[j]) - 1]) # Break to avoid the case of going in # other empty subsets, if available, # and forming the same combination break # Function to to find all possible ways to# split array into K subsetsdef partKSubsets(arr, N, K): # Stores K subset by splitting array # into K subsets v = [[] for i in range(K)] # Size of each subset must # be less than the number of elements if (K == 0 or K > N): print(\"Not Possible\", end = \"\") else: print(\"The Subset Combinations are: \") PartitionSub(arr, 0, N, K, 0, v) # Driver Codeif __name__ == '__main__': # Given array arr = [1, 2, 3, 4] # Given K K = 2 # Size of the array N = len(arr) # Prints all possible # splits into subsets partKSubsets(arr, N, K) # This code is contributed by bgangwar59.", "e": 10406, "s": 7615, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // arr: Store input array // i: Stores current index of arr // N: Stores length of arr // K: Stores count of subsets // nos: Stores count of feasible subsets formed // v: Store K subsets of the given array // Utility function to find all possible // ways to split array into K subsets static void PartitionSub(int []arr, int i, int N, int K, int nos, List<List<int>>v){ // If count of elements in K subsets // are greater than or equal to N if (i >= N) { // If count of subsets // formed is equal to K if (nos == K) { // Print K subsets by splitting // array into K subsets for (int x = 0; x < v.Count; x++) { Console.Write(\"{ \"); // Print current subset for (int y = 0; y < v[x].Count; y++) { Console.Write(v[x][y]); // If current element is the last // element of the subset if (y == v[x].Count - 1) { Console.Write(\" \"); } // Otherwise else { Console.Write(\", \"); } } if (x == v.Count - 1) { Console.Write(\"}\"); } else { Console.Write(\"}, \"); } } Console.Write(\"\\n\"); } return; } for (int j = 0; j < K; j++) { // If any subset is occupied, // then push the element // in that first if (v[j].Count > 0) { v[j].Add(arr[i]); // Recursively do the same // for remaining elements PartitionSub(arr, i + 1, N, K, nos, v); // Backtrack v[j].RemoveAt(v[j].Count - 1); } // Otherwise, push it in an empty // subset and increase the // subset count by 1 else { v[j].Add(arr[i]); PartitionSub(arr, i + 1, N, K, nos + 1, v); v[j].RemoveAt(v[j].Count - 1); // Break to avoid the case of going in // other empty subsets, if available, // and forming the same combination break; } }} // Function to to find all possible ways to // split array into K subsets static void partKSubsets(int []arr, int N, int K) { // Stores K subset by splitting array // into K subsets List<List<int> > v = new List<List<int>>(); for(int i=0;i<K;i++) v.Add(new List<int>()); // Size of each subset must // be less than the number of elements if (K == 0 || K > N) { Console.WriteLine(\"Not Possible\"); } else { Console.WriteLine(\"The Subset Combinations are: \"); PartitionSub(arr, 0, N, K, 0, v); } } // Driver Code public static void Main() { // Given array int []arr = {1, 2, 3, 4}; // Given K int K = 2; // Size of the array int N = arr.Length; // Prints all possible // splits into subsets partKSubsets(arr, N, K); }} // This code is contributed by SURENDRA_GANGWAR.", "e": 13291, "s": 10406, "text": null }, { "code": "<script> // Javascript program for above approach // arr: Store input array // i: Stores current index of arr // N: Stores length of arr // K: Stores count of subsets // nos: Stores count of feasible subsets formed // v: Store K subsets of the given array // Utility function to find all possible // ways to split array into K subsets function PartitionSub(arr, i, N, K, nos, v) { // If count of elements in K subsets // are greater than or equal to N if (i >= N) { // If count of subsets // formed is equal to K if (nos == K) { // Print K subsets by splitting // array into K subsets for (let x = 0; x < v.length; x++) { document.write(\"{ \"); // Print current subset for (let y = 0; y < v[x].length; y++) { document.write(v[x][y]); // If current element is the last // element of the subset if (y == v[x].length - 1) { document.write(\" \"); } // Otherwise else { document.write(\", \"); } } if (x == v.length - 1) { document.write(\"}\"); } else { document.write(\"}, \"); } } document.write(\"</br>\"); } return; } for (let j = 0; j < K; j++) { // If any subset is occupied, // then push the element // in that first if (v[j].length > 0) { v[j].push(arr[i]); // Recursively do the same // for remaining elements PartitionSub(arr, i + 1, N, K, nos, v); // Backtrack v[j].pop(); } // Otherwise, push it in an empty // subset and increase the // subset count by 1 else { v[j].push(arr[i]); PartitionSub(arr, i + 1, N, K, nos + 1, v); v[j].pop(); // Break to avoid the case of going in // other empty subsets, if available, // and forming the same combination break; } } } // Function to to find all possible ways to // split array into K subsets function partKSubsets(arr, N, K) { // Stores K subset by splitting array // into K subsets let v = []; for(let i = 0; i < K; i++) v.push([]); // Size of each subset must // be less than the number of elements if (K == 0 || K > N) { document.write(\"Not Possible\" + \"</br>\"); } else { document.write(\"The Subset Combinations are: \" + \"</br>\"); PartitionSub(arr, 0, N, K, 0, v); } } // Given array let arr = [ 1, 2, 3, 4 ]; // Given K let K = 2; // Size of the array let N = arr.length; // Prints all possible // splits into subsets partKSubsets(arr, N, K); // This code is contributed by decode2207.</script>", "e": 16380, "s": 13291, "text": null }, { "code": null, "e": 16543, "s": 16380, "text": "The Subset Combinations are: \n{ 1, 2, 3 }, { 4 }\n{ 1, 2, 4 }, { 3 }\n{ 1, 2 }, { 3, 4 }\n{ 1, 3, 4 }, { 2 }\n{ 1, 3 }, { 2, 4 }\n{ 1, 4 }, { 2, 3 }\n{ 1 }, { 2, 3, 4 }" }, { "code": null, "e": 16554, "s": 16543, "text": "bgangwar59" }, { "code": null, "e": 16571, "s": 16554, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 16579, "s": 16571, "text": "offbeat" }, { "code": null, "e": 16597, "s": 16579, "text": "gulshankumarar231" }, { "code": null, "e": 16608, "s": 16597, "text": "decode2207" }, { "code": null, "e": 16615, "s": 16608, "text": "subset" }, { "code": null, "e": 16639, "s": 16615, "text": "Technical Scripter 2020" }, { "code": null, "e": 16646, "s": 16639, "text": "Arrays" }, { "code": null, "e": 16659, "s": 16646, "text": "Backtracking" }, { "code": null, "e": 16669, "s": 16659, "text": "Recursion" }, { "code": null, "e": 16675, "s": 16669, "text": "Stack" }, { "code": null, "e": 16694, "s": 16675, "text": "Technical Scripter" }, { "code": null, "e": 16701, "s": 16694, "text": "Arrays" }, { "code": null, "e": 16711, "s": 16701, "text": "Recursion" }, { "code": null, "e": 16717, "s": 16711, "text": "Stack" }, { "code": null, "e": 16724, "s": 16717, "text": "subset" }, { "code": null, "e": 16737, "s": 16724, "text": "Backtracking" }, { "code": null, "e": 16835, "s": 16737, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16903, "s": 16835, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 16947, "s": 16903, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 16979, "s": 16947, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 17027, "s": 16979, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 17041, "s": 17027, "text": "Linear Search" }, { "code": null, "e": 17126, "s": 17041, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 17159, "s": 17126, "text": "N Queen Problem | Backtracking-3" }, { "code": null, "e": 17202, "s": 17159, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 17233, "s": 17202, "text": "Rat in a Maze | Backtracking-2" } ]
wxPython – Disable Button
18 Jun, 2020 In this article we are going to learn about how can we disable a button present in a frame. Sometimes when we dont want user to press a button we can disable a button and the button become unclickable.In order to disable a button we can use Disable() function associated with wx.Button class of wxPython. Syntax: wx.Button.Disable(Self) Parameters: No parameters required in Disable() function. Code Example: import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) self.pnl = wx.Panel(self) bmp = wx.Bitmap('download.jpg') # CREATE BUTTON AT POINT (20, 20) self.st = wx.Button(self.pnl, id = 1, label ="Button", pos =(20, 20), size =(100, 30), name ="button") # SET BUTTON DISABLED self.st.Disable() self.SetSize((350, 250)) self.SetTitle('wx.Button') self.Centre() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main() Output Image: Python wxPython-Button Python-gui Python-wxPython Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jun, 2020" }, { "code": null, "e": 333, "s": 28, "text": "In this article we are going to learn about how can we disable a button present in a frame. Sometimes when we dont want user to press a button we can disable a button and the button become unclickable.In order to disable a button we can use Disable() function associated with wx.Button class of wxPython." }, { "code": null, "e": 365, "s": 333, "text": "Syntax: wx.Button.Disable(Self)" }, { "code": null, "e": 423, "s": 365, "text": "Parameters: No parameters required in Disable() function." }, { "code": null, "e": 437, "s": 423, "text": "Code Example:" }, { "code": "import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) self.pnl = wx.Panel(self) bmp = wx.Bitmap('download.jpg') # CREATE BUTTON AT POINT (20, 20) self.st = wx.Button(self.pnl, id = 1, label =\"Button\", pos =(20, 20), size =(100, 30), name =\"button\") # SET BUTTON DISABLED self.st.Disable() self.SetSize((350, 250)) self.SetTitle('wx.Button') self.Centre() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()", "e": 1197, "s": 437, "text": null }, { "code": null, "e": 1211, "s": 1197, "text": "Output Image:" }, { "code": null, "e": 1234, "s": 1211, "text": "Python wxPython-Button" }, { "code": null, "e": 1245, "s": 1234, "text": "Python-gui" }, { "code": null, "e": 1261, "s": 1245, "text": "Python-wxPython" }, { "code": null, "e": 1268, "s": 1261, "text": "Python" }, { "code": null, "e": 1366, "s": 1268, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1384, "s": 1366, "text": "Python Dictionary" }, { "code": null, "e": 1426, "s": 1384, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1448, "s": 1426, "text": "Enumerate() in Python" }, { "code": null, "e": 1483, "s": 1448, "text": "Read a file line by line in Python" }, { "code": null, "e": 1509, "s": 1483, "text": "Python String | replace()" }, { "code": null, "e": 1541, "s": 1509, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1570, "s": 1541, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1597, "s": 1570, "text": "Python Classes and Objects" }, { "code": null, "e": 1618, "s": 1597, "text": "Python OOPs Concepts" } ]
Lodash _.random() Method
09 Sep, 2020 The _.random() method is used to return a random number which is in the range provided to the function. If floating is true, or either lower or upper are floats, a floating-point number is returned instead of an integer. Syntax: _.random([lower = 0], [upper = 1], [floating]) Parameters: This method accepts three parameters as mentioned above and described below: lower: This parameter holds the lower bound. upper: This parameter holds the upper bound. floating: This parameter specifies returning a floating-point number. Return Value: This method returns the random number. Example 1: Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.random method console.log(_.random(10)); console.log(_.random(10, 12)); console.log(_.random(10, 12)); console.log(_.random(10.3, 12.5)); Output: 3 11 10 12.000118273018167 Example 2: Javascript // Requiring the lodash library const _ = require("lodash"); // lower and upper valuelet lower = 2; let upper = 11; // Printing 5 random values // in range 2 and 11 for (let i = 0; i < 5; i++) { console.log(_.random(lower, upper)); } Output: 9 5 2 11 5 JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property How to append HTML code to a div using JavaScript ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Sep, 2020" }, { "code": null, "e": 249, "s": 28, "text": "The _.random() method is used to return a random number which is in the range provided to the function. If floating is true, or either lower or upper are floats, a floating-point number is returned instead of an integer." }, { "code": null, "e": 257, "s": 249, "text": "Syntax:" }, { "code": null, "e": 305, "s": 257, "text": "_.random([lower = 0], [upper = 1], [floating])\n" }, { "code": null, "e": 394, "s": 305, "text": "Parameters: This method accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 439, "s": 394, "text": "lower: This parameter holds the lower bound." }, { "code": null, "e": 484, "s": 439, "text": "upper: This parameter holds the upper bound." }, { "code": null, "e": 554, "s": 484, "text": "floating: This parameter specifies returning a floating-point number." }, { "code": null, "e": 607, "s": 554, "text": "Return Value: This method returns the random number." }, { "code": null, "e": 618, "s": 607, "text": "Example 1:" }, { "code": null, "e": 629, "s": 618, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.random method console.log(_.random(10)); console.log(_.random(10, 12)); console.log(_.random(10, 12)); console.log(_.random(10.3, 12.5)); ", "e": 853, "s": 629, "text": null }, { "code": null, "e": 861, "s": 853, "text": "Output:" }, { "code": null, "e": 889, "s": 861, "text": "3\n11\n10\n12.000118273018167\n" }, { "code": null, "e": 902, "s": 889, "text": "Example 2: " }, { "code": null, "e": 913, "s": 902, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // lower and upper valuelet lower = 2; let upper = 11; // Printing 5 random values // in range 2 and 11 for (let i = 0; i < 5; i++) { console.log(_.random(lower, upper)); }", "e": 1159, "s": 913, "text": null }, { "code": null, "e": 1167, "s": 1159, "text": "Output:" }, { "code": null, "e": 1179, "s": 1167, "text": "9\n5\n2\n11\n5\n" }, { "code": null, "e": 1197, "s": 1179, "text": "JavaScript-Lodash" }, { "code": null, "e": 1208, "s": 1197, "text": "JavaScript" }, { "code": null, "e": 1225, "s": 1208, "text": "Web Technologies" }, { "code": null, "e": 1323, "s": 1225, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1384, "s": 1323, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1456, "s": 1384, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1496, "s": 1456, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1549, "s": 1496, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 1601, "s": 1549, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 1663, "s": 1601, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1696, "s": 1663, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1757, "s": 1696, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1807, "s": 1757, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to get or set the selection state of JCheckBox in Java
The following is an example to get or set the selection state of JCheckBox: import java.awt.FlowLayout; import javax.swing.JCheckBox; import javax.swing.JFrame; public class SwingDemo extends JFrame { public SwingDemo() { setSize(500, 500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout(FlowLayout.CENTER)); JCheckBox checkBox = new JCheckBox("Demo"); checkBox.setSelected(true); boolean sel = checkBox.isSelected(); if (sel) System.out.println("Check box selected!"); getContentPane().add(checkBox); } public static void main(String[] args) { new SwingDemo().setVisible(true); } } Since the checkbox is selected by default, the following output would be visible in EclipseIDE:
[ { "code": null, "e": 1138, "s": 1062, "text": "The following is an example to get or set the selection state of JCheckBox:" }, { "code": null, "e": 1746, "s": 1138, "text": "import java.awt.FlowLayout;\nimport javax.swing.JCheckBox;\nimport javax.swing.JFrame;\npublic class SwingDemo extends JFrame {\n public SwingDemo() {\n setSize(500, 500);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLayout(new FlowLayout(FlowLayout.CENTER));\n JCheckBox checkBox = new JCheckBox(\"Demo\");\n checkBox.setSelected(true);\n boolean sel = checkBox.isSelected();\n if (sel)\n System.out.println(\"Check box selected!\");\n getContentPane().add(checkBox);\n }\n public static void main(String[] args) {\n new SwingDemo().setVisible(true);\n }\n}" }, { "code": null, "e": 1842, "s": 1746, "text": "Since the checkbox is selected by default, the following output would be visible in EclipseIDE:" } ]