title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Pointers in Golang
11 Aug, 2021 Pointers in Go programming language or Golang is a variable that is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like 0xFFAAF etc.). What is the need for the pointers? To understand this need, first, we have to understand the concept of variables. Variables are the names given to a memory location where the actual data is stored. To access the stored data we need the address of that particular memory location. To remember all the memory addresses(Hexadecimal Format) manually is an overhead that’s why we use variables to store data and variables can be accessed just by using their name. Golang also allows saving a hexadecimal number into a variable using the literal expression i.e. number starting from 0x is a hexadecimal number. Example: In the below program, we are storing the hexadecimal number into a variable. But you can see that the type of values is int and saved as the decimal or you can say the decimal value of type int is storing. But the main point to explain this example is that we are storing a hexadecimal value(consider it a memory address) but it is not a pointer as it is not pointing to any other memory location of another variable. It is just a user-defined variable. So this arises the need for pointers. Go Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English default, selected This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. // Golang program to demonstrate the variables// storing the hexadecimal valuespackage main import "fmt" func main() { // storing the hexadecimal // values in variables x := 0xFF y := 0x9C // Displaying the values fmt.Printf("Type of variable x is %T\n", x) fmt.Printf("Value of x in hexadecimal is %X\n", x) fmt.Printf("Value of x in decimal is %v\n", x) fmt.Printf("Type of variable y is %T\n", y) fmt.Printf("Value of y in hexadecimal is %X\n", y) fmt.Printf("Value of y in decimal is %v\n", y) } Output: Type of variable x is int Value of x in hexadecimal is FF Value of x in decimal is 255 Type of variable y is int Value of y in hexadecimal is 9C Value of y in decimal is 156 A pointer is a special kind of variable that is not only used to store the memory addresses of other variables but also points where the memory is located and provides ways to find out the value stored at that memory location. It is generally termed as a Special kind of Variable because it is almost declared as a variable but with *(dereferencing operator). Before we start there are two important operators which we will use in pointers i.e. * Operator also termed as the dereferencing operator used to declare pointer variable and access the value stored in the address. & operator termed as address operator used to returns the address of a variable or to access the address of a variable to a pointer. Declaring a pointer: var pointer_name *Data_Type Example: Below is a pointer of type string which can store only the memory addresses of string variables. var s *string Initialization of Pointer: To do this you need to initialize a pointer with the memory address of another variable using the address operator as shown in the below example: // normal variable declaration var a = 45 // Initialization of pointer s with // memory address of variable a var s *int = &a Example: Go // Golang program to demonstrate the declaration// and initialization of pointerspackage main import "fmt" func main() { // taking a normal variable var x int = 5748 // declaration of pointer var p *int // initialization of pointer p = &x // displaying the result fmt.Println("Value stored in x = ", x) fmt.Println("Address of x = ", &x) fmt.Println("Value stored in variable p = ", p)} Output: Value stored in x = 5748 Address of x = 0x414020 Value stored in variable p = 0x414020 1. The default value or zero-value of a pointer is always nil. Or you can say that an uninitialized pointer will always have a nil value. Example: Go // Golang program to demonstrate// the nil value of the pointerpackage main import "fmt" func main() { // taking a pointer var s *int // displaying the result fmt.Println("s = ", s)} Output: s = <nil> 2. Declaration and initialization of the pointers can be done into a single line. Example: var s *int = &a 3. If you are specifying the data type along with the pointer declaration then the pointer will be able to handle the memory address of that specified data type variable. For example, if you taking a pointer of string type then the address of the variable that you will give to a pointer will be only of string data type variable, not any other type. 4. To overcome the above mention problem you can use the Type Inference concept of the var keyword. There is no need to specify the data type during the declaration. The type of a pointer variable can also be determined by the compiler like a normal variable. Here we will not use the * operator. It will internally determine by the compiler as we are initializing the variable with the address of another variable. Example: Go // Golang program to demonstrate// the use of type inference in// Pointer variablespackage main import "fmt" func main() { // using var keyword // we are not defining // any type with variable var y = 458 // taking a pointer variable using // var keyword without specifying // the type var p = &y fmt.Println("Value stored in y = ", y) fmt.Println("Address of y = ", &y) fmt.Println("Value stored in pointer variable p = ", p)} Output: Value stored in y = 458 Address of y = 0x414020 Value stored in pointer variable p = 0x414020 5. You can also use the shorthand (:=) syntax to declare and initialize the pointer variables. The compiler will internally determine the variable is a pointer variable if we are passing the address of the variable using &(address) operator to it. Example: Go // Golang program to demonstrate// the use of shorthand syntax in// Pointer variablespackage main import "fmt" func main() { // using := operator to declare // and initialize the variable y := 458 // taking a pointer variable using // := by assigning it with the // address of variable y p := &y fmt.Println("Value stored in y = ", y) fmt.Println("Address of y = ", &y) fmt.Println("Value stored in pointer variable p = ", p)} Output: Value stored in y = 458 Address of y = 0x414020 Value stored in pointer variable p = 0x414020 As we know that * operator is also termed as the dereferencing operator. It is not only used to declare the pointer variable but also used to access the value stored in the variable which the pointer points to which is generally termed as indirecting or dereferencing. * operator is also termed as the value at the address of. Let’s take an example to get a better understandability of this concept: Example: Go // Golang program to illustrate the// concept of dereferencing a pointerpackage main import "fmt" func main() { // using var keyword // we are not defining // any type with variable var y = 458 // taking a pointer variable using // var keyword without specifying // the type var p = &y fmt.Println("Value stored in y = ", y) fmt.Println("Address of y = ", &y) fmt.Println("Value stored in pointer variable p = ", p) // this is dereferencing a pointer // using * operator before a pointer // variable to access the value stored // at the variable at which it is pointing fmt.Println("Value stored in y(*p) = ", *p) } Output: Value stored in y = 458 Address of y = 0x414020 Value stored in pointer variable p = 0x414020 Value stored in y(*p) = 458 You can also change the value of the pointer or at the memory location instead of assigning a new value to the variable. Example: Go // Golang program to illustrate the// above mentioned conceptpackage main import "fmt" func main() { // using var keyword // we are not defining // any type with variable var y = 458 // taking a pointer variable using // var keyword without specifying // the type var p = &y fmt.Println("Value stored in y before changing = ", y) fmt.Println("Address of y = ", &y) fmt.Println("Value stored in pointer variable p = ", p) // this is dereferencing a pointer // using * operator before a pointer // variable to access the value stored // at the variable at which it is pointing fmt.Println("Value stored in y(*p) Before Changing = ", *p) // changing the value of y by assigning // the new value to the pointer *p = 500 fmt.Println("Value stored in y(*p) after Changing = ",y) } Output: Value stored in y before changing = 458 Address of y = 0x414020 Value stored in pointer variable p = 0x414020 Value stored in y(*p) Before Changing = 458 Value stored in y(*p) after Changing = 500 sagartomar9927 YashPathak Golang Golang-Pointers Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to concatenate two strings in Golang time.Sleep() Function in Golang With Examples strings.Contains Function in Golang with Examples strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples Golang Maps Time Formatting in Golang Interfaces in Golang Different Ways to Find the Type of Variable in Golang How to convert a string in lower case in Golang?
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Aug, 2021" }, { "code": null, "e": 417, "s": 53, "text": "Pointers in Go programming language or Golang is a variable that is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like 0xFFAAF etc.)." }, { "code": null, "e": 453, "s": 417, "text": "What is the need for the pointers? " }, { "code": null, "e": 1024, "s": 453, "text": "To understand this need, first, we have to understand the concept of variables. Variables are the names given to a memory location where the actual data is stored. To access the stored data we need the address of that particular memory location. To remember all the memory addresses(Hexadecimal Format) manually is an overhead that’s why we use variables to store data and variables can be accessed just by using their name. Golang also allows saving a hexadecimal number into a variable using the literal expression i.e. number starting from 0x is a hexadecimal number." }, { "code": null, "e": 1526, "s": 1024, "text": "Example: In the below program, we are storing the hexadecimal number into a variable. But you can see that the type of values is int and saved as the decimal or you can say the decimal value of type int is storing. But the main point to explain this example is that we are storing a hexadecimal value(consider it a memory address) but it is not a pointer as it is not pointing to any other memory location of another variable. It is just a user-defined variable. So this arises the need for pointers. " }, { "code": null, "e": 1529, "s": 1526, "text": "Go" }, { "code": null, "e": 1538, "s": 1529, "text": "Chapters" }, { "code": null, "e": 1565, "s": 1538, "text": "descriptions off, selected" }, { "code": null, "e": 1615, "s": 1565, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1638, "s": 1615, "text": "captions off, selected" }, { "code": null, "e": 1646, "s": 1638, "text": "English" }, { "code": null, "e": 1664, "s": 1646, "text": "default, selected" }, { "code": null, "e": 1688, "s": 1664, "text": "This is a modal window." }, { "code": null, "e": 1757, "s": 1688, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1779, "s": 1757, "text": "End of dialog window." }, { "code": "// Golang program to demonstrate the variables// storing the hexadecimal valuespackage main import \"fmt\" func main() { // storing the hexadecimal // values in variables x := 0xFF y := 0x9C // Displaying the values fmt.Printf(\"Type of variable x is %T\\n\", x) fmt.Printf(\"Value of x in hexadecimal is %X\\n\", x) fmt.Printf(\"Value of x in decimal is %v\\n\", x) fmt.Printf(\"Type of variable y is %T\\n\", y) fmt.Printf(\"Value of y in hexadecimal is %X\\n\", y) fmt.Printf(\"Value of y in decimal is %v\\n\", y) }", "e": 2330, "s": 1779, "text": null }, { "code": null, "e": 2340, "s": 2330, "text": "Output: " }, { "code": null, "e": 2514, "s": 2340, "text": "Type of variable x is int\nValue of x in hexadecimal is FF\nValue of x in decimal is 255\nType of variable y is int\nValue of y in hexadecimal is 9C\nValue of y in decimal is 156" }, { "code": null, "e": 2875, "s": 2514, "text": "A pointer is a special kind of variable that is not only used to store the memory addresses of other variables but also points where the memory is located and provides ways to find out the value stored at that memory location. It is generally termed as a Special kind of Variable because it is almost declared as a variable but with *(dereferencing operator). " }, { "code": null, "e": 2961, "s": 2875, "text": "Before we start there are two important operators which we will use in pointers i.e. " }, { "code": null, "e": 3091, "s": 2961, "text": "* Operator also termed as the dereferencing operator used to declare pointer variable and access the value stored in the address." }, { "code": null, "e": 3224, "s": 3091, "text": "& operator termed as address operator used to returns the address of a variable or to access the address of a variable to a pointer." }, { "code": null, "e": 3245, "s": 3224, "text": "Declaring a pointer:" }, { "code": null, "e": 3273, "s": 3245, "text": "var pointer_name *Data_Type" }, { "code": null, "e": 3380, "s": 3273, "text": "Example: Below is a pointer of type string which can store only the memory addresses of string variables. " }, { "code": null, "e": 3394, "s": 3380, "text": "var s *string" }, { "code": null, "e": 3568, "s": 3394, "text": "Initialization of Pointer: To do this you need to initialize a pointer with the memory address of another variable using the address operator as shown in the below example: " }, { "code": null, "e": 3696, "s": 3568, "text": "// normal variable declaration\nvar a = 45\n\n// Initialization of pointer s with \n// memory address of variable a\nvar s *int = &a" }, { "code": null, "e": 3705, "s": 3696, "text": "Example:" }, { "code": null, "e": 3708, "s": 3705, "text": "Go" }, { "code": "// Golang program to demonstrate the declaration// and initialization of pointerspackage main import \"fmt\" func main() { // taking a normal variable var x int = 5748 // declaration of pointer var p *int // initialization of pointer p = &x // displaying the result fmt.Println(\"Value stored in x = \", x) fmt.Println(\"Address of x = \", &x) fmt.Println(\"Value stored in variable p = \", p)}", "e": 4141, "s": 3708, "text": null }, { "code": null, "e": 4151, "s": 4141, "text": "Output: " }, { "code": null, "e": 4241, "s": 4151, "text": "Value stored in x = 5748\nAddress of x = 0x414020\nValue stored in variable p = 0x414020" }, { "code": null, "e": 4379, "s": 4241, "text": "1. The default value or zero-value of a pointer is always nil. Or you can say that an uninitialized pointer will always have a nil value." }, { "code": null, "e": 4388, "s": 4379, "text": "Example:" }, { "code": null, "e": 4391, "s": 4388, "text": "Go" }, { "code": "// Golang program to demonstrate// the nil value of the pointerpackage main import \"fmt\" func main() { // taking a pointer var s *int // displaying the result fmt.Println(\"s = \", s)}", "e": 4596, "s": 4391, "text": null }, { "code": null, "e": 4606, "s": 4596, "text": "Output: " }, { "code": null, "e": 4617, "s": 4606, "text": "s = <nil>" }, { "code": null, "e": 4699, "s": 4617, "text": "2. Declaration and initialization of the pointers can be done into a single line." }, { "code": null, "e": 4709, "s": 4699, "text": "Example: " }, { "code": null, "e": 4725, "s": 4709, "text": "var s *int = &a" }, { "code": null, "e": 5076, "s": 4725, "text": "3. If you are specifying the data type along with the pointer declaration then the pointer will be able to handle the memory address of that specified data type variable. For example, if you taking a pointer of string type then the address of the variable that you will give to a pointer will be only of string data type variable, not any other type." }, { "code": null, "e": 5492, "s": 5076, "text": "4. To overcome the above mention problem you can use the Type Inference concept of the var keyword. There is no need to specify the data type during the declaration. The type of a pointer variable can also be determined by the compiler like a normal variable. Here we will not use the * operator. It will internally determine by the compiler as we are initializing the variable with the address of another variable." }, { "code": null, "e": 5501, "s": 5492, "text": "Example:" }, { "code": null, "e": 5504, "s": 5501, "text": "Go" }, { "code": "// Golang program to demonstrate// the use of type inference in// Pointer variablespackage main import \"fmt\" func main() { // using var keyword // we are not defining // any type with variable var y = 458 // taking a pointer variable using // var keyword without specifying // the type var p = &y fmt.Println(\"Value stored in y = \", y) fmt.Println(\"Address of y = \", &y) fmt.Println(\"Value stored in pointer variable p = \", p)}", "e": 5972, "s": 5504, "text": null }, { "code": null, "e": 5982, "s": 5972, "text": "Output: " }, { "code": null, "e": 6079, "s": 5982, "text": "Value stored in y = 458\nAddress of y = 0x414020\nValue stored in pointer variable p = 0x414020" }, { "code": null, "e": 6327, "s": 6079, "text": "5. You can also use the shorthand (:=) syntax to declare and initialize the pointer variables. The compiler will internally determine the variable is a pointer variable if we are passing the address of the variable using &(address) operator to it." }, { "code": null, "e": 6336, "s": 6327, "text": "Example:" }, { "code": null, "e": 6339, "s": 6336, "text": "Go" }, { "code": "// Golang program to demonstrate// the use of shorthand syntax in// Pointer variablespackage main import \"fmt\" func main() { // using := operator to declare // and initialize the variable y := 458 // taking a pointer variable using // := by assigning it with the // address of variable y p := &y fmt.Println(\"Value stored in y = \", y) fmt.Println(\"Address of y = \", &y) fmt.Println(\"Value stored in pointer variable p = \", p)}", "e": 6803, "s": 6339, "text": null }, { "code": null, "e": 6811, "s": 6803, "text": "Output:" }, { "code": null, "e": 6908, "s": 6811, "text": "Value stored in y = 458\nAddress of y = 0x414020\nValue stored in pointer variable p = 0x414020" }, { "code": null, "e": 7308, "s": 6908, "text": "As we know that * operator is also termed as the dereferencing operator. It is not only used to declare the pointer variable but also used to access the value stored in the variable which the pointer points to which is generally termed as indirecting or dereferencing. * operator is also termed as the value at the address of. Let’s take an example to get a better understandability of this concept:" }, { "code": null, "e": 7318, "s": 7308, "text": "Example: " }, { "code": null, "e": 7321, "s": 7318, "text": "Go" }, { "code": "// Golang program to illustrate the// concept of dereferencing a pointerpackage main import \"fmt\" func main() { // using var keyword // we are not defining // any type with variable var y = 458 // taking a pointer variable using // var keyword without specifying // the type var p = &y fmt.Println(\"Value stored in y = \", y) fmt.Println(\"Address of y = \", &y) fmt.Println(\"Value stored in pointer variable p = \", p) // this is dereferencing a pointer // using * operator before a pointer // variable to access the value stored // at the variable at which it is pointing fmt.Println(\"Value stored in y(*p) = \", *p) }", "e": 7998, "s": 7321, "text": null }, { "code": null, "e": 8007, "s": 7998, "text": "Output: " }, { "code": null, "e": 8133, "s": 8007, "text": "Value stored in y = 458\nAddress of y = 0x414020\nValue stored in pointer variable p = 0x414020\nValue stored in y(*p) = 458" }, { "code": null, "e": 8254, "s": 8133, "text": "You can also change the value of the pointer or at the memory location instead of assigning a new value to the variable." }, { "code": null, "e": 8264, "s": 8254, "text": "Example: " }, { "code": null, "e": 8267, "s": 8264, "text": "Go" }, { "code": "// Golang program to illustrate the// above mentioned conceptpackage main import \"fmt\" func main() { // using var keyword // we are not defining // any type with variable var y = 458 // taking a pointer variable using // var keyword without specifying // the type var p = &y fmt.Println(\"Value stored in y before changing = \", y) fmt.Println(\"Address of y = \", &y) fmt.Println(\"Value stored in pointer variable p = \", p) // this is dereferencing a pointer // using * operator before a pointer // variable to access the value stored // at the variable at which it is pointing fmt.Println(\"Value stored in y(*p) Before Changing = \", *p) // changing the value of y by assigning // the new value to the pointer *p = 500 fmt.Println(\"Value stored in y(*p) after Changing = \",y) }", "e": 9118, "s": 8267, "text": null }, { "code": null, "e": 9127, "s": 9118, "text": "Output: " }, { "code": null, "e": 9329, "s": 9127, "text": "Value stored in y before changing = 458\nAddress of y = 0x414020\nValue stored in pointer variable p = 0x414020\nValue stored in y(*p) Before Changing = 458\nValue stored in y(*p) after Changing = 500" }, { "code": null, "e": 9344, "s": 9329, "text": "sagartomar9927" }, { "code": null, "e": 9355, "s": 9344, "text": "YashPathak" }, { "code": null, "e": 9362, "s": 9355, "text": "Golang" }, { "code": null, "e": 9378, "s": 9362, "text": "Golang-Pointers" }, { "code": null, "e": 9390, "s": 9378, "text": "Go Language" }, { "code": null, "e": 9488, "s": 9390, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9540, "s": 9488, "text": "Different ways to concatenate two strings in Golang" }, { "code": null, "e": 9586, "s": 9540, "text": "time.Sleep() Function in Golang With Examples" }, { "code": null, "e": 9636, "s": 9586, "text": "strings.Contains Function in Golang with Examples" }, { "code": null, "e": 9687, "s": 9636, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 9734, "s": 9687, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 9746, "s": 9734, "text": "Golang Maps" }, { "code": null, "e": 9772, "s": 9746, "text": "Time Formatting in Golang" }, { "code": null, "e": 9793, "s": 9772, "text": "Interfaces in Golang" }, { "code": null, "e": 9847, "s": 9793, "text": "Different Ways to Find the Type of Variable in Golang" } ]
exportfs - Unix, Linux Command
Normally this xtab file is initialized with the list of all file systems named in /etc/exports by invoking exportfs -a. However, administrators can choose to add and delete individual file systems without modifying /etc/exports using exportfs. exportfs and it’s partner program mountd work in one of two modes, a legacy mode which applies to 2.4 and earlier versions of the Linux kernel, and a new mode which applies to 2.6 and later versions providing the nfsd virtual filesystem has been mounted at /proc/fs/nfsd or /proc/fs/nfs. If this filesystem is not mounted in 2.6, the legacy mode is used. In the new mode, exportfs does not give any information to the kernel but only provides it to mountd through the /var/lib/nfs/xtab file. mountd will listen to requests from the kernel and will provide information as needed. In the legacy mode, any export requests which identify a specific host (rather than a subnet or netgroup etc) are entered directly into the kernel’s export table as well as being written to /var/lib/nfs/xtab. Further, any mount points listed in /var/lib/nfs/rmtab which match a non host-specific export request will cause an appropriate export entry for the host given in rmtab to be entered into the kernel’s export table. The host:/path argument specifies the directory to export along with the host or hosts to export it to. All formats described in exports(5) are supported; to export a directory to the world, simply specify :/path. The export options for a particular host/directory pair derive from several sources. There is a set of default options which can be overridden by entries in /etc/exports (unless the -i option is given). In addition, the administrator may overide any options from these sources using the -o argument which takes a comma-separated list of options in the same fashion as one would specify them in exports(5) . Thus, exportfs can also be used to modify the export options of an already exported directory. Modifications of the kernel export table used by nfsd(8) take place immediately after parsing the command line and updating the xtab file. The default export options are sync,ro,root_squash,wdelay. To remove individial export entries, one can specify a host:/path pair. This deletes the specified entry from xtab and removes the corresponding kernel entry (if any). # exportfs -a To export the /usr/tmp directory to host django, allowing asynchronous writes, one would do this: # exportfs -o async django:/usr/tmp When unexporting a network or domain entry, any current exports to members of this group will be checked against the remaining valid exports and if they themselves are nolonger valid they will be removed.
[ { "code": null, "e": 10833, "s": 10711, "text": "\nNormally this\nxtab file is initialized with the list of all file systems named in\n/etc/exports by invoking\nexportfs -a. " }, { "code": null, "e": 10959, "s": 10833, "text": "\nHowever, administrators can choose to add and delete individual file systems\nwithout modifying\n/etc/exports using\nexportfs. " }, { "code": null, "e": 11316, "s": 10959, "text": "\nexportfs and it’s partner program\nmountd work in one of two modes, a legacy mode which applies to 2.4 and\nearlier versions of the Linux kernel, and a new mode which applies to\n2.6 and later versions providing the\nnfsd virtual filesystem has been mounted at\n/proc/fs/nfsd or\n/proc/fs/nfs. If this filesystem is not mounted in 2.6, the legacy mode is used.\n" }, { "code": null, "e": 11542, "s": 11316, "text": "\nIn the new mode,\nexportfs does not give any information to the kernel but only provides it to\nmountd through the\n/var/lib/nfs/xtab file.\nmountd will listen to requests from the kernel and will provide information\nas needed.\n" }, { "code": null, "e": 11968, "s": 11542, "text": "\nIn the legacy mode,\nany export requests which identify a specific host (rather than a\nsubnet or netgroup etc) are entered directly into the kernel’s export\ntable as well as being written to\n/var/lib/nfs/xtab. Further, any mount points listed in\n/var/lib/nfs/rmtab which match a non host-specific export request will cause an\nappropriate export entry for the host given in\nrmtab to be entered\ninto the kernel’s export table.\n" }, { "code": null, "e": 12184, "s": 11968, "text": "\nThe\nhost:/path argument specifies the directory to export along with the host or hosts to\nexport it to. All formats described in\nexports(5) are supported; to export a directory to the world, simply specify\n:/path. " }, { "code": null, "e": 12689, "s": 12184, "text": "\nThe export options for a particular host/directory pair derive from\nseveral sources. There is a set of default options which can be overridden by\nentries in\n/etc/exports (unless the\n-i option is given).\nIn addition, the administrator may overide any options from these sources\nusing the\n-o argument which takes a comma-separated list of options in the same fashion\nas one would specify them in\nexports(5) .\nThus,\nexportfs can also be used to modify the export options of an already exported\ndirectory.\n" }, { "code": null, "e": 12830, "s": 12689, "text": "\nModifications of the kernel export table used by\nnfsd(8) take place immediately after parsing the command line and updating the\nxtab file.\n" }, { "code": null, "e": 12891, "s": 12830, "text": "\nThe default export options are\nsync,ro,root_squash,wdelay. " }, { "code": null, "e": 13061, "s": 12891, "text": "\nTo remove individial export entries, one can specify a\nhost:/path pair. This deletes the specified entry from\nxtab and removes the corresponding kernel entry (if any).\n" }, { "code": null, "e": 13081, "s": 13065, "text": "# exportfs -a \n" }, { "code": null, "e": 13181, "s": 13081, "text": "\nTo export the\n/usr/tmp directory to host\ndjango, allowing asynchronous writes, one would do this:\n" }, { "code": null, "e": 13221, "s": 13183, "text": "# exportfs -o async django:/usr/tmp \n" } ]
Flutter – GridView
24 Nov, 2020 Flutter GridView is a widget that is similar to a 2-D Array in any programming language. As the name suggests, a GridView Widget is used when we have to display something on a Grid. We can display images, text, icons, etc on GridView. We can implement GridView in various ways in Flutter : GridView.count() GridView.builder() GridView.custom() GridView.extent() GridView( {Key key, Axis scrollDirection: Axis.vertical, bool reverse: false, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap: false, EdgeInsetsGeometry padding, @required SliverGridDelegate gridDelegate, bool addAutomaticKeepAlives: true, bool addRepaintBoundaries: true, bool addSemanticIndexes: true, double cacheExtent, List<Widget> children: const <Widget>[], int semanticChildCount, DragStartBehavior dragStartBehavior: DragStartBehavior.start, Clip clipBehavior: Clip.hardEdge, ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual, String restorationId} ) GridView.builder( {Key key, Axis scrollDirection: Axis.vertical, bool reverse: false, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap: false, EdgeInsetsGeometry padding, @required SliverGridDelegate gridDelegate, @required IndexedWidgetBuilder itemBuilder, int itemCount, bool addAutomaticKeepAlives: true, bool addRepaintBoundaries: true, bool addSemanticIndexes: true, double cacheExtent, int semanticChildCount, DragStartBehavior dragStartBehavior: DragStartBehavior.start, ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual, String restorationId, Clip clipBehavior: Clip.hardEdge} ) GridView.count( {Key key, Axis scrollDirection: Axis.vertical, bool reverse: false, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap: false, EdgeInsetsGeometry padding, @required int crossAxisCount, double mainAxisSpacing: 0.0, double crossAxisSpacing: 0.0, double childAspectRatio: 1.0, bool addAutomaticKeepAlives: true, bool addRepaintBoundaries: true, bool addSemanticIndexes: true, double cacheExtent, List<Widget> children: const <Widget>[], int semanticChildCount, DragStartBehavior dragStartBehavior: DragStartBehavior.start, ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual, String restorationId, Clip clipBehavior: Clip.hardEdge} ) const GridView.custom( {Key key, Axis scrollDirection: Axis.vertical, bool reverse: false, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap: false, EdgeInsetsGeometry padding, @required SliverGridDelegate gridDelegate, @required SliverChildDelegate childrenDelegate, double cacheExtent, int semanticChildCount, DragStartBehavior dragStartBehavior: DragStartBehavior.start, ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual, String restorationId, Clip clipBehavior: Clip.hardEdge} ) GridView.extent( {Key key, Axis scrollDirection: Axis.vertical, bool reverse: false, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap: false, EdgeInsetsGeometry padding, @required double maxCrossAxisExtent, double mainAxisSpacing: 0.0, double crossAxisSpacing: 0.0, double childAspectRatio: 1.0, bool addAutomaticKeepAlives: true, bool addRepaintBoundaries: true, bool addSemanticIndexes: true, double cacheExtent, List<Widget> children: const <Widget>[], int semanticChildCount, DragStartBehavior dragStartBehavior: DragStartBehavior.start, ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual, String restorationId, Clip clipBehavior: Clip.hardEdge} ) anchor: This property takes in a double value as the object to control the zero scroll effect. childrenDelegate: sliverChildDelegate is the object of this property. It provides a delegate that serves the children for the GridView. clipBehaviour: This property takes Clip enum as the object to decide whether the content in the GridView will be clipped or not. controller: This property holds ScrollController class as the object to control the position of the scroll view. dragStartBehaviour: This property takes DragStartBehavior enum as the object. It controls the way the drag behaviour works. gridDelegate: SliverGridDelegate class is the object to this property. It is responsible for the delegate that handles the layout of the children widget in the GridView. GridView.count() is one which is used frequently and it is used when we already know the size of Grids. Whenever we have to implement GridView dynamically, we use GridView.builder(). Both are just like a normal array and dynamic array. In Flutter, the two GridView is mostly used. GridView.count() is used with some named parameters. The properties that we can use with GridView.count() are: crossAxisCount: It defines the number of columns in GridView. crossAxisSpacing: It defines the number of pixels between each child listed along the cross axis. mainAxisSpacing: It defines the number of pixels between each child listed along the main axis. padding(EdgeInsetsGeometry): It defines the amount of space to surround the whole list of widgets. primary: If true, it’s ‘Scroll Controller’ is obtained implicitly by the framework. scrollDirection: It defines the direction in which the items on GridView will move, by default it is vertical. reverse: If it is set to true, it simply reverses the list of widgets in opposite direction along the main axis. physics: It determines how the list of widgets behaves when the user reaches the end or the start of the widget while scrolling. shrinkWrap: By default, it values is false then the scrollable list takes as much as space for scrolling in scroll direction which is not good because it takes memory that is wastage of memory and performance of app reduces and might give some error, so to avoid leakage of memory while scrolling, we wrap our children widgets using shrinkWrap by setting shrinkWrap to true and then scrollable list will be as big as it’s children widgets will allow. Dart import 'package:flutter/material.dart'; void main() { runApp(GeeksForGeeks());} class GeeksForGeeks extends StatelessWidget { // This widget is the root of your application @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( backgroundColor: Colors.black, appBar: AppBar( backgroundColor: Colors.blueGrey[900], title: Center( child: Text( 'Flutter GridView Demo', style: TextStyle( color: Colors.blueAccent, fontWeight: FontWeight.bold, fontSize: 30.0, ), ), ), ), body: GridView.count( crossAxisCount: 2, crossAxisSpacing: 10.0, mainAxisSpacing: 10.0, shrinkWrap: true, children: List.generate(20, (index) { return Padding( padding: const EdgeInsets.all(10.0), child: Container( decoration: BoxDecoration( image: DecorationImage( image: NetworkImage('img.png'), fit: BoxFit.cover, ), borderRadius: BorderRadius.all(Radius.circular(20.0),), ), ), ); },), ), ), ); }} Output: Flutter GridView Demo ankit_kumar_ Flutter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Nov, 2020" }, { "code": null, "e": 344, "s": 54, "text": "Flutter GridView is a widget that is similar to a 2-D Array in any programming language. As the name suggests, a GridView Widget is used when we have to display something on a Grid. We can display images, text, icons, etc on GridView. We can implement GridView in various ways in Flutter :" }, { "code": null, "e": 361, "s": 344, "text": "GridView.count()" }, { "code": null, "e": 380, "s": 361, "text": "GridView.builder()" }, { "code": null, "e": 398, "s": 380, "text": "GridView.custom()" }, { "code": null, "e": 416, "s": 398, "text": "GridView.extent()" }, { "code": null, "e": 1063, "s": 416, "text": "GridView(\n{Key key,\nAxis scrollDirection: Axis.vertical,\nbool reverse: false,\nScrollController controller,\nbool primary,\nScrollPhysics physics,\nbool shrinkWrap: false,\nEdgeInsetsGeometry padding,\n@required SliverGridDelegate gridDelegate,\nbool addAutomaticKeepAlives: true,\nbool addRepaintBoundaries: true,\nbool addSemanticIndexes: true,\ndouble cacheExtent,\nList<Widget> children: const <Widget>[],\nint semanticChildCount,\nDragStartBehavior dragStartBehavior: DragStartBehavior.start,\nClip clipBehavior: Clip.hardEdge,\nScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,\nString restorationId}\n)\n\n\n" }, { "code": null, "e": 1736, "s": 1063, "text": "GridView.builder(\n{Key key,\nAxis scrollDirection: Axis.vertical,\nbool reverse: false,\nScrollController controller,\nbool primary,\nScrollPhysics physics,\nbool shrinkWrap: false,\nEdgeInsetsGeometry padding,\n@required SliverGridDelegate gridDelegate,\n@required IndexedWidgetBuilder itemBuilder,\nint itemCount,\nbool addAutomaticKeepAlives: true,\nbool addRepaintBoundaries: true,\nbool addSemanticIndexes: true,\ndouble cacheExtent,\nint semanticChildCount,\nDragStartBehavior dragStartBehavior: DragStartBehavior.start,\nScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,\nString restorationId,\nClip clipBehavior: Clip.hardEdge}\n)\n\n\n" }, { "code": null, "e": 2465, "s": 1736, "text": "GridView.count(\n{Key key,\nAxis scrollDirection: Axis.vertical,\nbool reverse: false,\nScrollController controller,\nbool primary,\nScrollPhysics physics,\nbool shrinkWrap: false,\nEdgeInsetsGeometry padding,\n@required int crossAxisCount,\ndouble mainAxisSpacing: 0.0,\ndouble crossAxisSpacing: 0.0,\ndouble childAspectRatio: 1.0,\nbool addAutomaticKeepAlives: true,\nbool addRepaintBoundaries: true,\nbool addSemanticIndexes: true,\ndouble cacheExtent,\nList<Widget> children: const <Widget>[],\nint semanticChildCount,\nDragStartBehavior dragStartBehavior: DragStartBehavior.start,\nScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,\nString restorationId,\nClip clipBehavior: Clip.hardEdge}\n)\n\n\n" }, { "code": null, "e": 3033, "s": 2465, "text": "const GridView.custom(\n{Key key,\nAxis scrollDirection: Axis.vertical,\nbool reverse: false,\nScrollController controller,\nbool primary,\nScrollPhysics physics,\nbool shrinkWrap: false,\nEdgeInsetsGeometry padding,\n@required SliverGridDelegate gridDelegate,\n@required SliverChildDelegate childrenDelegate,\ndouble cacheExtent,\nint semanticChildCount,\nDragStartBehavior dragStartBehavior: DragStartBehavior.start,\nScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,\nString restorationId,\nClip clipBehavior: Clip.hardEdge}\n)\n\n\n" }, { "code": null, "e": 3770, "s": 3033, "text": "GridView.extent(\n{Key key,\nAxis scrollDirection: Axis.vertical,\nbool reverse: false,\nScrollController controller,\nbool primary,\nScrollPhysics physics,\nbool shrinkWrap: false,\nEdgeInsetsGeometry padding,\n@required double maxCrossAxisExtent,\ndouble mainAxisSpacing: 0.0,\ndouble crossAxisSpacing: 0.0,\ndouble childAspectRatio: 1.0,\nbool addAutomaticKeepAlives: true,\nbool addRepaintBoundaries: true,\nbool addSemanticIndexes: true,\ndouble cacheExtent,\nList<Widget> children: const <Widget>[],\nint semanticChildCount,\nDragStartBehavior dragStartBehavior: DragStartBehavior.start,\nScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,\nString restorationId,\nClip clipBehavior: Clip.hardEdge}\n)\n\n\n" }, { "code": null, "e": 3865, "s": 3770, "text": "anchor: This property takes in a double value as the object to control the zero scroll effect." }, { "code": null, "e": 4001, "s": 3865, "text": "childrenDelegate: sliverChildDelegate is the object of this property. It provides a delegate that serves the children for the GridView." }, { "code": null, "e": 4130, "s": 4001, "text": "clipBehaviour: This property takes Clip enum as the object to decide whether the content in the GridView will be clipped or not." }, { "code": null, "e": 4243, "s": 4130, "text": "controller: This property holds ScrollController class as the object to control the position of the scroll view." }, { "code": null, "e": 4367, "s": 4243, "text": "dragStartBehaviour: This property takes DragStartBehavior enum as the object. It controls the way the drag behaviour works." }, { "code": null, "e": 4537, "s": 4367, "text": "gridDelegate: SliverGridDelegate class is the object to this property. It is responsible for the delegate that handles the layout of the children widget in the GridView." }, { "code": null, "e": 4818, "s": 4537, "text": "GridView.count() is one which is used frequently and it is used when we already know the size of Grids. Whenever we have to implement GridView dynamically, we use GridView.builder(). Both are just like a normal array and dynamic array. In Flutter, the two GridView is mostly used." }, { "code": null, "e": 4930, "s": 4818, "text": "GridView.count() is used with some named parameters. The properties that we can use with GridView.count() are: " }, { "code": null, "e": 4992, "s": 4930, "text": "crossAxisCount: It defines the number of columns in GridView." }, { "code": null, "e": 5090, "s": 4992, "text": "crossAxisSpacing: It defines the number of pixels between each child listed along the cross axis." }, { "code": null, "e": 5186, "s": 5090, "text": "mainAxisSpacing: It defines the number of pixels between each child listed along the main axis." }, { "code": null, "e": 5285, "s": 5186, "text": "padding(EdgeInsetsGeometry): It defines the amount of space to surround the whole list of widgets." }, { "code": null, "e": 5369, "s": 5285, "text": "primary: If true, it’s ‘Scroll Controller’ is obtained implicitly by the framework." }, { "code": null, "e": 5480, "s": 5369, "text": "scrollDirection: It defines the direction in which the items on GridView will move, by default it is vertical." }, { "code": null, "e": 5593, "s": 5480, "text": "reverse: If it is set to true, it simply reverses the list of widgets in opposite direction along the main axis." }, { "code": null, "e": 5722, "s": 5593, "text": "physics: It determines how the list of widgets behaves when the user reaches the end or the start of the widget while scrolling." }, { "code": null, "e": 6173, "s": 5722, "text": "shrinkWrap: By default, it values is false then the scrollable list takes as much as space for scrolling in scroll direction which is not good because it takes memory that is wastage of memory and performance of app reduces and might give some error, so to avoid leakage of memory while scrolling, we wrap our children widgets using shrinkWrap by setting shrinkWrap to true and then scrollable list will be as big as it’s children widgets will allow." }, { "code": null, "e": 6178, "s": 6173, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(GeeksForGeeks());} class GeeksForGeeks extends StatelessWidget { // This widget is the root of your application @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( backgroundColor: Colors.black, appBar: AppBar( backgroundColor: Colors.blueGrey[900], title: Center( child: Text( 'Flutter GridView Demo', style: TextStyle( color: Colors.blueAccent, fontWeight: FontWeight.bold, fontSize: 30.0, ), ), ), ), body: GridView.count( crossAxisCount: 2, crossAxisSpacing: 10.0, mainAxisSpacing: 10.0, shrinkWrap: true, children: List.generate(20, (index) { return Padding( padding: const EdgeInsets.all(10.0), child: Container( decoration: BoxDecoration( image: DecorationImage( image: NetworkImage('img.png'), fit: BoxFit.cover, ), borderRadius: BorderRadius.all(Radius.circular(20.0),), ), ), ); },), ), ), ); }}", "e": 7545, "s": 6178, "text": null }, { "code": null, "e": 7553, "s": 7545, "text": "Output:" }, { "code": null, "e": 7575, "s": 7553, "text": "Flutter GridView Demo" }, { "code": null, "e": 7588, "s": 7575, "text": "ankit_kumar_" }, { "code": null, "e": 7596, "s": 7588, "text": "Flutter" }, { "code": null, "e": 7613, "s": 7596, "text": "Web Technologies" } ]
SQL Query to Match City Names Ending With Vowels
23 Sep, 2021 In this article, we will learn SQL Query How to Write an SQL Query to Match City Names Ending With Vowels in the Table. and we will implement with the help of an example for better understanding, first of all, we will create a database Name of the Database will Sample. and inside the database, we will create a table name As “office”. Step 1: Create a Database For database creation, there is the query we will use in SQL Platform. this is the query. Query: Create database sample; Step 2: Use database For using the database we will use another query in SQL Platform like Mysql, oracle, etc. Query: use Sample; Step 3: Creation of table in Database For the creation of a table in a database. We need to execute a query in SQL. So that we can store Records in the table. Syntax: create table table_name( column1 type(size), column2 type(size), . columnN type(size) ); Query: CREATE TABLE office ( EMPNAME VARCHAR(25), DEPT VARCHAR(20), CONTACTNO BIGINT NOT NULL, CITY VARCHAR(15) ); Above Query will create a table in our database Sample. Here table name is office. After the creation of the table, we can Justify the view and metadata of the table with the help of the below Query. It will return Schema, column, data type, size, and constraints. Syntax: EXEC sp_help table_name Query: EXEC sp_help office; Output: EXEC sp_help table_name; Query is Similar as DESC table_name; query in another platform like Oracle, MySql, etc. Step 4: Insert Data into a table To insert data into the table there is the query we will use here in the SQL server. Query: INSERT INTO office VALUES ('VISHAL','SALES',9193458625,'GAZIABAD'), ('VIPIN','MANAGER',7352158944,'BARIELLY'), ('ROHIT','IT',7830246946,'KOLKATA'), ('RAHUL','MARKETING',9635688441,'MEERUT'), ('SANJAY','SALES',9149335694,'MORADABAD'), ('ROHAN','MANAGER',7352158944,'BENGALURU'), ('RAJESH','SALES',9193458625,'VODODARA'), ('AMAN','IT',78359941265,'RAMPUR'), ('RAKESH','MARKETING',9645956441,'BOKARO'), ('VIJAY','SALES',9147844694,'Dehli'); Step 5: View Inserted data After inserting data into the table We can justify or confirm which data we have to insert correctly or not. With the help of the below query. Query: SELECT * FROM office; Output: Step 6: Query for matching city end with vowels Query: SELECT EMPNAME,CITY FROM office WHERE CITY LIKE '%a' OR CITY LIKE '%e' OR CITY LIKE '%i' OR CITY LIKE '%o' OR CITY LIKE '%u'; Output: Picked SQL-Query sql-serevr SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL | Sub queries in From Clause SQL using Python RANK() Function in SQL Server SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates How to Write a SQL Query For a Specific Date Range and Date Time?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Sep, 2021" }, { "code": null, "e": 364, "s": 28, "text": "In this article, we will learn SQL Query How to Write an SQL Query to Match City Names Ending With Vowels in the Table. and we will implement with the help of an example for better understanding, first of all, we will create a database Name of the Database will Sample. and inside the database, we will create a table name As “office”." }, { "code": null, "e": 390, "s": 364, "text": "Step 1: Create a Database" }, { "code": null, "e": 480, "s": 390, "text": "For database creation, there is the query we will use in SQL Platform. this is the query." }, { "code": null, "e": 487, "s": 480, "text": "Query:" }, { "code": null, "e": 511, "s": 487, "text": "Create database sample;" }, { "code": null, "e": 532, "s": 511, "text": "Step 2: Use database" }, { "code": null, "e": 622, "s": 532, "text": "For using the database we will use another query in SQL Platform like Mysql, oracle, etc." }, { "code": null, "e": 629, "s": 622, "text": "Query:" }, { "code": null, "e": 641, "s": 629, "text": "use Sample;" }, { "code": null, "e": 679, "s": 641, "text": "Step 3: Creation of table in Database" }, { "code": null, "e": 802, "s": 679, "text": " For the creation of a table in a database. We need to execute a query in SQL. So that we can store Records in the table. " }, { "code": null, "e": 810, "s": 802, "text": "Syntax:" }, { "code": null, "e": 900, "s": 810, "text": "create table table_name(\ncolumn1 type(size),\ncolumn2 type(size),\n.\n\ncolumnN type(size)\n);" }, { "code": null, "e": 908, "s": 900, "text": " Query:" }, { "code": null, "e": 1017, "s": 908, "text": "CREATE TABLE office\n(\nEMPNAME VARCHAR(25),\nDEPT VARCHAR(20),\nCONTACTNO BIGINT NOT NULL,\nCITY VARCHAR(15)\n); " }, { "code": null, "e": 1282, "s": 1017, "text": "Above Query will create a table in our database Sample. Here table name is office. After the creation of the table, we can Justify the view and metadata of the table with the help of the below Query. It will return Schema, column, data type, size, and constraints." }, { "code": null, "e": 1291, "s": 1282, "text": "Syntax: " }, { "code": null, "e": 1315, "s": 1291, "text": "EXEC sp_help table_name" }, { "code": null, "e": 1322, "s": 1315, "text": "Query:" }, { "code": null, "e": 1344, "s": 1322, "text": "EXEC sp_help office; " }, { "code": null, "e": 1352, "s": 1344, "text": "Output:" }, { "code": null, "e": 1465, "s": 1352, "text": "EXEC sp_help table_name; Query is Similar as DESC table_name; query in another platform like Oracle, MySql, etc." }, { "code": null, "e": 1498, "s": 1465, "text": "Step 4: Insert Data into a table" }, { "code": null, "e": 1583, "s": 1498, "text": "To insert data into the table there is the query we will use here in the SQL server." }, { "code": null, "e": 1590, "s": 1583, "text": "Query:" }, { "code": null, "e": 2028, "s": 1590, "text": "INSERT INTO office\nVALUES ('VISHAL','SALES',9193458625,'GAZIABAD'),\n('VIPIN','MANAGER',7352158944,'BARIELLY'),\n('ROHIT','IT',7830246946,'KOLKATA'),\n('RAHUL','MARKETING',9635688441,'MEERUT'),\n('SANJAY','SALES',9149335694,'MORADABAD'),\n('ROHAN','MANAGER',7352158944,'BENGALURU'),\n('RAJESH','SALES',9193458625,'VODODARA'),\n('AMAN','IT',78359941265,'RAMPUR'),\n('RAKESH','MARKETING',9645956441,'BOKARO'),\n('VIJAY','SALES',9147844694,'Dehli');" }, { "code": null, "e": 2056, "s": 2028, "text": "Step 5: View Inserted data " }, { "code": null, "e": 2199, "s": 2056, "text": "After inserting data into the table We can justify or confirm which data we have to insert correctly or not. With the help of the below query." }, { "code": null, "e": 2206, "s": 2199, "text": "Query:" }, { "code": null, "e": 2228, "s": 2206, "text": "SELECT * FROM office;" }, { "code": null, "e": 2237, "s": 2228, "text": " Output:" }, { "code": null, "e": 2285, "s": 2237, "text": "Step 6: Query for matching city end with vowels" }, { "code": null, "e": 2292, "s": 2285, "text": "Query:" }, { "code": null, "e": 2418, "s": 2292, "text": "SELECT EMPNAME,CITY FROM office\nWHERE CITY LIKE '%a'\nOR CITY LIKE '%e'\nOR CITY LIKE '%i'\nOR CITY LIKE '%o'\nOR CITY LIKE '%u';" }, { "code": null, "e": 2426, "s": 2418, "text": "Output:" }, { "code": null, "e": 2433, "s": 2426, "text": "Picked" }, { "code": null, "e": 2443, "s": 2433, "text": "SQL-Query" }, { "code": null, "e": 2454, "s": 2443, "text": "sql-serevr" }, { "code": null, "e": 2458, "s": 2454, "text": "SQL" }, { "code": null, "e": 2462, "s": 2458, "text": "SQL" }, { "code": null, "e": 2560, "s": 2462, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2626, "s": 2560, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2650, "s": 2626, "text": "Window functions in SQL" }, { "code": null, "e": 2682, "s": 2650, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2715, "s": 2682, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 2732, "s": 2715, "text": "SQL using Python" }, { "code": null, "e": 2762, "s": 2732, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 2840, "s": 2762, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 2876, "s": 2840, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2907, "s": 2876, "text": "SQL Query to Compare Two Dates" } ]
jQuery | after() with Examples
13 Feb, 2019 The after() is an inbuilt function in jQuery which is used to insert content, specified by the parameter for the each selected element in the set of matched element.Syntax: $(selector).after(A); Parameter: It accepts a parameter “A” which is either a content or function passed to the method.Return Value: It returns the selected element with the modification. <html> <head> <meta charset="utf-8"> <style> p { background: lightgreen; display: block; width: 150px; padding: 10px; border: 2px solid green; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"> </script></head> <body> <p>I would like to say: </p> <script> $("p").after("<b><h2>Hello Geeks</h2></b>"); </script></body> </html> Output: Code #2:In the below code, function is passed to the method that will work after the selected element. <html> <head> <meta charset="utf-8"> <style> p { background: lightgreen; width: 250px; padding: 10px; border: 2px solid green; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"> </script></head> <body> <p>This is first paragraph !!!</p> <p>This is the second paragraph !!! </p> <script> $("p").after(function() { return "<div>" + "GeeksforGeeks" + "</div>"; }); </script></body> </html> Output: jQuery-HTML/CSS JavaScript JQuery 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 Difference Between PUT and PATCH Request JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to add options to a select element using jQuery? Scroll to the top of the page using JavaScript/jQuery
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Feb, 2019" }, { "code": null, "e": 201, "s": 28, "text": "The after() is an inbuilt function in jQuery which is used to insert content, specified by the parameter for the each selected element in the set of matched element.Syntax:" }, { "code": null, "e": 224, "s": 201, "text": "$(selector).after(A);\n" }, { "code": null, "e": 390, "s": 224, "text": "Parameter: It accepts a parameter “A” which is either a content or function passed to the method.Return Value: It returns the selected element with the modification." }, { "code": "<html> <head> <meta charset=\"utf-8\"> <style> p { background: lightgreen; display: block; width: 150px; padding: 10px; border: 2px solid green; } </style> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"> </script></head> <body> <p>I would like to say: </p> <script> $(\"p\").after(\"<b><h2>Hello Geeks</h2></b>\"); </script></body> </html>", "e": 835, "s": 390, "text": null }, { "code": null, "e": 843, "s": 835, "text": "Output:" }, { "code": null, "e": 946, "s": 843, "text": "Code #2:In the below code, function is passed to the method that will work after the selected element." }, { "code": "<html> <head> <meta charset=\"utf-8\"> <style> p { background: lightgreen; width: 250px; padding: 10px; border: 2px solid green; } </style> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"> </script></head> <body> <p>This is first paragraph !!!</p> <p>This is the second paragraph !!! </p> <script> $(\"p\").after(function() { return \"<div>\" + \"GeeksforGeeks\" + \"</div>\"; }); </script></body> </html>", "e": 1462, "s": 946, "text": null }, { "code": null, "e": 1470, "s": 1462, "text": "Output:" }, { "code": null, "e": 1486, "s": 1470, "text": "jQuery-HTML/CSS" }, { "code": null, "e": 1497, "s": 1486, "text": "JavaScript" }, { "code": null, "e": 1504, "s": 1497, "text": "JQuery" }, { "code": null, "e": 1602, "s": 1504, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1663, "s": 1602, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1735, "s": 1663, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1775, "s": 1735, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1828, "s": 1775, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 1869, "s": 1828, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1915, "s": 1869, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 1944, "s": 1915, "text": "Form validation using jQuery" }, { "code": null, "e": 2007, "s": 1944, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 2060, "s": 2007, "text": "How to add options to a select element using jQuery?" } ]
Matrix manipulation in Python
28 Jun, 2021 In python matrix can be implemented as 2D list or 2D Array. Forming matrix from latter, gives the additional functionalities for performing various operations in matrix. These operations and array are defines in module “numpy“. Operation on Matrix : 1. add() :- This function is used to perform element wise matrix addition. 2. subtract() :- This function is used to perform element wise matrix subtraction. 3. divide() :- This function is used to perform element wise matrix division. # Python code to demonstrate matrix operations# add(), subtract() and divide() # importing numpy for matrix operationsimport numpy # initializing matricesx = numpy.array([[1, 2], [4, 5]])y = numpy.array([[7, 8], [9, 10]]) # using add() to add matricesprint ("The element wise addition of matrix is : ")print (numpy.add(x,y)) # using subtract() to subtract matricesprint ("The element wise subtraction of matrix is : ")print (numpy.subtract(x,y)) # using divide() to divide matricesprint ("The element wise division of matrix is : ")print (numpy.divide(x,y)) Output : The element wise addition of matrix is : [[ 8 10] [13 15]] The element wise subtraction of matrix is : [[-6 -6] [-5 -5]] The element wise division of matrix is : [[ 0.14285714 0.25 ] [ 0.44444444 0.5 ]] 4. multiply() :- This function is used to perform element wise matrix multiplication. 5. dot() :- This function is used to compute the matrix multiplication, rather than element wise multiplication. # Python code to demonstrate matrix operations# multiply() and dot() # importing numpy for matrix operationsimport numpy # initializing matricesx = numpy.array([[1, 2], [4, 5]])y = numpy.array([[7, 8], [9, 10]]) # using multiply() to multiply matrices element wiseprint ("The element wise multiplication of matrix is : ")print (numpy.multiply(x,y)) # using dot() to multiply matricesprint ("The product of matrices is : ")print (numpy.dot(x,y)) Output : The element wise multiplication of matrix is : [[ 7 16] [36 50]] The product of matrices is : [[25 28] [73 82]] 6. sqrt() :- This function is used to compute the square root of each element of matrix. 7. sum(x,axis) :- This function is used to add all the elements in matrix. Optional “axis” argument computes the column sum if axis is 0 and row sum if axis is 1. 8. “T” :- This argument is used to transpose the specified matrix. # Python code to demonstrate matrix operations# sqrt(), sum() and "T" # importing numpy for matrix operationsimport numpy # initializing matricesx = numpy.array([[1, 2], [4, 5]])y = numpy.array([[7, 8], [9, 10]]) # using sqrt() to print the square root of matrixprint ("The element wise square root is : ")print (numpy.sqrt(x)) # using sum() to print summation of all elements of matrixprint ("The summation of all matrix element is : ")print (numpy.sum(y)) # using sum(axis=0) to print summation of all columns of matrixprint ("The column wise summation of all matrix is : ")print (numpy.sum(y,axis=0)) # using sum(axis=1) to print summation of all columns of matrixprint ("The row wise summation of all matrix is : ")print (numpy.sum(y,axis=1)) # using "T" to transpose the matrixprint ("The transpose of given matrix is : ")print (x.T) Output : The element wise square root is : [[ 1. 1.41421356] [ 2. 2.23606798]] The summation of all matrix element is : 34 The column wise summation of all matrix is : [16 18] The row wise summation of all matrix is : [15 19] The transpose of given matrix is : [[1 4] [2 5]] This article is contributed by Manjeet Singh 100 . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Python matrix-program Matrix Python Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 280, "s": 52, "text": "In python matrix can be implemented as 2D list or 2D Array. Forming matrix from latter, gives the additional functionalities for performing various operations in matrix. These operations and array are defines in module “numpy“." }, { "code": null, "e": 302, "s": 280, "text": "Operation on Matrix :" }, { "code": null, "e": 377, "s": 302, "text": "1. add() :- This function is used to perform element wise matrix addition." }, { "code": null, "e": 460, "s": 377, "text": "2. subtract() :- This function is used to perform element wise matrix subtraction." }, { "code": null, "e": 538, "s": 460, "text": "3. divide() :- This function is used to perform element wise matrix division." }, { "code": "# Python code to demonstrate matrix operations# add(), subtract() and divide() # importing numpy for matrix operationsimport numpy # initializing matricesx = numpy.array([[1, 2], [4, 5]])y = numpy.array([[7, 8], [9, 10]]) # using add() to add matricesprint (\"The element wise addition of matrix is : \")print (numpy.add(x,y)) # using subtract() to subtract matricesprint (\"The element wise subtraction of matrix is : \")print (numpy.subtract(x,y)) # using divide() to divide matricesprint (\"The element wise division of matrix is : \")print (numpy.divide(x,y))", "e": 1101, "s": 538, "text": null }, { "code": null, "e": 1110, "s": 1101, "text": "Output :" }, { "code": null, "e": 1333, "s": 1110, "text": "The element wise addition of matrix is : \n[[ 8 10]\n [13 15]]\nThe element wise subtraction of matrix is : \n[[-6 -6]\n [-5 -5]]\nThe element wise division of matrix is : \n[[ 0.14285714 0.25 ]\n [ 0.44444444 0.5 ]]\n" }, { "code": null, "e": 1419, "s": 1333, "text": "4. multiply() :- This function is used to perform element wise matrix multiplication." }, { "code": null, "e": 1532, "s": 1419, "text": "5. dot() :- This function is used to compute the matrix multiplication, rather than element wise multiplication." }, { "code": "# Python code to demonstrate matrix operations# multiply() and dot() # importing numpy for matrix operationsimport numpy # initializing matricesx = numpy.array([[1, 2], [4, 5]])y = numpy.array([[7, 8], [9, 10]]) # using multiply() to multiply matrices element wiseprint (\"The element wise multiplication of matrix is : \")print (numpy.multiply(x,y)) # using dot() to multiply matricesprint (\"The product of matrices is : \")print (numpy.dot(x,y))", "e": 1981, "s": 1532, "text": null }, { "code": null, "e": 1990, "s": 1981, "text": "Output :" }, { "code": null, "e": 2107, "s": 1990, "text": "The element wise multiplication of matrix is : \n[[ 7 16]\n [36 50]]\nThe product of matrices is : \n[[25 28]\n [73 82]]\n" }, { "code": null, "e": 2196, "s": 2107, "text": "6. sqrt() :- This function is used to compute the square root of each element of matrix." }, { "code": null, "e": 2359, "s": 2196, "text": "7. sum(x,axis) :- This function is used to add all the elements in matrix. Optional “axis” argument computes the column sum if axis is 0 and row sum if axis is 1." }, { "code": null, "e": 2426, "s": 2359, "text": "8. “T” :- This argument is used to transpose the specified matrix." }, { "code": "# Python code to demonstrate matrix operations# sqrt(), sum() and \"T\" # importing numpy for matrix operationsimport numpy # initializing matricesx = numpy.array([[1, 2], [4, 5]])y = numpy.array([[7, 8], [9, 10]]) # using sqrt() to print the square root of matrixprint (\"The element wise square root is : \")print (numpy.sqrt(x)) # using sum() to print summation of all elements of matrixprint (\"The summation of all matrix element is : \")print (numpy.sum(y)) # using sum(axis=0) to print summation of all columns of matrixprint (\"The column wise summation of all matrix is : \")print (numpy.sum(y,axis=0)) # using sum(axis=1) to print summation of all columns of matrixprint (\"The row wise summation of all matrix is : \")print (numpy.sum(y,axis=1)) # using \"T\" to transpose the matrixprint (\"The transpose of given matrix is : \")print (x.T)", "e": 3274, "s": 2426, "text": null }, { "code": null, "e": 3283, "s": 3274, "text": "Output :" }, { "code": null, "e": 3577, "s": 3283, "text": "The element wise square root is : \n[[ 1. 1.41421356]\n [ 2. 2.23606798]]\nThe summation of all matrix element is : \n34\nThe column wise summation of all matrix is : \n[16 18]\nThe row wise summation of all matrix is : \n[15 19]\nThe transpose of given matrix is : \n[[1 4]\n [2 5]]\n" }, { "code": null, "e": 3880, "s": 3577, "text": "This article is contributed by Manjeet Singh 100 . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 4005, "s": 3880, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4027, "s": 4005, "text": "Python matrix-program" }, { "code": null, "e": 4034, "s": 4027, "text": "Matrix" }, { "code": null, "e": 4041, "s": 4034, "text": "Python" }, { "code": null, "e": 4048, "s": 4041, "text": "Matrix" } ]
Find the closest element in Binary Search Tree | Space Efficient Method
31 Mar, 2022 Given a binary search tree and a target node K. The task is to find the node with the minimum absolute difference with given target value K.NOTE: The approach used should have constant extra space consumed O(1). No recursion or stack/queue like containers should be used. Examples: Input: k = 4 Output: 4 Input: k = 18 Output: 17 A simple solution mentioned in this post uses recursion to get the closest element to a key in Binary search tree. The method used in the above mentioned post consumes O(n) extra space due to recursion. Now we can easily modify the above mentioned approach using Morris traversal which is a space efficient approach to do inorder tree traversal without using recursion or stack/queue in constant space O(1).Morris traversal is based on Threaded Binary trees which makes use of NULL pointers in a tree to make them point to some successor or predecessor nodes. As in a binary tree with n nodes, n+1 NULL pointers waste memory.In the algorithm mentioned below we simply do inorder tree traversal and while doing inorder tree traversal using Morris Traversal we check for differences between the node’s data and the key and maintain two variables ‘diff’ and ‘closest’ which are updated when we find a closer node to the key. When we are done with the complete inorder tree traversal we have the closest node.Algorithm : 1) Initialize Current as root. 2) Initialize a variable diff as INT_MAX. 3)initialize a variable closest(pointer to node) which will be returned. 4) While current is not NULL: 4.1) If the current has no left child: a) If the absolute difference between current's data and the key is smaller than diff: 1) Set diff as the absolute difference between the current node and the key. 2) Set closest as the current node. b)Otherwise, Move to the right child of current. 4.2) Else, here we have 2 cases: a) Find the inorder predecessor of the current node. Inorder predecessor is the rightmost node in the left subtree or left child itself. b) If the right child of the inorder predecessor is NULL: 1) Set current as the right child of its inorder predecessor(Making threads between nodes). 2) Move current node to its left child. c) Else, if the threaded link between the current node and it's inorder predecessor already exists : 1) Set right pointer of the inorder predecessor node as NULL. 2) If the absolute difference between current's data and the key is smaller than diff: a) Set diff variable as the absolute difference between the current node and the key. b) Set closest as the current node. 3) Move current to its right child. 5)By the time we have traversed the whole tree, we have the closest node, so we simply return closest. Below is the implementation of above approach: C++ Java Python3 C# Javascript // CPP program to find closest value in// a Binary Search Tree.#include <iostream>#include <limits.h>using namespace std; // Tree Nodestruct Node { int data; Node *left, *right;}; // Utility function to create a new NodeNode* newNode(int data){ Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // Function to find the Node closest to the// given key in BST using Morris TraversalNode* closestNodeUsingMorrisTraversal(Node* root, int key){ int diff = INT_MAX; Node* curr = root; Node* closest; while (curr) { if (curr->left == NULL) { // updating diff if the current diff is // smaller than prev difference if (diff > abs(curr->data - key)) { diff = abs(curr->data - key); closest = curr; } curr = curr->right; } else { // finding the inorder predecessor Node* pre = curr->left; while (pre->right != NULL && pre->right != curr) pre = pre->right; if (pre->right == NULL) { pre->right = curr; curr = curr->left; } // threaded link between curr and // its predecessor already exists else { pre->right = NULL; // if a closer Node found, then update // the diff and set closest to current if (diff > abs(curr->data - key)) { diff = abs(curr->data - key); closest = curr; } // moving to the right child curr = curr->right; } } } return closest;} // Driver Codeint main(){ /* Constructed binary tree is 5 / \ 3 9 / \ / \ 1 2 8 12 */ Node* root = newNode(5); root->left = newNode(3); root->right = newNode(9); root->left->left = newNode(1); root->left->right = newNode(2); root->right->left = newNode(8); root->right->right = newNode(12); cout << closestNodeUsingMorrisTraversal(root, 10)->data; return 0;} // Java program to find closest value in// a Binary Search Tree.class GFG{ // Tree Nodestatic class Node{ int data; Node left, right;}; // Utility function to create a new Nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to find the Node closest to the// given key in BST using Morris Traversalstatic Node closestNodeUsingMorrisTraversal(Node root, int key){ int diff = Integer.MAX_VALUE; Node curr = root; Node closest = null; while (curr != null) { if (curr.left == null) { // updating diff if the current diff is // smaller than prev difference if (diff > Math.abs(curr.data - key)) { diff = Math.abs(curr.data - key); closest = curr; } curr = curr.right; } else { // finding the inorder predecessor Node pre = curr.left; while (pre.right != null && pre.right != curr) pre = pre.right; if (pre.right == null) { pre.right = curr; curr = curr.left; } // threaded link between curr and // its predecessor already exists else { pre.right = null; // if a closer Node found, then update // the diff and set closest to current if (diff > Math.abs(curr.data - key)) { diff = Math.abs(curr.data - key); closest = curr; } // moving to the right child curr = curr.right; } } } return closest;} // Driver Codepublic static void main(String[] args){ /* Constructed binary tree is 5 / \ 3 9 / \ / \ 1 2 8 12 */ Node root = newNode(5); root.left = newNode(3); root.right = newNode(9); root.left.left = newNode(1); root.left.right = newNode(2); root.right.left = newNode(8); root.right.right = newNode(12); System.out.println(closestNodeUsingMorrisTraversal(root, 10).data);}} // This code is contributed by Rajput-Ji # Python program to find closest value in# Binary search Tree _MIN = -2147483648_MAX = 2147483648 # Helper function that allocates a new# node with the given data and None left# and right pointers. class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Function to find the Node closest to the# given key in BST using Morris Traversaldef closestNodeUsingMorrisTraversal(root,key): diff = _MAX curr = root closest=0 while (curr) : if (curr.left == None) : # updating diff if the current diff is # smaller than prev difference if (diff > abs(curr.data - key)) : diff = abs(curr.data - key) closest = curr curr = curr.right else : # finding the inorder predecessor pre = curr.left while (pre.right != None and pre.right != curr): pre = pre.right if (pre.right == None): pre.right = curr curr = curr.left # threaded link between curr and # its predecessor already exists else : pre.right = None # if a closer Node found, then update # the diff and set closest to current if (diff > abs(curr.data - key)) : diff = abs(curr.data - key) closest = curr # moving to the right child curr = curr.right return closest # Driver Codeif __name__ == '__main__': """ /* Constructed binary tree is 5 / \ 3 9 / \ / \ 1 2 8 12 */ """ root = newNode(5) root.left = newNode(3) root.right = newNode(9) root.left.right = newNode(2) root.left.left = newNode(1) root.right.right = newNode(12) root.right.left = newNode(8) print(closestNodeUsingMorrisTraversal(root, 10).data) # This code is contributed# Shubham Singh(SHUBHAMSINGH10) // C# program to find closest value in// a Binary Search Tree.using System; class GFG{ // Tree Nodepublic class Node{ public int data; public Node left, right;}; // Utility function to create a new Nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to find the Node closest to the// given key in BST using Morris Traversalstatic Node closestNodeUsingMorrisTraversal(Node root, int key){ int diff = int.MaxValue; Node curr = root; Node closest = null; while (curr != null) { if (curr.left == null) { // updating diff if the current diff is // smaller than prev difference if (diff > Math.Abs(curr.data - key)) { diff = Math.Abs(curr.data - key); closest = curr; } curr = curr.right; } else { // finding the inorder predecessor Node pre = curr.left; while (pre.right != null && pre.right != curr) pre = pre.right; if (pre.right == null) { pre.right = curr; curr = curr.left; } // threaded link between curr and // its predecessor already exists else { pre.right = null; // if a closer Node found, then update // the diff and set closest to current if (diff > Math.Abs(curr.data - key)) { diff = Math.Abs(curr.data - key); closest = curr; } // moving to the right child curr = curr.right; } } } return closest;} // Driver Codepublic static void Main(String[] args){ /* Constructed binary tree is 5 / \ 3 9 / \ / \ 1 2 8 12 */ Node root = newNode(5); root.left = newNode(3); root.right = newNode(9); root.left.left = newNode(1); root.left.right = newNode(2); root.right.left = newNode(8); root.right.right = newNode(12); Console.WriteLine(closestNodeUsingMorrisTraversal(root, 10).data);}} /* This code is contributed by PrinciRaj1992 */ <script> // Javascript program to find closest value in// a Binary Search Tree. // Tree Nodeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // Utility function to create a new Nodefunction newNode(data){ var temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to find the Node closest to the// given key in BST using Morris Traversalfunction closestNodeUsingMorrisTraversal(root, key){ var diff = 1000000000; var curr = root; var closest = null; while (curr != null) { if (curr.left == null) { // updating diff if the current diff is // smaller than prev difference if (diff > Math.abs(curr.data - key)) { diff = Math.abs(curr.data - key); closest = curr; } curr = curr.right; } else { // finding the inorder predecessor var pre = curr.left; while (pre.right != null && pre.right != curr) pre = pre.right; if (pre.right == null) { pre.right = curr; curr = curr.left; } // threaded link between curr and // its predecessor already exists else { pre.right = null; // if a closer Node found, then update // the diff and set closest to current if (diff > Math.abs(curr.data - key)) { diff = Math.abs(curr.data - key); closest = curr; } // moving to the right child curr = curr.right; } } } return closest;} // Driver Code/* Constructed binary tree is 5 / \3 9/ \ / \1 2 8 12 */var root = newNode(5);root.left = newNode(3);root.right = newNode(9);root.left.left = newNode(1);root.left.right = newNode(2);root.right.left = newNode(8);root.right.right = newNode(12);document.write(closestNodeUsingMorrisTraversal(root, 10).data); // This code is contributed by itsok.</script> 9 Time Complexity: O(n) Auxiliary Space : O(1) SHUBHAMSINGH10 Rajput-Ji princiraj1992 nidhi_biet itsok surinderdawra388 morris-traversal tree-traversal Binary Search Tree Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find postorder traversal of BST from preorder traversal Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Lowest Common Ancestor in a Binary Search Tree. Optimal Binary Search Tree | DP-24 Sorted Array to Balanced BST Inorder Successor in Binary Search Tree Merge Two Balanced Binary Search Trees Convert a normal BST to Balanced BST set vs unordered_set in C++ STL Inorder predecessor and successor for a given key in BST
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Mar, 2022" }, { "code": null, "e": 327, "s": 54, "text": "Given a binary search tree and a target node K. The task is to find the node with the minimum absolute difference with given target value K.NOTE: The approach used should have constant extra space consumed O(1). No recursion or stack/queue like containers should be used. " }, { "code": null, "e": 339, "s": 327, "text": "Examples: " }, { "code": null, "e": 392, "s": 339, "text": "Input: k = 4\nOutput: 4\n\nInput: k = 18\nOutput: 17" }, { "code": null, "e": 1412, "s": 394, "text": "A simple solution mentioned in this post uses recursion to get the closest element to a key in Binary search tree. The method used in the above mentioned post consumes O(n) extra space due to recursion. Now we can easily modify the above mentioned approach using Morris traversal which is a space efficient approach to do inorder tree traversal without using recursion or stack/queue in constant space O(1).Morris traversal is based on Threaded Binary trees which makes use of NULL pointers in a tree to make them point to some successor or predecessor nodes. As in a binary tree with n nodes, n+1 NULL pointers waste memory.In the algorithm mentioned below we simply do inorder tree traversal and while doing inorder tree traversal using Morris Traversal we check for differences between the node’s data and the key and maintain two variables ‘diff’ and ‘closest’ which are updated when we find a closer node to the key. When we are done with the complete inorder tree traversal we have the closest node.Algorithm : " }, { "code": null, "e": 2923, "s": 1412, "text": "1) Initialize Current as root.\n\n2) Initialize a variable diff as INT_MAX.\n\n3)initialize a variable closest(pointer to node) which \n will be returned.\n\n4) While current is not NULL:\n\n 4.1) If the current has no left child:\n a) If the absolute difference between current's data\n and the key is smaller than diff:\n 1) Set diff as the absolute difference between the \n current node and the key.\n 2) Set closest as the current node. \n\n b)Otherwise, Move to the right child of current.\n\n 4.2) Else, here we have 2 cases:\n\n a) Find the inorder predecessor of the current node. \n Inorder predecessor is the rightmost node \n in the left subtree or left child itself.\n\n b) If the right child of the inorder predecessor is NULL:\n 1) Set current as the right child of its inorder \n predecessor(Making threads between nodes).\n 2) Move current node to its left child.\n\n c) Else, if the threaded link between the current node \n and it's inorder predecessor already exists :\n\n 1) Set right pointer of the inorder predecessor node as NULL.\n\n 2) If the absolute difference between current's data and \n the key is smaller than diff:\n a) Set diff variable as the absolute difference between \n the current node and the key.\n b) Set closest as the current node. \n\n 3) Move current to its right child.\n\n5)By the time we have traversed the whole tree, we have the \n closest node, so we simply return closest." }, { "code": null, "e": 2972, "s": 2923, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 2976, "s": 2972, "text": "C++" }, { "code": null, "e": 2981, "s": 2976, "text": "Java" }, { "code": null, "e": 2989, "s": 2981, "text": "Python3" }, { "code": null, "e": 2992, "s": 2989, "text": "C#" }, { "code": null, "e": 3003, "s": 2992, "text": "Javascript" }, { "code": "// CPP program to find closest value in// a Binary Search Tree.#include <iostream>#include <limits.h>using namespace std; // Tree Nodestruct Node { int data; Node *left, *right;}; // Utility function to create a new NodeNode* newNode(int data){ Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // Function to find the Node closest to the// given key in BST using Morris TraversalNode* closestNodeUsingMorrisTraversal(Node* root, int key){ int diff = INT_MAX; Node* curr = root; Node* closest; while (curr) { if (curr->left == NULL) { // updating diff if the current diff is // smaller than prev difference if (diff > abs(curr->data - key)) { diff = abs(curr->data - key); closest = curr; } curr = curr->right; } else { // finding the inorder predecessor Node* pre = curr->left; while (pre->right != NULL && pre->right != curr) pre = pre->right; if (pre->right == NULL) { pre->right = curr; curr = curr->left; } // threaded link between curr and // its predecessor already exists else { pre->right = NULL; // if a closer Node found, then update // the diff and set closest to current if (diff > abs(curr->data - key)) { diff = abs(curr->data - key); closest = curr; } // moving to the right child curr = curr->right; } } } return closest;} // Driver Codeint main(){ /* Constructed binary tree is 5 / \\ 3 9 / \\ / \\ 1 2 8 12 */ Node* root = newNode(5); root->left = newNode(3); root->right = newNode(9); root->left->left = newNode(1); root->left->right = newNode(2); root->right->left = newNode(8); root->right->right = newNode(12); cout << closestNodeUsingMorrisTraversal(root, 10)->data; return 0;}", "e": 5225, "s": 3003, "text": null }, { "code": "// Java program to find closest value in// a Binary Search Tree.class GFG{ // Tree Nodestatic class Node{ int data; Node left, right;}; // Utility function to create a new Nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to find the Node closest to the// given key in BST using Morris Traversalstatic Node closestNodeUsingMorrisTraversal(Node root, int key){ int diff = Integer.MAX_VALUE; Node curr = root; Node closest = null; while (curr != null) { if (curr.left == null) { // updating diff if the current diff is // smaller than prev difference if (diff > Math.abs(curr.data - key)) { diff = Math.abs(curr.data - key); closest = curr; } curr = curr.right; } else { // finding the inorder predecessor Node pre = curr.left; while (pre.right != null && pre.right != curr) pre = pre.right; if (pre.right == null) { pre.right = curr; curr = curr.left; } // threaded link between curr and // its predecessor already exists else { pre.right = null; // if a closer Node found, then update // the diff and set closest to current if (diff > Math.abs(curr.data - key)) { diff = Math.abs(curr.data - key); closest = curr; } // moving to the right child curr = curr.right; } } } return closest;} // Driver Codepublic static void main(String[] args){ /* Constructed binary tree is 5 / \\ 3 9 / \\ / \\ 1 2 8 12 */ Node root = newNode(5); root.left = newNode(3); root.right = newNode(9); root.left.left = newNode(1); root.left.right = newNode(2); root.right.left = newNode(8); root.right.right = newNode(12); System.out.println(closestNodeUsingMorrisTraversal(root, 10).data);}} // This code is contributed by Rajput-Ji", "e": 7536, "s": 5225, "text": null }, { "code": "# Python program to find closest value in# Binary search Tree _MIN = -2147483648_MAX = 2147483648 # Helper function that allocates a new# node with the given data and None left# and right pointers. class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Function to find the Node closest to the# given key in BST using Morris Traversaldef closestNodeUsingMorrisTraversal(root,key): diff = _MAX curr = root closest=0 while (curr) : if (curr.left == None) : # updating diff if the current diff is # smaller than prev difference if (diff > abs(curr.data - key)) : diff = abs(curr.data - key) closest = curr curr = curr.right else : # finding the inorder predecessor pre = curr.left while (pre.right != None and pre.right != curr): pre = pre.right if (pre.right == None): pre.right = curr curr = curr.left # threaded link between curr and # its predecessor already exists else : pre.right = None # if a closer Node found, then update # the diff and set closest to current if (diff > abs(curr.data - key)) : diff = abs(curr.data - key) closest = curr # moving to the right child curr = curr.right return closest # Driver Codeif __name__ == '__main__': \"\"\" /* Constructed binary tree is 5 / \\ 3 9 / \\ / \\ 1 2 8 12 */ \"\"\" root = newNode(5) root.left = newNode(3) root.right = newNode(9) root.left.right = newNode(2) root.left.left = newNode(1) root.right.right = newNode(12) root.right.left = newNode(8) print(closestNodeUsingMorrisTraversal(root, 10).data) # This code is contributed# Shubham Singh(SHUBHAMSINGH10)", "e": 9690, "s": 7536, "text": null }, { "code": "// C# program to find closest value in// a Binary Search Tree.using System; class GFG{ // Tree Nodepublic class Node{ public int data; public Node left, right;}; // Utility function to create a new Nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to find the Node closest to the// given key in BST using Morris Traversalstatic Node closestNodeUsingMorrisTraversal(Node root, int key){ int diff = int.MaxValue; Node curr = root; Node closest = null; while (curr != null) { if (curr.left == null) { // updating diff if the current diff is // smaller than prev difference if (diff > Math.Abs(curr.data - key)) { diff = Math.Abs(curr.data - key); closest = curr; } curr = curr.right; } else { // finding the inorder predecessor Node pre = curr.left; while (pre.right != null && pre.right != curr) pre = pre.right; if (pre.right == null) { pre.right = curr; curr = curr.left; } // threaded link between curr and // its predecessor already exists else { pre.right = null; // if a closer Node found, then update // the diff and set closest to current if (diff > Math.Abs(curr.data - key)) { diff = Math.Abs(curr.data - key); closest = curr; } // moving to the right child curr = curr.right; } } } return closest;} // Driver Codepublic static void Main(String[] args){ /* Constructed binary tree is 5 / \\ 3 9 / \\ / \\ 1 2 8 12 */ Node root = newNode(5); root.left = newNode(3); root.right = newNode(9); root.left.left = newNode(1); root.left.right = newNode(2); root.right.left = newNode(8); root.right.right = newNode(12); Console.WriteLine(closestNodeUsingMorrisTraversal(root, 10).data);}} /* This code is contributed by PrinciRaj1992 */", "e": 12032, "s": 9690, "text": null }, { "code": "<script> // Javascript program to find closest value in// a Binary Search Tree. // Tree Nodeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // Utility function to create a new Nodefunction newNode(data){ var temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Function to find the Node closest to the// given key in BST using Morris Traversalfunction closestNodeUsingMorrisTraversal(root, key){ var diff = 1000000000; var curr = root; var closest = null; while (curr != null) { if (curr.left == null) { // updating diff if the current diff is // smaller than prev difference if (diff > Math.abs(curr.data - key)) { diff = Math.abs(curr.data - key); closest = curr; } curr = curr.right; } else { // finding the inorder predecessor var pre = curr.left; while (pre.right != null && pre.right != curr) pre = pre.right; if (pre.right == null) { pre.right = curr; curr = curr.left; } // threaded link between curr and // its predecessor already exists else { pre.right = null; // if a closer Node found, then update // the diff and set closest to current if (diff > Math.abs(curr.data - key)) { diff = Math.abs(curr.data - key); closest = curr; } // moving to the right child curr = curr.right; } } } return closest;} // Driver Code/* Constructed binary tree is 5 / \\3 9/ \\ / \\1 2 8 12 */var root = newNode(5);root.left = newNode(3);root.right = newNode(9);root.left.left = newNode(1);root.left.right = newNode(2);root.right.left = newNode(8);root.right.right = newNode(12);document.write(closestNodeUsingMorrisTraversal(root, 10).data); // This code is contributed by itsok.</script>", "e": 14240, "s": 12032, "text": null }, { "code": null, "e": 14242, "s": 14240, "text": "9" }, { "code": null, "e": 14291, "s": 14244, "text": "Time Complexity: O(n) Auxiliary Space : O(1) " }, { "code": null, "e": 14306, "s": 14291, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 14316, "s": 14306, "text": "Rajput-Ji" }, { "code": null, "e": 14330, "s": 14316, "text": "princiraj1992" }, { "code": null, "e": 14341, "s": 14330, "text": "nidhi_biet" }, { "code": null, "e": 14347, "s": 14341, "text": "itsok" }, { "code": null, "e": 14364, "s": 14347, "text": "surinderdawra388" }, { "code": null, "e": 14381, "s": 14364, "text": "morris-traversal" }, { "code": null, "e": 14396, "s": 14381, "text": "tree-traversal" }, { "code": null, "e": 14415, "s": 14396, "text": "Binary Search Tree" }, { "code": null, "e": 14434, "s": 14415, "text": "Binary Search Tree" }, { "code": null, "e": 14532, "s": 14434, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14588, "s": 14532, "text": "Find postorder traversal of BST from preorder traversal" }, { "code": null, "e": 14658, "s": 14588, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 14706, "s": 14658, "text": "Lowest Common Ancestor in a Binary Search Tree." }, { "code": null, "e": 14741, "s": 14706, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 14770, "s": 14741, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 14810, "s": 14770, "text": "Inorder Successor in Binary Search Tree" }, { "code": null, "e": 14849, "s": 14810, "text": "Merge Two Balanced Binary Search Trees" }, { "code": null, "e": 14886, "s": 14849, "text": "Convert a normal BST to Balanced BST" }, { "code": null, "e": 14918, "s": 14886, "text": "set vs unordered_set in C++ STL" } ]
Various kind of Framing in Data link layer
26 Aug, 2020 Framing is function of Data Link Layer that is used to separate message from source or sender to destination or receiver or simply from all other messages to all other destinations just by adding sender address and destination address. The destination or receiver address is simply used to represent where message or packet is to go and sender or source address is simply used to help recipient to acknowledge receipt. Frames are generally data unit of data link layer that is transmitted or transferred among various network points. It includes complete and full addressing, protocols that are essential, and information under control. Physical layers only just accept and transfer stream of bits without any regard to meaning or structure. Therefore it is up to data link layer to simply develop and recognize frame boundaries. This can be achieved by attaching special types of bit patterns to start and end of the frame. If all of these bit patterns might accidentally occur in data, special care is needed to be taken to simply make sure that these bit patterns are not interpreted incorrectly or wrong as frame delimiters. Framing is simply point-to-point connection among two computers or devices that consists or includes wire in which data is transferred as stream of bits. However, all of these bits should be framed into discernible blocks of information.Methods of Framing :There are basically four methods of framing as given below – 1. Character Count 2. Flag Byte with Character Stuffing 3. Starting and Ending Flags, with Bit Stuffing 4. Encoding Violations These are explained as following below. Character Count :This method is rarely used and is generally required to count total number of characters that are present in frame. This is be done by using field in header. Character count method ensures data link layer at the receiver or destination about total number of characters that follow, and about where the frame ends.There is disadvantage also of using this method i.e., if anyhow character count is disturbed or distorted by an error occurring during transmission, then destination or receiver might lose synchronization. The destination or receiver might also be not able to locate or identify beginning of next frame.Character Stuffing :Character stuffing is also known as byte stuffing or character-oriented framing and is same as that of bit stuffing but byte stuffing actually operates on bytes whereas bit stuffing operates on bits. In byte stuffing, special byte that is basically known as ESC (Escape Character) that has predefined pattern is generally added to data section of the data stream or frame when there is message or character that has same pattern as that of flag byte.But receiver removes this ESC and keeps data part that causes some problems or issues. In simple words, we can say that character stuffing is addition of 1 additional byte if there is presence of ESC or flag in text.Bit Stuffing :Bit stuffing is also known as bit-oriented framing or bit-oriented approach. In bit stuffing, extra bits are being added by network protocol designers to data streams. It is generally insertion or addition of extra bits into transmission unit or message to be transmitted as simple way to provide and give signaling information and data to receiver and to avoid or ignore appearance of unintended or unnecessary control sequences.It is type of protocol management simply performed to break up bit pattern that results in transmission to go out of synchronization. Bit stuffing is very essential part of transmission process in network and communication protocol. It is also required in USB.Physical Layer Coding Violations :Encoding violation is method that is used only for network in which encoding on physical medium includes some sort of redundancy i.e., use of more than one graphical or visual structure to simply encode or represent one variable of data. Character Count :This method is rarely used and is generally required to count total number of characters that are present in frame. This is be done by using field in header. Character count method ensures data link layer at the receiver or destination about total number of characters that follow, and about where the frame ends.There is disadvantage also of using this method i.e., if anyhow character count is disturbed or distorted by an error occurring during transmission, then destination or receiver might lose synchronization. The destination or receiver might also be not able to locate or identify beginning of next frame. There is disadvantage also of using this method i.e., if anyhow character count is disturbed or distorted by an error occurring during transmission, then destination or receiver might lose synchronization. The destination or receiver might also be not able to locate or identify beginning of next frame. Character Stuffing :Character stuffing is also known as byte stuffing or character-oriented framing and is same as that of bit stuffing but byte stuffing actually operates on bytes whereas bit stuffing operates on bits. In byte stuffing, special byte that is basically known as ESC (Escape Character) that has predefined pattern is generally added to data section of the data stream or frame when there is message or character that has same pattern as that of flag byte.But receiver removes this ESC and keeps data part that causes some problems or issues. In simple words, we can say that character stuffing is addition of 1 additional byte if there is presence of ESC or flag in text. But receiver removes this ESC and keeps data part that causes some problems or issues. In simple words, we can say that character stuffing is addition of 1 additional byte if there is presence of ESC or flag in text. Bit Stuffing :Bit stuffing is also known as bit-oriented framing or bit-oriented approach. In bit stuffing, extra bits are being added by network protocol designers to data streams. It is generally insertion or addition of extra bits into transmission unit or message to be transmitted as simple way to provide and give signaling information and data to receiver and to avoid or ignore appearance of unintended or unnecessary control sequences.It is type of protocol management simply performed to break up bit pattern that results in transmission to go out of synchronization. Bit stuffing is very essential part of transmission process in network and communication protocol. It is also required in USB. It is type of protocol management simply performed to break up bit pattern that results in transmission to go out of synchronization. Bit stuffing is very essential part of transmission process in network and communication protocol. It is also required in USB. Physical Layer Coding Violations :Encoding violation is method that is used only for network in which encoding on physical medium includes some sort of redundancy i.e., use of more than one graphical or visual structure to simply encode or represent one variable of data. Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) Introduction of Mobile Ad hoc Network (MANET) Advanced Encryption Standard (AES) Bluetooth Intrusion Detection System (IDS) Cryptography and its Types Difference between URL and URI
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Aug, 2020" }, { "code": null, "e": 473, "s": 54, "text": "Framing is function of Data Link Layer that is used to separate message from source or sender to destination or receiver or simply from all other messages to all other destinations just by adding sender address and destination address. The destination or receiver address is simply used to represent where message or packet is to go and sender or source address is simply used to help recipient to acknowledge receipt." }, { "code": null, "e": 884, "s": 473, "text": "Frames are generally data unit of data link layer that is transmitted or transferred among various network points. It includes complete and full addressing, protocols that are essential, and information under control. Physical layers only just accept and transfer stream of bits without any regard to meaning or structure. Therefore it is up to data link layer to simply develop and recognize frame boundaries." }, { "code": null, "e": 1183, "s": 884, "text": "This can be achieved by attaching special types of bit patterns to start and end of the frame. If all of these bit patterns might accidentally occur in data, special care is needed to be taken to simply make sure that these bit patterns are not interpreted incorrectly or wrong as frame delimiters." }, { "code": null, "e": 1501, "s": 1183, "text": "Framing is simply point-to-point connection among two computers or devices that consists or includes wire in which data is transferred as stream of bits. However, all of these bits should be framed into discernible blocks of information.Methods of Framing :There are basically four methods of framing as given below –" }, { "code": null, "e": 1629, "s": 1501, "text": "1. Character Count\n2. Flag Byte with Character Stuffing\n3. Starting and Ending Flags, with Bit Stuffing\n4. Encoding Violations " }, { "code": null, "e": 1669, "s": 1629, "text": "These are explained as following below." }, { "code": null, "e": 3964, "s": 1669, "text": "Character Count :This method is rarely used and is generally required to count total number of characters that are present in frame. This is be done by using field in header. Character count method ensures data link layer at the receiver or destination about total number of characters that follow, and about where the frame ends.There is disadvantage also of using this method i.e., if anyhow character count is disturbed or distorted by an error occurring during transmission, then destination or receiver might lose synchronization. The destination or receiver might also be not able to locate or identify beginning of next frame.Character Stuffing :Character stuffing is also known as byte stuffing or character-oriented framing and is same as that of bit stuffing but byte stuffing actually operates on bytes whereas bit stuffing operates on bits. In byte stuffing, special byte that is basically known as ESC (Escape Character) that has predefined pattern is generally added to data section of the data stream or frame when there is message or character that has same pattern as that of flag byte.But receiver removes this ESC and keeps data part that causes some problems or issues. In simple words, we can say that character stuffing is addition of 1 additional byte if there is presence of ESC or flag in text.Bit Stuffing :Bit stuffing is also known as bit-oriented framing or bit-oriented approach. In bit stuffing, extra bits are being added by network protocol designers to data streams. It is generally insertion or addition of extra bits into transmission unit or message to be transmitted as simple way to provide and give signaling information and data to receiver and to avoid or ignore appearance of unintended or unnecessary control sequences.It is type of protocol management simply performed to break up bit pattern that results in transmission to go out of synchronization. Bit stuffing is very essential part of transmission process in network and communication protocol. It is also required in USB.Physical Layer Coding Violations :Encoding violation is method that is used only for network in which encoding on physical medium includes some sort of redundancy i.e., use of more than one graphical or visual structure to simply encode or represent one variable of data." }, { "code": null, "e": 4598, "s": 3964, "text": "Character Count :This method is rarely used and is generally required to count total number of characters that are present in frame. This is be done by using field in header. Character count method ensures data link layer at the receiver or destination about total number of characters that follow, and about where the frame ends.There is disadvantage also of using this method i.e., if anyhow character count is disturbed or distorted by an error occurring during transmission, then destination or receiver might lose synchronization. The destination or receiver might also be not able to locate or identify beginning of next frame." }, { "code": null, "e": 4902, "s": 4598, "text": "There is disadvantage also of using this method i.e., if anyhow character count is disturbed or distorted by an error occurring during transmission, then destination or receiver might lose synchronization. The destination or receiver might also be not able to locate or identify beginning of next frame." }, { "code": null, "e": 5589, "s": 4902, "text": "Character Stuffing :Character stuffing is also known as byte stuffing or character-oriented framing and is same as that of bit stuffing but byte stuffing actually operates on bytes whereas bit stuffing operates on bits. In byte stuffing, special byte that is basically known as ESC (Escape Character) that has predefined pattern is generally added to data section of the data stream or frame when there is message or character that has same pattern as that of flag byte.But receiver removes this ESC and keeps data part that causes some problems or issues. In simple words, we can say that character stuffing is addition of 1 additional byte if there is presence of ESC or flag in text." }, { "code": null, "e": 5806, "s": 5589, "text": "But receiver removes this ESC and keeps data part that causes some problems or issues. In simple words, we can say that character stuffing is addition of 1 additional byte if there is presence of ESC or flag in text." }, { "code": null, "e": 6511, "s": 5806, "text": "Bit Stuffing :Bit stuffing is also known as bit-oriented framing or bit-oriented approach. In bit stuffing, extra bits are being added by network protocol designers to data streams. It is generally insertion or addition of extra bits into transmission unit or message to be transmitted as simple way to provide and give signaling information and data to receiver and to avoid or ignore appearance of unintended or unnecessary control sequences.It is type of protocol management simply performed to break up bit pattern that results in transmission to go out of synchronization. Bit stuffing is very essential part of transmission process in network and communication protocol. It is also required in USB." }, { "code": null, "e": 6772, "s": 6511, "text": "It is type of protocol management simply performed to break up bit pattern that results in transmission to go out of synchronization. Bit stuffing is very essential part of transmission process in network and communication protocol. It is also required in USB." }, { "code": null, "e": 7044, "s": 6772, "text": "Physical Layer Coding Violations :Encoding violation is method that is used only for network in which encoding on physical medium includes some sort of redundancy i.e., use of more than one graphical or visual structure to simply encode or represent one variable of data." }, { "code": null, "e": 7062, "s": 7044, "text": "Computer Networks" }, { "code": null, "e": 7080, "s": 7062, "text": "Computer Networks" }, { "code": null, "e": 7178, "s": 7080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7208, "s": 7178, "text": "GSM in Wireless Communication" }, { "code": null, "e": 7234, "s": 7208, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 7264, "s": 7234, "text": "Wireless Application Protocol" }, { "code": null, "e": 7304, "s": 7264, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 7350, "s": 7304, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 7385, "s": 7350, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 7395, "s": 7385, "text": "Bluetooth" }, { "code": null, "e": 7428, "s": 7395, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 7455, "s": 7428, "text": "Cryptography and its Types" } ]
What’s the difference between ng-pristine and ng-dirty in AngularJS?
31 Dec, 2019 AngularJS supports client-side form validation. AngularJS keeps tracks of all the form and input field and it also stores the information about whether anyone has touched or modified the field or not. Let’s See the two different class ng-dirty and ng-pristine that are used for form validation ng-pristine: The ng-pristine class tells that the form has not been modified by the user. This returns true if the form has not been modified by the user.Return type:Return Boolean True if the form/input field is not modified by the user else it returns False. ng-dirty: The ng-dirty class tells that the form has been made dirty (modified ) by the user. It returns true if the user has modified the form.Return type:Return Boolean True if the form/input field is modified by the user else it returns False. Difference between ng-pristine and ng-dirty:The main difference between both of them is that ng-dirty is used to tell that the input field is modified by the user and the ng-pristine is used to tell us that the field is untouched by the user.Let’s see with the help of a small example to clear out everything. <!DOCTYPE html><html> <head> <title> Difference between ng-pristine and ng-dirty </title></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"> </script> <form ng-app="" name="myForm"> <input name="email" ng-model="data.email"> <div class="info" ng-show="myForm.email.$pristine"> Now Pristine. </div> <div class="error" ng-show="myForm.email.$dirty"> Now Dirty </div> </form> </center></body> </html> Output:Before: After: AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Auth Guards in Angular 9/10/11 Routing in Angular 9/10 How to bundle an Angular app for production? What is AOT and JIT Compiler in Angular ? Angular PrimeNG Dropdown Component 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": 53, "s": 25, "text": "\n31 Dec, 2019" }, { "code": null, "e": 254, "s": 53, "text": "AngularJS supports client-side form validation. AngularJS keeps tracks of all the form and input field and it also stores the information about whether anyone has touched or modified the field or not." }, { "code": null, "e": 347, "s": 254, "text": "Let’s See the two different class ng-dirty and ng-pristine that are used for form validation" }, { "code": null, "e": 608, "s": 347, "text": "ng-pristine: The ng-pristine class tells that the form has not been modified by the user. This returns true if the form has not been modified by the user.Return type:Return Boolean True if the form/input field is not modified by the user else it returns False." }, { "code": null, "e": 855, "s": 608, "text": "ng-dirty: The ng-dirty class tells that the form has been made dirty (modified ) by the user. It returns true if the user has modified the form.Return type:Return Boolean True if the form/input field is modified by the user else it returns False." }, { "code": null, "e": 1165, "s": 855, "text": "Difference between ng-pristine and ng-dirty:The main difference between both of them is that ng-dirty is used to tell that the input field is modified by the user and the ng-pristine is used to tell us that the field is untouched by the user.Let’s see with the help of a small example to clear out everything." }, { "code": "<!DOCTYPE html><html> <head> <title> Difference between ng-pristine and ng-dirty </title></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js\"> </script> <form ng-app=\"\" name=\"myForm\"> <input name=\"email\" ng-model=\"data.email\"> <div class=\"info\" ng-show=\"myForm.email.$pristine\"> Now Pristine. </div> <div class=\"error\" ng-show=\"myForm.email.$dirty\"> Now Dirty </div> </form> </center></body> </html>", "e": 1851, "s": 1165, "text": null }, { "code": null, "e": 1866, "s": 1851, "text": "Output:Before:" }, { "code": null, "e": 1873, "s": 1866, "text": "After:" }, { "code": null, "e": 1888, "s": 1873, "text": "AngularJS-Misc" }, { "code": null, "e": 1895, "s": 1888, "text": "Picked" }, { "code": null, "e": 1905, "s": 1895, "text": "AngularJS" }, { "code": null, "e": 1922, "s": 1905, "text": "Web Technologies" }, { "code": null, "e": 2020, "s": 1922, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2051, "s": 2020, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 2075, "s": 2051, "text": "Routing in Angular 9/10" }, { "code": null, "e": 2120, "s": 2075, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 2162, "s": 2120, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 2197, "s": 2162, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 2259, "s": 2197, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2292, "s": 2259, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2353, "s": 2292, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2403, "s": 2353, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
JSF - h:outputLink
The h:outputLink tag renders an HTML "anchor" element. <h:outputLink value = "page1.jsf" >Page 1</h:outputLink> <a href = "page1.jsf">Page 1</a> id Identifier for a component binding Reference to the component that can be used in a backing bean rendered A boolean; false suppresses rendering styleClass Cascading stylesheet (CSS) class name value A component’s value, typically a value binding valueChangeListener A method binding to a method that responds to value changes converter Converter class name validator Class name of a validator that’s created and attached to a component required A boolean; if true, requires a value to be entered in the associated field accesskey A key, typically combined with a system-defined metakey, that gives focus to an element accept Comma-separated list of content types for a form accept-charset Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset. alt Alternative text for nontextual elements such as images or applets border Pixel value for an element’s border width charset Character encoding for a linked resource coords Coordinates for an element whose shape is a rectangle, circle, or polygon dir Direction for text. Valid values are ltr (left to right) and rtl (right to left) hreflang Base language of a resource specified with the href attribute; hreflang may only be used with href. lang Base language of an element’s attributes and text maxlength Maximum number of characters for text fields readonly Read-only state of an input field; text can be selected in a readonly field but not edited rel Relationship between the current document and a link specified with the href attribute rev Reverse link from the anchor specified with href to the current document. The value of the attribute is a space-separated list of link types size Size of an input field style Inline style information tabindex Numerical value specifying a tab index target The name of a frame in which a document is opened title A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value type Type of a link; for example, stylesheet width Width of an element onblur Element loses focus onchange Element’s value changes onclick Mouse button is clicked over the element ondblclick Mouse button is double-clicked over the element onfocus Element receives focus onkeydown Key is pressed onkeypress Key is pressed and subsequently released onkeyup Key is released onmousedown Mouse button is pressed over the element onmousemove Mouse moves over the element onmouseout Mouse leaves the element’s area onmouseover Mouse moves onto an element onmouseup Mouse button is released onreset Form is reset onselect Text is selected in an input field Let us create a test JSF application to test the above tag. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>JSF Tutorial!</title> </head> <body> <h2>h:outputLink example</h2> <hr /> <h:form> <h:outputLink value = "page1.jsf" >Page 1</h:outputLink> </h:form> </body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
[ { "code": null, "e": 2141, "s": 2086, "text": "The h:outputLink tag renders an HTML \"anchor\" element." }, { "code": null, "e": 2199, "s": 2141, "text": "<h:outputLink value = \"page1.jsf\" >Page 1</h:outputLink> " }, { "code": null, "e": 2234, "s": 2199, "text": "<a href = \"page1.jsf\">Page 1</a> \n" }, { "code": null, "e": 2237, "s": 2234, "text": "id" }, { "code": null, "e": 2264, "s": 2237, "text": "Identifier for a component" }, { "code": null, "e": 2272, "s": 2264, "text": "binding" }, { "code": null, "e": 2334, "s": 2272, "text": "Reference to the component that can be used in a backing bean" }, { "code": null, "e": 2343, "s": 2334, "text": "rendered" }, { "code": null, "e": 2381, "s": 2343, "text": "A boolean; false suppresses rendering" }, { "code": null, "e": 2392, "s": 2381, "text": "styleClass" }, { "code": null, "e": 2430, "s": 2392, "text": "Cascading stylesheet (CSS) class name" }, { "code": null, "e": 2436, "s": 2430, "text": "value" }, { "code": null, "e": 2483, "s": 2436, "text": "A component’s value, typically a value binding" }, { "code": null, "e": 2503, "s": 2483, "text": "valueChangeListener" }, { "code": null, "e": 2563, "s": 2503, "text": "A method binding to a method that responds to value changes" }, { "code": null, "e": 2573, "s": 2563, "text": "converter" }, { "code": null, "e": 2594, "s": 2573, "text": "Converter class name" }, { "code": null, "e": 2604, "s": 2594, "text": "validator" }, { "code": null, "e": 2673, "s": 2604, "text": "Class name of a validator that’s created and attached to a component" }, { "code": null, "e": 2682, "s": 2673, "text": "required" }, { "code": null, "e": 2757, "s": 2682, "text": "A boolean; if true, requires a value to be entered in the associated field" }, { "code": null, "e": 2767, "s": 2757, "text": "accesskey" }, { "code": null, "e": 2855, "s": 2767, "text": "A key, typically combined with a system-defined metakey, that gives focus to an element" }, { "code": null, "e": 2862, "s": 2855, "text": "accept" }, { "code": null, "e": 2911, "s": 2862, "text": "Comma-separated list of content types for a form" }, { "code": null, "e": 2926, "s": 2911, "text": "accept-charset" }, { "code": null, "e": 3083, "s": 2926, "text": "Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset." }, { "code": null, "e": 3087, "s": 3083, "text": "alt" }, { "code": null, "e": 3154, "s": 3087, "text": "Alternative text for nontextual elements such as images or applets" }, { "code": null, "e": 3161, "s": 3154, "text": "border" }, { "code": null, "e": 3203, "s": 3161, "text": "Pixel value for an element’s border width" }, { "code": null, "e": 3211, "s": 3203, "text": "charset" }, { "code": null, "e": 3252, "s": 3211, "text": "Character encoding for a linked resource" }, { "code": null, "e": 3259, "s": 3252, "text": "coords" }, { "code": null, "e": 3333, "s": 3259, "text": "Coordinates for an element whose shape is a rectangle, circle, or polygon" }, { "code": null, "e": 3337, "s": 3333, "text": "dir" }, { "code": null, "e": 3418, "s": 3337, "text": "Direction for text. Valid values are ltr (left to right) and rtl (right to left)" }, { "code": null, "e": 3427, "s": 3418, "text": "hreflang" }, { "code": null, "e": 3527, "s": 3427, "text": "Base language of a resource specified with the href attribute; hreflang may only be used with href." }, { "code": null, "e": 3532, "s": 3527, "text": "lang" }, { "code": null, "e": 3582, "s": 3532, "text": "Base language of an element’s attributes and text" }, { "code": null, "e": 3592, "s": 3582, "text": "maxlength" }, { "code": null, "e": 3637, "s": 3592, "text": "Maximum number of characters for text fields" }, { "code": null, "e": 3646, "s": 3637, "text": "readonly" }, { "code": null, "e": 3737, "s": 3646, "text": "Read-only state of an input field; text can be selected in a readonly field but not edited" }, { "code": null, "e": 3741, "s": 3737, "text": "rel" }, { "code": null, "e": 3828, "s": 3741, "text": "Relationship between the current document and a link specified with the href attribute" }, { "code": null, "e": 3832, "s": 3828, "text": "rev" }, { "code": null, "e": 3973, "s": 3832, "text": "Reverse link from the anchor specified with href to the current document. The value of the attribute is a space-separated list of link types" }, { "code": null, "e": 3978, "s": 3973, "text": "size" }, { "code": null, "e": 4001, "s": 3978, "text": "Size of an input field" }, { "code": null, "e": 4007, "s": 4001, "text": "style" }, { "code": null, "e": 4032, "s": 4007, "text": "Inline style information" }, { "code": null, "e": 4041, "s": 4032, "text": "tabindex" }, { "code": null, "e": 4080, "s": 4041, "text": "Numerical value specifying a tab index" }, { "code": null, "e": 4087, "s": 4080, "text": "target" }, { "code": null, "e": 4137, "s": 4087, "text": "The name of a frame in which a document is opened" }, { "code": null, "e": 4143, "s": 4137, "text": "title" }, { "code": null, "e": 4267, "s": 4143, "text": "A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value" }, { "code": null, "e": 4272, "s": 4267, "text": "type" }, { "code": null, "e": 4312, "s": 4272, "text": "Type of a link; for example, stylesheet" }, { "code": null, "e": 4318, "s": 4312, "text": "width" }, { "code": null, "e": 4338, "s": 4318, "text": "Width of an element" }, { "code": null, "e": 4345, "s": 4338, "text": "onblur" }, { "code": null, "e": 4365, "s": 4345, "text": "Element loses focus" }, { "code": null, "e": 4374, "s": 4365, "text": "onchange" }, { "code": null, "e": 4398, "s": 4374, "text": "Element’s value changes" }, { "code": null, "e": 4406, "s": 4398, "text": "onclick" }, { "code": null, "e": 4447, "s": 4406, "text": "Mouse button is clicked over the element" }, { "code": null, "e": 4458, "s": 4447, "text": "ondblclick" }, { "code": null, "e": 4506, "s": 4458, "text": "Mouse button is double-clicked over the element" }, { "code": null, "e": 4514, "s": 4506, "text": "onfocus" }, { "code": null, "e": 4537, "s": 4514, "text": "Element receives focus" }, { "code": null, "e": 4547, "s": 4537, "text": "onkeydown" }, { "code": null, "e": 4562, "s": 4547, "text": "Key is pressed" }, { "code": null, "e": 4573, "s": 4562, "text": "onkeypress" }, { "code": null, "e": 4614, "s": 4573, "text": "Key is pressed and subsequently released" }, { "code": null, "e": 4622, "s": 4614, "text": "onkeyup" }, { "code": null, "e": 4638, "s": 4622, "text": "Key is released" }, { "code": null, "e": 4650, "s": 4638, "text": "onmousedown" }, { "code": null, "e": 4691, "s": 4650, "text": "Mouse button is pressed over the element" }, { "code": null, "e": 4703, "s": 4691, "text": "onmousemove" }, { "code": null, "e": 4732, "s": 4703, "text": "Mouse moves over the element" }, { "code": null, "e": 4743, "s": 4732, "text": "onmouseout" }, { "code": null, "e": 4775, "s": 4743, "text": "Mouse leaves the element’s area" }, { "code": null, "e": 4787, "s": 4775, "text": "onmouseover" }, { "code": null, "e": 4815, "s": 4787, "text": "Mouse moves onto an element" }, { "code": null, "e": 4825, "s": 4815, "text": "onmouseup" }, { "code": null, "e": 4850, "s": 4825, "text": "Mouse button is released" }, { "code": null, "e": 4858, "s": 4850, "text": "onreset" }, { "code": null, "e": 4872, "s": 4858, "text": "Form is reset" }, { "code": null, "e": 4881, "s": 4872, "text": "onselect" }, { "code": null, "e": 4916, "s": 4881, "text": "Text is selected in an input field" }, { "code": null, "e": 4976, "s": 4916, "text": "Let us create a test JSF application to test the above tag." }, { "code": null, "e": 5390, "s": 4976, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\">\n <head>\n <title>JSF Tutorial!</title>\n </head>\n \n <body>\n <h2>h:outputLink example</h2>\n <hr />\n \n <h:form>\n <h:outputLink value = \"page1.jsf\" >Page 1</h:outputLink>\n </h:form>\n </body>\n</html>" } ]
Nagarro Interview Experience | Set 2
14 Oct, 2014 First Round:1.Aptitude Questions, basically logical aptitude, Not the standard aptitude questions which we get in other companies, it included some questions of geometry, trigonometry, and puzzle type questions, analytical ability, Question were like – find the measure of an angle in the figure, solve the trigonometric equation, data interpretation-a data table was given and based on that table question were given, find the sum of a given series, arrange in descending order -sruds ka, etc..Paper was not so easy Second Round:Technical ability test: questions on basic C language, like predict the output, find error, then puzzle type question of queues and stacks, then write level order traversal after insertion in a heap, dry run of bubble sort and quicksort, and some very basic question like no of nodes in binary tree and all... Overall this round was very easy.:):):) Third Round:Coding Round: Three questions 1. You’re given a m x m matrix. Write a function to rotate submatrix within the matrix by 90degree clock wise. Function takes x and y as starting row and column coordinate of matrix and N as size of submatrix as argument. Inplace rotation was required. I gave brute force I.e. With extra memory. 2. You are given a sorted array containing both negative and positive values. Resort the array taking absolute value of negative numbers. Your complexity should be O(n) Ex. A = {-8,-5,-3,-1,3,6,9} Output: {-1,-3,3,-5,6,-8,9} 3. Wap to find subsets that contains equal sum in an array: for eg{1,2,3,4,2}->{1,2,3}&&{4,2} {1,1,3,3,2,8}->{1,3,3,2}&&{1,8} {1,3,4,7}->no subset Fourth Round:He started with tell me something about urself. Meanwhile he was going through my coding paper. Then he said lets dry run the first program.. We started, then he was confused in my program, I said should I explain it to u?? He said let me see it.. Then he startedd asking why this variable, can I use anything else.. Finally, he was done with my first code,. Code was correct. Then he came to second code and again he said lets dry run it.. I used mergsort sort merging technique, so he said ok explain me this, and again why this variable, and can u do any thing else other than this and so on.. Maine third code m kuch nhi likha tha, so he asked the reason. Maine kaha ki mai sol tak nhi pahuch paya tha, toh usne kaha tell me jitna socha tha, then I told him jo maine socha tha.. Then he asked, ki is problem k baare m fir socha ya nhi free time m, I said yes, he said so how it is solved then, I said dynamic programming. He asked nothing.. He gave me a extra question- Given a text string and a sample string. Find if the characters of the sample string is in the same order in the text string.. Give a simple algo.. Eg.. TextString: abcNjhgAhGjhfhAljhRkhgRbhjbevfhO Sample string :NAGARRO I gave him few solution.. He was done with my interview, and he was happy with my solution.Fifth Round: HR Round: Tell me something about urself. Tell me something about ur family background. Tell me something about ur educational qualification. Schooling... Graduation... Etc.. Incidentally, What was ur Rank in MCA enterance?? Tell me about ur all achievements... Scholarshipholder...... second topper graduation.... Second topper matriculation... ranking in technical fests... Maths olmpiad... Etc... Tell me about ur strength and weakness.. PS: Try to give ur weakness such that it is counted as strength... My strength : Hard Working and dedicated to work. My Weakness : Relationship, relationship is the first priority before any work.. Give me incident when u ranked relationship above any other work. What do u know about Nagarro? PS:For this question just concentrate in the company ppt.. That will be sufficient Basically Jo ek do line Maine ppt m suni Thi use hi bol Diya Tha Maine.. Kuch lines aur jaise Ki there is small DUCS family there in nagarro, alumni batate hai ki there is time flexibility and a very good working environment...... Outings.... Festivals... Freshers party.... Headquarters... Etc.... Which area of the computer Science u liked most during this course of MCA? I said programming , data structure, Algorithm i liked the most Which kind of programming u do, i told him him i usually do contests in codechef, geeksforgeeks questions, and off course the curriculum assignments... Tell me in which language u r comfortable for programming, I told him JAVA. then he said why not C. I said, basically i also work in C but prefer java. But when language is not specified in assign, i prefer only Java. Then i asked , which language is used in company. She said Java, C plus plus, .net... Then i asked, which language will i get, she said it is decided after training. Are u comfortable in working outside your city, i said yes.. Do you have passport, i said No, she said apply as soon as possible. GeeksforGeeks helped me a lot Best site to prepare for Technical Interviews.. Big thanks to GeeksforGeeks If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Nagarro Interview Experiences Nagarro Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Oct, 2014" }, { "code": null, "e": 284, "s": 52, "text": "First Round:1.Aptitude Questions, basically logical aptitude, Not the standard aptitude questions which we get in other companies, it included some questions of geometry, trigonometry, and puzzle type questions, analytical ability," }, { "code": null, "e": 570, "s": 284, "text": "Question were like – find the measure of an angle in the figure, solve the trigonometric equation, data interpretation-a data table was given and based on that table question were given, find the sum of a given series, arrange in descending order -sruds ka, etc..Paper was not so easy " }, { "code": null, "e": 933, "s": 570, "text": "Second Round:Technical ability test: questions on basic C language, like predict the output, find error, then puzzle type question of queues and stacks, then write level order traversal after insertion in a heap, dry run of bubble sort and quicksort, and some very basic question like no of nodes in binary tree and all... Overall this round was very easy.:):):)" }, { "code": null, "e": 975, "s": 933, "text": "Third Round:Coding Round: Three questions" }, { "code": null, "e": 1271, "s": 975, "text": "1. You’re given a m x m matrix. Write a function to rotate submatrix within the matrix by 90degree clock wise. Function takes x and y as starting row and column coordinate of matrix and N as size of submatrix as argument. Inplace rotation was required. I gave brute force I.e. With extra memory." }, { "code": null, "e": 1440, "s": 1271, "text": "2. You are given a sorted array containing both negative and positive values. Resort the array taking absolute value of negative numbers. Your complexity should be O(n)" }, { "code": null, "e": 1497, "s": 1440, "text": "Ex. A = {-8,-5,-3,-1,3,6,9}\nOutput: {-1,-3,3,-5,6,-8,9} " }, { "code": null, "e": 1557, "s": 1497, "text": "3. Wap to find subsets that contains equal sum in an array:" }, { "code": null, "e": 1645, "s": 1557, "text": "for eg{1,2,3,4,2}->{1,2,3}&&{4,2}\n{1,1,3,3,2,8}->{1,3,3,2}&&{1,8}\n{1,3,4,7}->no subset " }, { "code": null, "e": 2603, "s": 1645, "text": "Fourth Round:He started with tell me something about urself. Meanwhile he was going through my coding paper. Then he said lets dry run the first program.. We started, then he was confused in my program, I said should I explain it to u?? He said let me see it.. Then he startedd asking why this variable, can I use anything else.. Finally, he was done with my first code,. Code was correct. Then he came to second code and again he said lets dry run it.. I used mergsort sort merging technique, so he said ok explain me this, and again why this variable, and can u do any thing else other than this and so on.. Maine third code m kuch nhi likha tha, so he asked the reason. Maine kaha ki mai sol tak nhi pahuch paya tha, toh usne kaha tell me jitna socha tha, then I told him jo maine socha tha.. Then he asked, ki is problem k baare m fir socha ya nhi free time m, I said yes, he said so how it is solved then, I said dynamic programming. He asked nothing.." }, { "code": null, "e": 2780, "s": 2603, "text": "He gave me a extra question- Given a text string and a sample string. Find if the characters of the sample string is in the same order in the text string.. Give a simple algo.." }, { "code": null, "e": 2854, "s": 2780, "text": "Eg.. TextString: abcNjhgAhGjhfhAljhRkhgRbhjbevfhO\nSample string :NAGARRO " }, { "code": null, "e": 2968, "s": 2854, "text": "I gave him few solution.. He was done with my interview, and he was happy with my solution.Fifth Round: HR Round:" }, { "code": null, "e": 3000, "s": 2968, "text": "Tell me something about urself." }, { "code": null, "e": 3046, "s": 3000, "text": "Tell me something about ur family background." }, { "code": null, "e": 3147, "s": 3046, "text": "Tell me something about ur educational qualification. Schooling... Graduation... Etc.. Incidentally," }, { "code": null, "e": 3183, "s": 3147, "text": "What was ur Rank in MCA enterance??" }, { "code": null, "e": 3358, "s": 3183, "text": "Tell me about ur all achievements... Scholarshipholder...... second topper graduation.... Second topper matriculation... ranking in technical fests... Maths olmpiad... Etc..." }, { "code": null, "e": 3663, "s": 3358, "text": "Tell me about ur strength and weakness.. PS: Try to give ur weakness such that it is counted as strength... My strength : Hard Working and dedicated to work. My Weakness : Relationship, relationship is the first priority before any work.. Give me incident when u ranked relationship above any other work." }, { "code": null, "e": 4076, "s": 3663, "text": "What do u know about Nagarro? PS:For this question just concentrate in the company ppt.. That will be sufficient Basically Jo ek do line Maine ppt m suni Thi use hi bol Diya Tha Maine.. Kuch lines aur jaise Ki there is small DUCS family there in nagarro, alumni batate hai ki there is time flexibility and a very good working environment...... Outings.... Festivals... Freshers party.... Headquarters... Etc...." }, { "code": null, "e": 4216, "s": 4076, "text": "Which area of the computer Science u liked most during this course of MCA? I said programming , data structure, Algorithm i liked the most " }, { "code": null, "e": 4368, "s": 4216, "text": "Which kind of programming u do, i told him him i usually do contests in codechef, geeksforgeeks questions, and off course the curriculum assignments..." }, { "code": null, "e": 4882, "s": 4368, "text": "Tell me in which language u r comfortable for programming, I told him JAVA. then he said why not C. I said, basically i also work in C but prefer java. But when language is not specified in assign, i prefer only Java. Then i asked , which language is used in company. She said Java, C plus plus, .net... Then i asked, which language will i get, she said it is decided after training. Are u comfortable in working outside your city, i said yes.. Do you have passport, i said No, she said apply as soon as possible." }, { "code": null, "e": 4961, "s": 4882, "text": "GeeksforGeeks helped me a lot Best site to prepare for Technical Interviews.." }, { "code": null, "e": 4990, "s": 4961, "text": "Big thanks to GeeksforGeeks " }, { "code": null, "e": 5211, "s": 4990, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5219, "s": 5211, "text": "Nagarro" }, { "code": null, "e": 5241, "s": 5219, "text": "Interview Experiences" }, { "code": null, "e": 5249, "s": 5241, "text": "Nagarro" } ]
Sum of digits written in different bases from 2 to n-1
08 Apr, 2021 Given a number n, find the sum of digits of n when represented in different bases from 2 to n-1.Examples: Input : 5 Output : 2 3 2 Representation of 5 is 101, 12, 11 in bases 2 , 3 , 4 . Input : 7 Output : 3 3 4 3 2 As the given question wants the sum of digits in different bases, first we have to calculate the given number of different bases and add each digit to the number of different bases.So, to calculate each number’s representation we will take the mod of given number by the base in which we want to represent that number.Then, we have to add all those mod values as the mod values obtained will represent that number in that base.Finally, the sum of those mod values gives the sum of digits of that number. As the given question wants the sum of digits in different bases, first we have to calculate the given number of different bases and add each digit to the number of different bases. So, to calculate each number’s representation we will take the mod of given number by the base in which we want to represent that number. Then, we have to add all those mod values as the mod values obtained will represent that number in that base. Finally, the sum of those mod values gives the sum of digits of that number. Below are implementations of this approach C++ Java Python3 C# PHP Javascript // CPP program to find sum of digits of// n in different bases from 2 to n-1.#include <bits/stdc++.h>using namespace std; // function to calculate sum of// digit for a given baseint solve(int n, int base){ // Sum of digits int result = 0 ; // Calculating the number (n) by // taking mod with the base and adding // remainder to the result and // parallelly reducing the num value . while (n > 0) { int remainder = n % base ; result = result + remainder ; n = n / base; } // returning the result return result ;} void printSumsOfDigits(int n){ // function calling for multiple bases for (int base = 2 ; base < n ; ++base) cout << solve(n, base) <<" ";} // Driver programint main(){ int n = 8; printSumsOfDigits(n); return 0;} // Java program to find sum of digits of// n in different bases from 2 to n-1.class GFG{// function to calculate sum of// digit for a given basestatic int solve(int n, int base){ // Sum of digits int result = 0 ; // Calculating the number (n) by // taking mod with the base and adding // remainder to the result and // parallelly reducing the num value . while (n > 0) { int remainder = n % base ; result = result + remainder ; n = n / base; } // returning the result return result ;} static void printSumsOfDigits(int n){ // function calling for multiple bases for (int base = 2 ; base < n ; ++base) System.out.print(solve(n, base)+" ");} // Driver Codepublic static void main(String[] args){ int n = 8; printSumsOfDigits(n);}}// This code is contributed by Smitha # Python program to find sum of digits of# n in different bases from 2 to n-1. # def to calculate sum of# digit for a given basedef solve(n, base) : # Sum of digits result = 0 # Calculating the number (n) by # taking mod with the base and adding # remainder to the result and # parallelly reducing the num value . while (n > 0) : remainder = n % base result = result + remainder n = int(n / base) # returning the result return result def printSumsOfDigits(n) : # def calling for # multiple bases for base in range(2, n) : print (solve(n, base), end=" ") # Driver coden = 8printSumsOfDigits(n) # This code is contributed by Manish Shaw# (manishshaw1) // Java program to find the sum of digits of// n in different base1s from 2 to n-1.using System; class GFG{// function to calculate sum of// digit for a given base1static int solve(int n, int base1){ // Sum of digits int result = 0 ; // Calculating the number (n) by // taking mod with the base1 and adding // remainder to the result and // parallelly reducing the num value . while (n > 0) { int remainder = n % base1 ; result = result + remainder ; n = n / base1; } // returning the result return result ;} static void printSumsOfDigits(int n){ // function calling for multiple base1s for (int base1 = 2 ; base1 < n ; ++base1) Console.Write(solve(n, base1)+" ");} // Driver Codepublic static void Main(){ int n = 8; printSumsOfDigits(n);}}// This code is contributed by Smitha <?php// PHP program to find sum of digits of// n in different bases from 2 to n-1. // function to calculate sum of// digit for a given basefunction solve($n, $base){ // Sum of digits $result = 0 ; // Calculating the number (n) by // taking mod with the base and adding // remainder to the result and // parallelly reducing the num value . while ($n > 0) { $remainder = $n % $base ; $result = $result + $remainder ; $n = $n / $base; } // returning the result return $result ;} function printSumsOfDigits($n){ // function calling for // multiple bases for ($base = 2 ; $base < $n ; ++$base) { echo(solve($n, $base)); echo(" "); }} // Driver code$n = 8;printSumsOfDigits($n); // This code is contributed by Ajit.?> <script> // JavaScript program to find sum of digits of// n in different bases from 2 to n-1. // function to calculate sum of // digit for a given base function solve(n , base) { // Sum of digits var result = 0; // Calculating the number (n) by // taking mod with the base and adding // remainder to the result and // parallelly reducing the num value . while (n > 0) { var remainder = n % base; result = result + remainder; n = parseInt(n / base); } // returning the result return result; } function printSumsOfDigits(n) { // function calling for multiple bases for (base = 2; base < n; ++base) document.write(solve(n, base) + " "); } // Driver Code var n = 8; printSumsOfDigits(n); // This code contributed by Rajput-Ji </script> Output : 1 4 2 4 3 2 Smitha Dinesh Semwal jit_t manishshaw1 sanskar27jain Rajput-Ji base-conversion number-digits Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Find next greater number with same set of digits Segment Tree | Set 1 (Sum of given range) Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Apr, 2021" }, { "code": null, "e": 160, "s": 52, "text": "Given a number n, find the sum of digits of n when represented in different bases from 2 to n-1.Examples: " }, { "code": null, "e": 271, "s": 160, "text": "Input : 5\nOutput : 2 3 2\nRepresentation of 5 is 101, 12, 11 in bases 2 , 3 , 4 .\n\nInput : 7\nOutput : 3 3 4 3 2" }, { "code": null, "e": 779, "s": 275, "text": "As the given question wants the sum of digits in different bases, first we have to calculate the given number of different bases and add each digit to the number of different bases.So, to calculate each number’s representation we will take the mod of given number by the base in which we want to represent that number.Then, we have to add all those mod values as the mod values obtained will represent that number in that base.Finally, the sum of those mod values gives the sum of digits of that number." }, { "code": null, "e": 961, "s": 779, "text": "As the given question wants the sum of digits in different bases, first we have to calculate the given number of different bases and add each digit to the number of different bases." }, { "code": null, "e": 1099, "s": 961, "text": "So, to calculate each number’s representation we will take the mod of given number by the base in which we want to represent that number." }, { "code": null, "e": 1209, "s": 1099, "text": "Then, we have to add all those mod values as the mod values obtained will represent that number in that base." }, { "code": null, "e": 1286, "s": 1209, "text": "Finally, the sum of those mod values gives the sum of digits of that number." }, { "code": null, "e": 1330, "s": 1286, "text": "Below are implementations of this approach " }, { "code": null, "e": 1336, "s": 1332, "text": "C++" }, { "code": null, "e": 1341, "s": 1336, "text": "Java" }, { "code": null, "e": 1349, "s": 1341, "text": "Python3" }, { "code": null, "e": 1352, "s": 1349, "text": "C#" }, { "code": null, "e": 1356, "s": 1352, "text": "PHP" }, { "code": null, "e": 1367, "s": 1356, "text": "Javascript" }, { "code": "// CPP program to find sum of digits of// n in different bases from 2 to n-1.#include <bits/stdc++.h>using namespace std; // function to calculate sum of// digit for a given baseint solve(int n, int base){ // Sum of digits int result = 0 ; // Calculating the number (n) by // taking mod with the base and adding // remainder to the result and // parallelly reducing the num value . while (n > 0) { int remainder = n % base ; result = result + remainder ; n = n / base; } // returning the result return result ;} void printSumsOfDigits(int n){ // function calling for multiple bases for (int base = 2 ; base < n ; ++base) cout << solve(n, base) <<\" \";} // Driver programint main(){ int n = 8; printSumsOfDigits(n); return 0;}", "e": 2181, "s": 1367, "text": null }, { "code": "// Java program to find sum of digits of// n in different bases from 2 to n-1.class GFG{// function to calculate sum of// digit for a given basestatic int solve(int n, int base){ // Sum of digits int result = 0 ; // Calculating the number (n) by // taking mod with the base and adding // remainder to the result and // parallelly reducing the num value . while (n > 0) { int remainder = n % base ; result = result + remainder ; n = n / base; } // returning the result return result ;} static void printSumsOfDigits(int n){ // function calling for multiple bases for (int base = 2 ; base < n ; ++base) System.out.print(solve(n, base)+\" \");} // Driver Codepublic static void main(String[] args){ int n = 8; printSumsOfDigits(n);}}// This code is contributed by Smitha", "e": 3030, "s": 2181, "text": null }, { "code": "# Python program to find sum of digits of# n in different bases from 2 to n-1. # def to calculate sum of# digit for a given basedef solve(n, base) : # Sum of digits result = 0 # Calculating the number (n) by # taking mod with the base and adding # remainder to the result and # parallelly reducing the num value . while (n > 0) : remainder = n % base result = result + remainder n = int(n / base) # returning the result return result def printSumsOfDigits(n) : # def calling for # multiple bases for base in range(2, n) : print (solve(n, base), end=\" \") # Driver coden = 8printSumsOfDigits(n) # This code is contributed by Manish Shaw# (manishshaw1)", "e": 3777, "s": 3030, "text": null }, { "code": "// Java program to find the sum of digits of// n in different base1s from 2 to n-1.using System; class GFG{// function to calculate sum of// digit for a given base1static int solve(int n, int base1){ // Sum of digits int result = 0 ; // Calculating the number (n) by // taking mod with the base1 and adding // remainder to the result and // parallelly reducing the num value . while (n > 0) { int remainder = n % base1 ; result = result + remainder ; n = n / base1; } // returning the result return result ;} static void printSumsOfDigits(int n){ // function calling for multiple base1s for (int base1 = 2 ; base1 < n ; ++base1) Console.Write(solve(n, base1)+\" \");} // Driver Codepublic static void Main(){ int n = 8; printSumsOfDigits(n);}}// This code is contributed by Smitha", "e": 4639, "s": 3777, "text": null }, { "code": "<?php// PHP program to find sum of digits of// n in different bases from 2 to n-1. // function to calculate sum of// digit for a given basefunction solve($n, $base){ // Sum of digits $result = 0 ; // Calculating the number (n) by // taking mod with the base and adding // remainder to the result and // parallelly reducing the num value . while ($n > 0) { $remainder = $n % $base ; $result = $result + $remainder ; $n = $n / $base; } // returning the result return $result ;} function printSumsOfDigits($n){ // function calling for // multiple bases for ($base = 2 ; $base < $n ; ++$base) { echo(solve($n, $base)); echo(\" \"); }} // Driver code$n = 8;printSumsOfDigits($n); // This code is contributed by Ajit.?>", "e": 5454, "s": 4639, "text": null }, { "code": "<script> // JavaScript program to find sum of digits of// n in different bases from 2 to n-1. // function to calculate sum of // digit for a given base function solve(n , base) { // Sum of digits var result = 0; // Calculating the number (n) by // taking mod with the base and adding // remainder to the result and // parallelly reducing the num value . while (n > 0) { var remainder = n % base; result = result + remainder; n = parseInt(n / base); } // returning the result return result; } function printSumsOfDigits(n) { // function calling for multiple bases for (base = 2; base < n; ++base) document.write(solve(n, base) + \" \"); } // Driver Code var n = 8; printSumsOfDigits(n); // This code contributed by Rajput-Ji </script>", "e": 6359, "s": 5454, "text": null }, { "code": null, "e": 6369, "s": 6359, "text": "Output : " }, { "code": null, "e": 6382, "s": 6369, "text": "1 4 2 4 3 2 " }, { "code": null, "e": 6405, "s": 6384, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 6411, "s": 6405, "text": "jit_t" }, { "code": null, "e": 6423, "s": 6411, "text": "manishshaw1" }, { "code": null, "e": 6437, "s": 6423, "text": "sanskar27jain" }, { "code": null, "e": 6447, "s": 6437, "text": "Rajput-Ji" }, { "code": null, "e": 6463, "s": 6447, "text": "base-conversion" }, { "code": null, "e": 6477, "s": 6463, "text": "number-digits" }, { "code": null, "e": 6490, "s": 6477, "text": "Mathematical" }, { "code": null, "e": 6509, "s": 6490, "text": "School Programming" }, { "code": null, "e": 6522, "s": 6509, "text": "Mathematical" }, { "code": null, "e": 6620, "s": 6522, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6652, "s": 6620, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 6698, "s": 6652, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 6742, "s": 6698, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 6791, "s": 6742, "text": "Find next greater number with same set of digits" }, { "code": null, "e": 6833, "s": 6791, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 6851, "s": 6833, "text": "Python Dictionary" }, { "code": null, "e": 6876, "s": 6851, "text": "Reverse a string in Java" }, { "code": null, "e": 6892, "s": 6876, "text": "Arrays in C/C++" }, { "code": null, "e": 6915, "s": 6892, "text": "Introduction To PYTHON" } ]
How to design a modern sidebar menu using HTML and CSS?
05 Mar, 2021 Sidebar menu is a component that is used for vertical navigation. It can be customized and made responsive by using simple HTML and CSS. To make a collapsing sidebar, you need to have HTML and CSS knowledge for creating it. Example: In this example, first we will create a structure by using HTML after that we will decorate that structure by using CSS. HTML File: In this file, we will design the structure of our modern side navbar, here we will not use any single line of CSS. We will do that after the structure is ready.HTMLHTML<!DOCTYPE html><html> <head> <!-- You can Include your CSS here--> </head> <body> <div> <!-- Div Header--> <h2>GeeksforGeeks</h2> <!-- Links in Div --> <a href="#"> Data Structures </a> <a href="#"> Algorithms </a> <a href="#"> Interview Preparation </a> <a href="#"> Python </a> <a href="#"> Java </a> </div> </body></html> HTML File: In this file, we will design the structure of our modern side navbar, here we will not use any single line of CSS. We will do that after the structure is ready. HTML <!DOCTYPE html><html> <head> <!-- You can Include your CSS here--> </head> <body> <div> <!-- Div Header--> <h2>GeeksforGeeks</h2> <!-- Links in Div --> <a href="#"> Data Structures </a> <a href="#"> Algorithms </a> <a href="#"> Interview Preparation </a> <a href="#"> Python </a> <a href="#"> Java </a> </div> </body></html> CSS File: This file contains all the CSS styling rules to create the custom animated sidebar. This file is used in the above HTML code.CSSCSS/* Sidebar Div */ div { color: #fff; width: 250px; padding-left: 20px; height: 100vh; background-image: linear-gradient(30deg, #11cf4d, #055e21); border-top-right-radius: 90px; } /* Div header */ div h2 { padding: 40px 0 0 0; cursor: pointer; } /* Div links */ div a { font-size: 14px; color: #fff; display: block; padding: 12px; padding-left: 30px; text-decoration: none; outline: none; } /* Div link on hover */ div a:hover { color: #56ff38; background: #fff; position: relative; background-color: #fff; border-top-left-radius: 22px; border-bottom-left-radius: 22px; } CSS File: This file contains all the CSS styling rules to create the custom animated sidebar. This file is used in the above HTML code. CSS /* Sidebar Div */ div { color: #fff; width: 250px; padding-left: 20px; height: 100vh; background-image: linear-gradient(30deg, #11cf4d, #055e21); border-top-right-radius: 90px; } /* Div header */ div h2 { padding: 40px 0 0 0; cursor: pointer; } /* Div links */ div a { font-size: 14px; color: #fff; display: block; padding: 12px; padding-left: 30px; text-decoration: none; outline: none; } /* Div link on hover */ div a:hover { color: #56ff38; background: #fff; position: relative; background-color: #fff; border-top-left-radius: 22px; border-bottom-left-radius: 22px; } Complete Solution: Here we will combine above sections HTML and CSS to create a perfect modern side bar menu. HTML <!DOCTYPE html><html> <head> <style> /* Sidebar Div */ div { color: #fff; width: 250px; padding-left: 20px; height: 100vh; background-image: linear-gradient(30deg, #11cf4d, #055e21); border-top-right-radius: 90px; } /* Div header */ div h2 { padding: 40px 0 0 0; cursor: pointer; } /* Div links */ div a { font-size: 14px; color: #fff; display: block; padding: 12px; padding-left: 30px; text-decoration: none; outline: none; } /* Div link on hover */ div a:hover { color: #56ff38; background: #fff; position: relative; background-color: #fff; border-top-left-radius: 22px; border-bottom-left-radius: 22px; } </style> </head> <body> <div> <!-- Div Header--> <h2>GeeksforGeeks</h2> <!-- Links in Div --> <a href="#"> Data Structures </a> <a href="#"> Algorithms </a> <a href="#"> Interview Preparation </a> <a href="#"> Python </a> <a href="#"> Java </a> </div> </body></html> CSS-Questions CSS-Selectors HTML-Questions CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Mar, 2021" }, { "code": null, "e": 276, "s": 52, "text": "Sidebar menu is a component that is used for vertical navigation. It can be customized and made responsive by using simple HTML and CSS. To make a collapsing sidebar, you need to have HTML and CSS knowledge for creating it." }, { "code": null, "e": 406, "s": 276, "text": "Example: In this example, first we will create a structure by using HTML after that we will decorate that structure by using CSS." }, { "code": null, "e": 1019, "s": 406, "text": "HTML File: In this file, we will design the structure of our modern side navbar, here we will not use any single line of CSS. We will do that after the structure is ready.HTMLHTML<!DOCTYPE html><html> <head> <!-- You can Include your CSS here--> </head> <body> <div> <!-- Div Header--> <h2>GeeksforGeeks</h2> <!-- Links in Div --> <a href=\"#\"> Data Structures </a> <a href=\"#\"> Algorithms </a> <a href=\"#\"> Interview Preparation </a> <a href=\"#\"> Python </a> <a href=\"#\"> Java </a> </div> </body></html>" }, { "code": null, "e": 1191, "s": 1019, "text": "HTML File: In this file, we will design the structure of our modern side navbar, here we will not use any single line of CSS. We will do that after the structure is ready." }, { "code": null, "e": 1196, "s": 1191, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- You can Include your CSS here--> </head> <body> <div> <!-- Div Header--> <h2>GeeksforGeeks</h2> <!-- Links in Div --> <a href=\"#\"> Data Structures </a> <a href=\"#\"> Algorithms </a> <a href=\"#\"> Interview Preparation </a> <a href=\"#\"> Python </a> <a href=\"#\"> Java </a> </div> </body></html>", "e": 1630, "s": 1196, "text": null }, { "code": null, "e": 2422, "s": 1630, "text": "CSS File: This file contains all the CSS styling rules to create the custom animated sidebar. This file is used in the above HTML code.CSSCSS/* Sidebar Div */ div { color: #fff; width: 250px; padding-left: 20px; height: 100vh; background-image: linear-gradient(30deg, #11cf4d, #055e21); border-top-right-radius: 90px; } /* Div header */ div h2 { padding: 40px 0 0 0; cursor: pointer; } /* Div links */ div a { font-size: 14px; color: #fff; display: block; padding: 12px; padding-left: 30px; text-decoration: none; outline: none; } /* Div link on hover */ div a:hover { color: #56ff38; background: #fff; position: relative; background-color: #fff; border-top-left-radius: 22px; border-bottom-left-radius: 22px; }" }, { "code": null, "e": 2558, "s": 2422, "text": "CSS File: This file contains all the CSS styling rules to create the custom animated sidebar. This file is used in the above HTML code." }, { "code": null, "e": 2562, "s": 2558, "text": "CSS" }, { "code": "/* Sidebar Div */ div { color: #fff; width: 250px; padding-left: 20px; height: 100vh; background-image: linear-gradient(30deg, #11cf4d, #055e21); border-top-right-radius: 90px; } /* Div header */ div h2 { padding: 40px 0 0 0; cursor: pointer; } /* Div links */ div a { font-size: 14px; color: #fff; display: block; padding: 12px; padding-left: 30px; text-decoration: none; outline: none; } /* Div link on hover */ div a:hover { color: #56ff38; background: #fff; position: relative; background-color: #fff; border-top-left-radius: 22px; border-bottom-left-radius: 22px; }", "e": 3213, "s": 2562, "text": null }, { "code": null, "e": 3323, "s": 3213, "text": "Complete Solution: Here we will combine above sections HTML and CSS to create a perfect modern side bar menu." }, { "code": null, "e": 3328, "s": 3323, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> /* Sidebar Div */ div { color: #fff; width: 250px; padding-left: 20px; height: 100vh; background-image: linear-gradient(30deg, #11cf4d, #055e21); border-top-right-radius: 90px; } /* Div header */ div h2 { padding: 40px 0 0 0; cursor: pointer; } /* Div links */ div a { font-size: 14px; color: #fff; display: block; padding: 12px; padding-left: 30px; text-decoration: none; outline: none; } /* Div link on hover */ div a:hover { color: #56ff38; background: #fff; position: relative; background-color: #fff; border-top-left-radius: 22px; border-bottom-left-radius: 22px; } </style> </head> <body> <div> <!-- Div Header--> <h2>GeeksforGeeks</h2> <!-- Links in Div --> <a href=\"#\"> Data Structures </a> <a href=\"#\"> Algorithms </a> <a href=\"#\"> Interview Preparation </a> <a href=\"#\"> Python </a> <a href=\"#\"> Java </a> </div> </body></html>", "e": 4530, "s": 3328, "text": null }, { "code": null, "e": 4544, "s": 4530, "text": "CSS-Questions" }, { "code": null, "e": 4558, "s": 4544, "text": "CSS-Selectors" }, { "code": null, "e": 4573, "s": 4558, "text": "HTML-Questions" }, { "code": null, "e": 4577, "s": 4573, "text": "CSS" }, { "code": null, "e": 4582, "s": 4577, "text": "HTML" }, { "code": null, "e": 4599, "s": 4582, "text": "Web Technologies" }, { "code": null, "e": 4604, "s": 4599, "text": "HTML" } ]
Count BST nodes that lie in a given range
11 Feb, 2022 Given a Binary Search Tree (BST) and a range, count number of nodes that lie in the given range.Examples: Input: 10 / \ 5 50 / / \ 1 40 100 Range: [5, 45] Output: 3 There are three nodes in range, 5, 10 and 40 The idea is to traverse the given binary search tree starting from root. For every node being visited, check if this node lies in range, if yes, then add 1 to result and recur for both of its children. If current node is smaller than low value of range, then recur for right child, else recur for left child.Below is the implementation of above idea. C++ Java Python3 C# Javascript // C++ program to count BST nodes within a given range#include<bits/stdc++.h>using namespace std; // A BST nodestruct node{ int data; struct node* left, *right;}; // Utility function to create new nodenode *newNode(int data){ node *temp = new node; temp->data = data; temp->left = temp->right = NULL; return (temp);} // Returns count of nodes in BST in range [low, high]int getCount(node *root, int low, int high){ // Base case if (!root) return 0; // Special Optional case for improving efficiency if (root->data == high && root->data == low) return 1; // If current node is in range, then include it in count and // recur for left and right children of it if (root->data <= high && root->data >= low) return 1 + getCount(root->left, low, high) + getCount(root->right, low, high); // If current node is smaller than low, then recur for right // child else if (root->data < low) return getCount(root->right, low, high); // Else recur for left child else return getCount(root->left, low, high);} // Driver programint main(){ // Let us construct the BST shown in the above figure node *root = newNode(10); root->left = newNode(5); root->right = newNode(50); root->left->left = newNode(1); root->right->left = newNode(40); root->right->right = newNode(100); /* Let us constructed BST shown in above example 10 / \ 5 50 / / \ 1 40 100 */ int l = 5; int h = 45; cout << "Count of nodes between [" << l << ", " << h << "] is " << getCount(root, l, h); return 0;} // Java code to count BST nodes that// lie in a given rangeclass BinarySearchTree { /* Class containing left and right child of current node and key value*/ static class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; } } // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // Returns count of nodes in BST in // range [low, high] int getCount(Node node, int low, int high) { // Base Case if(node == null) return 0; // If current node is in range, then // include it in count and recur for // left and right children of it if(node.data >= low && node.data <= high) return 1 + this.getCount(node.left, low, high)+ this.getCount(node.right, low, high); // If current node is smaller than low, // then recur for right child else if(node.data < low) return this.getCount(node.right, low, high); // Else recur for left child else return this.getCount(node.left, low, high); } // Driver function public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); tree.root = new Node(10); tree.root.left = new Node(5); tree.root.right = new Node(50); tree.root.left.left = new Node(1); tree.root.right.left = new Node(40); tree.root.right.right = new Node(100); /* Let us constructed BST shown in above example 10 / \ 5 50 / / \ 1 40 100 */ int l=5; int h=45; System.out.println("Count of nodes between [" + l + ", " + h+ "] is " + tree.getCount(tree.root, l, h)); }}// This code is contributed by Kamal Rawal # Python3 program to count BST nodes# within a given range # Utility function to create new nodeclass newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Returns count of nodes in BST in# range [low, high]def getCount(root, low, high): # Base case if root == None: return 0 # Special Optional case for improving # efficiency if root.data == high and root.data == low: return 1 # If current node is in range, then # include it in count and recur for # left and right children of it if root.data <= high and root.data >= low: return (1 + getCount(root.left, low, high) + getCount(root.right, low, high)) # If current node is smaller than low, # then recur for right child elif root.data < low: return getCount(root.right, low, high) # Else recur for left child else: return getCount(root.left, low, high) # Driver Codeif __name__ == '__main__': # Let us construct the BST shown in # the above figure root = newNode(10) root.left = newNode(5) root.right = newNode(50) root.left.left = newNode(1) root.right.left = newNode(40) root.right.right = newNode(100) # Let us constructed BST shown in above example # 10 # / \ # 5 50 # / / \ # 1 40 100 l = 5 h = 45 print("Count of nodes between [", l, ", ", h,"] is ", getCount(root, l, h)) # This code is contributed by PranchalK using System; // C# code to count BST nodes that// lie in a given rangepublic class BinarySearchTree{ /* Class containing left and right child of current node and key value*/ public class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; } } // Root of BST public Node root; // Constructor public BinarySearchTree() { root = null; } // Returns count of nodes in BST in // range [low, high] public virtual int getCount(Node node, int low, int high) { // Base Case if (node == null) { return 0; } // If current node is in range, then // include it in count and recur for // left and right children of it if (node.data >= low && node.data <= high) { return 1 + this.getCount(node.left, low, high) + this.getCount(node.right, low, high); } // If current node is smaller than low, // then recur for right child else if (node.data < low) { return this.getCount(node.right, low, high); } // Else recur for left child else { return this.getCount(node.left, low, high); } } // Driver function public static void Main(string[] args) { BinarySearchTree tree = new BinarySearchTree(); tree.root = new Node(10); tree.root.left = new Node(5); tree.root.right = new Node(50); tree.root.left.left = new Node(1); tree.root.right.left = new Node(40); tree.root.right.right = new Node(100); /* Let us constructed BST shown in above example 10 / \ 5 50 / / \ 1 40 100 */ int l = 5; int h = 45; Console.WriteLine("Count of nodes between [" + l + ", " + h + "] is " + tree.getCount(tree.root, l, h)); }} // This code is contributed by Shrikant13 <script>// javascript code to count BST nodes that// lie in a given range /* * Class containing left and right child of current node and key value */ class Node { constructor(item) { this.data = item; this.left =this.right = null; } } // Root of BST var root = null; // Returns count of nodes in BST in // range [low, high] function getCount( node , low , high) { // Base Case if (node == null) return 0; // If current node is in range, then // include it in count and recur for // left and right children of it if (node.data >= low && node.data <= high) return 1 + this.getCount(node.left, low, high) + this.getCount(node.right, low, high); // If current node is smaller than low, // then recur for right child else if (node.data < low) return this.getCount(node.right, low, high); // Else recur for left child else return this.getCount(node.left, low, high); } // Driver function root = new Node(10); root.left = new Node(5); root.right = new Node(50); root.left.left = new Node(1); root.right.left = new Node(40); root.right.right = new Node(100); /* * Let us constructed BST shown in above example 10 / \ 5 50 / / \ 1 40 100 */ var l = 5; var h = 45; document.write("Count of nodes between [" + l + ", " + h + "] is " + getCount(root, l, h)); // This code contributed by aashish1995</script> Output: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Count of nodes between [5, 45] is 3 Time complexity of the above program is O(h + k) where h is height of BST and k is number of nodes in given range. https://youtu.be/jfk -uX_xKK4?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbkThis article is contributed by Gaurav Ahirwar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shrikanth13 PranchalKatiyar GauravRajput1 rkbhola5 simmytarika5 D-E-Shaw Google Binary Search Tree Tree D-E-Shaw Google Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find postorder traversal of BST from preorder traversal Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Lowest Common Ancestor in a Binary Search Tree. Optimal Binary Search Tree | DP-24 Merge Two Balanced Binary Search Trees Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal Introduction to Data Structures Introduction to Tree Data Structure
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Feb, 2022" }, { "code": null, "e": 160, "s": 52, "text": "Given a Binary Search Tree (BST) and a range, count number of nodes that lie in the given range.Examples: " }, { "code": null, "e": 312, "s": 160, "text": "Input:\n 10\n / \\\n 5 50\n / / \\\n 1 40 100\nRange: [5, 45]\n\nOutput: 3\nThere are three nodes in range, 5, 10 and 40" }, { "code": null, "e": 667, "s": 314, "text": "The idea is to traverse the given binary search tree starting from root. For every node being visited, check if this node lies in range, if yes, then add 1 to result and recur for both of its children. If current node is smaller than low value of range, then recur for right child, else recur for left child.Below is the implementation of above idea. " }, { "code": null, "e": 671, "s": 667, "text": "C++" }, { "code": null, "e": 676, "s": 671, "text": "Java" }, { "code": null, "e": 684, "s": 676, "text": "Python3" }, { "code": null, "e": 687, "s": 684, "text": "C#" }, { "code": null, "e": 698, "s": 687, "text": "Javascript" }, { "code": "// C++ program to count BST nodes within a given range#include<bits/stdc++.h>using namespace std; // A BST nodestruct node{ int data; struct node* left, *right;}; // Utility function to create new nodenode *newNode(int data){ node *temp = new node; temp->data = data; temp->left = temp->right = NULL; return (temp);} // Returns count of nodes in BST in range [low, high]int getCount(node *root, int low, int high){ // Base case if (!root) return 0; // Special Optional case for improving efficiency if (root->data == high && root->data == low) return 1; // If current node is in range, then include it in count and // recur for left and right children of it if (root->data <= high && root->data >= low) return 1 + getCount(root->left, low, high) + getCount(root->right, low, high); // If current node is smaller than low, then recur for right // child else if (root->data < low) return getCount(root->right, low, high); // Else recur for left child else return getCount(root->left, low, high);} // Driver programint main(){ // Let us construct the BST shown in the above figure node *root = newNode(10); root->left = newNode(5); root->right = newNode(50); root->left->left = newNode(1); root->right->left = newNode(40); root->right->right = newNode(100); /* Let us constructed BST shown in above example 10 / \\ 5 50 / / \\ 1 40 100 */ int l = 5; int h = 45; cout << \"Count of nodes between [\" << l << \", \" << h << \"] is \" << getCount(root, l, h); return 0;}", "e": 2376, "s": 698, "text": null }, { "code": "// Java code to count BST nodes that// lie in a given rangeclass BinarySearchTree { /* Class containing left and right child of current node and key value*/ static class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; } } // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // Returns count of nodes in BST in // range [low, high] int getCount(Node node, int low, int high) { // Base Case if(node == null) return 0; // If current node is in range, then // include it in count and recur for // left and right children of it if(node.data >= low && node.data <= high) return 1 + this.getCount(node.left, low, high)+ this.getCount(node.right, low, high); // If current node is smaller than low, // then recur for right child else if(node.data < low) return this.getCount(node.right, low, high); // Else recur for left child else return this.getCount(node.left, low, high); } // Driver function public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); tree.root = new Node(10); tree.root.left = new Node(5); tree.root.right = new Node(50); tree.root.left.left = new Node(1); tree.root.right.left = new Node(40); tree.root.right.right = new Node(100); /* Let us constructed BST shown in above example 10 / \\ 5 50 / / \\ 1 40 100 */ int l=5; int h=45; System.out.println(\"Count of nodes between [\" + l + \", \" + h+ \"] is \" + tree.getCount(tree.root, l, h)); }}// This code is contributed by Kamal Rawal", "e": 4363, "s": 2376, "text": null }, { "code": "# Python3 program to count BST nodes# within a given range # Utility function to create new nodeclass newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Returns count of nodes in BST in# range [low, high]def getCount(root, low, high): # Base case if root == None: return 0 # Special Optional case for improving # efficiency if root.data == high and root.data == low: return 1 # If current node is in range, then # include it in count and recur for # left and right children of it if root.data <= high and root.data >= low: return (1 + getCount(root.left, low, high) + getCount(root.right, low, high)) # If current node is smaller than low, # then recur for right child elif root.data < low: return getCount(root.right, low, high) # Else recur for left child else: return getCount(root.left, low, high) # Driver Codeif __name__ == '__main__': # Let us construct the BST shown in # the above figure root = newNode(10) root.left = newNode(5) root.right = newNode(50) root.left.left = newNode(1) root.right.left = newNode(40) root.right.right = newNode(100) # Let us constructed BST shown in above example # 10 # / \\ # 5 50 # / / \\ # 1 40 100 l = 5 h = 45 print(\"Count of nodes between [\", l, \", \", h,\"] is \", getCount(root, l, h)) # This code is contributed by PranchalK", "e": 5961, "s": 4363, "text": null }, { "code": "using System; // C# code to count BST nodes that// lie in a given rangepublic class BinarySearchTree{ /* Class containing left and right child of current node and key value*/ public class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; } } // Root of BST public Node root; // Constructor public BinarySearchTree() { root = null; } // Returns count of nodes in BST in // range [low, high] public virtual int getCount(Node node, int low, int high) { // Base Case if (node == null) { return 0; } // If current node is in range, then // include it in count and recur for // left and right children of it if (node.data >= low && node.data <= high) { return 1 + this.getCount(node.left, low, high) + this.getCount(node.right, low, high); } // If current node is smaller than low, // then recur for right child else if (node.data < low) { return this.getCount(node.right, low, high); } // Else recur for left child else { return this.getCount(node.left, low, high); } } // Driver function public static void Main(string[] args) { BinarySearchTree tree = new BinarySearchTree(); tree.root = new Node(10); tree.root.left = new Node(5); tree.root.right = new Node(50); tree.root.left.left = new Node(1); tree.root.right.left = new Node(40); tree.root.right.right = new Node(100); /* Let us constructed BST shown in above example 10 / \\ 5 50 / / \\ 1 40 100 */ int l = 5; int h = 45; Console.WriteLine(\"Count of nodes between [\" + l + \", \" + h + \"] is \" + tree.getCount(tree.root, l, h)); }} // This code is contributed by Shrikant13", "e": 7978, "s": 5961, "text": null }, { "code": "<script>// javascript code to count BST nodes that// lie in a given range /* * Class containing left and right child of current node and key value */ class Node { constructor(item) { this.data = item; this.left =this.right = null; } } // Root of BST var root = null; // Returns count of nodes in BST in // range [low, high] function getCount( node , low , high) { // Base Case if (node == null) return 0; // If current node is in range, then // include it in count and recur for // left and right children of it if (node.data >= low && node.data <= high) return 1 + this.getCount(node.left, low, high) + this.getCount(node.right, low, high); // If current node is smaller than low, // then recur for right child else if (node.data < low) return this.getCount(node.right, low, high); // Else recur for left child else return this.getCount(node.left, low, high); } // Driver function root = new Node(10); root.left = new Node(5); root.right = new Node(50); root.left.left = new Node(1); root.right.left = new Node(40); root.right.right = new Node(100); /* * Let us constructed BST shown in above example 10 / \\ 5 50 / / \\ 1 40 100 */ var l = 5; var h = 45; document.write(\"Count of nodes between [\" + l + \", \" + h + \"] is \" + getCount(root, l, h)); // This code contributed by aashish1995</script>", "e": 9585, "s": 7978, "text": null }, { "code": null, "e": 9594, "s": 9585, "text": "Output: " }, { "code": null, "e": 9603, "s": 9594, "text": "Chapters" }, { "code": null, "e": 9630, "s": 9603, "text": "descriptions off, selected" }, { "code": null, "e": 9680, "s": 9630, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 9703, "s": 9680, "text": "captions off, selected" }, { "code": null, "e": 9711, "s": 9703, "text": "English" }, { "code": null, "e": 9735, "s": 9711, "text": "This is a modal window." }, { "code": null, "e": 9804, "s": 9735, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 9826, "s": 9804, "text": "End of dialog window." }, { "code": null, "e": 9862, "s": 9826, "text": "Count of nodes between [5, 45] is 3" }, { "code": null, "e": 9978, "s": 9862, "text": "Time complexity of the above program is O(h + k) where h is height of BST and k is number of nodes in given range. " }, { "code": null, "e": 9999, "s": 9978, "text": "https://youtu.be/jfk" }, { "code": null, "e": 10220, "s": 9999, "text": "-uX_xKK4?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbkThis article is contributed by Gaurav Ahirwar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 10232, "s": 10220, "text": "shrikanth13" }, { "code": null, "e": 10248, "s": 10232, "text": "PranchalKatiyar" }, { "code": null, "e": 10262, "s": 10248, "text": "GauravRajput1" }, { "code": null, "e": 10271, "s": 10262, "text": "rkbhola5" }, { "code": null, "e": 10284, "s": 10271, "text": "simmytarika5" }, { "code": null, "e": 10293, "s": 10284, "text": "D-E-Shaw" }, { "code": null, "e": 10300, "s": 10293, "text": "Google" }, { "code": null, "e": 10319, "s": 10300, "text": "Binary Search Tree" }, { "code": null, "e": 10324, "s": 10319, "text": "Tree" }, { "code": null, "e": 10333, "s": 10324, "text": "D-E-Shaw" }, { "code": null, "e": 10340, "s": 10333, "text": "Google" }, { "code": null, "e": 10359, "s": 10340, "text": "Binary Search Tree" }, { "code": null, "e": 10364, "s": 10359, "text": "Tree" }, { "code": null, "e": 10462, "s": 10364, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10518, "s": 10462, "text": "Find postorder traversal of BST from preorder traversal" }, { "code": null, "e": 10588, "s": 10518, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 10636, "s": 10588, "text": "Lowest Common Ancestor in a Binary Search Tree." }, { "code": null, "e": 10671, "s": 10636, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 10710, "s": 10671, "text": "Merge Two Balanced Binary Search Trees" }, { "code": null, "e": 10760, "s": 10710, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 10795, "s": 10760, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 10829, "s": 10795, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 10861, "s": 10829, "text": "Introduction to Data Structures" } ]
Python – Right and Left Shift characters in String
22 Apr, 2020 Sometimes, while working with Python Strings, we can have problem in which we have both right and left rotate count of characters in String and would like to know the resultant condition of String. This type of problem occurs in competitive programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using String multiplication + string slicingThe combination of above functions can be used to perform this task. In this, we multiple string thrice, perform the concatenation and selectively slice string to get required result. # Python3 code to demonstrate working of # Right and Left Shift characters in String# Using String multiplication + string slicing # initializing stringtest_str = 'geeksforgeeks' # printing original stringprint("The original string is : " + test_str) # initializing right rot r_rot = 7 # initializing left rot l_rot = 3 # Right and Left Shift characters in String# Using String multiplication + string slicingres = (test_str * 3)[len(test_str) + r_rot - l_rot : 2 * len(test_str) + r_rot - l_rot] # printing result print("The string after rotation is : " + str(res)) The original string is : geeksforgeeks The string after rotation is : sforgeeksgeek Method #2 : Using % operator and string slicingThe combination of above functionalities can also be used to perform this task. In this, we find the mod of rotation difference with length to compute the string position. # Python3 code to demonstrate working of # Right and Left Shift characters in String# Using % operator and string slicing # initializing stringtest_str = 'geeksforgeeks' # printing original stringprint("The original string is : " + test_str) # initializing right rot r_rot = 7 # initializing left rot l_rot = 3 # Right and Left Shift characters in String# Using % operator and string slicingtemp = (r_rot - l_rot) % len(test_str)res = test_str[temp : ] + test_str[ : temp] # printing result print("The string after rotation is : " + str(res)) The original string is : geeksforgeeks The string after rotation is : sforgeeksgeek Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 345, "s": 28, "text": "Sometimes, while working with Python Strings, we can have problem in which we have both right and left rotate count of characters in String and would like to know the resultant condition of String. This type of problem occurs in competitive programming. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 585, "s": 345, "text": "Method #1 : Using String multiplication + string slicingThe combination of above functions can be used to perform this task. In this, we multiple string thrice, perform the concatenation and selectively slice string to get required result." }, { "code": "# Python3 code to demonstrate working of # Right and Left Shift characters in String# Using String multiplication + string slicing # initializing stringtest_str = 'geeksforgeeks' # printing original stringprint(\"The original string is : \" + test_str) # initializing right rot r_rot = 7 # initializing left rot l_rot = 3 # Right and Left Shift characters in String# Using String multiplication + string slicingres = (test_str * 3)[len(test_str) + r_rot - l_rot : 2 * len(test_str) + r_rot - l_rot] # printing result print(\"The string after rotation is : \" + str(res)) ", "e": 1177, "s": 585, "text": null }, { "code": null, "e": 1262, "s": 1177, "text": "The original string is : geeksforgeeks\nThe string after rotation is : sforgeeksgeek\n" }, { "code": null, "e": 1483, "s": 1264, "text": "Method #2 : Using % operator and string slicingThe combination of above functionalities can also be used to perform this task. In this, we find the mod of rotation difference with length to compute the string position." }, { "code": "# Python3 code to demonstrate working of # Right and Left Shift characters in String# Using % operator and string slicing # initializing stringtest_str = 'geeksforgeeks' # printing original stringprint(\"The original string is : \" + test_str) # initializing right rot r_rot = 7 # initializing left rot l_rot = 3 # Right and Left Shift characters in String# Using % operator and string slicingtemp = (r_rot - l_rot) % len(test_str)res = test_str[temp : ] + test_str[ : temp] # printing result print(\"The string after rotation is : \" + str(res)) ", "e": 2033, "s": 1483, "text": null }, { "code": null, "e": 2118, "s": 2033, "text": "The original string is : geeksforgeeks\nThe string after rotation is : sforgeeksgeek\n" }, { "code": null, "e": 2141, "s": 2118, "text": "Python string-programs" }, { "code": null, "e": 2148, "s": 2141, "text": "Python" }, { "code": null, "e": 2164, "s": 2148, "text": "Python Programs" }, { "code": null, "e": 2262, "s": 2164, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2280, "s": 2262, "text": "Python Dictionary" }, { "code": null, "e": 2322, "s": 2280, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2344, "s": 2322, "text": "Enumerate() in Python" }, { "code": null, "e": 2379, "s": 2344, "text": "Read a file line by line in Python" }, { "code": null, "e": 2405, "s": 2379, "text": "Python String | replace()" }, { "code": null, "e": 2448, "s": 2405, "text": "Python program to convert a list to string" }, { "code": null, "e": 2470, "s": 2448, "text": "Defaultdict in Python" }, { "code": null, "e": 2509, "s": 2470, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2547, "s": 2509, "text": "Python | Convert a list to dictionary" } ]
Using NumPy to Convert Array Elements to Float Type
02 Sep, 2020 There are often times when it is necessary for us to convert an array in Python to a differing type. One of these times would be when given an array and having to convert it to an array of float types. This is often useful when conducting data analysis and there are a variety of ways of doing this. Whilst iterating through the array and using Python’s inbuilt float() casting function is perfectly valid, NumPy offers us some even more elegant ways to conduct the same procedure. Method 1 : Here, we can utilize the astype() function that is offered by NumPy. This function creates another copy of the initial array with the specified data type, float in this case, and we can then assign this copy to a specific identifier, which is convertedArray. Note that the data type is specified in terms of NumPy, mainly because of the constraints of the NumPy astype() function, which will only take NumPy types as parameters. # Process utilizing astype() function # Import NumPy Libraryimport numpy as np # Initialize our Array with Strings# The String Type is denoted by the quotes ""initialArray = ["1.1", "2.2", "3.3", "4.4"] # Convert initial Array to NumPy Array# Use the array() functionsampleArray = np.array(initialArray) # Print our Initial Arrayprint("Our initial array: ", str(initialArray))print("Original type: " + str(type(initialArray[0]))) # Actual Conversion of Array# Note usage of astype() function# np.float can be changed to represent differing typesconvertedArray = sampleArray.astype(np.float) # Print our final result# Note that usage of str() is due to Python conventionsprint("Our final array: ", str(convertedArray))print("Final type: " + str(type(convertedArray[0]))) Output : Our initial array: ['1.1', '2.2', '3.3', '4.4'] Original type: <class 'numpy.str_'> Our final array: [1.1 2.2 3.3 4.4] Final type: <class 'numpy.float64'> Method 2 : Here, we will utilize the asarray() function that is offered by NumPy. # Process utilizing asarray() function # Import NumPy Libraryimport numpy as np # Initialize our array# Note, once again, that this is of type String# Non-NumPy arrays can be usedinitialArray = np.array(["1.1", "2.2", "3.3", "4.4"]) # Print our initial arrayprint("Our Initial Array: ", str(initialArray))print("Original type: " + str(type(initialArray[0]))) # Actual conversion of array# Note that we utilize np.float64 as the finalize data typefinalArray = np.asarray(initialArray, dtype = np.float64, order ='C') # Print our converted arrayprint("Our Final Array: ", str(finalArray))print("Final type: " + str(type(finalArray[0]))) Output : Our initial array: ['1.1', '2.2', '3.3', '4.4'] Original type: <class 'numpy.str_'> Our final array: [1.1 2.2 3.3 4.4] Final type: <class 'numpy.float64'> Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 510, "s": 28, "text": "There are often times when it is necessary for us to convert an array in Python to a differing type. One of these times would be when given an array and having to convert it to an array of float types. This is often useful when conducting data analysis and there are a variety of ways of doing this. Whilst iterating through the array and using Python’s inbuilt float() casting function is perfectly valid, NumPy offers us some even more elegant ways to conduct the same procedure." }, { "code": null, "e": 950, "s": 510, "text": "Method 1 : Here, we can utilize the astype() function that is offered by NumPy. This function creates another copy of the initial array with the specified data type, float in this case, and we can then assign this copy to a specific identifier, which is convertedArray. Note that the data type is specified in terms of NumPy, mainly because of the constraints of the NumPy astype() function, which will only take NumPy types as parameters." }, { "code": "# Process utilizing astype() function # Import NumPy Libraryimport numpy as np # Initialize our Array with Strings# The String Type is denoted by the quotes \"\"initialArray = [\"1.1\", \"2.2\", \"3.3\", \"4.4\"] # Convert initial Array to NumPy Array# Use the array() functionsampleArray = np.array(initialArray) # Print our Initial Arrayprint(\"Our initial array: \", str(initialArray))print(\"Original type: \" + str(type(initialArray[0]))) # Actual Conversion of Array# Note usage of astype() function# np.float can be changed to represent differing typesconvertedArray = sampleArray.astype(np.float) # Print our final result# Note that usage of str() is due to Python conventionsprint(\"Our final array: \", str(convertedArray))print(\"Final type: \" + str(type(convertedArray[0])))", "e": 1726, "s": 950, "text": null }, { "code": null, "e": 1735, "s": 1726, "text": "Output :" }, { "code": null, "e": 1893, "s": 1735, "text": "Our initial array: ['1.1', '2.2', '3.3', '4.4']\nOriginal type: <class 'numpy.str_'>\nOur final array: [1.1 2.2 3.3 4.4]\nFinal type: <class 'numpy.float64'>\n" }, { "code": null, "e": 1975, "s": 1893, "text": "Method 2 : Here, we will utilize the asarray() function that is offered by NumPy." }, { "code": "# Process utilizing asarray() function # Import NumPy Libraryimport numpy as np # Initialize our array# Note, once again, that this is of type String# Non-NumPy arrays can be usedinitialArray = np.array([\"1.1\", \"2.2\", \"3.3\", \"4.4\"]) # Print our initial arrayprint(\"Our Initial Array: \", str(initialArray))print(\"Original type: \" + str(type(initialArray[0]))) # Actual conversion of array# Note that we utilize np.float64 as the finalize data typefinalArray = np.asarray(initialArray, dtype = np.float64, order ='C') # Print our converted arrayprint(\"Our Final Array: \", str(finalArray))print(\"Final type: \" + str(type(finalArray[0])))", "e": 2639, "s": 1975, "text": null }, { "code": null, "e": 2648, "s": 2639, "text": "Output :" }, { "code": null, "e": 2806, "s": 2648, "text": "Our initial array: ['1.1', '2.2', '3.3', '4.4']\nOriginal type: <class 'numpy.str_'>\nOur final array: [1.1 2.2 3.3 4.4]\nFinal type: <class 'numpy.float64'>\n" }, { "code": null, "e": 2837, "s": 2806, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 2850, "s": 2837, "text": "Python-numpy" }, { "code": null, "e": 2857, "s": 2850, "text": "Python" }, { "code": null, "e": 2955, "s": 2857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2987, "s": 2955, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3014, "s": 2987, "text": "Python Classes and Objects" }, { "code": null, "e": 3035, "s": 3014, "text": "Python OOPs Concepts" }, { "code": null, "e": 3058, "s": 3035, "text": "Introduction To PYTHON" }, { "code": null, "e": 3114, "s": 3058, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3145, "s": 3114, "text": "Python | os.path.join() method" }, { "code": null, "e": 3187, "s": 3145, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3229, "s": 3187, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3268, "s": 3229, "text": "Python | Get unique values from a list" } ]
Program to find the transpose of given matrix in Python
Suppose we have a (n by n) matrix M, we have to find its transpose. As we know the transpose of a matrix switches the row and column indices. More formally, for every r and c, matrix[r][c] = matrix[c][r]. So, if the input is like then the output will be To solve this, we will follow these steps − M := a new list tracker := 0 while tracker < row count of matrix, dotemp := a new listfor each row in matrix, dotemp := join temp and a list with element row[tracker]M := M join another list with element temptracker := tracker + 1 temp := a new list for each row in matrix, dotemp := join temp and a list with element row[tracker] temp := join temp and a list with element row[tracker] M := M join another list with element temp tracker := tracker + 1 return M Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, matrix): M = [] tracker = 0 while tracker < len(matrix): temp = [] for row in matrix: temp += [row[tracker]] M += [temp] tracker += 1 return M ob = Solution() matrix = [ [7, 2, 6], [3, 7, 2], [5, 3, 7] ] print(ob.solve(matrix)) [[7, 2, 6], [3, 7, 2], [5, 3, 7]] [[7, 3, 5], [2, 7, 3],[6, 2, 7]]
[ { "code": null, "e": 1392, "s": 1187, "text": "Suppose we have a (n by n) matrix M, we have to find its transpose. As we know the transpose of a matrix switches the row and column indices. More formally, for every r and c, matrix[r][c] = matrix[c][r]." }, { "code": null, "e": 1417, "s": 1392, "text": "So, if the input is like" }, { "code": null, "e": 1441, "s": 1417, "text": "then the output will be" }, { "code": null, "e": 1485, "s": 1441, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1501, "s": 1485, "text": "M := a new list" }, { "code": null, "e": 1514, "s": 1501, "text": "tracker := 0" }, { "code": null, "e": 1716, "s": 1514, "text": "while tracker < row count of matrix, dotemp := a new listfor each row in matrix, dotemp := join temp and a list with element row[tracker]M := M join another list with element temptracker := tracker + 1" }, { "code": null, "e": 1735, "s": 1716, "text": "temp := a new list" }, { "code": null, "e": 1816, "s": 1735, "text": "for each row in matrix, dotemp := join temp and a list with element row[tracker]" }, { "code": null, "e": 1871, "s": 1816, "text": "temp := join temp and a list with element row[tracker]" }, { "code": null, "e": 1914, "s": 1871, "text": "M := M join another list with element temp" }, { "code": null, "e": 1937, "s": 1914, "text": "tracker := tracker + 1" }, { "code": null, "e": 1946, "s": 1937, "text": "return M" }, { "code": null, "e": 2016, "s": 1946, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2027, "s": 2016, "text": " Live Demo" }, { "code": null, "e": 2362, "s": 2027, "text": "class Solution:\n def solve(self, matrix):\n M = []\n tracker = 0\n while tracker < len(matrix):\n temp = []\n for row in matrix:\n temp += [row[tracker]]\n M += [temp]\n tracker += 1\n return M\nob = Solution()\nmatrix = [ [7, 2, 6], [3, 7, 2], [5, 3, 7] ]\nprint(ob.solve(matrix))" }, { "code": null, "e": 2396, "s": 2362, "text": "[[7, 2, 6],\n[3, 7, 2],\n[5, 3, 7]]" }, { "code": null, "e": 2429, "s": 2396, "text": "[[7, 3, 5], [2, 7, 3],[6, 2, 7]]" } ]
Scanner useDelimiter() method in Java with Examples
23 Nov, 2020 The useDelimiter(Pattern pattern) method of java.util.Scanner class sets this scanner’s delimiting pattern to the specified pattern. Syntax: public Scanner useDelimiter(Pattern pattern) Parameter: The function accepts a mandatory parameter pattern which specifies a delimiting pattern. Return Value: The function returns this scanner. Below programs illustrate the above function: Program 1: Java // Java program to illustrate the useDelimiter(Pattern Pattern)// method of Scanner class in Java import java.util.*;import java.util.regex.Pattern; public class GFG1 { public static void main(String[] argv) throws Exception { String s = "Geeksforgeeks has Scanner Class Methods"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // print a line of the scanner System.out.println("Scanner String: \n" + scanner.nextLine()); // display the old delimiter System.out.println("Old delimiter: " + scanner.delimiter()); // change the delimiter of this scanner scanner.useDelimiter(Pattern.compile(".ll.")); // display the new delimiter System.out.println("New delimiter: " + scanner.delimiter()); // close the scanner scanner.close(); }} Scanner String: Geeksforgeeks has Scanner Class Methods Old delimiter: \p{javaWhitespace}+ New delimiter: .ll. The useDelimiter(String pattern) method of java.util.Scanner class Sets this scanner’s delimiting pattern to a pattern constructed from the specified String. Syntax: public Scanner useDelimiter(String pattern) Parameter: The function accepts a mandatory parameter string pattern which specifies a delimiting pattern. Return Value: The function returns this scanner. Below programs illustrate the above function: Program 1: Java // Java program to illustrate the useDelimter(String Pattern)// method of Scanner class in Java import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = "Geeksforgeeks has Scanner Class Methods"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // print a line of the scanner System.out.println("Scanner String: \n" + scanner.nextLine()); // print the old delimiter System.out.println("Old Delimiter: " + scanner.delimiter()); // change the delimiter scanner.useDelimiter("Wor"); // print the new delimiter System.out.println("New Delimiter: " + scanner.delimiter()); // close the scanner scanner.close(); }} Scanner String: Geeksforgeeks has Scanner Class Methods Old Delimiter: \p{javaWhitespace}+ New Delimiter: Wor Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String) arorakashish0911 Java - util package Java-Library 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": "\n23 Nov, 2020" }, { "code": null, "e": 187, "s": 54, "text": "The useDelimiter(Pattern pattern) method of java.util.Scanner class sets this scanner’s delimiting pattern to the specified pattern." }, { "code": null, "e": 196, "s": 187, "text": "Syntax: " }, { "code": null, "e": 242, "s": 196, "text": "public Scanner useDelimiter(Pattern pattern)\n" }, { "code": null, "e": 342, "s": 242, "text": "Parameter: The function accepts a mandatory parameter pattern which specifies a delimiting pattern." }, { "code": null, "e": 391, "s": 342, "text": "Return Value: The function returns this scanner." }, { "code": null, "e": 437, "s": 391, "text": "Below programs illustrate the above function:" }, { "code": null, "e": 450, "s": 437, "text": "Program 1: " }, { "code": null, "e": 455, "s": 450, "text": "Java" }, { "code": "// Java program to illustrate the useDelimiter(Pattern Pattern)// method of Scanner class in Java import java.util.*;import java.util.regex.Pattern; public class GFG1 { public static void main(String[] argv) throws Exception { String s = \"Geeksforgeeks has Scanner Class Methods\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // print a line of the scanner System.out.println(\"Scanner String: \\n\" + scanner.nextLine()); // display the old delimiter System.out.println(\"Old delimiter: \" + scanner.delimiter()); // change the delimiter of this scanner scanner.useDelimiter(Pattern.compile(\".ll.\")); // display the new delimiter System.out.println(\"New delimiter: \" + scanner.delimiter()); // close the scanner scanner.close(); }}", "e": 1431, "s": 455, "text": null }, { "code": null, "e": 1547, "s": 1431, "text": "Scanner String: \nGeeksforgeeks has Scanner Class Methods\nOld delimiter: \\p{javaWhitespace}+\nNew delimiter: .ll.\n\n\n\n" }, { "code": null, "e": 1707, "s": 1549, "text": "The useDelimiter(String pattern) method of java.util.Scanner class Sets this scanner’s delimiting pattern to a pattern constructed from the specified String." }, { "code": null, "e": 1717, "s": 1707, "text": "Syntax: " }, { "code": null, "e": 1762, "s": 1717, "text": "public Scanner useDelimiter(String pattern)\n" }, { "code": null, "e": 1869, "s": 1762, "text": "Parameter: The function accepts a mandatory parameter string pattern which specifies a delimiting pattern." }, { "code": null, "e": 1918, "s": 1869, "text": "Return Value: The function returns this scanner." }, { "code": null, "e": 1964, "s": 1918, "text": "Below programs illustrate the above function:" }, { "code": null, "e": 1977, "s": 1964, "text": "Program 1: " }, { "code": null, "e": 1982, "s": 1977, "text": "Java" }, { "code": "// Java program to illustrate the useDelimter(String Pattern)// method of Scanner class in Java import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = \"Geeksforgeeks has Scanner Class Methods\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // print a line of the scanner System.out.println(\"Scanner String: \\n\" + scanner.nextLine()); // print the old delimiter System.out.println(\"Old Delimiter: \" + scanner.delimiter()); // change the delimiter scanner.useDelimiter(\"Wor\"); // print the new delimiter System.out.println(\"New Delimiter: \" + scanner.delimiter()); // close the scanner scanner.close(); }}", "e": 2887, "s": 1982, "text": null }, { "code": null, "e": 3002, "s": 2887, "text": "Scanner String: \nGeeksforgeeks has Scanner Class Methods\nOld Delimiter: \\p{javaWhitespace}+\nNew Delimiter: Wor\n\n\n\n" }, { "code": null, "e": 3112, "s": 3004, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String) " }, { "code": null, "e": 3129, "s": 3112, "text": "arorakashish0911" }, { "code": null, "e": 3149, "s": 3129, "text": "Java - util package" }, { "code": null, "e": 3162, "s": 3149, "text": "Java-Library" }, { "code": null, "e": 3167, "s": 3162, "text": "Java" }, { "code": null, "e": 3172, "s": 3167, "text": "Java" } ]
How to setup 404 page in angular routing ?
26 May, 2021 To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred. In the following approach, we will create a simple angular component called PagenotfoundComponent. Creating Component: Run the below command to create pagenotfound component. ng generate component pagenotfound Project Structure: It will look like this. Implementation: Add the below code inside HTML template of this component to display a simple 404 error message. pagenotfound.component.html <div> <h1>404 Error</h1> <h1>Page Not Found</h1></div> Then inside the routing file, we have to provide this component route and make this available for every 404 requests. So, inside the app-routing.module.ts file, we have to create a new route for this PagenotfoundComponent. app-routing.module.ts import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { PagenotfoundComponent } from './pagenotfound/pagenotfound.component';import { PostCreateComponent } from './posts/post-create/post-create.component';import { PostListComponent } from './posts/post-list/post-list.component'; const routes: Routes = [ { path: '', component: PostListComponent }, { path: 'create', component: PostCreateComponent }, { path: 'edit/:postId', component: PostCreateComponent }, //Wild Card Route for 404 request { path: '**', pathMatch: 'full', component: PagenotfoundComponent }, ];@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: []})export class AppRoutingModule { } Explanation: Here the route for PagenotfoundComponent is provided inside the routes array. Here any path except the provided routes is handled by this PagenotfoundComponent and our HTML template is displayed in the browser. So now if someone tries to send a request to any page that is not present in the routes array then that user is automatically navigated to this PagenotfoundComponent. Steps to run the application: Run the following command to start the application: ng serve Now open the browser and go to http://localhost:4200, where everything is working fine. Now go to http://localhost:4200/anything, where we will get the 404 error as shown below. AngularJS-Function AngularJS-Questions Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Routing in Angular 9/10 Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? 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": "\n26 May, 2021" }, { "code": null, "e": 251, "s": 28, "text": "To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred. In the following approach, we will create a simple angular component called PagenotfoundComponent. " }, { "code": null, "e": 327, "s": 251, "text": "Creating Component: Run the below command to create pagenotfound component." }, { "code": null, "e": 362, "s": 327, "text": "ng generate component pagenotfound" }, { "code": null, "e": 405, "s": 362, "text": "Project Structure: It will look like this." }, { "code": null, "e": 518, "s": 405, "text": "Implementation: Add the below code inside HTML template of this component to display a simple 404 error message." }, { "code": null, "e": 546, "s": 518, "text": "pagenotfound.component.html" }, { "code": "<div> <h1>404 Error</h1> <h1>Page Not Found</h1></div>", "e": 607, "s": 546, "text": null }, { "code": null, "e": 830, "s": 607, "text": "Then inside the routing file, we have to provide this component route and make this available for every 404 requests. So, inside the app-routing.module.ts file, we have to create a new route for this PagenotfoundComponent." }, { "code": null, "e": 852, "s": 830, "text": "app-routing.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { PagenotfoundComponent } from './pagenotfound/pagenotfound.component';import { PostCreateComponent } from './posts/post-create/post-create.component';import { PostListComponent } from './posts/post-list/post-list.component'; const routes: Routes = [ { path: '', component: PostListComponent }, { path: 'create', component: PostCreateComponent }, { path: 'edit/:postId', component: PostCreateComponent }, //Wild Card Route for 404 request { path: '**', pathMatch: 'full', component: PagenotfoundComponent }, ];@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: []})export class AppRoutingModule { }", "e": 1648, "s": 852, "text": null }, { "code": null, "e": 2039, "s": 1648, "text": "Explanation: Here the route for PagenotfoundComponent is provided inside the routes array. Here any path except the provided routes is handled by this PagenotfoundComponent and our HTML template is displayed in the browser. So now if someone tries to send a request to any page that is not present in the routes array then that user is automatically navigated to this PagenotfoundComponent." }, { "code": null, "e": 2121, "s": 2039, "text": "Steps to run the application: Run the following command to start the application:" }, { "code": null, "e": 2130, "s": 2121, "text": "ng serve" }, { "code": null, "e": 2308, "s": 2130, "text": "Now open the browser and go to http://localhost:4200, where everything is working fine. Now go to http://localhost:4200/anything, where we will get the 404 error as shown below." }, { "code": null, "e": 2327, "s": 2308, "text": "AngularJS-Function" }, { "code": null, "e": 2347, "s": 2327, "text": "AngularJS-Questions" }, { "code": null, "e": 2354, "s": 2347, "text": "Picked" }, { "code": null, "e": 2364, "s": 2354, "text": "AngularJS" }, { "code": null, "e": 2381, "s": 2364, "text": "Web Technologies" }, { "code": null, "e": 2479, "s": 2381, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2503, "s": 2479, "text": "Routing in Angular 9/10" }, { "code": null, "e": 2538, "s": 2503, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 2562, "s": 2538, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 2615, "s": 2562, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 2664, "s": 2615, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 2697, "s": 2664, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2759, "s": 2697, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2820, "s": 2759, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2870, "s": 2820, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
CSS text-align Property
09 Nov, 2021 The text-align property in CSS is used to specify the horizontal alignment of text in an element ie., it is used to set the alignment of the content horizontally, inside a block element or table-cell box. Syntax: text-align: left|right|center|justify|initial|inherit; Default Value : left if direction is ltr, and right if direction is rtl Property Value: left: It is used to set the text-alignment into left. This is the default property. right: It is used to set the text-alignment to right. center: It is used to set the text-alignment into the center. justify: It is used to spreads the words into the complete line i.e., by stretching the content of an element. initial: It is used to set an element’s CSS property to its default value. inherit: It is used to inherit a property to an element from its parent element property value. Please refer to the CSS Align article for further details. Example: This example illustrates the use of the text-align property, in order to align it to specified values. HTML <!DOCTYPE html><html><head> <title>text-align property</title> <style> h1 { color: green; } .main { border: 1px solid black; } .gfg1 { text-align: left; } .gfg2 { text-align: right; ; } .gfg3 { text-align: center; } .gfg4 { text-align: justify; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>text-align property</h2> <div class="main"> <h3>text-align: left;</h3> <div class="gfg1"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div> </div> <br> <div class="main"> <h3 style="text-align: right;">text-align: right;</h3> <div class="gfg2"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div> </div> <br> <div class="main"> <h3 style="text-align: center;">text-align: center;</h3> <div class="gfg3"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div> </div> <br> <div class="main"> <h3 style="text-align: justify;">text-align: justify;</h3> <div class="gfg4"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div> </div></body></html> Output: Supported Browsers: The browser supported by the text-align property are listed below: Google Chrome 1.0 Internet Explorer 3.0 Microsoft Edge 12.0 Firefox 1.0 Opera 3.5 Safari 1.0 arorakashish0911 bhaskargeeksforgeeks hritikbhatnagar2182 CSS-Properties CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form 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": "\n09 Nov, 2021" }, { "code": null, "e": 233, "s": 28, "text": "The text-align property in CSS is used to specify the horizontal alignment of text in an element ie., it is used to set the alignment of the content horizontally, inside a block element or table-cell box." }, { "code": null, "e": 241, "s": 233, "text": "Syntax:" }, { "code": null, "e": 296, "s": 241, "text": "text-align: left|right|center|justify|initial|inherit;" }, { "code": null, "e": 368, "s": 296, "text": "Default Value : left if direction is ltr, and right if direction is rtl" }, { "code": null, "e": 384, "s": 368, "text": "Property Value:" }, { "code": null, "e": 468, "s": 384, "text": "left: It is used to set the text-alignment into left. This is the default property." }, { "code": null, "e": 522, "s": 468, "text": "right: It is used to set the text-alignment to right." }, { "code": null, "e": 584, "s": 522, "text": "center: It is used to set the text-alignment into the center." }, { "code": null, "e": 695, "s": 584, "text": "justify: It is used to spreads the words into the complete line i.e., by stretching the content of an element." }, { "code": null, "e": 770, "s": 695, "text": "initial: It is used to set an element’s CSS property to its default value." }, { "code": null, "e": 866, "s": 770, "text": "inherit: It is used to inherit a property to an element from its parent element property value." }, { "code": null, "e": 925, "s": 866, "text": "Please refer to the CSS Align article for further details." }, { "code": null, "e": 1037, "s": 925, "text": "Example: This example illustrates the use of the text-align property, in order to align it to specified values." }, { "code": null, "e": 1042, "s": 1037, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>text-align property</title> <style> h1 { color: green; } .main { border: 1px solid black; } .gfg1 { text-align: left; } .gfg2 { text-align: right; ; } .gfg3 { text-align: center; } .gfg4 { text-align: justify; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>text-align property</h2> <div class=\"main\"> <h3>text-align: left;</h3> <div class=\"gfg1\"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div> </div> <br> <div class=\"main\"> <h3 style=\"text-align: right;\">text-align: right;</h3> <div class=\"gfg2\"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div> </div> <br> <div class=\"main\"> <h3 style=\"text-align: center;\">text-align: center;</h3> <div class=\"gfg3\"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div> </div> <br> <div class=\"main\"> <h3 style=\"text-align: justify;\">text-align: justify;</h3> <div class=\"gfg4\"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div> </div></body></html>", "e": 3241, "s": 1042, "text": null }, { "code": null, "e": 3250, "s": 3241, "text": "Output: " }, { "code": null, "e": 3338, "s": 3250, "text": "Supported Browsers: The browser supported by the text-align property are listed below: " }, { "code": null, "e": 3356, "s": 3338, "text": "Google Chrome 1.0" }, { "code": null, "e": 3378, "s": 3356, "text": "Internet Explorer 3.0" }, { "code": null, "e": 3398, "s": 3378, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 3410, "s": 3398, "text": "Firefox 1.0" }, { "code": null, "e": 3420, "s": 3410, "text": "Opera 3.5" }, { "code": null, "e": 3431, "s": 3420, "text": "Safari 1.0" }, { "code": null, "e": 3448, "s": 3431, "text": "arorakashish0911" }, { "code": null, "e": 3469, "s": 3448, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 3489, "s": 3469, "text": "hritikbhatnagar2182" }, { "code": null, "e": 3504, "s": 3489, "text": "CSS-Properties" }, { "code": null, "e": 3508, "s": 3504, "text": "CSS" }, { "code": null, "e": 3525, "s": 3508, "text": "Web Technologies" }, { "code": null, "e": 3623, "s": 3525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3671, "s": 3623, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3733, "s": 3671, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3783, "s": 3733, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3841, "s": 3783, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 3891, "s": 3841, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 3924, "s": 3891, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3986, "s": 3924, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4047, "s": 3986, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4097, "s": 4047, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Animated expanding card using framer-motion and ReactJS
17 Jan, 2022 In this article, we are going to learn how to create an animated expanding card using react and framer. Prerequisites: Knowledge of JavaScript (ES6).JavaScript inbuilt methods we are going to make use are :Arrow function (ES6)Ternary operatorObjects in JavaScriptKnowledge of HTML/CSS.Basic knowledge of ReactJS Knowledge of JavaScript (ES6).JavaScript inbuilt methods we are going to make use are :Arrow function (ES6)Ternary operatorObjects in JavaScript JavaScript inbuilt methods we are going to make use are : Arrow function (ES6)Ternary operatorObjects in JavaScript Arrow function (ES6) Ternary operator Objects in JavaScript Knowledge of HTML/CSS. Basic knowledge of ReactJS React hooks used in building this application are: React useState React useState Framer: components and hooks we are going to make use of in this tutorial are : https://www.framer.com/api/frame/https://www.framer.com/api/scroll/https://www.framer.com/api/utilities/#useanimation https://www.framer.com/api/frame/ https://www.framer.com/api/scroll/ https://www.framer.com/api/utilities/#useanimation Creating React Application And Installing Module : Step 1: Now, you will start a new project using create-react-app so open your terminal and type.$ npx create-react-app animated-card Step 1: Now, you will start a new project using create-react-app so open your terminal and type. $ npx create-react-app animated-card Step 2: After creating your project folder i.e. animated-card, move to it using the following command.$ cd animated-card Step 2: After creating your project folder i.e. animated-card, move to it using the following command. $ cd animated-card Step 3: Add the npm packages you will need during the project.$ npm install framer react-icons // For yarn $ yarn add framer react-icons Step 3: Add the npm packages you will need during the project. $ npm install framer react-icons // For yarn $ yarn add framer react-icons Open the src folder and delete the following files : logo.svgserviceWorker.jssetupTests.jsApp.cssApp.jsApp.test.js (if any) logo.svg serviceWorker.js setupTests.js App.css App.js App.test.js (if any) Create a file named Card.js. Project structure: Your project structure tree should look like this : Project structure Example: index.js import React from "react";import { Frame, Scroll } from "framer";import Card from "./Card";import ReactDOM from "react-dom"; import "./index.css"; // main App HOCexport const App = () => { return ( <Frame height={"100%"} width={"100%"} background={"#333"}> <Frame width={375} height={"100%"} background={"#FFF"} center> <Scroll width={375} height={"100%"}> {/* Card component with props yPos,title,subtitle */} <Card yPos={48} title={"GEEKSFORGEEKS"} subtitle="Don't learn alone" /> <Card yPos={48 + 300 + 24} title={"reactJS"} subtitle="Most starred JavaScript library" /> </Scroll> </Frame> </Frame> );}; const rootElement = document.getElementById("root");ReactDOM.render(<App />, rootElement); index.css body { margin: 0; cursor: pointer;} Card.js import React, { useState } from "react";import { ImCross } from "react-icons/im";import { Frame, Scroll, useAnimation } from "framer"; // Card component with destructured props :// yPos, title, subtitleconst Card = ({ yPos, title, subtitle }) => { // useState hook to manage the state of // expanding of card const [state, setState] = useState(false); // utility function to handle // onTap on card component const handleTap = () => { state ? controls.start({ y: 0 }) : setState(!state); }; const controls = useAnimation(); // Variants allow you to define animation // states and organise them by name. // They allow you to control animations // throughout a component // tree by switching a single animate prop. const variants = { active: { width: 320, height: 800, borderRadius: 0, overflow: "visible", left: 28, right:0, y: 0, transition: { duration: 0.125, type: "spring", damping: 10, mass: 0.6 } }, inactive: { width: 280, height: 280, borderRadius: 24, overflow: "hidden", left: 45, y: yPos, transition: { duration: 0.125, type: "spring", damping: 10, mass: 0.6 } } }; return ( // basic container for layout, styling, // animation and events. <Frame y={yPos} variants={variants} animate={state ? "active" : "inactive"} width={300} height={300} borderRadius={24} style={state ? { zIndex: 10 } : { zIndex: 1 }} left={37.5} onTap={handleTap} shadow={ state ? "0 0 0 0 rgba(0, 0, 0, 0)" : "0px 0px 20px 0px rgba(0, 0, 0, .25)" } > <Scroll width="100%" height="100%" backgroundColor={null} scrollAnimate={controls} > <Frame position="relative" backgroundColor={"#09a960"} width="100%" height={300} /> <Frame position="relative" height={1200} background="white" /> <Frame top={20} left={20} height={""} width={""} background={null} style={{ color: "white", fontFamily: "sans-serif" }} > <span style={{ fontSize: "1.6em", fontWeight: 600 }}> {title} </span> <br /> <span style={{ fontSize: "1em", fontWeight: 500, opacity: 0.5 }} > {subtitle} </span> </Frame> </Scroll> {state && ( <Frame borderRadius={20} size={15} top={15} right={20} backgroundColor={"#09a960"} onTap={() => { setState(false); }} > <ImCross color="red" /> </Frame> )} </Frame> );}; export default Card; Step to Run Application: Run the application using the following command from the root directory of the project. npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: adnanirshad158 CSS-Properties Framer-motion ReactJS 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": "\n17 Jan, 2022" }, { "code": null, "e": 132, "s": 28, "text": "In this article, we are going to learn how to create an animated expanding card using react and framer." }, { "code": null, "e": 147, "s": 132, "text": "Prerequisites:" }, { "code": null, "e": 340, "s": 147, "text": "Knowledge of JavaScript (ES6).JavaScript inbuilt methods we are going to make use are :Arrow function (ES6)Ternary operatorObjects in JavaScriptKnowledge of HTML/CSS.Basic knowledge of ReactJS" }, { "code": null, "e": 485, "s": 340, "text": "Knowledge of JavaScript (ES6).JavaScript inbuilt methods we are going to make use are :Arrow function (ES6)Ternary operatorObjects in JavaScript" }, { "code": null, "e": 543, "s": 485, "text": "JavaScript inbuilt methods we are going to make use are :" }, { "code": null, "e": 601, "s": 543, "text": "Arrow function (ES6)Ternary operatorObjects in JavaScript" }, { "code": null, "e": 622, "s": 601, "text": "Arrow function (ES6)" }, { "code": null, "e": 639, "s": 622, "text": "Ternary operator" }, { "code": null, "e": 661, "s": 639, "text": "Objects in JavaScript" }, { "code": null, "e": 684, "s": 661, "text": "Knowledge of HTML/CSS." }, { "code": null, "e": 711, "s": 684, "text": "Basic knowledge of ReactJS" }, { "code": null, "e": 762, "s": 711, "text": "React hooks used in building this application are:" }, { "code": null, "e": 777, "s": 762, "text": "React useState" }, { "code": null, "e": 792, "s": 777, "text": "React useState" }, { "code": null, "e": 872, "s": 792, "text": "Framer: components and hooks we are going to make use of in this tutorial are :" }, { "code": null, "e": 990, "s": 872, "text": "https://www.framer.com/api/frame/https://www.framer.com/api/scroll/https://www.framer.com/api/utilities/#useanimation" }, { "code": null, "e": 1024, "s": 990, "text": "https://www.framer.com/api/frame/" }, { "code": null, "e": 1059, "s": 1024, "text": "https://www.framer.com/api/scroll/" }, { "code": null, "e": 1110, "s": 1059, "text": "https://www.framer.com/api/utilities/#useanimation" }, { "code": null, "e": 1161, "s": 1110, "text": "Creating React Application And Installing Module :" }, { "code": null, "e": 1294, "s": 1161, "text": "Step 1: Now, you will start a new project using create-react-app so open your terminal and type.$ npx create-react-app animated-card" }, { "code": null, "e": 1391, "s": 1294, "text": "Step 1: Now, you will start a new project using create-react-app so open your terminal and type." }, { "code": null, "e": 1428, "s": 1391, "text": "$ npx create-react-app animated-card" }, { "code": null, "e": 1549, "s": 1428, "text": "Step 2: After creating your project folder i.e. animated-card, move to it using the following command.$ cd animated-card" }, { "code": null, "e": 1652, "s": 1549, "text": "Step 2: After creating your project folder i.e. animated-card, move to it using the following command." }, { "code": null, "e": 1671, "s": 1652, "text": "$ cd animated-card" }, { "code": null, "e": 1808, "s": 1671, "text": "Step 3: Add the npm packages you will need during the project.$ npm install framer react-icons\n// For yarn\n$ yarn add framer react-icons" }, { "code": null, "e": 1871, "s": 1808, "text": "Step 3: Add the npm packages you will need during the project." }, { "code": null, "e": 1946, "s": 1871, "text": "$ npm install framer react-icons\n// For yarn\n$ yarn add framer react-icons" }, { "code": null, "e": 1999, "s": 1946, "text": "Open the src folder and delete the following files :" }, { "code": null, "e": 2070, "s": 1999, "text": "logo.svgserviceWorker.jssetupTests.jsApp.cssApp.jsApp.test.js (if any)" }, { "code": null, "e": 2079, "s": 2070, "text": "logo.svg" }, { "code": null, "e": 2096, "s": 2079, "text": "serviceWorker.js" }, { "code": null, "e": 2110, "s": 2096, "text": "setupTests.js" }, { "code": null, "e": 2118, "s": 2110, "text": "App.css" }, { "code": null, "e": 2125, "s": 2118, "text": "App.js" }, { "code": null, "e": 2146, "s": 2125, "text": "App.test.js (if any)" }, { "code": null, "e": 2175, "s": 2146, "text": "Create a file named Card.js." }, { "code": null, "e": 2246, "s": 2175, "text": "Project structure: Your project structure tree should look like this :" }, { "code": null, "e": 2264, "s": 2246, "text": "Project structure" }, { "code": null, "e": 2274, "s": 2264, "text": "Example: " }, { "code": null, "e": 2283, "s": 2274, "text": "index.js" }, { "code": "import React from \"react\";import { Frame, Scroll } from \"framer\";import Card from \"./Card\";import ReactDOM from \"react-dom\"; import \"./index.css\"; // main App HOCexport const App = () => { return ( <Frame height={\"100%\"} width={\"100%\"} background={\"#333\"}> <Frame width={375} height={\"100%\"} background={\"#FFF\"} center> <Scroll width={375} height={\"100%\"}> {/* Card component with props yPos,title,subtitle */} <Card yPos={48} title={\"GEEKSFORGEEKS\"} subtitle=\"Don't learn alone\" /> <Card yPos={48 + 300 + 24} title={\"reactJS\"} subtitle=\"Most starred JavaScript library\" /> </Scroll> </Frame> </Frame> );}; const rootElement = document.getElementById(\"root\");ReactDOM.render(<App />, rootElement);", "e": 3127, "s": 2283, "text": null }, { "code": null, "e": 3137, "s": 3127, "text": "index.css" }, { "code": "body { margin: 0; cursor: pointer;}", "e": 3175, "s": 3137, "text": null }, { "code": null, "e": 3183, "s": 3175, "text": "Card.js" }, { "code": "import React, { useState } from \"react\";import { ImCross } from \"react-icons/im\";import { Frame, Scroll, useAnimation } from \"framer\"; // Card component with destructured props :// yPos, title, subtitleconst Card = ({ yPos, title, subtitle }) => { // useState hook to manage the state of // expanding of card const [state, setState] = useState(false); // utility function to handle // onTap on card component const handleTap = () => { state ? controls.start({ y: 0 }) : setState(!state); }; const controls = useAnimation(); // Variants allow you to define animation // states and organise them by name. // They allow you to control animations // throughout a component // tree by switching a single animate prop. const variants = { active: { width: 320, height: 800, borderRadius: 0, overflow: \"visible\", left: 28, right:0, y: 0, transition: { duration: 0.125, type: \"spring\", damping: 10, mass: 0.6 } }, inactive: { width: 280, height: 280, borderRadius: 24, overflow: \"hidden\", left: 45, y: yPos, transition: { duration: 0.125, type: \"spring\", damping: 10, mass: 0.6 } } }; return ( // basic container for layout, styling, // animation and events. <Frame y={yPos} variants={variants} animate={state ? \"active\" : \"inactive\"} width={300} height={300} borderRadius={24} style={state ? { zIndex: 10 } : { zIndex: 1 }} left={37.5} onTap={handleTap} shadow={ state ? \"0 0 0 0 rgba(0, 0, 0, 0)\" : \"0px 0px 20px 0px rgba(0, 0, 0, .25)\" } > <Scroll width=\"100%\" height=\"100%\" backgroundColor={null} scrollAnimate={controls} > <Frame position=\"relative\" backgroundColor={\"#09a960\"} width=\"100%\" height={300} /> <Frame position=\"relative\" height={1200} background=\"white\" /> <Frame top={20} left={20} height={\"\"} width={\"\"} background={null} style={{ color: \"white\", fontFamily: \"sans-serif\" }} > <span style={{ fontSize: \"1.6em\", fontWeight: 600 }}> {title} </span> <br /> <span style={{ fontSize: \"1em\", fontWeight: 500, opacity: 0.5 }} > {subtitle} </span> </Frame> </Scroll> {state && ( <Frame borderRadius={20} size={15} top={15} right={20} backgroundColor={\"#09a960\"} onTap={() => { setState(false); }} > <ImCross color=\"red\" /> </Frame> )} </Frame> );}; export default Card;", "e": 6216, "s": 3183, "text": null }, { "code": null, "e": 6329, "s": 6216, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 6339, "s": 6329, "text": "npm start" }, { "code": null, "e": 6438, "s": 6339, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 6453, "s": 6438, "text": "adnanirshad158" }, { "code": null, "e": 6468, "s": 6453, "text": "CSS-Properties" }, { "code": null, "e": 6482, "s": 6468, "text": "Framer-motion" }, { "code": null, "e": 6490, "s": 6482, "text": "ReactJS" }, { "code": null, "e": 6507, "s": 6490, "text": "Web Technologies" } ]
Removing Levels from a Factor in R Programming – droplevels() Function
05 Jun, 2020 droplevels() function in R programming used to remove unused levels from a Factor. Syntax:# For vector objectdroplevels(x, exclude = if(anyNA(levels(x))) NULL else NA, ...) # For data frame objectdroplevels(x, except, exclude) Parameter values:x represents object from which unused level has to be droppedexclude represents factor levels which should be excluded even if presentexcept represents indices of columns from which levels should not be dropped Example 1: # Defining vectorx <- c(1, 3, 4, 8, 1, 5, 4, 4, 5, 6) # Defining factor object for vectorf <- factor(x) # Print factor objectcat("Factor object before deleting value:\n")print(f)cat("\n") # Delete value at index 2f <- f[-2] # Print factor objectcat("Factor object after deleting value:\n")print(f)cat("\n") cat("After dropping unused level:\n")new_f <- droplevels(f)print(new_f) Output: Factor object before deleting value: [1] 1 3 4 8 1 5 4 4 5 6 Levels: 1 3 4 5 6 8 Factor object after deleting value: [1] 1 4 8 1 5 4 4 5 6 Levels: 1 3 4 5 6 8 After dropping unused level: [1] 1 4 8 1 5 4 4 5 6 Levels: 1 4 5 6 8 Example 2: # Defining columnsx <- factor(c(7, 3, 3, 7, 5, 5, 1))y <- factor(c(1, 1, 1, 4, 4, 4, 2))z <- c(1, 5, 3, 2, 9, 4, 7) # Defining data framedf <- data.frame(x, y, z)df <- df[1:6, ] # Print structure of data framestr(df)cat("\n") # Drop levels from data framedf_drop <- droplevels(df) # Print structure of new data framestr(df_drop) Output: 'data.frame': 6 obs. of 3 variables: $ x: Factor w/ 4 levels "1", "3", "5", "7": 4 2 2 4 3 3 $ y: Factor w/ 3 levels "1", "2", "4": 1 1 1 3 3 3 $ z: num 1 5 3 2 9 4 'data.frame': 6 obs. of 3 variables: $ x: Factor w/ 3 levels "3", "5", "7": 3 1 1 3 2 2 $ y: Factor w/ 2 levels "1", "4": 1 1 1 2 2 2 $ z: num 1 5 3 2 9 4 R Factor-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2020" }, { "code": null, "e": 111, "s": 28, "text": "droplevels() function in R programming used to remove unused levels from a Factor." }, { "code": null, "e": 201, "s": 111, "text": "Syntax:# For vector objectdroplevels(x, exclude = if(anyNA(levels(x))) NULL else NA, ...)" }, { "code": null, "e": 255, "s": 201, "text": "# For data frame objectdroplevels(x, except, exclude)" }, { "code": null, "e": 483, "s": 255, "text": "Parameter values:x represents object from which unused level has to be droppedexclude represents factor levels which should be excluded even if presentexcept represents indices of columns from which levels should not be dropped" }, { "code": null, "e": 494, "s": 483, "text": "Example 1:" }, { "code": "# Defining vectorx <- c(1, 3, 4, 8, 1, 5, 4, 4, 5, 6) # Defining factor object for vectorf <- factor(x) # Print factor objectcat(\"Factor object before deleting value:\\n\")print(f)cat(\"\\n\") # Delete value at index 2f <- f[-2] # Print factor objectcat(\"Factor object after deleting value:\\n\")print(f)cat(\"\\n\") cat(\"After dropping unused level:\\n\")new_f <- droplevels(f)print(new_f)", "e": 878, "s": 494, "text": null }, { "code": null, "e": 886, "s": 878, "text": "Output:" }, { "code": null, "e": 1118, "s": 886, "text": "Factor object before deleting value:\n [1] 1 3 4 8 1 5 4 4 5 6\nLevels: 1 3 4 5 6 8\n\nFactor object after deleting value:\n[1] 1 4 8 1 5 4 4 5 6\nLevels: 1 3 4 5 6 8\n\nAfter dropping unused level:\n[1] 1 4 8 1 5 4 4 5 6\nLevels: 1 4 5 6 8\n" }, { "code": null, "e": 1129, "s": 1118, "text": "Example 2:" }, { "code": "# Defining columnsx <- factor(c(7, 3, 3, 7, 5, 5, 1))y <- factor(c(1, 1, 1, 4, 4, 4, 2))z <- c(1, 5, 3, 2, 9, 4, 7) # Defining data framedf <- data.frame(x, y, z)df <- df[1:6, ] # Print structure of data framestr(df)cat(\"\\n\") # Drop levels from data framedf_drop <- droplevels(df) # Print structure of new data framestr(df_drop)", "e": 1462, "s": 1129, "text": null }, { "code": null, "e": 1470, "s": 1462, "text": "Output:" }, { "code": null, "e": 1808, "s": 1470, "text": "'data.frame': 6 obs. of 3 variables:\n $ x: Factor w/ 4 levels \"1\", \"3\", \"5\", \"7\": 4 2 2 4 3 3\n $ y: Factor w/ 3 levels \"1\", \"2\", \"4\": 1 1 1 3 3 3\n $ z: num 1 5 3 2 9 4\n \n 'data.frame': 6 obs. of 3 variables:\n $ x: Factor w/ 3 levels \"3\", \"5\", \"7\": 3 1 1 3 2 2\n $ y: Factor w/ 2 levels \"1\", \"4\": 1 1 1 2 2 2\n $ z: num 1 5 3 2 9 4\n" }, { "code": null, "e": 1826, "s": 1808, "text": "R Factor-Function" }, { "code": null, "e": 1837, "s": 1826, "text": "R Language" } ]
ReactJS Reactstrap InputGroup Component
30 Jul, 2021 Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The InputGroup component provides a way to put one add-on or button on either side or both sides of an input. We can use the following approach in ReactJS to use the ReactJS Reactstrap InputGroup Component. InputGroup Props: tag: It is used to denote the tag for this component. size: It is used to denote the size of this component. className: It is used to denote the class name for styling. InputGroupAddOn Props: tag: It is used to denote the tag for this component. addonType: It is used to denote the addon type like prepend or append. className: It is used to denote the class name for styling. InputGroupButton Props: tag: It is used to denote the tag for this component. addonType: It is used to denote the addon type like prepend or append. children: It is used to denote the children element for this component. groupClassName: It is used to denote the group class name for this component. groupAttributes: It is used to denote the group attributes for this component. className: It is used to denote the class name for styling. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install reactstrap bootstrap Step 3: After creating the ReactJS application, Install the required module using the following command: npm install reactstrap bootstrap Project Structure: It will look like the following. Project Structure Example 1: Now write down the following code in the App.js file. Here, we have shown the InputGroup component with text field type input field. App.js import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Input, InputGroup, InputGroupText, InputGroupAddon} from 'reactstrap'; function App() { return ( <div style={{ display: 'block', width: 550, padding: 30 }}> <h5>ReactJS Reactstrap InputGroup Component</h5> <InputGroup> <InputGroupAddon addonType="prepend"> <InputGroupText>Detail</InputGroupText> </InputGroupAddon> <Input placeholder="Enter your username" /> </InputGroup> </div > );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Example 2: Now write down the following code in the App.js file. Here, we have shown the InputGroup component with a checkbox type input field. App.js import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Input, InputGroup, InputGroupText, InputGroupAddon} from 'reactstrap'; function App() { return ( <div style={{ display: 'block', width: 550, padding: 30 }}> <h5>ReactJS Reactstrap InputGroup Component</h5> <InputGroup size="sm"> <InputGroupAddon addonType="prepend"> <InputGroupText> <Input type="checkbox"/> </InputGroupText> </InputGroupAddon> <Input placeholder="Accepts terms and Condition" /> </InputGroup> </div > );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://reactstrap.github.io/components/input-group/ Reactstrap JavaScript ReactJS 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": "\n30 Jul, 2021" }, { "code": null, "e": 397, "s": 28, "text": "Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The InputGroup component provides a way to put one add-on or button on either side or both sides of an input. We can use the following approach in ReactJS to use the ReactJS Reactstrap InputGroup Component." }, { "code": null, "e": 415, "s": 397, "text": "InputGroup Props:" }, { "code": null, "e": 469, "s": 415, "text": "tag: It is used to denote the tag for this component." }, { "code": null, "e": 524, "s": 469, "text": "size: It is used to denote the size of this component." }, { "code": null, "e": 584, "s": 524, "text": "className: It is used to denote the class name for styling." }, { "code": null, "e": 607, "s": 584, "text": "InputGroupAddOn Props:" }, { "code": null, "e": 661, "s": 607, "text": "tag: It is used to denote the tag for this component." }, { "code": null, "e": 732, "s": 661, "text": "addonType: It is used to denote the addon type like prepend or append." }, { "code": null, "e": 792, "s": 732, "text": "className: It is used to denote the class name for styling." }, { "code": null, "e": 816, "s": 792, "text": "InputGroupButton Props:" }, { "code": null, "e": 870, "s": 816, "text": "tag: It is used to denote the tag for this component." }, { "code": null, "e": 941, "s": 870, "text": "addonType: It is used to denote the addon type like prepend or append." }, { "code": null, "e": 1013, "s": 941, "text": "children: It is used to denote the children element for this component." }, { "code": null, "e": 1091, "s": 1013, "text": "groupClassName: It is used to denote the group class name for this component." }, { "code": null, "e": 1170, "s": 1091, "text": "groupAttributes: It is used to denote the group attributes for this component." }, { "code": null, "e": 1230, "s": 1170, "text": "className: It is used to denote the class name for styling." }, { "code": null, "e": 1282, "s": 1232, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 1377, "s": 1282, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 1441, "s": 1377, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 1473, "s": 1441, "text": "npx create-react-app foldername" }, { "code": null, "e": 1586, "s": 1473, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 1686, "s": 1586, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 1700, "s": 1686, "text": "cd foldername" }, { "code": null, "e": 1837, "s": 1700, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install reactstrap bootstrap" }, { "code": null, "e": 1942, "s": 1837, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 1975, "s": 1942, "text": "npm install reactstrap bootstrap" }, { "code": null, "e": 2027, "s": 1975, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 2045, "s": 2027, "text": "Project Structure" }, { "code": null, "e": 2189, "s": 2045, "text": "Example 1: Now write down the following code in the App.js file. Here, we have shown the InputGroup component with text field type input field." }, { "code": null, "e": 2196, "s": 2189, "text": "App.js" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Input, InputGroup, InputGroupText, InputGroupAddon} from 'reactstrap'; function App() { return ( <div style={{ display: 'block', width: 550, padding: 30 }}> <h5>ReactJS Reactstrap InputGroup Component</h5> <InputGroup> <InputGroupAddon addonType=\"prepend\"> <InputGroupText>Detail</InputGroupText> </InputGroupAddon> <Input placeholder=\"Enter your username\" /> </InputGroup> </div > );} export default App;", "e": 2827, "s": 2196, "text": null }, { "code": null, "e": 2942, "s": 2829, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2952, "s": 2942, "text": "npm start" }, { "code": null, "e": 3051, "s": 2952, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 3195, "s": 3051, "text": "Example 2: Now write down the following code in the App.js file. Here, we have shown the InputGroup component with a checkbox type input field." }, { "code": null, "e": 3202, "s": 3195, "text": "App.js" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Input, InputGroup, InputGroupText, InputGroupAddon} from 'reactstrap'; function App() { return ( <div style={{ display: 'block', width: 550, padding: 30 }}> <h5>ReactJS Reactstrap InputGroup Component</h5> <InputGroup size=\"sm\"> <InputGroupAddon addonType=\"prepend\"> <InputGroupText> <Input type=\"checkbox\"/> </InputGroupText> </InputGroupAddon> <Input placeholder=\"Accepts terms and Condition\" /> </InputGroup> </div > );} export default App;", "e": 3913, "s": 3202, "text": null }, { "code": null, "e": 4026, "s": 3913, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 4036, "s": 4026, "text": "npm start" }, { "code": null, "e": 4135, "s": 4036, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 4199, "s": 4135, "text": "Reference: https://reactstrap.github.io/components/input-group/" }, { "code": null, "e": 4210, "s": 4199, "text": "Reactstrap" }, { "code": null, "e": 4221, "s": 4210, "text": "JavaScript" }, { "code": null, "e": 4229, "s": 4221, "text": "ReactJS" }, { "code": null, "e": 4246, "s": 4229, "text": "Web Technologies" } ]
Array implementation of queue (Simple)
20 May, 2022 In queue, insertion and deletion happen at the opposite ends, so implementation is not as simple as stack. To implement a queue using array, create an array arr of size n and take two variables front and rear both of which will be initialized to 0 which means the queue is currently empty. Element rear is the index upto which the elements are stored in the array and front is the index of the first element of the array. Now, some of the implementation of queue operations are as follows: Enqueue: Addition of an element to the queue. Adding an element will be performed after checking whether the queue is full or not. If rear < n which indicates that the array is not full then store the element at arr[rear] and increment rear by 1 but if rear == n then it is said to be an Overflow condition as the array is full.Dequeue: Removal of an element from the queue. An element can only be deleted when there is at least an element to delete i.e. rear > 0. Now, element at arr[front] can be deleted but all the remaining elements have to shifted to the left by one position in order for the dequeue operation to delete the second element from the left on another dequeue operation.Front: Get the front element from the queue i.e. arr[front] if queue is not empty.Display: Print all element of the queue. If the queue is non-empty, traverse and print all the elements from index front to rear. Enqueue: Addition of an element to the queue. Adding an element will be performed after checking whether the queue is full or not. If rear < n which indicates that the array is not full then store the element at arr[rear] and increment rear by 1 but if rear == n then it is said to be an Overflow condition as the array is full. Dequeue: Removal of an element from the queue. An element can only be deleted when there is at least an element to delete i.e. rear > 0. Now, element at arr[front] can be deleted but all the remaining elements have to shifted to the left by one position in order for the dequeue operation to delete the second element from the left on another dequeue operation. Front: Get the front element from the queue i.e. arr[front] if queue is not empty. Display: Print all element of the queue. If the queue is non-empty, traverse and print all the elements from index front to rear. Below is the implementation of a queue using an array: C++ Java Python3 C# Javascript // C++ program to implement a queue using an array#include <bits/stdc++.h>using namespace std; struct Queue { int front, rear, capacity; int* queue; Queue(int c) { front = rear = 0; capacity = c; queue = new int; } ~Queue() { delete[] queue; } // function to insert an element // at the rear of the queue void queueEnqueue(int data) { // check queue is full or not if (capacity == rear) { printf("\nQueue is full\n"); return; } // insert element at the rear else { queue[rear] = data; rear++; } return; } // function to delete an element // from the front of the queue void queueDequeue() { // if queue is empty if (front == rear) { printf("\nQueue is empty\n"); return; } // shift all the elements from index 2 till rear // to the left by one else { for (int i = 0; i < rear - 1; i++) { queue[i] = queue[i + 1]; } // decrement rear rear--; } return; } // print queue elements void queueDisplay() { int i; if (front == rear) { printf("\nQueue is Empty\n"); return; } // traverse front to rear and print elements for (i = front; i < rear; i++) { printf(" %d <-- ", queue[i]); } return; } // print front of queue void queueFront() { if (front == rear) { printf("\nQueue is Empty\n"); return; } printf("\nFront Element is: %d", queue[front]); return; }}; // Driver codeint main(void){ // Create a queue of capacity 4 Queue q(4); // print Queue elements q.queueDisplay(); // inserting elements in the queue q.queueEnqueue(20); q.queueEnqueue(30); q.queueEnqueue(40); q.queueEnqueue(50); // print Queue elements q.queueDisplay(); // insert element in the queue q.queueEnqueue(60); // print Queue elements q.queueDisplay(); q.queueDequeue(); q.queueDequeue(); printf("\n\nafter two node deletion\n\n"); // print Queue elements q.queueDisplay(); // print front of the queue q.queueFront(); return 0;} // Java program to implement a queue using an arrayclass Queue { private int front, rear, capacity; private int queue[]; Queue(int c) { front = rear = 0; capacity = c; queue = new int[capacity]; } // function to insert an element // at the rear of the queue static void queueEnqueue(int data) { // check queue is full or not if (capacity == rear) { System.out.printf("\nQueue is full\n"); return; } // insert element at the rear else { queue[rear] = data; rear++; } return; } // function to delete an element // from the front of the queue static void queueDequeue() { // if queue is empty if (front == rear) { System.out.printf("\nQueue is empty\n"); return; } // shift all the elements from index 2 till rear // to the right by one else { for (int i = 0; i < rear - 1; i++) { queue[i] = queue[i + 1]; } // store 0 at rear indicating there's no element if (rear < capacity) queue[rear] = 0; // decrement rear rear--; } return; } // print queue elements static void queueDisplay() { int i; if (front == rear) { System.out.printf("\nQueue is Empty\n"); return; } // traverse front to rear and print elements for (i = front; i < rear; i++) { System.out.printf(" %d <-- ", queue[i]); } return; } // print front of queue static void queueFront() { if (front == rear) { System.out.printf("\nQueue is Empty\n"); return; } System.out.printf("\nFront Element is: %d", queue[front]); return; }} public class StaticQueueinjava { // Driver code public static void main(String[] args) { // Create a queue of capacity 4 Queue q = new Queue(4); // print Queue elements q.queueDisplay(); // inserting elements in the queue q.queueEnqueue(20); q.queueEnqueue(30); q.queueEnqueue(40); q.queueEnqueue(50); // print Queue elements q.queueDisplay(); // insert element in the queue q.queueEnqueue(60); // print Queue elements q.queueDisplay(); q.queueDequeue(); q.queueDequeue(); System.out.printf("\n\nafter two node deletion\n\n"); // print Queue elements q.queueDisplay(); // print front of the queue q.queueFront(); }} # Python3 program to implement# a queue using an arrayclass Queue: # To initialize the object. def __init__(self, c): self.queue = [] self.front = self.rear = 0 self.capacity = c # Function to insert an element # at the rear of the queue def queueEnqueue(self, data): # Check queue is full or not if(self.capacity == self.rear): print("\nQueue is full") # Insert element at the rear else: self.queue.append(data) self.rear += 1 # Function to delete an element # from the front of the queue def queueDequeue(self): # If queue is empty if(self.front == self.rear): print("Queue is empty") # Pop the front element from list else: x = self.queue.pop(0) self.rear -= 1 # Function to print queue elements def queueDisplay(self): if(self.front == self.rear): print("\nQueue is Empty") # Traverse front to rear to # print elements for i in self.queue: print(i, "<--", end = '') # Print front of queue def queueFront(self): if(self.front == self.rear): print("\nQueue is Empty") print("\nFront Element is:", self.queue[self.front]) # Driver codeif __name__=='__main__': # Create a new queue of # capacity 4 q = Queue(4) # Print queue elements q.queueDisplay() # Inserting elements in the queue q.queueEnqueue(20) q.queueEnqueue(30) q.queueEnqueue(40) q.queueEnqueue(50) # Print queue elements q.queueDisplay() # Insert element in queue q.queueEnqueue(60) # Print queue elements q.queueDisplay() q.queueDequeue() q.queueDequeue() print("\n\nafter two node deletion\n") # Print queue elements q.queueDisplay() # Print front of queue q.queueFront() # This code is contributed by Amit Mangal // C# program to implement a queue using an arrayusing System; public class Queue{ private int front, rear, capacity; private int []queue; public Queue(int c) { front = rear = 0; capacity = c; queue = new int[capacity]; } // function to insert an element // at the rear of the queue public void queueEnqueue(int data) { // check queue is full or not if (capacity == rear) { Console.Write("\nQueue is full\n"); return; } // insert element at the rear else { queue[rear] = data; rear++; } return; } // function to delete an element // from the front of the queue public void queueDequeue() { // if queue is empty if (front == rear) { Console.Write("\nQueue is empty\n"); return; } // shift all the elements from index 2 till rear // to the right by one else { for (int i = 0; i < rear - 1; i++) { queue[i] = queue[i + 1]; } // store 0 at rear indicating there's no element if (rear < capacity) queue[rear] = 0; // decrement rear rear--; } return; } // print queue elements public void queueDisplay() { int i; if (front == rear) { Console.Write("\nQueue is Empty\n"); return; } // traverse front to rear and print elements for (i = front; i < rear; i++) { Console.Write(" {0} <-- ", queue[i]); } return; } // print front of queue public void queueFront() { if (front == rear) { Console.Write("\nQueue is Empty\n"); return; } Console.Write("\nFront Element is: {0}", queue[front]); return; }} public class StaticQueueinjava { // Driver code public static void Main(String[] args) { // Create a queue of capacity 4 Queue q = new Queue(4); // print Queue elements q.queueDisplay(); // inserting elements in the queue q.queueEnqueue(20); q.queueEnqueue(30); q.queueEnqueue(40); q.queueEnqueue(50); // print Queue elements q.queueDisplay(); // insert element in the queue q.queueEnqueue(60); // print Queue elements q.queueDisplay(); q.queueDequeue(); q.queueDequeue(); Console.Write("\n\nafter two node deletion\n\n"); // print Queue elements q.queueDisplay(); // print front of the queue q.queueFront(); }} // This code has been contributed by 29AjayKumar <script> // Javascript program to implement a queue using an arrayclass Queue{ constructor(c){ this.front = this.rear = 0; this.capacity = c; this.queue = new Array(this.capacity);} // Function to insert an element// at the rear of the queuequeueEnqueue(data){ // Check queue is full or not if (this.capacity == this.rear) { document.write("<br>Queue is full<br>"); return; } // insert element at the rear else { this.queue[this.rear] = data; this.rear++; } return;} // Function to delete an element// from the front of the queuequeueDequeue(){ // If queue is empty if (this.front == this.rear) { document.write("<br>Queue is empty<br>"); return; } // Shift all the elements from index 2 till rear // to the right by one else { for(let i = 0; i < this.rear - 1; i++) { this.queue[i] = this.queue[i + 1]; } // Store 0 at rear indicating there's no element if (this.rear < this.capacity) this.queue[this.rear] = 0; // Decrement rear this.rear--; } return;} // Print queue elementsqueueDisplay(){ let i; if (this.front == this.rear) { document.write("<br>Queue is Empty<br>"); return; } // Traverse front to rear and print elements for(i = this.front; i < this.rear; i++) { document.write(this.queue[i] + " <-- "); } return;} // Print front of queuequeueFront(){ if (this.front == this.rear) { document.write("<br>Queue is Empty<br>"); return; } document.write("<br>Front Element is: " + this.queue[this.front]); return;}} // Driver code // Create a queue of capacity 4let q = new Queue(4); // Print Queue elementsq.queueDisplay(); // Inserting elements in the queueq.queueEnqueue(20);q.queueEnqueue(30);q.queueEnqueue(40);q.queueEnqueue(50); // Print Queue elementsq.queueDisplay(); // Insert element in the queueq.queueEnqueue(60); // Print Queue elementsq.queueDisplay(); q.queueDequeue();q.queueDequeue();document.write("<br><br> after two node deletion <br><br>"); // Print Queue elementsq.queueDisplay(); // Print front of the queueq.queueFront(); // This code is contributed by rag2127 </script> Queue is Empty 20 <-- 30 <-- 40 <-- 50 <-- Queue is full 20 <-- 30 <-- 40 <-- 50 <-- after two node deletion 40 <-- 50 <-- Front Element is: 40 Time Complexity of Enqueue : O(1) Time Complexity of Dequeue : O(n) Optimizations : We can implement both enqueue and dequeue operations in O(1) time. To achieve this, we can either use Linked List Implementation of Queue or circular array implementation of queue. 29AjayKumar shashnagaral amit_mangal_ rag2127 adityagarg1 Technical Scripter 2018 Queue Technical Scripter Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 May, 2022" }, { "code": null, "e": 543, "s": 52, "text": "In queue, insertion and deletion happen at the opposite ends, so implementation is not as simple as stack. To implement a queue using array, create an array arr of size n and take two variables front and rear both of which will be initialized to 0 which means the queue is currently empty. Element rear is the index upto which the elements are stored in the array and front is the index of the first element of the array. Now, some of the implementation of queue operations are as follows: " }, { "code": null, "e": 1444, "s": 543, "text": "Enqueue: Addition of an element to the queue. Adding an element will be performed after checking whether the queue is full or not. If rear < n which indicates that the array is not full then store the element at arr[rear] and increment rear by 1 but if rear == n then it is said to be an Overflow condition as the array is full.Dequeue: Removal of an element from the queue. An element can only be deleted when there is at least an element to delete i.e. rear > 0. Now, element at arr[front] can be deleted but all the remaining elements have to shifted to the left by one position in order for the dequeue operation to delete the second element from the left on another dequeue operation.Front: Get the front element from the queue i.e. arr[front] if queue is not empty.Display: Print all element of the queue. If the queue is non-empty, traverse and print all the elements from index front to rear." }, { "code": null, "e": 1773, "s": 1444, "text": "Enqueue: Addition of an element to the queue. Adding an element will be performed after checking whether the queue is full or not. If rear < n which indicates that the array is not full then store the element at arr[rear] and increment rear by 1 but if rear == n then it is said to be an Overflow condition as the array is full." }, { "code": null, "e": 2135, "s": 1773, "text": "Dequeue: Removal of an element from the queue. An element can only be deleted when there is at least an element to delete i.e. rear > 0. Now, element at arr[front] can be deleted but all the remaining elements have to shifted to the left by one position in order for the dequeue operation to delete the second element from the left on another dequeue operation." }, { "code": null, "e": 2218, "s": 2135, "text": "Front: Get the front element from the queue i.e. arr[front] if queue is not empty." }, { "code": null, "e": 2348, "s": 2218, "text": "Display: Print all element of the queue. If the queue is non-empty, traverse and print all the elements from index front to rear." }, { "code": null, "e": 2404, "s": 2348, "text": "Below is the implementation of a queue using an array: " }, { "code": null, "e": 2408, "s": 2404, "text": "C++" }, { "code": null, "e": 2413, "s": 2408, "text": "Java" }, { "code": null, "e": 2421, "s": 2413, "text": "Python3" }, { "code": null, "e": 2424, "s": 2421, "text": "C#" }, { "code": null, "e": 2435, "s": 2424, "text": "Javascript" }, { "code": "// C++ program to implement a queue using an array#include <bits/stdc++.h>using namespace std; struct Queue { int front, rear, capacity; int* queue; Queue(int c) { front = rear = 0; capacity = c; queue = new int; } ~Queue() { delete[] queue; } // function to insert an element // at the rear of the queue void queueEnqueue(int data) { // check queue is full or not if (capacity == rear) { printf(\"\\nQueue is full\\n\"); return; } // insert element at the rear else { queue[rear] = data; rear++; } return; } // function to delete an element // from the front of the queue void queueDequeue() { // if queue is empty if (front == rear) { printf(\"\\nQueue is empty\\n\"); return; } // shift all the elements from index 2 till rear // to the left by one else { for (int i = 0; i < rear - 1; i++) { queue[i] = queue[i + 1]; } // decrement rear rear--; } return; } // print queue elements void queueDisplay() { int i; if (front == rear) { printf(\"\\nQueue is Empty\\n\"); return; } // traverse front to rear and print elements for (i = front; i < rear; i++) { printf(\" %d <-- \", queue[i]); } return; } // print front of queue void queueFront() { if (front == rear) { printf(\"\\nQueue is Empty\\n\"); return; } printf(\"\\nFront Element is: %d\", queue[front]); return; }}; // Driver codeint main(void){ // Create a queue of capacity 4 Queue q(4); // print Queue elements q.queueDisplay(); // inserting elements in the queue q.queueEnqueue(20); q.queueEnqueue(30); q.queueEnqueue(40); q.queueEnqueue(50); // print Queue elements q.queueDisplay(); // insert element in the queue q.queueEnqueue(60); // print Queue elements q.queueDisplay(); q.queueDequeue(); q.queueDequeue(); printf(\"\\n\\nafter two node deletion\\n\\n\"); // print Queue elements q.queueDisplay(); // print front of the queue q.queueFront(); return 0;}", "e": 4773, "s": 2435, "text": null }, { "code": "// Java program to implement a queue using an arrayclass Queue { private int front, rear, capacity; private int queue[]; Queue(int c) { front = rear = 0; capacity = c; queue = new int[capacity]; } // function to insert an element // at the rear of the queue static void queueEnqueue(int data) { // check queue is full or not if (capacity == rear) { System.out.printf(\"\\nQueue is full\\n\"); return; } // insert element at the rear else { queue[rear] = data; rear++; } return; } // function to delete an element // from the front of the queue static void queueDequeue() { // if queue is empty if (front == rear) { System.out.printf(\"\\nQueue is empty\\n\"); return; } // shift all the elements from index 2 till rear // to the right by one else { for (int i = 0; i < rear - 1; i++) { queue[i] = queue[i + 1]; } // store 0 at rear indicating there's no element if (rear < capacity) queue[rear] = 0; // decrement rear rear--; } return; } // print queue elements static void queueDisplay() { int i; if (front == rear) { System.out.printf(\"\\nQueue is Empty\\n\"); return; } // traverse front to rear and print elements for (i = front; i < rear; i++) { System.out.printf(\" %d <-- \", queue[i]); } return; } // print front of queue static void queueFront() { if (front == rear) { System.out.printf(\"\\nQueue is Empty\\n\"); return; } System.out.printf(\"\\nFront Element is: %d\", queue[front]); return; }} public class StaticQueueinjava { // Driver code public static void main(String[] args) { // Create a queue of capacity 4 Queue q = new Queue(4); // print Queue elements q.queueDisplay(); // inserting elements in the queue q.queueEnqueue(20); q.queueEnqueue(30); q.queueEnqueue(40); q.queueEnqueue(50); // print Queue elements q.queueDisplay(); // insert element in the queue q.queueEnqueue(60); // print Queue elements q.queueDisplay(); q.queueDequeue(); q.queueDequeue(); System.out.printf(\"\\n\\nafter two node deletion\\n\\n\"); // print Queue elements q.queueDisplay(); // print front of the queue q.queueFront(); }}", "e": 7449, "s": 4773, "text": null }, { "code": "# Python3 program to implement# a queue using an arrayclass Queue: # To initialize the object. def __init__(self, c): self.queue = [] self.front = self.rear = 0 self.capacity = c # Function to insert an element # at the rear of the queue def queueEnqueue(self, data): # Check queue is full or not if(self.capacity == self.rear): print(\"\\nQueue is full\") # Insert element at the rear else: self.queue.append(data) self.rear += 1 # Function to delete an element # from the front of the queue def queueDequeue(self): # If queue is empty if(self.front == self.rear): print(\"Queue is empty\") # Pop the front element from list else: x = self.queue.pop(0) self.rear -= 1 # Function to print queue elements def queueDisplay(self): if(self.front == self.rear): print(\"\\nQueue is Empty\") # Traverse front to rear to # print elements for i in self.queue: print(i, \"<--\", end = '') # Print front of queue def queueFront(self): if(self.front == self.rear): print(\"\\nQueue is Empty\") print(\"\\nFront Element is:\", self.queue[self.front]) # Driver codeif __name__=='__main__': # Create a new queue of # capacity 4 q = Queue(4) # Print queue elements q.queueDisplay() # Inserting elements in the queue q.queueEnqueue(20) q.queueEnqueue(30) q.queueEnqueue(40) q.queueEnqueue(50) # Print queue elements q.queueDisplay() # Insert element in queue q.queueEnqueue(60) # Print queue elements q.queueDisplay() q.queueDequeue() q.queueDequeue() print(\"\\n\\nafter two node deletion\\n\") # Print queue elements q.queueDisplay() # Print front of queue q.queueFront() # This code is contributed by Amit Mangal", "e": 9415, "s": 7449, "text": null }, { "code": "// C# program to implement a queue using an arrayusing System; public class Queue{ private int front, rear, capacity; private int []queue; public Queue(int c) { front = rear = 0; capacity = c; queue = new int[capacity]; } // function to insert an element // at the rear of the queue public void queueEnqueue(int data) { // check queue is full or not if (capacity == rear) { Console.Write(\"\\nQueue is full\\n\"); return; } // insert element at the rear else { queue[rear] = data; rear++; } return; } // function to delete an element // from the front of the queue public void queueDequeue() { // if queue is empty if (front == rear) { Console.Write(\"\\nQueue is empty\\n\"); return; } // shift all the elements from index 2 till rear // to the right by one else { for (int i = 0; i < rear - 1; i++) { queue[i] = queue[i + 1]; } // store 0 at rear indicating there's no element if (rear < capacity) queue[rear] = 0; // decrement rear rear--; } return; } // print queue elements public void queueDisplay() { int i; if (front == rear) { Console.Write(\"\\nQueue is Empty\\n\"); return; } // traverse front to rear and print elements for (i = front; i < rear; i++) { Console.Write(\" {0} <-- \", queue[i]); } return; } // print front of queue public void queueFront() { if (front == rear) { Console.Write(\"\\nQueue is Empty\\n\"); return; } Console.Write(\"\\nFront Element is: {0}\", queue[front]); return; }} public class StaticQueueinjava { // Driver code public static void Main(String[] args) { // Create a queue of capacity 4 Queue q = new Queue(4); // print Queue elements q.queueDisplay(); // inserting elements in the queue q.queueEnqueue(20); q.queueEnqueue(30); q.queueEnqueue(40); q.queueEnqueue(50); // print Queue elements q.queueDisplay(); // insert element in the queue q.queueEnqueue(60); // print Queue elements q.queueDisplay(); q.queueDequeue(); q.queueDequeue(); Console.Write(\"\\n\\nafter two node deletion\\n\\n\"); // print Queue elements q.queueDisplay(); // print front of the queue q.queueFront(); }} // This code has been contributed by 29AjayKumar", "e": 12199, "s": 9415, "text": null }, { "code": "<script> // Javascript program to implement a queue using an arrayclass Queue{ constructor(c){ this.front = this.rear = 0; this.capacity = c; this.queue = new Array(this.capacity);} // Function to insert an element// at the rear of the queuequeueEnqueue(data){ // Check queue is full or not if (this.capacity == this.rear) { document.write(\"<br>Queue is full<br>\"); return; } // insert element at the rear else { this.queue[this.rear] = data; this.rear++; } return;} // Function to delete an element// from the front of the queuequeueDequeue(){ // If queue is empty if (this.front == this.rear) { document.write(\"<br>Queue is empty<br>\"); return; } // Shift all the elements from index 2 till rear // to the right by one else { for(let i = 0; i < this.rear - 1; i++) { this.queue[i] = this.queue[i + 1]; } // Store 0 at rear indicating there's no element if (this.rear < this.capacity) this.queue[this.rear] = 0; // Decrement rear this.rear--; } return;} // Print queue elementsqueueDisplay(){ let i; if (this.front == this.rear) { document.write(\"<br>Queue is Empty<br>\"); return; } // Traverse front to rear and print elements for(i = this.front; i < this.rear; i++) { document.write(this.queue[i] + \" <-- \"); } return;} // Print front of queuequeueFront(){ if (this.front == this.rear) { document.write(\"<br>Queue is Empty<br>\"); return; } document.write(\"<br>Front Element is: \" + this.queue[this.front]); return;}} // Driver code // Create a queue of capacity 4let q = new Queue(4); // Print Queue elementsq.queueDisplay(); // Inserting elements in the queueq.queueEnqueue(20);q.queueEnqueue(30);q.queueEnqueue(40);q.queueEnqueue(50); // Print Queue elementsq.queueDisplay(); // Insert element in the queueq.queueEnqueue(60); // Print Queue elementsq.queueDisplay(); q.queueDequeue();q.queueDequeue();document.write(\"<br><br> after two node deletion <br><br>\"); // Print Queue elementsq.queueDisplay(); // Print front of the queueq.queueFront(); // This code is contributed by rag2127 </script>", "e": 14493, "s": 12199, "text": null }, { "code": null, "e": 14652, "s": 14493, "text": "Queue is Empty\n 20 <-- 30 <-- 40 <-- 50 <-- \nQueue is full\n 20 <-- 30 <-- 40 <-- 50 <-- \n\nafter two node deletion\n\n 40 <-- 50 <-- \nFront Element is: 40" }, { "code": null, "e": 14722, "s": 14654, "text": "Time Complexity of Enqueue : O(1) Time Complexity of Dequeue : O(n)" }, { "code": null, "e": 14920, "s": 14722, "text": "Optimizations : We can implement both enqueue and dequeue operations in O(1) time. To achieve this, we can either use Linked List Implementation of Queue or circular array implementation of queue. " }, { "code": null, "e": 14932, "s": 14920, "text": "29AjayKumar" }, { "code": null, "e": 14945, "s": 14932, "text": "shashnagaral" }, { "code": null, "e": 14958, "s": 14945, "text": "amit_mangal_" }, { "code": null, "e": 14966, "s": 14958, "text": "rag2127" }, { "code": null, "e": 14978, "s": 14966, "text": "adityagarg1" }, { "code": null, "e": 15002, "s": 14978, "text": "Technical Scripter 2018" }, { "code": null, "e": 15008, "s": 15002, "text": "Queue" }, { "code": null, "e": 15027, "s": 15008, "text": "Technical Scripter" }, { "code": null, "e": 15033, "s": 15027, "text": "Queue" } ]
Print sums of all subsets of a given set
30 May, 2022 Given an array of integers, print sums of all subsets in it. Output sums can be printed in any order. Examples : Input : arr[] = {2, 3} Output: 0 2 3 5 Input : arr[] = {2, 4, 5} Output : 0 2 4 5 6 7 9 11 Method 1 (Recursive) We can recursively solve this problem. There are total 2n subsets. For every element, we consider two choices, we include it in a subset and we don’t include it in a subset. Below is recursive solution based on this idea. C++ Java Python3 C# PHP Javascript // C++ program to print sums of all possible// subsets.#include <bits/stdc++.h>using namespace std; // Prints sums of all subsets of arr[l..r]void subsetSums(int arr[], int l, int r, int sum = 0){ // Print current subset if (l > r) { cout << sum << " "; return; } // Subset including arr[l] subsetSums(arr, l + 1, r, sum + arr[l]); // Subset excluding arr[l] subsetSums(arr, l + 1, r, sum);} // Driver codeint main(){ int arr[] = { 5, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); subsetSums(arr, 0, n - 1); return 0;} // Java program to print sums// of all possible subsets.import java.io.*; class GFG { // Prints sums of all // subsets of arr[l..r] static void subsetSums(int[] arr, int l, int r, int sum) { // Print current subset if (l > r) { System.out.print(sum + " "); return; } // Subset including arr[l] subsetSums(arr, l + 1, r, sum + arr[l]); // Subset excluding arr[l] subsetSums(arr, l + 1, r, sum); } // Driver code public static void main(String[] args) { int[] arr = { 5, 4, 3 }; int n = arr.length; subsetSums(arr, 0, n - 1, 0); }} // This code is contributed by anuj_67 # Python3 program to print sums of# all possible subsets. # Prints sums of all subsets of arr[l..r] def subsetSums(arr, l, r, sum=0): # Print current subset if l > r: print(sum, end=" ") return # Subset including arr[l] subsetSums(arr, l + 1, r, sum + arr[l]) # Subset excluding arr[l] subsetSums(arr, l + 1, r, sum) # Driver codearr = [5, 4, 3]n = len(arr)subsetSums(arr, 0, n - 1) # This code is contributed by Shreyanshi Arun. // C# program to print sums of all possible// subsets.using System; class GFG { // Prints sums of all subsets of // arr[l..r] static void subsetSums(int[] arr, int l, int r, int sum) { // Print current subset if (l > r) { Console.Write(sum + " "); return; } // Subset including arr[l] subsetSums(arr, l + 1, r, sum + arr[l]); // Subset excluding arr[l] subsetSums(arr, l + 1, r, sum); } // Driver code public static void Main() { int[] arr = { 5, 4, 3 }; int n = arr.Length; subsetSums(arr, 0, n - 1, 0); }} // This code is contributed by anuj_67 <?php// PHP program to print sums// of all possible subsets. // Prints sums of all// subsets of arr[l..r]function subsetSums($arr, $l, $r, $sum = 0){ // Print current subset if ($l > $r) { echo $sum , " "; return; } // Subset including arr[l] subsetSums($arr, $l + 1, $r, $sum + $arr[$l]); // Subset excluding arr[l] subsetSums($arr, $l + 1, $r, $sum);} // Driver code$arr = array(5, 4, 3);$n = count($arr); subsetSums($arr, 0, $n - 1); // This code is contributed by anuj_67.?> <script>// Javascript program to program to print// sums of all possible subsets. // Prints sums of all// subsets of arr[l..r]function subsetSums(arr, l, r, sum){ // Print current subset if (l > r) { document.write(sum + " "); return; } // Subset including arr[l] subsetSums(arr, l + 1, r, sum + arr[l]); // Subset excluding arr[l] subsetSums(arr, l + 1, r, sum);} // Driver codelet arr = [5, 4, 3];let n = arr.length; subsetSums(arr, 0, n - 1, 0); // This code is contributed by code_hunt </script> Output : 12 9 8 5 7 4 3 0 Time complexity : O(2^n) Auxiliary Space : O(n) Method 2 (Iterative) As discussed above, there are total 2n subsets. The idea is generate loop from 0 to 2n – 1. For every number, pick all array elements which correspond to 1s in binary representation of current number. C++ Java Python3 C# PHP Javascript // Iterative C++ program to print sums of all// possible subsets.#include <bits/stdc++.h>using namespace std; // Prints sums of all subsets of arrayvoid subsetSums(int arr[], int n){ // There are total 2^n subsets long long total = 1 << n; // Consider all numbers from 0 to 2^n - 1 for (long long i = 0; i < total; i++) { long long sum = 0; // Consider binary representation of // current i to decide which elements // to pick. for (int j = 0; j < n; j++) if (i & (1 << j)) sum += arr[j]; // Print sum of picked elements. cout << sum << " "; }} // Driver codeint main(){ int arr[] = { 5, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); subsetSums(arr, n); return 0;} // Iterative Java program to print sums of all// possible subsets.import java.util.*; class GFG { // Prints sums of all subsets of array static void subsetSums(int arr[], int n) { // There are total 2^n subsets int total = 1 << n; // Consider all numbers from 0 to 2^n - 1 for (int i = 0; i < total; i++) { int sum = 0; // Consider binary representation of // current i to decide which elements // to pick. for (int j = 0; j < n; j++) if ((i & (1 << j)) != 0) sum += arr[j]; // Print sum of picked elements. System.out.print(sum + " "); } } // Driver code public static void main(String args[]) { int arr[] = new int[] { 5, 4, 3 }; int n = arr.length; subsetSums(arr, n); }} // This code is contributed by spp____ # Iterative Python3 program to print sums of all possible subsets # Prints sums of all subsets of arraydef subsetSums(arr, n): # There are total 2^n subsets total = 1 << n # Consider all numbers from 0 to 2^n - 1 for i in range(total): Sum = 0 # Consider binary representation of # current i to decide which elements # to pick. for j in range(n): if ((i & (1 << j)) != 0): Sum += arr[j] # Print sum of picked elements. print(Sum, "", end = "") arr = [ 5, 4, 3 ]n = len(arr) subsetSums(arr, n); # This code is contributed by mukesh07. // Iterative C# program to print sums of all// possible subsets.using System;class GFG { // Prints sums of all subsets of array static void subsetSums(int[] arr, int n) { // There are total 2^n subsets int total = 1 << n; // Consider all numbers from 0 to 2^n - 1 for (int i = 0; i < total; i++) { int sum = 0; // Consider binary representation of // current i to decide which elements // to pick. for (int j = 0; j < n; j++) if ((i & (1 << j)) != 0) sum += arr[j]; // Print sum of picked elements. Console.Write(sum + " "); } } static void Main() { int[] arr = { 5, 4, 3 }; int n = arr.Length; subsetSums(arr, n); }} // This code is contributed by divyesh072019. <?php// Iterative PHP program to print// sums of all possible subsets. // Prints sums of all subsets of arrayfunction subsetSums($arr, $n){ // There are total 2^n subsets $total = 1 << $n; // Consider all numbers // from 0 to 2^n - 1 for ($i = 0; $i < $total; $i++) { $sum = 0; // Consider binary representation of // current i to decide which elements // to pick. for ($j = 0; $j < $n; $j++) if ($i & (1 << $j)) $sum += $arr[$j]; // Print sum of picked elements. echo $sum , " "; }} // Driver code $arr = array(5, 4, 3); $n = sizeof($arr); subsetSums($arr, $n); // This Code is Contributed by ajit?> <script> // Iterative Javascript program to print sums of all // possible subsets. // Prints sums of all subsets of array function subsetSums(arr, n) { // There are total 2^n subsets let total = 1 << n; // Consider all numbers from 0 to 2^n - 1 for(let i = 0; i < total; i++) { let sum = 0; // Consider binary representation of // current i to decide which elements // to pick. for(let j = 0; j < n; j++) if ((i & (1 << j)) != 0) sum += arr[j]; // Print sum of picked elements. document.write(sum + " "); } } let arr = [ 5, 4, 3 ]; let n = arr.length; subsetSums(arr, n); </script> Output : 0 5 4 9 3 8 7 12 Time Complexity: O()Auxiliary Space: O(1) Thanks to cfh for suggesting above iterative solution in a comment.Note: We haven’t actually created sub-sets to find their sums rather we have just used recursion to find sum of non-contiguous sub-sets of the given set. The above mentioned techniques can be used to perform various operations on sub-sets like multiplication, division, XOR, OR, etc, without actually creating and storing the sub-sets and thus making the program memory efficient. This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m jit_t spp____ code_hunt divyeshrabadiya07 atulp99945 rgarg2580 varshagumber28 pankajsharmagfg divyesh072019 mukesh07 avtarkumar719 as5853535 abhigyanpatek Algorithms Recursion Recursion Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Understanding Time Complexity with Simple Examples CPU Scheduling in Operating Systems Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Program for Tower of Hanoi Backtracking | Introduction Print all subsequences of a string Recursive Practice Problems with Solutions
[ { "code": null, "e": 54, "s": 26, "text": "\n30 May, 2022" }, { "code": null, "e": 156, "s": 54, "text": "Given an array of integers, print sums of all subsets in it. Output sums can be printed in any order." }, { "code": null, "e": 168, "s": 156, "text": "Examples : " }, { "code": null, "e": 260, "s": 168, "text": "Input : arr[] = {2, 3}\nOutput: 0 2 3 5\n\nInput : arr[] = {2, 4, 5}\nOutput : 0 2 4 5 6 7 9 11" }, { "code": null, "e": 505, "s": 260, "text": "Method 1 (Recursive) We can recursively solve this problem. There are total 2n subsets. For every element, we consider two choices, we include it in a subset and we don’t include it in a subset. Below is recursive solution based on this idea. " }, { "code": null, "e": 509, "s": 505, "text": "C++" }, { "code": null, "e": 514, "s": 509, "text": "Java" }, { "code": null, "e": 522, "s": 514, "text": "Python3" }, { "code": null, "e": 525, "s": 522, "text": "C#" }, { "code": null, "e": 529, "s": 525, "text": "PHP" }, { "code": null, "e": 540, "s": 529, "text": "Javascript" }, { "code": "// C++ program to print sums of all possible// subsets.#include <bits/stdc++.h>using namespace std; // Prints sums of all subsets of arr[l..r]void subsetSums(int arr[], int l, int r, int sum = 0){ // Print current subset if (l > r) { cout << sum << \" \"; return; } // Subset including arr[l] subsetSums(arr, l + 1, r, sum + arr[l]); // Subset excluding arr[l] subsetSums(arr, l + 1, r, sum);} // Driver codeint main(){ int arr[] = { 5, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); subsetSums(arr, 0, n - 1); return 0;}", "e": 1109, "s": 540, "text": null }, { "code": "// Java program to print sums// of all possible subsets.import java.io.*; class GFG { // Prints sums of all // subsets of arr[l..r] static void subsetSums(int[] arr, int l, int r, int sum) { // Print current subset if (l > r) { System.out.print(sum + \" \"); return; } // Subset including arr[l] subsetSums(arr, l + 1, r, sum + arr[l]); // Subset excluding arr[l] subsetSums(arr, l + 1, r, sum); } // Driver code public static void main(String[] args) { int[] arr = { 5, 4, 3 }; int n = arr.length; subsetSums(arr, 0, n - 1, 0); }} // This code is contributed by anuj_67", "e": 1803, "s": 1109, "text": null }, { "code": "# Python3 program to print sums of# all possible subsets. # Prints sums of all subsets of arr[l..r] def subsetSums(arr, l, r, sum=0): # Print current subset if l > r: print(sum, end=\" \") return # Subset including arr[l] subsetSums(arr, l + 1, r, sum + arr[l]) # Subset excluding arr[l] subsetSums(arr, l + 1, r, sum) # Driver codearr = [5, 4, 3]n = len(arr)subsetSums(arr, 0, n - 1) # This code is contributed by Shreyanshi Arun.", "e": 2270, "s": 1803, "text": null }, { "code": "// C# program to print sums of all possible// subsets.using System; class GFG { // Prints sums of all subsets of // arr[l..r] static void subsetSums(int[] arr, int l, int r, int sum) { // Print current subset if (l > r) { Console.Write(sum + \" \"); return; } // Subset including arr[l] subsetSums(arr, l + 1, r, sum + arr[l]); // Subset excluding arr[l] subsetSums(arr, l + 1, r, sum); } // Driver code public static void Main() { int[] arr = { 5, 4, 3 }; int n = arr.Length; subsetSums(arr, 0, n - 1, 0); }} // This code is contributed by anuj_67", "e": 2942, "s": 2270, "text": null }, { "code": "<?php// PHP program to print sums// of all possible subsets. // Prints sums of all// subsets of arr[l..r]function subsetSums($arr, $l, $r, $sum = 0){ // Print current subset if ($l > $r) { echo $sum , \" \"; return; } // Subset including arr[l] subsetSums($arr, $l + 1, $r, $sum + $arr[$l]); // Subset excluding arr[l] subsetSums($arr, $l + 1, $r, $sum);} // Driver code$arr = array(5, 4, 3);$n = count($arr); subsetSums($arr, 0, $n - 1); // This code is contributed by anuj_67.?>", "e": 3494, "s": 2942, "text": null }, { "code": "<script>// Javascript program to program to print// sums of all possible subsets. // Prints sums of all// subsets of arr[l..r]function subsetSums(arr, l, r, sum){ // Print current subset if (l > r) { document.write(sum + \" \"); return; } // Subset including arr[l] subsetSums(arr, l + 1, r, sum + arr[l]); // Subset excluding arr[l] subsetSums(arr, l + 1, r, sum);} // Driver codelet arr = [5, 4, 3];let n = arr.length; subsetSums(arr, 0, n - 1, 0); // This code is contributed by code_hunt </script>", "e": 4078, "s": 3494, "text": null }, { "code": null, "e": 4088, "s": 4078, "text": "Output : " }, { "code": null, "e": 4105, "s": 4088, "text": "12 9 8 5 7 4 3 0" }, { "code": null, "e": 4131, "s": 4105, "text": "Time complexity : O(2^n) " }, { "code": null, "e": 4154, "s": 4131, "text": "Auxiliary Space : O(n)" }, { "code": null, "e": 4376, "s": 4154, "text": "Method 2 (Iterative) As discussed above, there are total 2n subsets. The idea is generate loop from 0 to 2n – 1. For every number, pick all array elements which correspond to 1s in binary representation of current number." }, { "code": null, "e": 4380, "s": 4376, "text": "C++" }, { "code": null, "e": 4385, "s": 4380, "text": "Java" }, { "code": null, "e": 4393, "s": 4385, "text": "Python3" }, { "code": null, "e": 4396, "s": 4393, "text": "C#" }, { "code": null, "e": 4400, "s": 4396, "text": "PHP" }, { "code": null, "e": 4411, "s": 4400, "text": "Javascript" }, { "code": "// Iterative C++ program to print sums of all// possible subsets.#include <bits/stdc++.h>using namespace std; // Prints sums of all subsets of arrayvoid subsetSums(int arr[], int n){ // There are total 2^n subsets long long total = 1 << n; // Consider all numbers from 0 to 2^n - 1 for (long long i = 0; i < total; i++) { long long sum = 0; // Consider binary representation of // current i to decide which elements // to pick. for (int j = 0; j < n; j++) if (i & (1 << j)) sum += arr[j]; // Print sum of picked elements. cout << sum << \" \"; }} // Driver codeint main(){ int arr[] = { 5, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); subsetSums(arr, n); return 0;}", "e": 5182, "s": 4411, "text": null }, { "code": "// Iterative Java program to print sums of all// possible subsets.import java.util.*; class GFG { // Prints sums of all subsets of array static void subsetSums(int arr[], int n) { // There are total 2^n subsets int total = 1 << n; // Consider all numbers from 0 to 2^n - 1 for (int i = 0; i < total; i++) { int sum = 0; // Consider binary representation of // current i to decide which elements // to pick. for (int j = 0; j < n; j++) if ((i & (1 << j)) != 0) sum += arr[j]; // Print sum of picked elements. System.out.print(sum + \" \"); } } // Driver code public static void main(String args[]) { int arr[] = new int[] { 5, 4, 3 }; int n = arr.length; subsetSums(arr, n); }} // This code is contributed by spp____", "e": 6094, "s": 5182, "text": null }, { "code": "# Iterative Python3 program to print sums of all possible subsets # Prints sums of all subsets of arraydef subsetSums(arr, n): # There are total 2^n subsets total = 1 << n # Consider all numbers from 0 to 2^n - 1 for i in range(total): Sum = 0 # Consider binary representation of # current i to decide which elements # to pick. for j in range(n): if ((i & (1 << j)) != 0): Sum += arr[j] # Print sum of picked elements. print(Sum, \"\", end = \"\") arr = [ 5, 4, 3 ]n = len(arr) subsetSums(arr, n); # This code is contributed by mukesh07.", "e": 6707, "s": 6094, "text": null }, { "code": "// Iterative C# program to print sums of all// possible subsets.using System;class GFG { // Prints sums of all subsets of array static void subsetSums(int[] arr, int n) { // There are total 2^n subsets int total = 1 << n; // Consider all numbers from 0 to 2^n - 1 for (int i = 0; i < total; i++) { int sum = 0; // Consider binary representation of // current i to decide which elements // to pick. for (int j = 0; j < n; j++) if ((i & (1 << j)) != 0) sum += arr[j]; // Print sum of picked elements. Console.Write(sum + \" \"); } } static void Main() { int[] arr = { 5, 4, 3 }; int n = arr.Length; subsetSums(arr, n); }} // This code is contributed by divyesh072019.", "e": 7563, "s": 6707, "text": null }, { "code": "<?php// Iterative PHP program to print// sums of all possible subsets. // Prints sums of all subsets of arrayfunction subsetSums($arr, $n){ // There are total 2^n subsets $total = 1 << $n; // Consider all numbers // from 0 to 2^n - 1 for ($i = 0; $i < $total; $i++) { $sum = 0; // Consider binary representation of // current i to decide which elements // to pick. for ($j = 0; $j < $n; $j++) if ($i & (1 << $j)) $sum += $arr[$j]; // Print sum of picked elements. echo $sum , \" \"; }} // Driver code $arr = array(5, 4, 3); $n = sizeof($arr); subsetSums($arr, $n); // This Code is Contributed by ajit?>", "e": 8293, "s": 7563, "text": null }, { "code": "<script> // Iterative Javascript program to print sums of all // possible subsets. // Prints sums of all subsets of array function subsetSums(arr, n) { // There are total 2^n subsets let total = 1 << n; // Consider all numbers from 0 to 2^n - 1 for(let i = 0; i < total; i++) { let sum = 0; // Consider binary representation of // current i to decide which elements // to pick. for(let j = 0; j < n; j++) if ((i & (1 << j)) != 0) sum += arr[j]; // Print sum of picked elements. document.write(sum + \" \"); } } let arr = [ 5, 4, 3 ]; let n = arr.length; subsetSums(arr, n); </script>", "e": 9065, "s": 8293, "text": null }, { "code": null, "e": 9075, "s": 9065, "text": "Output : " }, { "code": null, "e": 9093, "s": 9075, "text": "0 5 4 9 3 8 7 12 " }, { "code": null, "e": 9356, "s": 9093, "text": "Time Complexity: O()Auxiliary Space: O(1) Thanks to cfh for suggesting above iterative solution in a comment.Note: We haven’t actually created sub-sets to find their sums rather we have just used recursion to find sum of non-contiguous sub-sets of the given set." }, { "code": null, "e": 10003, "s": 9356, "text": "The above mentioned techniques can be used to perform various operations on sub-sets like multiplication, division, XOR, OR, etc, without actually creating and storing the sub-sets and thus making the program memory efficient. This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 10008, "s": 10003, "text": "vt_m" }, { "code": null, "e": 10014, "s": 10008, "text": "jit_t" }, { "code": null, "e": 10022, "s": 10014, "text": "spp____" }, { "code": null, "e": 10032, "s": 10022, "text": "code_hunt" }, { "code": null, "e": 10050, "s": 10032, "text": "divyeshrabadiya07" }, { "code": null, "e": 10061, "s": 10050, "text": "atulp99945" }, { "code": null, "e": 10071, "s": 10061, "text": "rgarg2580" }, { "code": null, "e": 10086, "s": 10071, "text": "varshagumber28" }, { "code": null, "e": 10102, "s": 10086, "text": "pankajsharmagfg" }, { "code": null, "e": 10116, "s": 10102, "text": "divyesh072019" }, { "code": null, "e": 10125, "s": 10116, "text": "mukesh07" }, { "code": null, "e": 10139, "s": 10125, "text": "avtarkumar719" }, { "code": null, "e": 10149, "s": 10139, "text": "as5853535" }, { "code": null, "e": 10163, "s": 10149, "text": "abhigyanpatek" }, { "code": null, "e": 10174, "s": 10163, "text": "Algorithms" }, { "code": null, "e": 10184, "s": 10174, "text": "Recursion" }, { "code": null, "e": 10194, "s": 10184, "text": "Recursion" }, { "code": null, "e": 10205, "s": 10194, "text": "Algorithms" }, { "code": null, "e": 10303, "s": 10205, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10328, "s": 10303, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 10377, "s": 10328, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 10415, "s": 10377, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 10466, "s": 10415, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 10502, "s": 10466, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 10587, "s": 10502, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 10614, "s": 10587, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 10642, "s": 10614, "text": "Backtracking | Introduction" }, { "code": null, "e": 10677, "s": 10642, "text": "Print all subsequences of a string" } ]
Sum of all array elements less than X and greater than Y for Q queries
14 Aug, 2020 Given a sorted array arr[], and a set Q having M queries, where each query has values X and Y, the task is to find the sum of all integers less than X and greater than Y present in the array.Note: X and Y may or may not be present in the array. Examples: Input: arr[] = [3 5 8 12 15], Q = {{5, 12}, {4, 8}}Output:1830Explanation:For query 1, X = 5 and Y = 12. Sum = 3( < 5) + 15( > 12) = 18.For query 2, X = 4 and Y = 8. Sum = 3( < 4) + 15 ( > 8) + 12 ( > 8) = 30. Input: arr[] = [4 7 7 12 15], Q = {{3, 8}, {4, 8}}Output:2727Explanation:For query 1, X = 3 and Y = 8. Sum = 12( > 8) + 15 ( > 8) = 27.For query 2, Sum = 12 + 15 = 27. Approach: Build a prefix sum array where prefix_sum[i] denotes the sum of arr[0] + arr[1] + ... arr[i].Find the last index i which has a value less than X and extract the prefix sum up to the ith index. The index can be obtained in O(logN) complexity by using bisect_left() or lower_bound() in Python and C++ respectively..Similarly, find the first index i in the array with a value greater than Y and calculate the sum prefix_sum[n-1] – prefix_sum[i-1]. Inbuilt functions bisect() and upper_bound() in Python and C++ respectively, perform the required operation in O(logN).Sum of the two results calculated in the above two steps is the required answer. Keep repeating these steps for every query. Build a prefix sum array where prefix_sum[i] denotes the sum of arr[0] + arr[1] + ... arr[i]. Find the last index i which has a value less than X and extract the prefix sum up to the ith index. The index can be obtained in O(logN) complexity by using bisect_left() or lower_bound() in Python and C++ respectively.. Similarly, find the first index i in the array with a value greater than Y and calculate the sum prefix_sum[n-1] – prefix_sum[i-1]. Inbuilt functions bisect() and upper_bound() in Python and C++ respectively, perform the required operation in O(logN). Sum of the two results calculated in the above two steps is the required answer. Keep repeating these steps for every query. Below is the implementation of the above approach: Python3 # Python code for the above programfrom bisect import bisect, bisect_left def createPrefixSum(ar, n): # Initialize prefix sum # array prefix_sum = [0]*n # Initialize prefix_sum[0] # by ar[0] prefix_sum[0] = ar[0] # Compute prefix sum for # all indices for i in range(1, n): prefix_sum[i] = prefix_sum[i-1]+ar[i] return prefix_sum # Function to return sum of all# elements less than Xdef sumLessThanX(ar, x, prefix_xum): # Index of the last element # which is less than x pos_x = bisect_left(ar, x) - 1 if pos_x >= 0 : return prefix_sum[pos_x] # If no element is less than x else: return 0 # Function to return sum of all# elements greater than Ydef sumGreaterThanY(ar, y, prefix_sum): # Index of the first element # which is greater than y pos_y = bisect(ar, y) pos_y -= 1 if pos_y < len(ar)-1 : return prefix_sum[-1]-prefix_sum[pos_y] # If no element is greater than y else: return 0 def solve(ar, x, y, prefix_sum): ltx = sumLessThanX(ar, x, prefix_sum) gty = sumGreaterThanY(ar, y, prefix_sum) # printing the final sum print(ltx + gty) def print_l(lb, ub): print("sum of integers less than {}".format(lb) + " and greater than {} is ".format(ub), end = '') if __name__ == '__main__': # example 1 ar = [3, 6, 6, 12, 15] n = len(ar) prefix_sum = createPrefixSum(ar, n) # for query 1 q1x = 5 q1y = 12 print_l(q1x, q1y) solve(ar, q1x, q1y, prefix_sum) # for query 2 q2x = 7 q2y = 8 print_l(q2x, q2y) solve(ar, q2x, q2y, prefix_sum) sum of integers less than 5 and greater than 12 is 18 sum of integers less than 7 and greater than 8 is 42 Time Complexity: O(N + (M * logN))Auxiliary Space complexity: O(N) nidhi_biet array-range-queries Algorithms Arrays Divide and Conquer Searching Arrays Searching Divide and Conquer Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Understanding Time Complexity with Simple Examples Find if there is a path between two vertices in an undirected graph Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Largest Sum Contiguous Subarray Arrays in C/C++
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Aug, 2020" }, { "code": null, "e": 297, "s": 52, "text": "Given a sorted array arr[], and a set Q having M queries, where each query has values X and Y, the task is to find the sum of all integers less than X and greater than Y present in the array.Note: X and Y may or may not be present in the array." }, { "code": null, "e": 307, "s": 297, "text": "Examples:" }, { "code": null, "e": 517, "s": 307, "text": "Input: arr[] = [3 5 8 12 15], Q = {{5, 12}, {4, 8}}Output:1830Explanation:For query 1, X = 5 and Y = 12. Sum = 3( < 5) + 15( > 12) = 18.For query 2, X = 4 and Y = 8. Sum = 3( < 4) + 15 ( > 8) + 12 ( > 8) = 30." }, { "code": null, "e": 685, "s": 517, "text": "Input: arr[] = [4 7 7 12 15], Q = {{3, 8}, {4, 8}}Output:2727Explanation:For query 1, X = 3 and Y = 8. Sum = 12( > 8) + 15 ( > 8) = 27.For query 2, Sum = 12 + 15 = 27." }, { "code": null, "e": 695, "s": 685, "text": "Approach:" }, { "code": null, "e": 1384, "s": 695, "text": "Build a prefix sum array where prefix_sum[i] denotes the sum of arr[0] + arr[1] + ... arr[i].Find the last index i which has a value less than X and extract the prefix sum up to the ith index. The index can be obtained in O(logN) complexity by using bisect_left() or lower_bound() in Python and C++ respectively..Similarly, find the first index i in the array with a value greater than Y and calculate the sum prefix_sum[n-1] – prefix_sum[i-1]. Inbuilt functions bisect() and upper_bound() in Python and C++ respectively, perform the required operation in O(logN).Sum of the two results calculated in the above two steps is the required answer. Keep repeating these steps for every query." }, { "code": null, "e": 1478, "s": 1384, "text": "Build a prefix sum array where prefix_sum[i] denotes the sum of arr[0] + arr[1] + ... arr[i]." }, { "code": null, "e": 1699, "s": 1478, "text": "Find the last index i which has a value less than X and extract the prefix sum up to the ith index. The index can be obtained in O(logN) complexity by using bisect_left() or lower_bound() in Python and C++ respectively.." }, { "code": null, "e": 1951, "s": 1699, "text": "Similarly, find the first index i in the array with a value greater than Y and calculate the sum prefix_sum[n-1] – prefix_sum[i-1]. Inbuilt functions bisect() and upper_bound() in Python and C++ respectively, perform the required operation in O(logN)." }, { "code": null, "e": 2076, "s": 1951, "text": "Sum of the two results calculated in the above two steps is the required answer. Keep repeating these steps for every query." }, { "code": null, "e": 2127, "s": 2076, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2135, "s": 2127, "text": "Python3" }, { "code": "# Python code for the above programfrom bisect import bisect, bisect_left def createPrefixSum(ar, n): # Initialize prefix sum # array prefix_sum = [0]*n # Initialize prefix_sum[0] # by ar[0] prefix_sum[0] = ar[0] # Compute prefix sum for # all indices for i in range(1, n): prefix_sum[i] = prefix_sum[i-1]+ar[i] return prefix_sum # Function to return sum of all# elements less than Xdef sumLessThanX(ar, x, prefix_xum): # Index of the last element # which is less than x pos_x = bisect_left(ar, x) - 1 if pos_x >= 0 : return prefix_sum[pos_x] # If no element is less than x else: return 0 # Function to return sum of all# elements greater than Ydef sumGreaterThanY(ar, y, prefix_sum): # Index of the first element # which is greater than y pos_y = bisect(ar, y) pos_y -= 1 if pos_y < len(ar)-1 : return prefix_sum[-1]-prefix_sum[pos_y] # If no element is greater than y else: return 0 def solve(ar, x, y, prefix_sum): ltx = sumLessThanX(ar, x, prefix_sum) gty = sumGreaterThanY(ar, y, prefix_sum) # printing the final sum print(ltx + gty) def print_l(lb, ub): print(\"sum of integers less than {}\".format(lb) + \" and greater than {} is \".format(ub), end = '') if __name__ == '__main__': # example 1 ar = [3, 6, 6, 12, 15] n = len(ar) prefix_sum = createPrefixSum(ar, n) # for query 1 q1x = 5 q1y = 12 print_l(q1x, q1y) solve(ar, q1x, q1y, prefix_sum) # for query 2 q2x = 7 q2y = 8 print_l(q2x, q2y) solve(ar, q2x, q2y, prefix_sum)", "e": 3784, "s": 2135, "text": null }, { "code": null, "e": 3892, "s": 3784, "text": "sum of integers less than 5 and greater than 12 is 18\nsum of integers less than 7 and greater than 8 is 42\n" }, { "code": null, "e": 3959, "s": 3892, "text": "Time Complexity: O(N + (M * logN))Auxiliary Space complexity: O(N)" }, { "code": null, "e": 3970, "s": 3959, "text": "nidhi_biet" }, { "code": null, "e": 3990, "s": 3970, "text": "array-range-queries" }, { "code": null, "e": 4001, "s": 3990, "text": "Algorithms" }, { "code": null, "e": 4008, "s": 4001, "text": "Arrays" }, { "code": null, "e": 4027, "s": 4008, "text": "Divide and Conquer" }, { "code": null, "e": 4037, "s": 4027, "text": "Searching" }, { "code": null, "e": 4044, "s": 4037, "text": "Arrays" }, { "code": null, "e": 4054, "s": 4044, "text": "Searching" }, { "code": null, "e": 4073, "s": 4054, "text": "Divide and Conquer" }, { "code": null, "e": 4084, "s": 4073, "text": "Algorithms" }, { "code": null, "e": 4182, "s": 4084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4207, "s": 4182, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 4256, "s": 4207, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 4294, "s": 4256, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 4345, "s": 4294, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 4413, "s": 4345, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 4428, "s": 4413, "text": "Arrays in Java" }, { "code": null, "e": 4474, "s": 4428, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 4542, "s": 4474, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 4574, "s": 4542, "text": "Largest Sum Contiguous Subarray" } ]
How to add simple DatePicker in Next.js ?
30 Nov, 2021 In this article, we are going to learn how we can add a Simple Datepicker in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally. Approach: To add our DatePicker we are going to use the react-datepicker package. The react-datepicker package helps us to add a DatePicker anywhere in our app. So first, we will install the react-datepicker package and then we will add a DatePicker on our homepage. Create NextJS Application: You can create a new NextJs project using the below command: npx create-next-app gfg Install the required package: Now we will install the react-datepicker package using the below command: npm i react-datepicker Project Structure: It will look like this Adding the DatePicker: We can easily add the DatePicker in our app after installing the react-datepicker package. For this example, we are going to add the DatePicker to our homepage. Add the below content in the file: index.js import React, { useState } from 'react';import DatePicker from "react-datindex.jsepicker";import "react-datepicker/dist/react-datepicker.css"; export default function GfgDatePicker() { const [startDate, setStartDate] = useState(new Date()); return ( <div> <h4>GeeksforGeeks - DatePicker</h4> <DatePicker selected={startDate} onChange= {(date) => setStartDate(date)} /> </div> );} Explanation: In the above example first, we are importing the DatePocker from the installed package and useState hook from react. After that, we are using creating a constant variable and used the useState hook to store the values. Then we will add our datepicker using the DatePicker component. Steps to run the application: Run the below command in the terminal to run the app. npm run dev Next.js JavaScript Node.js ReactJS 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 How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request How to update Node.js and NPM to next version ? Installation of Node.js on Linux Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to install the previous version of node.js and npm ?
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Nov, 2021" }, { "code": null, "e": 343, "s": 28, "text": "In this article, we are going to learn how we can add a Simple Datepicker in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally." }, { "code": null, "e": 610, "s": 343, "text": "Approach: To add our DatePicker we are going to use the react-datepicker package. The react-datepicker package helps us to add a DatePicker anywhere in our app. So first, we will install the react-datepicker package and then we will add a DatePicker on our homepage." }, { "code": null, "e": 698, "s": 610, "text": "Create NextJS Application: You can create a new NextJs project using the below command:" }, { "code": null, "e": 722, "s": 698, "text": "npx create-next-app gfg" }, { "code": null, "e": 826, "s": 722, "text": "Install the required package: Now we will install the react-datepicker package using the below command:" }, { "code": null, "e": 849, "s": 826, "text": "npm i react-datepicker" }, { "code": null, "e": 891, "s": 849, "text": "Project Structure: It will look like this" }, { "code": null, "e": 1075, "s": 891, "text": "Adding the DatePicker: We can easily add the DatePicker in our app after installing the react-datepicker package. For this example, we are going to add the DatePicker to our homepage." }, { "code": null, "e": 1110, "s": 1075, "text": "Add the below content in the file:" }, { "code": null, "e": 1119, "s": 1110, "text": "index.js" }, { "code": "import React, { useState } from 'react';import DatePicker from \"react-datindex.jsepicker\";import \"react-datepicker/dist/react-datepicker.css\"; export default function GfgDatePicker() { const [startDate, setStartDate] = useState(new Date()); return ( <div> <h4>GeeksforGeeks - DatePicker</h4> <DatePicker selected={startDate} onChange= {(date) => setStartDate(date)} /> </div> );}", "e": 1534, "s": 1119, "text": null }, { "code": null, "e": 1830, "s": 1534, "text": "Explanation: In the above example first, we are importing the DatePocker from the installed package and useState hook from react. After that, we are using creating a constant variable and used the useState hook to store the values. Then we will add our datepicker using the DatePicker component." }, { "code": null, "e": 1914, "s": 1830, "text": "Steps to run the application: Run the below command in the terminal to run the app." }, { "code": null, "e": 1926, "s": 1914, "text": "npm run dev" }, { "code": null, "e": 1934, "s": 1926, "text": "Next.js" }, { "code": null, "e": 1945, "s": 1934, "text": "JavaScript" }, { "code": null, "e": 1953, "s": 1945, "text": "Node.js" }, { "code": null, "e": 1961, "s": 1953, "text": "ReactJS" }, { "code": null, "e": 1978, "s": 1961, "text": "Web Technologies" }, { "code": null, "e": 2076, "s": 1978, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2137, "s": 2076, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2209, "s": 2137, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2249, "s": 2209, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2301, "s": 2249, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2342, "s": 2301, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2390, "s": 2342, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2423, "s": 2390, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2456, "s": 2423, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 2486, "s": 2456, "text": "Node.js fs.writeFile() Method" } ]
Decidability, Semi-Decidability, and Undecidability in TOC
08 Apr, 2021 We know about Decidable, Semi-decidable, and Undecidable problems and in this article, we will briefly define these problems and provide the most commonly asked questions on these problems and classify them accordingly. Prerequisite – https://www.geeksforgeeks.org/decidable-and-undecidable-problems-in-theory-of-computation/ Introduction :Identifying the type of language is a very frequently asked question in Gate and other exams. However, there are some problems which are frequently asked and here in this article we shall discuss all those problems. We shall also solve few examples in this article to make the topic more clear. Decidable Problems : The decidable problems are those problems for which there exists a corresponding Turing machine that halts on every input with an answer- yes (accepting) or no (rejecting). It is also called Turing Decidable. Semi-Decidable Problems : Semi-Decidable problems are those problems for which a Turing machine halts on the input accepted by it but can either loop forever or halt on the input which is rejected by the Turing Machine. It is also called Turing Recognizable problems. Undecidable Problems : Undecidable problems are those problems for which there exists no Turing machine which will always halt an infinite amount of time to give an answer as ‘yes’ or ‘no’. An undecidable problem has no algorithm to determine the answer for a given input. It can be partially decidable but never decidable. They are also known as Non-Recursively Enumerable Language. Classification Table:Now we will classify most commonly asked problems as Decidable, Semi-decidable and Undecidable. Here in the tables below, D means Decidable, SD means Semi-Decidable and NR means Not-Recursively Enumerable. Undecidable can be either Semi-Decidable or Not-Recursively Enumerable language. Decidability Classification Table :Another table is as follows. Examples :Here, we will discuss some examples for better understanding as follows. Example-1 : {TM | No. of states in TM=2. } Solution –Decidable as for this we have to find no. of nodes in the graph. Example-2 : TM halts after 100 moves.Solution – Decidable as we have logic for both ‘yes’ or ‘no’. Yes : No string halts within 100 moves. (Check up to 100 length string). No : At least one string halts within 100 moves. Example-3 : TM halts on w after 100 moves.Solution – Semi-Decidable as we have logic for only ‘yes’ and no logic for ‘no’. Yes : Halts after 100 moves has a logic. No : Doesn't halt after 100 moves have no logic as can go into an infinite loop or never halt. Example-4 : TM reaches state q.Solution – Semi-Decidable as we have logic for only ‘yes’ and no logic for ‘no’. Yes : We have logic for yes as TM reaches state q we will come to know. No : No logic for no as TM can never reach state q or can fall into an infinite loop before reaching q and will never come to know. Example-5 : Consider when given grammar generates Context Free Language.Solution – Undecidable as we have no logic for ‘Yes’ — that the given grammar generates CFL. GATE CS Theory of Computation Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Clustered and Non-clustered index Three address code in Compiler Introduction of Process Synchronization Differences between IPv4 and IPv6 Phases of a Compiler Difference Between NPDA and DPDA Construct a DFA that Start With aa or bb Conversion of Regular Expression to Finite Automata GATE | GATE CS 2012 | Question 23 Automata Theory | Set 8
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Apr, 2021" }, { "code": null, "e": 273, "s": 52, "text": "We know about Decidable, Semi-decidable, and Undecidable problems and in this article, we will briefly define these problems and provide the most commonly asked questions on these problems and classify them accordingly. " }, { "code": null, "e": 379, "s": 273, "text": "Prerequisite – https://www.geeksforgeeks.org/decidable-and-undecidable-problems-in-theory-of-computation/" }, { "code": null, "e": 689, "s": 379, "text": "Introduction :Identifying the type of language is a very frequently asked question in Gate and other exams. However, there are some problems which are frequently asked and here in this article we shall discuss all those problems. We shall also solve few examples in this article to make the topic more clear. " }, { "code": null, "e": 921, "s": 689, "text": "Decidable Problems : The decidable problems are those problems for which there exists a corresponding Turing machine that halts on every input with an answer- yes (accepting) or no (rejecting). It is also called Turing Decidable." }, { "code": null, "e": 1189, "s": 921, "text": "Semi-Decidable Problems : Semi-Decidable problems are those problems for which a Turing machine halts on the input accepted by it but can either loop forever or halt on the input which is rejected by the Turing Machine. It is also called Turing Recognizable problems." }, { "code": null, "e": 1574, "s": 1189, "text": "Undecidable Problems : Undecidable problems are those problems for which there exists no Turing machine which will always halt an infinite amount of time to give an answer as ‘yes’ or ‘no’. An undecidable problem has no algorithm to determine the answer for a given input. It can be partially decidable but never decidable. They are also known as Non-Recursively Enumerable Language. " }, { "code": null, "e": 1882, "s": 1574, "text": "Classification Table:Now we will classify most commonly asked problems as Decidable, Semi-decidable and Undecidable. Here in the tables below, D means Decidable, SD means Semi-Decidable and NR means Not-Recursively Enumerable. Undecidable can be either Semi-Decidable or Not-Recursively Enumerable language." }, { "code": null, "e": 1946, "s": 1882, "text": "Decidability Classification Table :Another table is as follows." }, { "code": null, "e": 2029, "s": 1946, "text": "Examples :Here, we will discuss some examples for better understanding as follows." }, { "code": null, "e": 2147, "s": 2029, "text": "Example-1 : {TM | No. of states in TM=2. } Solution –Decidable as for this we have to find no. of nodes in the graph." }, { "code": null, "e": 2247, "s": 2147, "text": "Example-2 : TM halts after 100 moves.Solution – Decidable as we have logic for both ‘yes’ or ‘no’. " }, { "code": null, "e": 2370, "s": 2247, "text": "Yes : No string halts within 100 moves. (Check up to 100 length string).\nNo : At least one string halts within 100 moves." }, { "code": null, "e": 2493, "s": 2370, "text": "Example-3 : TM halts on w after 100 moves.Solution – Semi-Decidable as we have logic for only ‘yes’ and no logic for ‘no’." }, { "code": null, "e": 2630, "s": 2493, "text": "Yes : Halts after 100 moves has a logic.\nNo : Doesn't halt after 100 moves have no logic as can go into an infinite loop or never halt." }, { "code": null, "e": 2742, "s": 2630, "text": "Example-4 : TM reaches state q.Solution – Semi-Decidable as we have logic for only ‘yes’ and no logic for ‘no’." }, { "code": null, "e": 2954, "s": 2742, "text": "Yes : We have logic for yes as TM reaches state q we will come to know.\nNo : No logic for no as TM can never reach state q or can fall into \n an infinite loop before reaching q and will never come to know." }, { "code": null, "e": 3119, "s": 2954, "text": "Example-5 : Consider when given grammar generates Context Free Language.Solution – Undecidable as we have no logic for ‘Yes’ — that the given grammar generates CFL." }, { "code": null, "e": 3127, "s": 3119, "text": "GATE CS" }, { "code": null, "e": 3149, "s": 3127, "text": "Theory of Computation" }, { "code": null, "e": 3247, "s": 3149, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3300, "s": 3247, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 3331, "s": 3300, "text": "Three address code in Compiler" }, { "code": null, "e": 3371, "s": 3331, "text": "Introduction of Process Synchronization" }, { "code": null, "e": 3405, "s": 3371, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 3426, "s": 3405, "text": "Phases of a Compiler" }, { "code": null, "e": 3459, "s": 3426, "text": "Difference Between NPDA and DPDA" }, { "code": null, "e": 3500, "s": 3459, "text": "Construct a DFA that Start With aa or bb" }, { "code": null, "e": 3552, "s": 3500, "text": "Conversion of Regular Expression to Finite Automata" }, { "code": null, "e": 3586, "s": 3552, "text": "GATE | GATE CS 2012 | Question 23" } ]
Append multiple lists at once in Python
For various data analysis work in python we may be needed to combine many python lists into one list. This will help processing it as a single input list for the other parts of the program that need it. It provides performance gains by reducing number of loops required for processing the data further. The + operator does a straight forward job of joining the lists together. We just apply the operator between the name of the lists and the final result is stored in the bigger list. The sequence of the elements in the lists are preserved. Live Demo listA = ['Mon', 'Tue', 'Wed'] listB = ['2 pm', '11 am','1 pm'] listC = [1, 3, 6] # Given lists print("Given list A: " ,listA) print("Given list B: " ,listB) print("Given list C: ",listC) # using + operator res_list = listA + listB + listC # printing result print("Combined list is : ",res_list) Running the above code gives us the following result − Given list A: ['Mon', 'Tue', 'Wed'] Given list B: ['2 pm', '11 am', '1 pm'] Given list C: [1, 3, 6] Combined list is : ['Mon', 'Tue', 'Wed', '2 pm', '11 am', '1 pm', 1, 3, 6] The zip function brings together elements form each of the lists from the same index and then moves on to the next index. This type of appending is useful when you want to preserver the elements form the lists at the same index position together. Live Demo listA = ['Mon', 'Tue', 'Wed'] listB = ['2 pm', '11 am','1 pm'] listC = [1, 3, 6] # Given lists print("Given list A: " ,listA) print("Given list B: " ,listB) print("Given list C: ",listC) # using zip res_list = list(zip(listA,listB , listC)) # printing result print("Combined list is : ",res_list) Running the above code gives us the following result − Given list A: ['Mon', 'Tue', 'Wed'] Given list B: ['2 pm', '11 am', '1 pm'] Given list C: [1, 3, 6] Combined list is : [('Mon', '2 pm', 1), ('Tue', '11 am', 3), ('Wed', '1 pm', 6)] The chain function from itertools module can bring the elements of the lists together preserving the sequence in which they are present. Live Demo from itertools import chain listA = ['Mon', 'Tue', 'Wed'] listB = ['2 pm', '11 am','1 pm'] listC = [1, 3, 6] # Given lists print("Given list A: " ,listA) print("Given list B: " ,listB) print("Given list C: ",listC) # using chain res_list = list(chain(listA, listB, listC)) # printing result print("Combined list is : ",res_list) Running the above code gives us the following result − Given list A: ['Mon', 'Tue', 'Wed'] Given list B: ['2 pm', '11 am', '1 pm'] Given list C: [1, 3, 6] Combined list is : ['Mon', 'Tue', 'Wed', '2 pm', '11 am', '1 pm', 1, 3, 6]
[ { "code": null, "e": 1490, "s": 1187, "text": "For various data analysis work in python we may be needed to combine many python lists into one list. This will help processing it as a single input list for the other parts of the program that need it. It provides performance gains by reducing number of loops required for processing the data further." }, { "code": null, "e": 1729, "s": 1490, "text": "The + operator does a straight forward job of joining the lists together. We just apply the operator between the name of the lists and the final result is stored in the bigger list. The sequence of the elements in the lists are preserved." }, { "code": null, "e": 1740, "s": 1729, "text": " Live Demo" }, { "code": null, "e": 2038, "s": 1740, "text": "listA = ['Mon', 'Tue', 'Wed']\nlistB = ['2 pm', '11 am','1 pm']\nlistC = [1, 3, 6]\n\n# Given lists\nprint(\"Given list A: \" ,listA)\nprint(\"Given list B: \" ,listB)\nprint(\"Given list C: \",listC)\n\n# using + operator\nres_list = listA + listB + listC\n\n# printing result\nprint(\"Combined list is : \",res_list)" }, { "code": null, "e": 2093, "s": 2038, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2268, "s": 2093, "text": "Given list A: ['Mon', 'Tue', 'Wed']\nGiven list B: ['2 pm', '11 am', '1 pm']\nGiven list C: [1, 3, 6]\nCombined list is : ['Mon', 'Tue', 'Wed', '2 pm', '11 am', '1 pm', 1, 3, 6]" }, { "code": null, "e": 2515, "s": 2268, "text": "The zip function brings together elements form each of the lists from the same index and then moves on to the next index. This type of appending is useful when you want to preserver the elements form the lists at the same index position together." }, { "code": null, "e": 2526, "s": 2515, "text": " Live Demo" }, { "code": null, "e": 2826, "s": 2526, "text": "listA = ['Mon', 'Tue', 'Wed']\nlistB = ['2 pm', '11 am','1 pm']\nlistC = [1, 3, 6]\n\n# Given lists\nprint(\"Given list A: \" ,listA)\nprint(\"Given list B: \" ,listB)\nprint(\"Given list C: \",listC)\n\n# using zip\nres_list = list(zip(listA,listB , listC))\n\n# printing result\nprint(\"Combined list is : \",res_list)" }, { "code": null, "e": 2881, "s": 2826, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3062, "s": 2881, "text": "Given list A: ['Mon', 'Tue', 'Wed']\nGiven list B: ['2 pm', '11 am', '1 pm']\nGiven list C: [1, 3, 6]\nCombined list is : [('Mon', '2 pm', 1), ('Tue', '11 am', 3), ('Wed', '1 pm', 6)]" }, { "code": null, "e": 3199, "s": 3062, "text": "The chain function from itertools module can bring the elements of the lists together preserving the sequence in which they are present." }, { "code": null, "e": 3210, "s": 3199, "text": " Live Demo" }, { "code": null, "e": 3544, "s": 3210, "text": "from itertools import chain\n\nlistA = ['Mon', 'Tue', 'Wed']\nlistB = ['2 pm', '11 am','1 pm']\nlistC = [1, 3, 6]\n\n# Given lists\nprint(\"Given list A: \" ,listA)\nprint(\"Given list B: \" ,listB)\nprint(\"Given list C: \",listC)\n\n# using chain\nres_list = list(chain(listA, listB, listC))\n\n# printing result\nprint(\"Combined list is : \",res_list)\n" }, { "code": null, "e": 3599, "s": 3544, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3774, "s": 3599, "text": "Given list A: ['Mon', 'Tue', 'Wed']\nGiven list B: ['2 pm', '11 am', '1 pm']\nGiven list C: [1, 3, 6]\nCombined list is : ['Mon', 'Tue', 'Wed', '2 pm', '11 am', '1 pm', 1, 3, 6]" } ]
College Management System using Django - Python Project - GeeksforGeeks
11 Apr, 2022 In this article, we are going to build College Management System using Django and will be using dbsqlite database. In the times of covid, when education has totally become digital, there comes a need for a system that can connect teachers, students, and HOD and that was the motivation behind building this project. This project allows HOD, staff, and students to register themselves. This project has three interfaces. The below image shows the interface for the Head of Departments of the College: HOD Interface The below image shows the interface for the Staff of the College: Staff Interface The below image shows the interface for the Students of the College: Student Interface HTMLCSSJAVASCRIPTJQUERYBOOTSTRAPDJANGO HTML CSS JAVASCRIPT JQUERY BOOTSTRAP DJANGO Required Skillset to Build the Project: Basic knowledge of HTML, CSS, JavaScript, and Django. Follow the below steps to implement the discussed project: Step 1: Install Django. Step 2: Create a folder with the name College_Management_System and open it with VS Code. Step 3: Open the terminal and create a new project “student_management_project” using the below command. django-admin startproject student_management_project Step 4: Enter inside the folder “student_management_project” and create the app “student_management_app”. python manage.py startapp student_management_app Step 5: Go to student_management_project -> settings.py -> INSTALLED_APPS and add our app ‘student_management_app’. Step 6: Go to urls.py of student_management_project and add the below path in urlpatterns. (Note – Import include as from django.urls import path, include) path('', include('student_management_app.urls')) Step 7: Now enter the views that are going to use in views.py of student_management_app. Python3 from django.shortcuts import render,HttpResponse, redirect,HttpResponseRedirectfrom django.contrib.auth import logout, authenticate, loginfrom .models import CustomUser, Staffs, Students, AdminHODfrom django.contrib import messages def home(request): return render(request, 'home.html') def contact(request): return render(request, 'contact.html') def loginUser(request): return render(request, 'login_page.html') def doLogin(request): print("here") email_id = request.GET.get('email') password = request.GET.get('password') # user_type = request.GET.get('user_type') print(email_id) print(password) print(request.user) if not (email_id and password): messages.error(request, "Please provide all the details!!") return render(request, 'login_page.html') user = CustomUser.objects.filter(email=email_id, password=password).last() if not user: messages.error(request, 'Invalid Login Credentials!!') return render(request, 'login_page.html') login(request, user) print(request.user) if user.user_type == CustomUser.STUDENT: return redirect('student_home/') elif user.user_type == CustomUser.STAFF: return redirect('staff_home/') elif user.user_type == CustomUser.HOD: return redirect('admin_home/') return render(request, 'home.html') def registration(request): return render(request, 'registration.html') def doRegistration(request): first_name = request.GET.get('first_name') last_name = request.GET.get('last_name') email_id = request.GET.get('email') password = request.GET.get('password') confirm_password = request.GET.get('confirmPassword') print(email_id) print(password) print(confirm_password) print(first_name) print(last_name) if not (email_id and password and confirm_password): messages.error(request, 'Please provide all the details!!') return render(request, 'registration.html') if password != confirm_password: messages.error(request, 'Both passwords should match!!') return render(request, 'registration.html') is_user_exists = CustomUser.objects.filter(email=email_id).exists() if is_user_exists: messages.error(request, 'User with this email id already exists. Please proceed to login!!') return render(request, 'registration.html') user_type = get_user_type_from_email(email_id) if user_type is None: messages.error(request, "Please use valid format for the email id: '<username>.<staff|student|hod>@<college_domain>'") return render(request, 'registration.html') username = email_id.split('@')[0].split('.')[0] if CustomUser.objects.filter(username=username).exists(): messages.error(request, 'User with this username already exists. Please use different username') return render(request, 'registration.html') user = CustomUser() user.username = username user.email = email_id user.password = password user.user_type = user_type user.first_name = first_name user.last_name = last_name user.save() if user_type == CustomUser.STAFF: Staffs.objects.create(admin=user) elif user_type == CustomUser.STUDENT: Students.objects.create(admin=user) elif user_type == CustomUser.HOD: AdminHOD.objects.create(admin=user) return render(request, 'login_page.html') def logout_user(request): logout(request) return HttpResponseRedirect('/') def get_user_type_from_email(email_id): """ Returns CustomUser.user_type corresponding to the given email address email_id should be in following format: '<username>.<staff|student|hod>@<college_domain>' eg.: '[email protected]' """ try: email_id = email_id.split('@')[0] email_user_type = email_id.split('.')[1] return CustomUser.EMAIL_TO_USER_TYPE_MAP[email_user_type] except: return None Step 8: Create or Go to urls.py of student_management_app and add the following URLs. Python3 from django.contrib import adminfrom django.urls import path, includefrom . import viewsfrom .import HodViews, StaffViews, StudentViews urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home"), path('contact', views.contact, name="contact"), path('login', views.loginUser, name="login"), path('logout_user', views.logout_user, name="logout_user"), path('registration', views.registration, name="registration"), path('doLogin', views.doLogin, name="doLogin"), path('doRegistration', views.doRegistration, name="doRegistration"), # URLS for Student path('student_home/', StudentViews.student_home, name="student_home"), path('student_view_attendance/', StudentViews.student_view_attendance, name="student_view_attendance"), path('student_view_attendance_post/', StudentViews.student_view_attendance_post, name="student_view_attendance_post"), path('student_apply_leave/', StudentViews.student_apply_leave, name="student_apply_leave"), path('student_apply_leave_save/', StudentViews.student_apply_leave_save, name="student_apply_leave_save"), path('student_feedback/', StudentViews.student_feedback, name="student_feedback"), path('student_feedback_save/', StudentViews.student_feedback_save, name="student_feedback_save"), path('student_profile/', StudentViews.student_profile, name="student_profile"), path('student_profile_update/', StudentViews.student_profile_update, name="student_profile_update"), path('student_view_result/', StudentViews.student_view_result, name="student_view_result"), # URLS for Staff path('staff_home/', StaffViews.staff_home, name="staff_home"), path('staff_take_attendance/', StaffViews.staff_take_attendance, name="staff_take_attendance"), path('get_students/', StaffViews.get_students, name="get_students"), path('save_attendance_data/', StaffViews.save_attendance_data, name="save_attendance_data"), path('staff_update_attendance/', StaffViews.staff_update_attendance, name="staff_update_attendance"), path('get_attendance_dates/', StaffViews.get_attendance_dates, name="get_attendance_dates"), path('get_attendance_student/', StaffViews.get_attendance_student, name="get_attendance_student"), path('update_attendance_data/', StaffViews.update_attendance_data, name="update_attendance_data"), path('staff_apply_leave/', StaffViews.staff_apply_leave, name="staff_apply_leave"), path('staff_apply_leave_save/', StaffViews.staff_apply_leave_save, name="staff_apply_leave_save"), path('staff_feedback/', StaffViews.staff_feedback, name="staff_feedback"), path('staff_feedback_save/', StaffViews.staff_feedback_save, name="staff_feedback_save"), path('staff_profile/', StaffViews.staff_profile, name="staff_profile"), path('staff_profile_update/', StaffViews.staff_profile_update, name="staff_profile_update"), path('staff_add_result/', StaffViews.staff_add_result, name="staff_add_result"), path('staff_add_result_save/', StaffViews.staff_add_result_save, name="staff_add_result_save"), # URL for Admin path('admin_home/', HodViews.admin_home, name="admin_home"), path('add_staff/', HodViews.add_staff, name="add_staff"), path('add_staff_save/', HodViews.add_staff_save, name="add_staff_save"), path('manage_staff/', HodViews.manage_staff, name="manage_staff"), path('edit_staff/<staff_id>/', HodViews.edit_staff, name="edit_staff"), path('edit_staff_save/', HodViews.edit_staff_save, name="edit_staff_save"), path('delete_staff/<staff_id>/', HodViews.delete_staff, name="delete_staff"), path('add_course/', HodViews.add_course, name="add_course"), path('add_course_save/', HodViews.add_course_save, name="add_course_save"), path('manage_course/', HodViews.manage_course, name="manage_course"), path('edit_course/<course_id>/', HodViews.edit_course, name="edit_course"), path('edit_course_save/', HodViews.edit_course_save, name="edit_course_save"), path('delete_course/<course_id>/', HodViews.delete_course, name="delete_course"), path('manage_session/', HodViews.manage_session, name="manage_session"), path('add_session/', HodViews.add_session, name="add_session"), path('add_session_save/', HodViews.add_session_save, name="add_session_save"), path('edit_session/<session_id>', HodViews.edit_session, name="edit_session"), path('edit_session_save/', HodViews.edit_session_save, name="edit_session_save"), path('delete_session/<session_id>/', HodViews.delete_session, name="delete_session"), path('add_student/', HodViews.add_student, name="add_student"), path('add_student_save/', HodViews.add_student_save, name="add_student_save"), path('edit_student/<student_id>', HodViews.edit_student, name="edit_student"), path('edit_student_save/', HodViews.edit_student_save, name="edit_student_save"), path('manage_student/', HodViews.manage_student, name="manage_student"), path('delete_student/<student_id>/', HodViews.delete_student, name="delete_student"), path('add_subject/', HodViews.add_subject, name="add_subject"), path('add_subject_save/', HodViews.add_subject_save, name="add_subject_save"), path('manage_subject/', HodViews.manage_subject, name="manage_subject"), path('edit_subject/<subject_id>/', HodViews.edit_subject, name="edit_subject"), path('edit_subject_save/', HodViews.edit_subject_save, name="edit_subject_save"), path('delete_subject/<subject_id>/', HodViews.delete_subject, name="delete_subject"), path('check_email_exist/', HodViews.check_email_exist, name="check_email_exist"), path('check_username_exist/', HodViews.check_username_exist, name="check_username_exist"), path('student_feedback_message/', HodViews.student_feedback_message, name="student_feedback_message"), path('student_feedback_message_reply/', HodViews.student_feedback_message_reply, name="student_feedback_message_reply"), path('staff_feedback_message/', HodViews.staff_feedback_message, name="staff_feedback_message"), path('staff_feedback_message_reply/', HodViews.staff_feedback_message_reply, name="staff_feedback_message_reply"), path('student_leave_view/', HodViews.student_leave_view, name="student_leave_view"), path('student_leave_approve/<leave_id>/', HodViews.student_leave_approve, name="student_leave_approve"), path('student_leave_reject/<leave_id>/', HodViews.student_leave_reject, name="student_leave_reject"), path('staff_leave_view/', HodViews.staff_leave_view, name="staff_leave_view"), path('staff_leave_approve/<leave_id>/', HodViews.staff_leave_approve, name="staff_leave_approve"), path('staff_leave_reject/<leave_id>/', HodViews.staff_leave_reject, name="staff_leave_reject"), path('admin_view_attendance/', HodViews.admin_view_attendance, name="admin_view_attendance"), path('admin_get_attendance_dates/', HodViews.admin_get_attendance_dates, name="admin_get_attendance_dates"), path('admin_get_attendance_student/', HodViews.admin_get_attendance_student, name="admin_get_attendance_student"), path('admin_profile/', HodViews.admin_profile, name="admin_profile"), path('admin_profile_update/', HodViews.admin_profile_update, name="admin_profile_update"), ] Step 9: Now create a file StudentViews.py. It contains the views that are used on the student Interface. Python3 from django.shortcuts import render, redirectfrom django.http import HttpResponse, HttpResponseRedirectfrom django.contrib import messagesfrom django.core.files.storage import FileSystemStoragefrom django.urls import reverseimport datetimefrom .models import CustomUser, Staffs, Courses, Subjects, Students, Attendance, AttendanceReport, LeaveReportStudent, FeedBackStudent, StudentResult def student_home(request): student_obj = Students.objects.get(admin=request.user.id) total_attendance = AttendanceReport.objects.filter(student_id=student_obj).count() attendance_present = AttendanceReport.objects.filter(student_id=student_obj, status=True).count() attendance_absent = AttendanceReport.objects.filter(student_id=student_obj, status=False).count() course_obj = Courses.objects.get(id=student_obj.course_id.id) total_subjects = Subjects.objects.filter(course_id=course_obj).count() subject_name = [] data_present = [] data_absent = [] subject_data = Subjects.objects.filter(course_id=student_obj.course_id) for subject in subject_data: attendance = Attendance.objects.filter(subject_id=subject.id) attendance_present_count = AttendanceReport.objects.filter(attendance_id__in=attendance, status=True, student_id=student_obj.id).count() attendance_absent_count = AttendanceReport.objects.filter(attendance_id__in=attendance, status=False, student_id=student_obj.id).count() subject_name.append(subject.subject_name) data_present.append(attendance_present_count) data_absent.append(attendance_absent_count) context={ "total_attendance": total_attendance, "attendance_present": attendance_present, "attendance_absent": attendance_absent, "total_subjects": total_subjects, "subject_name": subject_name, "data_present": data_present, "data_absent": data_absent } return render(request, "student_template/student_home_template.html") def student_view_attendance(request): # Getting Logged in Student Data student = Students.objects.get(admin=request.user.id) # Getting Course Enrolled of LoggedIn Student course = student.course_id # Getting the Subjects of Course Enrolled subjects = Subjects.objects.filter(course_id=course) context = { "subjects": subjects } return render(request, "student_template/student_view_attendance.html", context) def student_view_attendance_post(request): if request.method != "POST": messages.error(request, "Invalid Method") return redirect('student_view_attendance') else: # Getting all the Input Data subject_id = request.POST.get('subject') start_date = request.POST.get('start_date') end_date = request.POST.get('end_date') # Parsing the date data into Python object start_date_parse = datetime.datetime.strptime(start_date, '%Y-%m-%d').date() end_date_parse = datetime.datetime.strptime(end_date, '%Y-%m-%d').date() # Getting all the Subject Data based on Selected Subject subject_obj = Subjects.objects.get(id=subject_id) # Getting Logged In User Data user_obj = CustomUser.objects.get(id=request.user.id) # Getting Student Data Based on Logged in Data stud_obj = Students.objects.get(admin=user_obj) # Now Accessing Attendance Data based on the Range of Date # Selected and Subject Selected attendance = Attendance.objects.filter(attendance_date__range=(start_date_parse, end_date_parse), subject_id=subject_obj) # Getting Attendance Report based on the attendance # details obtained above attendance_reports = AttendanceReport.objects.filter(attendance_id__in=attendance, student_id=stud_obj) context = { "subject_obj": subject_obj, "attendance_reports": attendance_reports } return render(request, 'student_template/student_attendance_data.html', context) def student_apply_leave(request): student_obj = Students.objects.get(admin=request.user.id) leave_data = LeaveReportStudent.objects.filter(student_id=student_obj) context = { "leave_data": leave_data } return render(request, 'student_template/student_apply_leave.html', context) def student_apply_leave_save(request): if request.method != "POST": messages.error(request, "Invalid Method") return redirect('student_apply_leave') else: leave_date = request.POST.get('leave_date') leave_message = request.POST.get('leave_message') student_obj = Students.objects.get(admin=request.user.id) try: leave_report = LeaveReportStudent(student_id=student_obj, leave_date=leave_date, leave_message=leave_message, leave_status=0) leave_report.save() messages.success(request, "Applied for Leave.") return redirect('student_apply_leave') except: messages.error(request, "Failed to Apply Leave") return redirect('student_apply_leave') def student_feedback(request): student_obj = Students.objects.get(admin=request.user.id) feedback_data = FeedBackStudent.objects.filter(student_id=student_obj) context = { "feedback_data": feedback_data } return render(request, 'student_template/student_feedback.html', context) def student_feedback_save(request): if request.method != "POST": messages.error(request, "Invalid Method.") return redirect('student_feedback') else: feedback = request.POST.get('feedback_message') student_obj = Students.objects.get(admin=request.user.id) try: add_feedback = FeedBackStudent(student_id=student_obj, feedback=feedback, feedback_reply="") add_feedback.save() messages.success(request, "Feedback Sent.") return redirect('student_feedback') except: messages.error(request, "Failed to Send Feedback.") return redirect('student_feedback') def student_profile(request): user = CustomUser.objects.get(id=request.user.id) student = Students.objects.get(admin=user) context={ "user": user, "student": student } return render(request, 'student_template/student_profile.html', context) def student_profile_update(request): if request.method != "POST": messages.error(request, "Invalid Method!") return redirect('student_profile') else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') password = request.POST.get('password') address = request.POST.get('address') try: customuser = CustomUser.objects.get(id=request.user.id) customuser.first_name = first_name customuser.last_name = last_name if password != None and password != "": customuser.set_password(password) customuser.save() student = Students.objects.get(admin=customuser.id) student.address = address student.save() messages.success(request, "Profile Updated Successfully") return redirect('student_profile') except: messages.error(request, "Failed to Update Profile") return redirect('student_profile') def student_view_result(request): student = Students.objects.get(admin=request.user.id) student_result = StudentResult.objects.filter(student_id=student.id) context = { "student_result": student_result, } return render(request, "student_template/student_view_result.html", context) Step 10: Now add the StaffViews.py. It contains the views of the staff interface. Python3 from django.shortcuts import render, redirectfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponsefrom django.contrib import messagesfrom django.core.files.storage import FileSystemStoragefrom django.urls import reversefrom django.views.decorators.csrf import csrf_exemptfrom django.core import serializersimport json from .models import CustomUser, Staffs, Courses, Subjects, Students, SessionYearModel, Attendance, AttendanceReport, LeaveReportStaff, FeedBackStaffs, StudentResult def staff_home(request): # Fetching All Students under Staff print(request.user.id) subjects = Subjects.objects.filter(staff_id=request.user.id) print(subjects) course_id_list = [] for subject in subjects: course = Courses.objects.get(id=subject.course_id.id) course_id_list.append(course.id) final_course = [] # Removing Duplicate Course Id for course_id in course_id_list: if course_id not in final_course: final_course.append(course_id) print(final_course) students_count = Students.objects.filter(course_id__in=final_course).count() subject_count = subjects.count() print(subject_count) print(students_count) # Fetch All Attendance Count attendance_count = Attendance.objects.filter(subject_id__in=subjects).count() # Fetch All Approve Leave # print(request.user) print(request.user.user_type) staff = Staffs.objects.get(admin=request.user.id) leave_count = LeaveReportStaff.objects.filter(staff_id=staff.id, leave_status=1).count() # Fetch Attendance Data by Subjects subject_list = [] attendance_list = [] for subject in subjects: attendance_count1 = Attendance.objects.filter(subject_id=subject.id).count() subject_list.append(subject.subject_name) attendance_list.append(attendance_count1) students_attendance = Students.objects.filter(course_id__in=final_course) student_list = [] student_list_attendance_present = [] student_list_attendance_absent = [] for student in students_attendance: attendance_present_count = AttendanceReport.objects.filter(status=True, student_id=student.id).count() attendance_absent_count = AttendanceReport.objects.filter(status=False, student_id=student.id).count() student_list.append(student.admin.first_name+" "+ student.admin.last_name) student_list_attendance_present.append(attendance_present_count) student_list_attendance_absent.append(attendance_absent_count) context={ "students_count": students_count, "attendance_count": attendance_count, "leave_count": leave_count, "subject_count": subject_count, "subject_list": subject_list, "attendance_list": attendance_list, "student_list": student_list, "attendance_present_list": student_list_attendance_present, "attendance_absent_list": student_list_attendance_absent } return render(request, "staff_template/staff_home_template.html", context) def staff_take_attendance(request): subjects = Subjects.objects.filter(staff_id=request.user.id) session_years = SessionYearModel.objects.all() context = { "subjects": subjects, "session_years": session_years } return render(request, "staff_template/take_attendance_template.html", context) def staff_apply_leave(request): print(request.user.id) staff_obj = Staffs.objects.get(admin=request.user.id) leave_data = LeaveReportStaff.objects.filter(staff_id=staff_obj) context = { "leave_data": leave_data } return render(request, "staff_template/staff_apply_leave_template.html", context) def staff_apply_leave_save(request): if request.method != "POST": messages.error(request, "Invalid Method") return redirect('staff_apply_leave') else: leave_date = request.POST.get('leave_date') leave_message = request.POST.get('leave_message') staff_obj = Staffs.objects.get(admin=request.user.id) try: leave_report = LeaveReportStaff(staff_id=staff_obj, leave_date=leave_date, leave_message=leave_message, leave_status=0) leave_report.save() messages.success(request, "Applied for Leave.") return redirect('staff_apply_leave') except: messages.error(request, "Failed to Apply Leave") return redirect('staff_apply_leave') def staff_feedback(request): return render(request, "staff_template/staff_feedback_template.html") def staff_feedback_save(request): if request.method != "POST": messages.error(request, "Invalid Method.") return redirect('staff_feedback') else: feedback = request.POST.get('feedback_message') staff_obj = Staffs.objects.get(admin=request.user.id) try: add_feedback = FeedBackStaffs(staff_id=staff_obj, feedback=feedback, feedback_reply="") add_feedback.save() messages.success(request, "Feedback Sent.") return redirect('staff_feedback') except: messages.error(request, "Failed to Send Feedback.") return redirect('staff_feedback') @csrf_exemptdef get_students(request): subject_id = request.POST.get("subject") session_year = request.POST.get("session_year") # Students enroll to Course, Course has Subjects # Getting all data from subject model based on subject_id subject_model = Subjects.objects.get(id=subject_id) session_model = SessionYearModel.objects.get(id=session_year) students = Students.objects.filter(course_id=subject_model.course_id, session_year_id=session_model) # Only Passing Student Id and Student Name Only list_data = [] for student in students: data_small={"id":student.admin.id, "name":student.admin.first_name+" "+student.admin.last_name} list_data.append(data_small) return JsonResponse(json.dumps(list_data), content_type="application/json", safe=False) @csrf_exemptdef save_attendance_data(request): # Get Values from Staf Take Attendance form via AJAX (JavaScript) # Use getlist to access HTML Array/List Input Data student_ids = request.POST.get("student_ids") subject_id = request.POST.get("subject_id") attendance_date = request.POST.get("attendance_date") session_year_id = request.POST.get("session_year_id") subject_model = Subjects.objects.get(id=subject_id) session_year_model = SessionYearModel.objects.get(id=session_year_id) json_student = json.loads(student_ids) try: # First Attendance Data is Saved on Attendance Model attendance = Attendance(subject_id=subject_model, attendance_date=attendance_date, session_year_id=session_year_model) attendance.save() for stud in json_student: # Attendance of Individual Student saved on AttendanceReport Model student = Students.objects.get(admin=stud['id']) attendance_report = AttendanceReport(student_id=student, attendance_id=attendance, status=stud['status']) attendance_report.save() return HttpResponse("OK") except: return HttpResponse("Error") def staff_update_attendance(request): subjects = Subjects.objects.filter(staff_id=request.user.id) session_years = SessionYearModel.objects.all() context = { "subjects": subjects, "session_years": session_years } return render(request, "staff_template/update_attendance_template.html", context) @csrf_exemptdef get_attendance_dates(request): # Getting Values from Ajax POST 'Fetch Student' subject_id = request.POST.get("subject") session_year = request.POST.get("session_year_id") # Students enroll to Course, Course has Subjects # Getting all data from subject model based on subject_id subject_model = Subjects.objects.get(id=subject_id) session_model = SessionYearModel.objects.get(id=session_year) attendance = Attendance.objects.filter(subject_id=subject_model, session_year_id=session_model) # Only Passing Student Id and Student Name Only list_data = [] for attendance_single in attendance: data_small={"id":attendance_single.id, "attendance_date":str(attendance_single.attendance_date), "session_year_id":attendance_single.session_year_id.id} list_data.append(data_small) return JsonResponse(json.dumps(list_data), content_type="application/json", safe=False) @csrf_exemptdef get_attendance_student(request): # Getting Values from Ajax POST 'Fetch Student' attendance_date = request.POST.get('attendance_date') attendance = Attendance.objects.get(id=attendance_date) attendance_data = AttendanceReport.objects.filter(attendance_id=attendance) # Only Passing Student Id and Student Name Only list_data = [] for student in attendance_data: data_small={"id":student.student_id.admin.id, "name":student.student_id.admin.first_name+" "+student.student_id.admin.last_name, "status":student.status} list_data.append(data_small) return JsonResponse(json.dumps(list_data), content_type="application/json", safe=False) @csrf_exemptdef update_attendance_data(request): student_ids = request.POST.get("student_ids") attendance_date = request.POST.get("attendance_date") attendance = Attendance.objects.get(id=attendance_date) json_student = json.loads(student_ids) try: for stud in json_student: # Attendance of Individual Student saved on AttendanceReport Model student = Students.objects.get(admin=stud['id']) attendance_report = AttendanceReport.objects.get(student_id=student, attendance_id=attendance) attendance_report.status=stud['status'] attendance_report.save() return HttpResponse("OK") except: return HttpResponse("Error") def staff_profile(request): user = CustomUser.objects.get(id=request.user.id) staff = Staffs.objects.get(admin=user) context={ "user": user, "staff": staff } return render(request, 'staff_template/staff_profile.html', context) def staff_profile_update(request): if request.method != "POST": messages.error(request, "Invalid Method!") return redirect('staff_profile') else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') password = request.POST.get('password') address = request.POST.get('address') try: customuser = CustomUser.objects.get(id=request.user.id) customuser.first_name = first_name customuser.last_name = last_name if password != None and password != "": customuser.set_password(password) customuser.save() staff = Staffs.objects.get(admin=customuser.id) staff.address = address staff.save() messages.success(request, "Profile Updated Successfully") return redirect('staff_profile') except: messages.error(request, "Failed to Update Profile") return redirect('staff_profile') def staff_add_result(request): subjects = Subjects.objects.filter(staff_id=request.user.id) session_years = SessionYearModel.objects.all() context = { "subjects": subjects, "session_years": session_years, } return render(request, "staff_template/add_result_template.html", context) def staff_add_result_save(request): if request.method != "POST": messages.error(request, "Invalid Method") return redirect('staff_add_result') else: student_admin_id = request.POST.get('student_list') assignment_marks = request.POST.get('assignment_marks') exam_marks = request.POST.get('exam_marks') subject_id = request.POST.get('subject') student_obj = Students.objects.get(admin=student_admin_id) subject_obj = Subjects.objects.get(id=subject_id) try: # Check if Students Result Already Exists or not check_exist = StudentResult.objects.filter(subject_id=subject_obj, student_id=student_obj).exists() if check_exist: result = StudentResult.objects.get(subject_id=subject_obj, student_id=student_obj) result.subject_assignment_marks = assignment_marks result.subject_exam_marks = exam_marks result.save() messages.success(request, "Result Updated Successfully!") return redirect('staff_add_result') else: result = StudentResult(student_id=student_obj, subject_id=subject_obj, subject_exam_marks=exam_marks, subject_assignment_marks=assignment_marks) result.save() messages.success(request, "Result Added Successfully!") return redirect('staff_add_result') except: messages.error(request, "Failed to Add Result!") return redirect('staff_add_result') Step 11: Now add the HodViews.py. It contains the views of the HOD interface. Python3 from django.shortcuts import render, redirectfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponsefrom django.contrib import messagesfrom django.core.files.storage import FileSystemStoragefrom django.urls import reversefrom django.views.decorators.csrf import csrf_exemptimport json from .forms import AddStudentForm, EditStudentForm from .models import CustomUser, Staffs, Courses, Subjects, Students, SessionYearModel, FeedBackStudent, FeedBackStaffs, LeaveReportStudent, LeaveReportStaff, Attendance, AttendanceReport def admin_home(request): all_student_count = Students.objects.all().count() subject_count = Subjects.objects.all().count() course_count = Courses.objects.all().count() staff_count = Staffs.objects.all().count() course_all = Courses.objects.all() course_name_list = [] subject_count_list = [] student_count_list_in_course = [] for course in course_all: subjects = Subjects.objects.filter(course_id=course.id).count() students = Students.objects.filter(course_id=course.id).count() course_name_list.append(course.course_name) subject_count_list.append(subjects) student_count_list_in_course.append(students) subject_all = Subjects.objects.all() subject_list = [] student_count_list_in_subject = [] for subject in subject_all: course = Courses.objects.get(id=subject.course_id.id) student_count = Students.objects.filter(course_id=course.id).count() subject_list.append(subject.subject_name) student_count_list_in_subject.append(student_count) # For Saffs staff_attendance_present_list=[] staff_attendance_leave_list=[] staff_name_list=[] staffs = Staffs.objects.all() for staff in staffs: subject_ids = Subjects.objects.filter(staff_id=staff.admin.id) attendance = Attendance.objects.filter(subject_id__in=subject_ids).count() leaves = LeaveReportStaff.objects.filter(staff_id=staff.id, leave_status=1).count() staff_attendance_present_list.append(attendance) staff_attendance_leave_list.append(leaves) staff_name_list.append(staff.admin.first_name) # For Students student_attendance_present_list=[] student_attendance_leave_list=[] student_name_list=[] students = Students.objects.all() for student in students: attendance = AttendanceReport.objects.filter(student_id=student.id, status=True).count() absent = AttendanceReport.objects.filter(student_id=student.id, status=False).count() leaves = LeaveReportStudent.objects.filter(student_id=student.id, leave_status=1).count() student_attendance_present_list.append(attendance) student_attendance_leave_list.append(leaves+absent) student_name_list.append(student.admin.first_name) context={ "all_student_count": all_student_count, "subject_count": subject_count, "course_count": course_count, "staff_count": staff_count, "course_name_list": course_name_list, "subject_count_list": subject_count_list, "student_count_list_in_course": student_count_list_in_course, "subject_list": subject_list, "student_count_list_in_subject": student_count_list_in_subject, "staff_attendance_present_list": staff_attendance_present_list, "staff_attendance_leave_list": staff_attendance_leave_list, "staff_name_list": staff_name_list, "student_attendance_present_list": student_attendance_present_list, "student_attendance_leave_list": student_attendance_leave_list, "student_name_list": student_name_list, } return render(request, "hod_template/home_content.html", context) def add_staff(request): return render(request, "hod_template/add_staff_template.html") def add_staff_save(request): if request.method != "POST": messages.error(request, "Invalid Method ") return redirect('add_staff') else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') address = request.POST.get('address') try: user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=2) user.staffs.address = address user.save() messages.success(request, "Staff Added Successfully!") return redirect('add_staff') except: messages.error(request, "Failed to Add Staff!") return redirect('add_staff') def manage_staff(request): staffs = Staffs.objects.all() context = { "staffs": staffs } return render(request, "hod_template/manage_staff_template.html", context) def edit_staff(request, staff_id): staff = Staffs.objects.get(admin=staff_id) context = { "staff": staff, "id": staff_id } return render(request, "hod_template/edit_staff_template.html", context) def edit_staff_save(request): if request.method != "POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: staff_id = request.POST.get('staff_id') username = request.POST.get('username') email = request.POST.get('email') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') address = request.POST.get('address') try: # INSERTING into Customuser Model user = CustomUser.objects.get(id=staff_id) user.first_name = first_name user.last_name = last_name user.email = email user.username = username user.save() # INSERTING into Staff Model staff_model = Staffs.objects.get(admin=staff_id) staff_model.address = address staff_model.save() messages.success(request, "Staff Updated Successfully.") return redirect('/edit_staff/'+staff_id) except: messages.error(request, "Failed to Update Staff.") return redirect('/edit_staff/'+staff_id) def delete_staff(request, staff_id): staff = Staffs.objects.get(admin=staff_id) try: staff.delete() messages.success(request, "Staff Deleted Successfully.") return redirect('manage_staff') except: messages.error(request, "Failed to Delete Staff.") return redirect('manage_staff') def add_course(request): return render(request, "hod_template/add_course_template.html") def add_course_save(request): if request.method != "POST": messages.error(request, "Invalid Method!") return redirect('add_course') else: course = request.POST.get('course') try: course_model = Courses(course_name=course) course_model.save() messages.success(request, "Course Added Successfully!") return redirect('add_course') except: messages.error(request, "Failed to Add Course!") return redirect('add_course') def manage_course(request): courses = Courses.objects.all() context = { "courses": courses } return render(request, 'hod_template/manage_course_template.html', context) def edit_course(request, course_id): course = Courses.objects.get(id=course_id) context = { "course": course, "id": course_id } return render(request, 'hod_template/edit_course_template.html', context) def edit_course_save(request): if request.method != "POST": HttpResponse("Invalid Method") else: course_id = request.POST.get('course_id') course_name = request.POST.get('course') try: course = Courses.objects.get(id=course_id) course.course_name = course_name course.save() messages.success(request, "Course Updated Successfully.") return redirect('/edit_course/'+course_id) except: messages.error(request, "Failed to Update Course.") return redirect('/edit_course/'+course_id) def delete_course(request, course_id): course = Courses.objects.get(id=course_id) try: course.delete() messages.success(request, "Course Deleted Successfully.") return redirect('manage_course') except: messages.error(request, "Failed to Delete Course.") return redirect('manage_course') def manage_session(request): session_years = SessionYearModel.objects.all() context = { "session_years": session_years } return render(request, "hod_template/manage_session_template.html", context) def add_session(request): return render(request, "hod_template/add_session_template.html") def add_session_save(request): if request.method != "POST": messages.error(request, "Invalid Method") return redirect('add_course') else: session_start_year = request.POST.get('session_start_year') session_end_year = request.POST.get('session_end_year') try: sessionyear = SessionYearModel(session_start_year=session_start_year, session_end_year=session_end_year) sessionyear.save() messages.success(request, "Session Year added Successfully!") return redirect("add_session") except: messages.error(request, "Failed to Add Session Year") return redirect("add_session") def edit_session(request, session_id): session_year = SessionYearModel.objects.get(id=session_id) context = { "session_year": session_year } return render(request, "hod_template/edit_session_template.html", context) def edit_session_save(request): if request.method != "POST": messages.error(request, "Invalid Method!") return redirect('manage_session') else: session_id = request.POST.get('session_id') session_start_year = request.POST.get('session_start_year') session_end_year = request.POST.get('session_end_year') try: session_year = SessionYearModel.objects.get(id=session_id) session_year.session_start_year = session_start_year session_year.session_end_year = session_end_year session_year.save() messages.success(request, "Session Year Updated Successfully.") return redirect('/edit_session/'+session_id) except: messages.error(request, "Failed to Update Session Year.") return redirect('/edit_session/'+session_id) def delete_session(request, session_id): session = SessionYearModel.objects.get(id=session_id) try: session.delete() messages.success(request, "Session Deleted Successfully.") return redirect('manage_session') except: messages.error(request, "Failed to Delete Session.") return redirect('manage_session') def add_student(request): form = AddStudentForm() context = { "form": form } return render(request, 'hod_template/add_student_template.html', context) def add_student_save(request): if request.method != "POST": messages.error(request, "Invalid Method") return redirect('add_student') else: form = AddStudentForm(request.POST, request.FILES) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] address = form.cleaned_data['address'] session_year_id = form.cleaned_data['session_year_id'] course_id = form.cleaned_data['course_id'] gender = form.cleaned_data['gender'] if len(request.FILES) != 0: profile_pic = request.FILES['profile_pic'] fs = FileSystemStorage() filename = fs.save(profile_pic.name, profile_pic) profile_pic_url = fs.url(filename) else: profile_pic_url = None try: user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=3) user.students.address = address course_obj = Courses.objects.get(id=course_id) user.students.course_id = course_obj session_year_obj = SessionYearModel.objects.get(id=session_year_id) user.students.session_year_id = session_year_obj user.students.gender = gender user.students.profile_pic = profile_pic_url user.save() messages.success(request, "Student Added Successfully!") return redirect('add_student') except: messages.error(request, "Failed to Add Student!") return redirect('add_student') else: return redirect('add_student') def manage_student(request): students = Students.objects.all() context = { "students": students } return render(request, 'hod_template/manage_student_template.html', context) def edit_student(request, student_id): # Adding Student ID into Session Variable request.session['student_id'] = student_id student = Students.objects.get(admin=student_id) form = EditStudentForm() # Filling the form with Data from Database form.fields['email'].initial = student.admin.email form.fields['username'].initial = student.admin.username form.fields['first_name'].initial = student.admin.first_name form.fields['last_name'].initial = student.admin.last_name form.fields['address'].initial = student.address form.fields['course_id'].initial = student.course_id.id form.fields['gender'].initial = student.gender form.fields['session_year_id'].initial = student.session_year_id.id context = { "id": student_id, "username": student.admin.username, "form": form } return render(request, "hod_template/edit_student_template.html", context) def edit_student_save(request): if request.method != "POST": return HttpResponse("Invalid Method!") else: student_id = request.session.get('student_id') if student_id == None: return redirect('/manage_student') form = EditStudentForm(request.POST, request.FILES) if form.is_valid(): email = form.cleaned_data['email'] username = form.cleaned_data['username'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] address = form.cleaned_data['address'] course_id = form.cleaned_data['course_id'] gender = form.cleaned_data['gender'] session_year_id = form.cleaned_data['session_year_id'] # Getting Profile Pic first # First Check whether the file is selected or not # Upload only if file is selected if len(request.FILES) != 0: profile_pic = request.FILES['profile_pic'] fs = FileSystemStorage() filename = fs.save(profile_pic.name, profile_pic) profile_pic_url = fs.url(filename) else: profile_pic_url = None try: # First Update into Custom User Model user = CustomUser.objects.get(id=student_id) user.first_name = first_name user.last_name = last_name user.email = email user.username = username user.save() # Then Update Students Table student_model = Students.objects.get(admin=student_id) student_model.address = address course = Courses.objects.get(id=course_id) student_model.course_id = course session_year_obj = SessionYearModel.objects.get(id=session_year_id) student_model.session_year_id = session_year_obj student_model.gender = gender if profile_pic_url != None: student_model.profile_pic = profile_pic_url student_model.save() # Delete student_id SESSION after the data is updated del request.session['student_id'] messages.success(request, "Student Updated Successfully!") return redirect('/edit_student/'+student_id) except: messages.success(request, "Failed to Uupdate Student.") return redirect('/edit_student/'+student_id) else: return redirect('/edit_student/'+student_id) def delete_student(request, student_id): student = Students.objects.get(admin=student_id) try: student.delete() messages.success(request, "Student Deleted Successfully.") return redirect('manage_student') except: messages.error(request, "Failed to Delete Student.") return redirect('manage_student') def add_subject(request): courses = Courses.objects.all() staffs = CustomUser.objects.filter(user_type='2') context = { "courses": courses, "staffs": staffs } return render(request, 'hod_template/add_subject_template.html', context) def add_subject_save(request): if request.method != "POST": messages.error(request, "Method Not Allowed!") return redirect('add_subject') else: subject_name = request.POST.get('subject') course_id = request.POST.get('course') course = Courses.objects.get(id=course_id) staff_id = request.POST.get('staff') staff = CustomUser.objects.get(id=staff_id) try: subject = Subjects(subject_name=subject_name, course_id=course, staff_id=staff) subject.save() messages.success(request, "Subject Added Successfully!") return redirect('add_subject') except: messages.error(request, "Failed to Add Subject!") return redirect('add_subject') def manage_subject(request): subjects = Subjects.objects.all() context = { "subjects": subjects } return render(request, 'hod_template/manage_subject_template.html', context) def edit_subject(request, subject_id): subject = Subjects.objects.get(id=subject_id) courses = Courses.objects.all() staffs = CustomUser.objects.filter(user_type='2') context = { "subject": subject, "courses": courses, "staffs": staffs, "id": subject_id } return render(request, 'hod_template/edit_subject_template.html', context) def edit_subject_save(request): if request.method != "POST": HttpResponse("Invalid Method.") else: subject_id = request.POST.get('subject_id') subject_name = request.POST.get('subject') course_id = request.POST.get('course') staff_id = request.POST.get('staff') try: subject = Subjects.objects.get(id=subject_id) subject.subject_name = subject_name course = Courses.objects.get(id=course_id) subject.course_id = course staff = CustomUser.objects.get(id=staff_id) subject.staff_id = staff subject.save() messages.success(request, "Subject Updated Successfully.") return HttpResponseRedirect(reverse("edit_subject", kwargs={"subject_id":subject_id})) except: messages.error(request, "Failed to Update Subject.") return HttpResponseRedirect(reverse("edit_subject", kwargs={"subject_id":subject_id})) def delete_subject(request, subject_id): subject = Subjects.objects.get(id=subject_id) try: subject.delete() messages.success(request, "Subject Deleted Successfully.") return redirect('manage_subject') except: messages.error(request, "Failed to Delete Subject.") return redirect('manage_subject') @csrf_exemptdef check_email_exist(request): email = request.POST.get("email") user_obj = CustomUser.objects.filter(email=email).exists() if user_obj: return HttpResponse(True) else: return HttpResponse(False) @csrf_exemptdef check_username_exist(request): username = request.POST.get("username") user_obj = CustomUser.objects.filter(username=username).exists() if user_obj: return HttpResponse(True) else: return HttpResponse(False) def student_feedback_message(request): feedbacks = FeedBackStudent.objects.all() context = { "feedbacks": feedbacks } return render(request, 'hod_template/student_feedback_template.html', context) @csrf_exemptdef student_feedback_message_reply(request): feedback_id = request.POST.get('id') feedback_reply = request.POST.get('reply') try: feedback = FeedBackStudent.objects.get(id=feedback_id) feedback.feedback_reply = feedback_reply feedback.save() return HttpResponse("True") except: return HttpResponse("False") def staff_feedback_message(request): feedbacks = FeedBackStaffs.objects.all() context = { "feedbacks": feedbacks } return render(request, 'hod_template/staff_feedback_template.html', context) @csrf_exemptdef staff_feedback_message_reply(request): feedback_id = request.POST.get('id') feedback_reply = request.POST.get('reply') try: feedback = FeedBackStaffs.objects.get(id=feedback_id) feedback.feedback_reply = feedback_reply feedback.save() return HttpResponse("True") except: return HttpResponse("False") def student_leave_view(request): leaves = LeaveReportStudent.objects.all() context = { "leaves": leaves } return render(request, 'hod_template/student_leave_view.html', context) def student_leave_approve(request, leave_id): leave = LeaveReportStudent.objects.get(id=leave_id) leave.leave_status = 1 leave.save() return redirect('student_leave_view') def student_leave_reject(request, leave_id): leave = LeaveReportStudent.objects.get(id=leave_id) leave.leave_status = 2 leave.save() return redirect('student_leave_view') def staff_leave_view(request): leaves = LeaveReportStaff.objects.all() context = { "leaves": leaves } return render(request, 'hod_template/staff_leave_view.html', context) def staff_leave_approve(request, leave_id): leave = LeaveReportStaff.objects.get(id=leave_id) leave.leave_status = 1 leave.save() return redirect('staff_leave_view') def staff_leave_reject(request, leave_id): leave = LeaveReportStaff.objects.get(id=leave_id) leave.leave_status = 2 leave.save() return redirect('staff_leave_view') def admin_view_attendance(request): subjects = Subjects.objects.all() session_years = SessionYearModel.objects.all() context = { "subjects": subjects, "session_years": session_years } return render(request, "hod_template/admin_view_attendance.html", context) @csrf_exemptdef admin_get_attendance_dates(request): subject_id = request.POST.get("subject") session_year = request.POST.get("session_year_id") # Students enroll to Course, Course has Subjects # Getting all data from subject model based on subject_id subject_model = Subjects.objects.get(id=subject_id) session_model = SessionYearModel.objects.get(id=session_year) attendance = Attendance.objects.filter(subject_id=subject_model, session_year_id=session_model) # Only Passing Student Id and Student Name Only list_data = [] for attendance_single in attendance: data_small={"id":attendance_single.id, "attendance_date":str(attendance_single.attendance_date), "session_year_id":attendance_single.session_year_id.id} list_data.append(data_small) return JsonResponse(json.dumps(list_data), content_type="application/json", safe=False) @csrf_exemptdef admin_get_attendance_student(request): # Getting Values from Ajax POST 'Fetch Student' attendance_date = request.POST.get('attendance_date') attendance = Attendance.objects.get(id=attendance_date) attendance_data = AttendanceReport.objects.filter(attendance_id=attendance) # Only Passing Student Id and Student Name Only list_data = [] for student in attendance_data: data_small={"id":student.student_id.admin.id, "name":student.student_id.admin.first_name+" "+student.student_id.admin.last_name, "status":student.status} list_data.append(data_small) return JsonResponse(json.dumps(list_data), content_type="application/json", safe=False) def admin_profile(request): user = CustomUser.objects.get(id=request.user.id) context={ "user": user } return render(request, 'hod_template/admin_profile.html', context) def admin_profile_update(request): if request.method != "POST": messages.error(request, "Invalid Method!") return redirect('admin_profile') else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') password = request.POST.get('password') try: customuser = CustomUser.objects.get(id=request.user.id) customuser.first_name = first_name customuser.last_name = last_name if password != None and password != "": customuser.set_password(password) customuser.save() messages.success(request, "Profile Updated Successfully") return redirect('admin_profile') except: messages.error(request, "Failed to Update Profile") return redirect('admin_profile') def staff_profile(request): pass def student_profile(requtest): pass Step 12: Now add models.py to our project. It stores all the models that will be used in our project. Python3 from django.contrib.auth.models import AbstractUserfrom django.db import modelsfrom django.db.models.signals import post_savefrom django.dispatch import receiver class SessionYearModel(models.Model): id = models.AutoField(primary_key=True) session_start_year = models.DateField() session_end_year = models.DateField() objects = models.Manager() # Overriding the Default Django Auth# User and adding One More Field (user_type)class CustomUser(AbstractUser): HOD = '1' STAFF = '2' STUDENT = '3' EMAIL_TO_USER_TYPE_MAP = { 'hod': HOD, 'staff': STAFF, 'student': STUDENT } user_type_data = ((HOD, "HOD"), (STAFF, "Staff"), (STUDENT, "Student")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) class AdminHOD(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Staffs(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) address = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Courses(models.Model): id = models.AutoField(primary_key=True) course_name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Subjects(models.Model): id =models.AutoField(primary_key=True) subject_name = models.CharField(max_length=255) # need to give default course course_id = models.ForeignKey(Courses, on_delete=models.CASCADE, default=1) staff_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Students(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) gender = models.CharField(max_length=50) profile_pic = models.FileField() address = models.TextField() course_id = models.ForeignKey(Courses, on_delete=models.DO_NOTHING, default=1) session_year_id = models.ForeignKey(SessionYearModel, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Attendance(models.Model): # Subject Attendance id = models.AutoField(primary_key=True) subject_id = models.ForeignKey(Subjects, on_delete=models.DO_NOTHING) attendance_date = models.DateField() session_year_id = models.ForeignKey(SessionYearModel, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class AttendanceReport(models.Model): # Individual Student Attendance id = models.AutoField(primary_key=True) student_id = models.ForeignKey(Students, on_delete=models.DO_NOTHING) attendance_id = models.ForeignKey(Attendance, on_delete=models.CASCADE) status = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class LeaveReportStudent(models.Model): id = models.AutoField(primary_key=True) student_id = models.ForeignKey(Students, on_delete=models.CASCADE) leave_date = models.CharField(max_length=255) leave_message = models.TextField() leave_status = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class LeaveReportStaff(models.Model): id = models.AutoField(primary_key=True) staff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE) leave_date = models.CharField(max_length=255) leave_message = models.TextField() leave_status = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class FeedBackStudent(models.Model): id = models.AutoField(primary_key=True) student_id = models.ForeignKey(Students, on_delete=models.CASCADE) feedback = models.TextField() feedback_reply = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class FeedBackStaffs(models.Model): id = models.AutoField(primary_key=True) staff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE) feedback = models.TextField() feedback_reply = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class NotificationStudent(models.Model): id = models.AutoField(primary_key=True) student_id = models.ForeignKey(Students, on_delete=models.CASCADE) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class NotificationStaffs(models.Model): id = models.AutoField(primary_key=True) stafff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class StudentResult(models.Model): id = models.AutoField(primary_key=True) student_id = models.ForeignKey(Students, on_delete=models.CASCADE) subject_id = models.ForeignKey(Subjects, on_delete=models.CASCADE, default=1) subject_exam_marks = models.FloatField(default=0) subject_assignment_marks = models.FloatField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() #Creating Django Signals@receiver(post_save, sender=CustomUser) # Now Creating a Function which will# automatically insert data in HOD, Staff or Studentdef create_user_profile(sender, instance, created, **kwargs): # if Created is true (Means Data Inserted) if created: # Check the user_type and insert the data in respective tables if instance.user_type == 1: AdminHOD.objects.create(admin=instance) if instance.user_type == 2: Staffs.objects.create(admin=instance) if instance.user_type == 3: Students.objects.create(admin=instance, course_id=Courses.objects.get(id=1), session_year_id=SessionYearModel.objects.get(id=1), address="", profile_pic="", gender="") @receiver(post_save, sender=CustomUser)def save_user_profile(sender, instance, **kwargs): if instance.user_type == 1: instance.adminhod.save() if instance.user_type == 2: instance.staffs.save() if instance.user_type == 3: instance.students.save() Step 13: Go to student_management_project -> setting and add AUTH_USER_MODEL = ‘student_management_app.CustomUser’. Step 14: Now create forms.py Python3 from django import formsfrom .models import Courses, SessionYearModel class DateInput(forms.DateInput): input_type = "date" class AddStudentForm(forms.Form): email = forms.EmailField(label="Email", max_length=50, widget=forms.EmailInput(attrs={"class":"form-control"})) password = forms.CharField(label="Password", max_length=50, widget=forms.PasswordInput(attrs={"class":"form-control"})) first_name = forms.CharField(label="First Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) last_name = forms.CharField(label="Last Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) username = forms.CharField(label="Username", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) address = forms.CharField(label="Address", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) #For Displaying Courses try: courses = Courses.objects.all() course_list = [] for course in courses: single_course = (course.id, course.course_name) course_list.append(single_course) except: print("here") course_list = [] #For Displaying Session Years try: session_years = SessionYearModel.objects.all() session_year_list = [] for session_year in session_years: single_session_year = (session_year.id, str(session_year.session_start_year)+" to "+str(session_year.session_end_year)) session_year_list.append(single_session_year) except: session_year_list = [] gender_list = ( ('Male','Male'), ('Female','Female') ) course_id = forms.ChoiceField(label="Course", choices=course_list, widget=forms.Select(attrs={"class":"form-control"})) gender = forms.ChoiceField(label="Gender", choices=gender_list, widget=forms.Select(attrs={"class":"form-control"})) session_year_id = forms.ChoiceField(label="Session Year", choices=session_year_list, widget=forms.Select(attrs={"class":"form-control"})) profile_pic = forms.FileField(label="Profile Pic", required=False, widget=forms.FileInput(attrs={"class":"form-control"})) class EditStudentForm(forms.Form): email = forms.EmailField(label="Email", max_length=50, widget=forms.EmailInput(attrs={"class":"form-control"})) first_name = forms.CharField(label="First Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) last_name = forms.CharField(label="Last Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) username = forms.CharField(label="Username", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) address = forms.CharField(label="Address", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) # For Displaying Courses try: courses = Courses.objects.all() course_list = [] for course in courses: single_course = (course.id, course.course_name) course_list.append(single_course) except: course_list = [] # For Displaying Session Years try: session_years = SessionYearModel.objects.all() session_year_list = [] for session_year in session_years: single_session_year = (session_year.id, str(session_year.session_start_year)+" to "+str(session_year.session_end_year)) session_year_list.append(single_session_year) except: session_year_list = [] gender_list = ( ('Male','Male'), ('Female','Female') ) course_id = forms.ChoiceField(label="Course", choices=course_list, widget=forms.Select(attrs={"class":"form-control"})) gender = forms.ChoiceField(label="Gender", choices=gender_list, widget=forms.Select(attrs={"class":"form-control"})) session_year_id = forms.ChoiceField(label="Session Year", choices=session_year_list, widget=forms.Select(attrs={"class":"form-control"})) profile_pic = forms.FileField(label="Profile Pic", required=False, widget=forms.FileInput(attrs={"class":"form-control"})) Step 15: Now register the models in admin.py Python3 from django.contrib import adminfrom django.contrib.auth.admin import UserAdminfrom .models import CustomUser, AdminHOD, Staffs, Courses, Subjects, Students, Attendance, AttendanceReport, LeaveReportStudent, LeaveReportStaff, FeedBackStudent, FeedBackStaffs, NotificationStudent, NotificationStaffs # Register your models here.class UserModel(UserAdmin): pass admin.site.register(CustomUser, UserModel) admin.site.register(AdminHOD)admin.site.register(Staffs)admin.site.register(Courses)admin.site.register(Subjects)admin.site.register(Students)admin.site.register(Attendance)admin.site.register(AttendanceReport)admin.site.register(LeaveReportStudent)admin.site.register(LeaveReportStaff)admin.site.register(FeedBackStudent)admin.site.register(FeedBackStaffs)admin.site.register(NotificationStudent)admin.site.register(NotificationStaffs) Step 16: Now Create a new folder as templates which includes Student_template, Hod_template, Staff_template folders. It contains the different templates used in each interface.Create another folder as static which also includes some files. ( Note – All these folders must be in student_management_project ). All these files can be downloaded from here. Step 17: Add media, static URLs, and root path. import os MEDIA_URL="/media/" MEDIA_ROOT=os.path.join(BASE_DIR,"media") STATIC_URL="/static/" STATIC_ROOT=os.path.join(BASE_DIR,"static") Step 18: Now create a base.html page. HTML {% load static %} <!DOCTYPE html><html><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>College Management System | Dashboard</title> <!-- Tell the browser to be responsive to screen width --> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Font Awesome --> <link rel="stylesheet" href="{% static "fontawesome-free/css/all.min.css" %}"> <!-- Ionicons --> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <!-- Tempusdominus Bbootstrap 4 --> <link rel="stylesheet" href="{% static 'tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css' %}"> <!-- iCheck --> <link rel="stylesheet" href="{% static "icheck-bootstrap/icheck-bootstrap.min.css" %}"> <!-- JQVMap --> <link rel="stylesheet" href="{% static "jqvmap/jqvmap.min.css" %}"> <!-- Theme style --> <link rel="stylesheet" href="{% static 'dist/css/adminlte.min.css' %}"> <!-- overlayScrollbars --> <link rel="stylesheet" href="{% static "overlayScrollbars/css/OverlayScrollbars.min.css" %}"> <!-- Daterange picker --> <link rel="stylesheet" href="{% static "daterangepicker/daterangepicker.css" %}"> <!-- summernote --> <link rel="stylesheet" href="{% static "summernote/summernote-bs4.css" %}"> <!-- Google Font: Source Sans Pro --> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet"> </head> {% block content %} {% endblock content %} <!-- jQuery --> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script src="{% static "jquery/jquery.min.js" %}"></script><!-- jQuery UI 1.11.4 --><script src="{% static "jquery-ui/jquery-ui.min.js" %}"></script><!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip --><script> $.widget.bridge('uibutton', $.ui.button)</script><!-- Bootstrap 4 --><script src="{% static "bootstrap/js/bootstrap.bundle.min.js" %}"></script><!-- ChartJS --><script src="{% static "chart.js/Chart.min.js" %}"></script><!-- Sparkline --><script src="{% static "sparklines/sparkline.js" %}"></script><!-- JQVMap --><script src="{% static "jqvmap/jquery.vmap.min.js" %}"></script><script src="{% static "jqvmap/maps/jquery.vmap.usa.js" %}"></script><!-- jQuery Knob Chart --><script src="{% static "jquery-knob/jquery.knob.min.js" %}"></script><!-- daterangepicker --><script src="{% static "moment/moment.min.js" %}"></script><script src="{% static "daterangepicker/daterangepicker.js" %}"></script><!-- Tempusdominus Bootstrap 4 --><script src="{% static "tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js" %}"></script><!-- Summernote --><script src="{% static "summernote/summernote-bs4.min.js" %}"></script><!-- overlayScrollbars --><script src="{% static "overlayScrollbars/js/jquery.overlayScrollbars.min.js" %}"></script><!-- AdminLTE App --><script src="{% static 'dist/js/adminlte.js' %}"></script><!-- AdminLTE dashboard demo (This is only for demo purposes) --><script src="{% static 'dist/js/pages/dashboard.js' %}"></script><!-- AdminLTE for demo purposes --><script src="{% static 'dist/js/demo.js' %}"></script></body></html> Step 19: Now create a home.html page of our project in the student_management_app\templates folder. HTML {% extends 'base.html' %}{% load static %}{% block title %}Home{% endblock title %} {% block content %}<html><head> <style>img { background-size: cover;}body {background-color: coral;} </style> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"><script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script><script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> </head> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href=""><h3>WELCOME TO CMS</h3></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> </ul> <form class="form-inline my-2 my-lg-0"> <!--<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">--> <a href="/logi" class="btn btn-outline-success my-1 mx-2">Login</a> <!--<input class="form-control mr-sm-2" type="Register" placeholder="Register" aria-label="Register">--> <a href="/registration" class="btn btn-outline-success my-1 mx-2">Register</a> <a href="/contact" class="btn btn-outline-danger my-1 mx-2">Contact Us</a> </form> </div></nav> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> </ol> <div class="carousel-inner"> <div class="carousel-item active"> {% comment %} <img class="d-block w-100" src="https://images.unsplash.com/20/cambridge.JPG?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1030&q=80" alt="First slide"> {% endcomment %} <img src="{% static 'dist/img/111.png' %}" class="d-block w-100 h-100 size-cover" alt="..."> </div> <div class="carousel-item"> {% comment %} <img class="d-block w-100" src="https://images.unsplash.com/photo-1541339907198-e08756dedf3f?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" alt="Second slide"> {% endcomment %} <img src="{% static 'dist/img/re.png' %}" class="d-block w-100 h-100 size-cover " alt="..."> </div> <div class="carousel-item"> {% comment %} <img class="d-block w-100" src="https://images.unsplash.com/photo-1541339907198-e08756dedf3f?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" alt="Second slide"> {% endcomment %} <img src="{% static 'dist/img/e.png' %}" class="d-block w-100 h-100 size-cover " alt="..."> </div> <div class="carousel-item"> {% comment %} <img class="d-block w-100" src="https://images.unsplash.com/photo-1541339907198-e08756dedf3f?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" alt="Second slide"> {% endcomment %} <img src="{% static 'dist/img/22.png' %}" class="d-block w-100 h-100 size-cover " alt="..."> </div> <div class="carousel-item"> {% comment %} <img class="d-block w-100" src="https://images.unsplash.com/photo-1503676260728-1c00da094a0b?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1009&q=80" alt="Third slide"> {% endcomment %} <img src="{% static 'dist/img/33.png' %}" class="d-block w-100 h-100 size-cover" alt="..."> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a></div> </html> {% endblock content %} Output : Step 20: Now create a registration.html page where students, staff, HOD can register themselves. HTML {% extends 'base.html' %}{% load static %}{% block content %}<head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Untitled</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css"> <link rel="stylesheet" href="assets/css/style.css"> <style> body{ height:1000px; background:#475d62; background-color: cover; font-family: sans-seriff; } .login-dark { max-width:320px; width:90%; background-color: #1e2833; padding:40px; border-radius:4px; transform: translate(-50%,-50%); position: absolute; top: 50%; left: 50%; color:#fff; box-shadow:3px 3px 4px rgba(0,0,0,0.2); } .login-dark form { max-width:320px; width:90%; background-color:#1e2833; padding:40px; border-radius:4px; transform:translate(-50%, -50%); position:absolute; top:50%; left:50%; color:#fff; box-shadow:3px 3px 4px rgba(0,0,0,0.2); } .login-dark .illustration { text-align:center; padding:15px 0 20px; font-size:100px; color:#2980ef; } .login-dark form .form-control { background:none; border:none; border-bottom:1px solid #434a52; border-radius:0; box-shadow:none; outline:none; color:inherit; } .login-dark form .btn-primary { background:#214a80; border:none; border-radius:4px; padding:11px; box-shadow:none; margin-top:26px; text-shadow:none; outline:none; } .login-dark form .btn-primary:hover, .login-dark form .btn-primary:active { background:#214a80; outline:none; } .login-dark form .forgot { display:block; text-align:center; font-size:12px; color:#6f7a85; opacity:0.9; text-decoration:none; } .login-dark form .forgot:hover, .login-dark form .forgot:active { opacity:1; text-decoration:none; } .login-dark form .btn-primary:active { transform:translateY(1px); } </style></head><nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="/ "> <h4>BACK TO HOME</h4> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> </ul> <form class="form-inline my-2 my-lg-0"> <!-- <input class="form-control mr-sm-2" type="login" placeholder="login" aria-label="login">--> <!--<input class="form-control mr-sm-2" type="Register" placeholder="Register" aria-label="Register">--> <a href="/logi" class="btn btn-outline-success my-1 mx-2">Login Here</a> <a href="/contact" class="btn btn-outline-danger my-1 mx-2">Contact Us</a> <!--<input class="form-control mr-sm-2" type="register" placeholder="register" aria-label="register">--> </form> </div></nav><div class="login-dark form-inline py-0 mx-4 my-4 pl-4 pr-4"><form action="{% url 'doRegistration' %}" method="get">{% csrf_token %}<h1 class="text-center">Signup</h1><div class="illustration"><i class="icon ion-ios-locked-outline"></i></div><div class="form-group"><input class="form-control mb-2" type="text" name="first_name" placeholder="First Name"></div><div class="form-group"><input class="form-control mb-2" type="text" name="last_name" placeholder="Last Name"></div><div class="form-group"><input class="form-control mb-2" type="email" name="email" placeholder="Email"></div><div class="form-group"><input class="form-control mb-2" type="password" name="password" placeholder="Password"></div><div class="form-group"><input class="form-control mb-2" type="password" name="confirmPassword" placeholder="Confirm Password"></div><div class="form-group"><button class="btn btn-primary btn-block mt-2 ml-2" type="submit">Register</button></div>{% comment %} Display Messages {% endcomment %}{% if messages %}<div class="col-12"> {% for message in messages %} {% if message.tags == "error" %} <div class="alert alert-danger alert-dismissible fade show" role="alert" style="margin-top: 10px;"> <b>{{ message }}</b> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endif %} {% endfor %}</div>{% endif %}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>{% endblock content %} Output: REGISTRATION PAGE Step 21: Now create a login_page.html where students, staff, HOD can log in themselves. HTML {% extends 'base.html' %}{% load static %}{% block content %}<head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1; maximum-scale=1.0; user-scalable=0;"> <title>Untitled</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css"> <link rel="stylesheet" href="assets/css/style.css"> <style> body{ height:1000px; background:#475d62; background-color: cover; font-family: sans-seriff; } .login-dark { max-width:320px; width:90%; background-color: #1e2833; padding:40px; border-radius:4px; transform: translate(-50%,-50%); position: absolute; top: 50%; left: 50%; color:#fff; box-shadow:3px 3px 4px rgba(0,0,0,0.2); } .login-dark form { max-width:320px; width:90%; background-color:#1e2833; padding:40px; border-radius:4px; transform:translate(-50%, -50%); position:absolute; top:50%; left:50%; color:#fff; box-shadow:3px 3px 4px rgba(0,0,0,0.2); } .login-dark .illustration { text-align:center; padding:15px 0 20px; font-size:100px; color:#2980ef; } .login-dark form .form-control { background:none; border:none; border-bottom:1px solid #434a52; border-radius:0; box-shadow:none; outline:none; color:inherit; } .login-dark form .btn-primary { background:#214a80; border:none; border-radius:4px; padding:11px; box-shadow:none; margin-top:26px; text-shadow:none; outline:none; } .login-dark form .btn-primary:hover, .login-dark form .btn-primary:active { background:#214a80; outline:none; } .login-dark form .forgot { display:block; text-align:center; font-size:12px; color:#6f7a85; opacity:0.9; text-decoration:none; } .login-dark form .forgot:hover, .login-dark form .forgot:active { opacity:1; text-decoration:none; } .login-dark form .btn-primary:active { transform:translateY(1px); } </style></head><nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="/ ">BACK TO HOME</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> </ul> <form class="form-inline my-2 my-lg-0"> <a href="{% url 'contact' %}" class="btn btn-outline-danger my-1 mx-2">Contact Us</a> </form> <!-- <form class="form-inline my-2 my-lg-0">--> </div></nav><div class="login-dark form-inline py-0 mx-4 my-4 pl-4 pr-4"> <form action="{% url 'doLogin' %}" method="get"> {% csrf_token %} <h1 class="text-center">Login</h1> <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div> <div class="form-group"><input class="form-control mb-2" type="email" name="email" placeholder="Email"></div> <div class="form-group"><input class="form-control mb-2" type="password" name="password" placeholder="Password"></div> <div class="form-group"><button class="btn btn-primary btn-block mb-2 ml-2" type="submit">Log In</button></div> <a href="/registration" class="forgot">Not Registered Yet? Register Now</a> </form></div>{% comment %} Display Messages {% endcomment %}{% if messages %}<div class="col-12"> {% for message in messages %} {% if message.tags == "error" %} {% comment %} <div class="alert alert-danger alert-dismissible fade show" role="alert" style="margin-top: 10px;"> <b>{{ message }}</b> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endcomment %} <div class="alert alert-danger alert-dismissible fade show" role="alert"> <strong>Invalid Login Credentials!</strong> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> {% endif %} {% endfor %}</div>{% endif %}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>{% endblock content %} Output: LOGIN page Step 22: Create contact.html HTML {% extends 'base.html' %}{% load static %} {% block content %} <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a href="/ " class="btn btn-outline-primary my-1 mx-2">Go Back To Home </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> </ul> <form class="form-inline my-2 my-lg-0"> <!-- <input class="form-control mr-sm-2" type="login" placeholder="login" aria-label="login">--> <!--<input class="form-control mr-sm-2" type="Register" placeholder="Register" aria-label="Register">--> <!--<input class="form-control mr-sm-2" type="register" placeholder="register" aria-label="register">--> </form> <form class="form-inline my-2 my-lg-0"> </div> </nav><div class="container-fluid px-0"> <img src="{% static 'dist/img/contact.jpg' %}" class="d-block w-100 mx-0" alt="..." height=450px width=10px></div><div class="container"> <h1 class="text-center my-3 display-2"> <b>Contact Us</b> </h1><form action="/contact" method="post">{% csrf_token %} <div class="mb-3 py-2"> <label for="exampleFormControlInput1" class="form-label"><b>Name</b></label> <input type="name" class="form-control" id="exampleFormControlInput1" name = "name" placeholder="Enter your Name"></div> <div class="mb-3 py-2"> <label for="exampleFormControlInput1" class="form-label"><b>Email id</b></label> <input type="email" class="form-control" id="exampleFormControlInpu2"name = "email" placeholder="Enter your Email"></div> <div class="mb-3 py-2"> <label for="exampleFormControlInput1" class="form-label"><b>Phone number</b></label> <input type="number" class="form-control" id="exampleFormControlInput3" name = "phone" placeholder="Enter your Phone number"></div><div class="mb-3 py-2"> <label for="exampleFormControlTextarea1" class="form-label"><b>How can we help you ??</b></label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="7" name = "desc"></textarea></div> <button type="submit" class="btn btn-primary btn-lg ">Submit</button> </form></div> {% endblock content%} Step 23: Run these commands to migrate your models into the database. When you successfully do all the steps you will get this type of output in CMD. python manage.py makemigrations python manage.py migrate Project Overview: Media error: Format(s) not supported or source(s) not found This project can be used in the colleges to keep HOD, students, and staff connected with each other. The deployed project can be checked here. This project is developed by: Nalin Goyal Kanchan Jeswani Vaishali Goyal simmytarika5 sagartomar9927 as5853535 clintra surajkumarguptaintern Django-Projects ProGeek 2021 Python Django ProGeek Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Project Idea - A website acting as transaction between oxygen sellers and buyers Project Idea | Fuel Balance Online Schooling System - Python Project Project Idea | FILEit - An online filing system Project Idea | Electric Vehicle Charging Lane SDE SHEET - A Complete Guide for SDE Preparation XML parsing in Python Working with zip files in Python Python | Simple GUI calculator using Tkinter Implementing Web Scraping in Python with BeautifulSoup
[ { "code": null, "e": 25130, "s": 25102, "text": "\n11 Apr, 2022" }, { "code": null, "e": 25446, "s": 25130, "text": "In this article, we are going to build College Management System using Django and will be using dbsqlite database. In the times of covid, when education has totally become digital, there comes a need for a system that can connect teachers, students, and HOD and that was the motivation behind building this project." }, { "code": null, "e": 25550, "s": 25446, "text": "This project allows HOD, staff, and students to register themselves. This project has three interfaces." }, { "code": null, "e": 25630, "s": 25550, "text": "The below image shows the interface for the Head of Departments of the College:" }, { "code": null, "e": 25644, "s": 25630, "text": "HOD Interface" }, { "code": null, "e": 25710, "s": 25644, "text": "The below image shows the interface for the Staff of the College:" }, { "code": null, "e": 25726, "s": 25710, "text": "Staff Interface" }, { "code": null, "e": 25795, "s": 25726, "text": "The below image shows the interface for the Students of the College:" }, { "code": null, "e": 25813, "s": 25795, "text": "Student Interface" }, { "code": null, "e": 25852, "s": 25813, "text": "HTMLCSSJAVASCRIPTJQUERYBOOTSTRAPDJANGO" }, { "code": null, "e": 25857, "s": 25852, "text": "HTML" }, { "code": null, "e": 25861, "s": 25857, "text": "CSS" }, { "code": null, "e": 25872, "s": 25861, "text": "JAVASCRIPT" }, { "code": null, "e": 25879, "s": 25872, "text": "JQUERY" }, { "code": null, "e": 25889, "s": 25879, "text": "BOOTSTRAP" }, { "code": null, "e": 25896, "s": 25889, "text": "DJANGO" }, { "code": null, "e": 25936, "s": 25896, "text": "Required Skillset to Build the Project:" }, { "code": null, "e": 25990, "s": 25936, "text": "Basic knowledge of HTML, CSS, JavaScript, and Django." }, { "code": null, "e": 26049, "s": 25990, "text": "Follow the below steps to implement the discussed project:" }, { "code": null, "e": 26073, "s": 26049, "text": "Step 1: Install Django." }, { "code": null, "e": 26163, "s": 26073, "text": "Step 2: Create a folder with the name College_Management_System and open it with VS Code." }, { "code": null, "e": 26268, "s": 26163, "text": "Step 3: Open the terminal and create a new project “student_management_project” using the below command." }, { "code": null, "e": 26321, "s": 26268, "text": "django-admin startproject student_management_project" }, { "code": null, "e": 26427, "s": 26321, "text": "Step 4: Enter inside the folder “student_management_project” and create the app “student_management_app”." }, { "code": null, "e": 26476, "s": 26427, "text": "python manage.py startapp student_management_app" }, { "code": null, "e": 26592, "s": 26476, "text": "Step 5: Go to student_management_project -> settings.py -> INSTALLED_APPS and add our app ‘student_management_app’." }, { "code": null, "e": 26748, "s": 26592, "text": "Step 6: Go to urls.py of student_management_project and add the below path in urlpatterns. (Note – Import include as from django.urls import path, include)" }, { "code": null, "e": 26797, "s": 26748, "text": "path('', include('student_management_app.urls'))" }, { "code": null, "e": 26886, "s": 26797, "text": "Step 7: Now enter the views that are going to use in views.py of student_management_app." }, { "code": null, "e": 26894, "s": 26886, "text": "Python3" }, { "code": "from django.shortcuts import render,HttpResponse, redirect,HttpResponseRedirectfrom django.contrib.auth import logout, authenticate, loginfrom .models import CustomUser, Staffs, Students, AdminHODfrom django.contrib import messages def home(request): return render(request, 'home.html') def contact(request): return render(request, 'contact.html') def loginUser(request): return render(request, 'login_page.html') def doLogin(request): print(\"here\") email_id = request.GET.get('email') password = request.GET.get('password') # user_type = request.GET.get('user_type') print(email_id) print(password) print(request.user) if not (email_id and password): messages.error(request, \"Please provide all the details!!\") return render(request, 'login_page.html') user = CustomUser.objects.filter(email=email_id, password=password).last() if not user: messages.error(request, 'Invalid Login Credentials!!') return render(request, 'login_page.html') login(request, user) print(request.user) if user.user_type == CustomUser.STUDENT: return redirect('student_home/') elif user.user_type == CustomUser.STAFF: return redirect('staff_home/') elif user.user_type == CustomUser.HOD: return redirect('admin_home/') return render(request, 'home.html') def registration(request): return render(request, 'registration.html') def doRegistration(request): first_name = request.GET.get('first_name') last_name = request.GET.get('last_name') email_id = request.GET.get('email') password = request.GET.get('password') confirm_password = request.GET.get('confirmPassword') print(email_id) print(password) print(confirm_password) print(first_name) print(last_name) if not (email_id and password and confirm_password): messages.error(request, 'Please provide all the details!!') return render(request, 'registration.html') if password != confirm_password: messages.error(request, 'Both passwords should match!!') return render(request, 'registration.html') is_user_exists = CustomUser.objects.filter(email=email_id).exists() if is_user_exists: messages.error(request, 'User with this email id already exists. Please proceed to login!!') return render(request, 'registration.html') user_type = get_user_type_from_email(email_id) if user_type is None: messages.error(request, \"Please use valid format for the email id: '<username>.<staff|student|hod>@<college_domain>'\") return render(request, 'registration.html') username = email_id.split('@')[0].split('.')[0] if CustomUser.objects.filter(username=username).exists(): messages.error(request, 'User with this username already exists. Please use different username') return render(request, 'registration.html') user = CustomUser() user.username = username user.email = email_id user.password = password user.user_type = user_type user.first_name = first_name user.last_name = last_name user.save() if user_type == CustomUser.STAFF: Staffs.objects.create(admin=user) elif user_type == CustomUser.STUDENT: Students.objects.create(admin=user) elif user_type == CustomUser.HOD: AdminHOD.objects.create(admin=user) return render(request, 'login_page.html') def logout_user(request): logout(request) return HttpResponseRedirect('/') def get_user_type_from_email(email_id): \"\"\" Returns CustomUser.user_type corresponding to the given email address email_id should be in following format: '<username>.<staff|student|hod>@<college_domain>' eg.: '[email protected]' \"\"\" try: email_id = email_id.split('@')[0] email_user_type = email_id.split('.')[1] return CustomUser.EMAIL_TO_USER_TYPE_MAP[email_user_type] except: return None", "e": 30832, "s": 26894, "text": null }, { "code": null, "e": 30918, "s": 30832, "text": "Step 8: Create or Go to urls.py of student_management_app and add the following URLs." }, { "code": null, "e": 30926, "s": 30918, "text": "Python3" }, { "code": "from django.contrib import adminfrom django.urls import path, includefrom . import viewsfrom .import HodViews, StaffViews, StudentViews urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name=\"home\"), path('contact', views.contact, name=\"contact\"), path('login', views.loginUser, name=\"login\"), path('logout_user', views.logout_user, name=\"logout_user\"), path('registration', views.registration, name=\"registration\"), path('doLogin', views.doLogin, name=\"doLogin\"), path('doRegistration', views.doRegistration, name=\"doRegistration\"), # URLS for Student path('student_home/', StudentViews.student_home, name=\"student_home\"), path('student_view_attendance/', StudentViews.student_view_attendance, name=\"student_view_attendance\"), path('student_view_attendance_post/', StudentViews.student_view_attendance_post, name=\"student_view_attendance_post\"), path('student_apply_leave/', StudentViews.student_apply_leave, name=\"student_apply_leave\"), path('student_apply_leave_save/', StudentViews.student_apply_leave_save, name=\"student_apply_leave_save\"), path('student_feedback/', StudentViews.student_feedback, name=\"student_feedback\"), path('student_feedback_save/', StudentViews.student_feedback_save, name=\"student_feedback_save\"), path('student_profile/', StudentViews.student_profile, name=\"student_profile\"), path('student_profile_update/', StudentViews.student_profile_update, name=\"student_profile_update\"), path('student_view_result/', StudentViews.student_view_result, name=\"student_view_result\"), # URLS for Staff path('staff_home/', StaffViews.staff_home, name=\"staff_home\"), path('staff_take_attendance/', StaffViews.staff_take_attendance, name=\"staff_take_attendance\"), path('get_students/', StaffViews.get_students, name=\"get_students\"), path('save_attendance_data/', StaffViews.save_attendance_data, name=\"save_attendance_data\"), path('staff_update_attendance/', StaffViews.staff_update_attendance, name=\"staff_update_attendance\"), path('get_attendance_dates/', StaffViews.get_attendance_dates, name=\"get_attendance_dates\"), path('get_attendance_student/', StaffViews.get_attendance_student, name=\"get_attendance_student\"), path('update_attendance_data/', StaffViews.update_attendance_data, name=\"update_attendance_data\"), path('staff_apply_leave/', StaffViews.staff_apply_leave, name=\"staff_apply_leave\"), path('staff_apply_leave_save/', StaffViews.staff_apply_leave_save, name=\"staff_apply_leave_save\"), path('staff_feedback/', StaffViews.staff_feedback, name=\"staff_feedback\"), path('staff_feedback_save/', StaffViews.staff_feedback_save, name=\"staff_feedback_save\"), path('staff_profile/', StaffViews.staff_profile, name=\"staff_profile\"), path('staff_profile_update/', StaffViews.staff_profile_update, name=\"staff_profile_update\"), path('staff_add_result/', StaffViews.staff_add_result, name=\"staff_add_result\"), path('staff_add_result_save/', StaffViews.staff_add_result_save, name=\"staff_add_result_save\"), # URL for Admin path('admin_home/', HodViews.admin_home, name=\"admin_home\"), path('add_staff/', HodViews.add_staff, name=\"add_staff\"), path('add_staff_save/', HodViews.add_staff_save, name=\"add_staff_save\"), path('manage_staff/', HodViews.manage_staff, name=\"manage_staff\"), path('edit_staff/<staff_id>/', HodViews.edit_staff, name=\"edit_staff\"), path('edit_staff_save/', HodViews.edit_staff_save, name=\"edit_staff_save\"), path('delete_staff/<staff_id>/', HodViews.delete_staff, name=\"delete_staff\"), path('add_course/', HodViews.add_course, name=\"add_course\"), path('add_course_save/', HodViews.add_course_save, name=\"add_course_save\"), path('manage_course/', HodViews.manage_course, name=\"manage_course\"), path('edit_course/<course_id>/', HodViews.edit_course, name=\"edit_course\"), path('edit_course_save/', HodViews.edit_course_save, name=\"edit_course_save\"), path('delete_course/<course_id>/', HodViews.delete_course, name=\"delete_course\"), path('manage_session/', HodViews.manage_session, name=\"manage_session\"), path('add_session/', HodViews.add_session, name=\"add_session\"), path('add_session_save/', HodViews.add_session_save, name=\"add_session_save\"), path('edit_session/<session_id>', HodViews.edit_session, name=\"edit_session\"), path('edit_session_save/', HodViews.edit_session_save, name=\"edit_session_save\"), path('delete_session/<session_id>/', HodViews.delete_session, name=\"delete_session\"), path('add_student/', HodViews.add_student, name=\"add_student\"), path('add_student_save/', HodViews.add_student_save, name=\"add_student_save\"), path('edit_student/<student_id>', HodViews.edit_student, name=\"edit_student\"), path('edit_student_save/', HodViews.edit_student_save, name=\"edit_student_save\"), path('manage_student/', HodViews.manage_student, name=\"manage_student\"), path('delete_student/<student_id>/', HodViews.delete_student, name=\"delete_student\"), path('add_subject/', HodViews.add_subject, name=\"add_subject\"), path('add_subject_save/', HodViews.add_subject_save, name=\"add_subject_save\"), path('manage_subject/', HodViews.manage_subject, name=\"manage_subject\"), path('edit_subject/<subject_id>/', HodViews.edit_subject, name=\"edit_subject\"), path('edit_subject_save/', HodViews.edit_subject_save, name=\"edit_subject_save\"), path('delete_subject/<subject_id>/', HodViews.delete_subject, name=\"delete_subject\"), path('check_email_exist/', HodViews.check_email_exist, name=\"check_email_exist\"), path('check_username_exist/', HodViews.check_username_exist, name=\"check_username_exist\"), path('student_feedback_message/', HodViews.student_feedback_message, name=\"student_feedback_message\"), path('student_feedback_message_reply/', HodViews.student_feedback_message_reply, name=\"student_feedback_message_reply\"), path('staff_feedback_message/', HodViews.staff_feedback_message, name=\"staff_feedback_message\"), path('staff_feedback_message_reply/', HodViews.staff_feedback_message_reply, name=\"staff_feedback_message_reply\"), path('student_leave_view/', HodViews.student_leave_view, name=\"student_leave_view\"), path('student_leave_approve/<leave_id>/', HodViews.student_leave_approve, name=\"student_leave_approve\"), path('student_leave_reject/<leave_id>/', HodViews.student_leave_reject, name=\"student_leave_reject\"), path('staff_leave_view/', HodViews.staff_leave_view, name=\"staff_leave_view\"), path('staff_leave_approve/<leave_id>/', HodViews.staff_leave_approve, name=\"staff_leave_approve\"), path('staff_leave_reject/<leave_id>/', HodViews.staff_leave_reject, name=\"staff_leave_reject\"), path('admin_view_attendance/', HodViews.admin_view_attendance, name=\"admin_view_attendance\"), path('admin_get_attendance_dates/', HodViews.admin_get_attendance_dates, name=\"admin_get_attendance_dates\"), path('admin_get_attendance_student/', HodViews.admin_get_attendance_student, name=\"admin_get_attendance_student\"), path('admin_profile/', HodViews.admin_profile, name=\"admin_profile\"), path('admin_profile_update/', HodViews.admin_profile_update, name=\"admin_profile_update\"), ]", "e": 38132, "s": 30926, "text": null }, { "code": null, "e": 38237, "s": 38132, "text": "Step 9: Now create a file StudentViews.py. It contains the views that are used on the student Interface." }, { "code": null, "e": 38245, "s": 38237, "text": "Python3" }, { "code": "from django.shortcuts import render, redirectfrom django.http import HttpResponse, HttpResponseRedirectfrom django.contrib import messagesfrom django.core.files.storage import FileSystemStoragefrom django.urls import reverseimport datetimefrom .models import CustomUser, Staffs, Courses, Subjects, Students, Attendance, AttendanceReport, LeaveReportStudent, FeedBackStudent, StudentResult def student_home(request): student_obj = Students.objects.get(admin=request.user.id) total_attendance = AttendanceReport.objects.filter(student_id=student_obj).count() attendance_present = AttendanceReport.objects.filter(student_id=student_obj, status=True).count() attendance_absent = AttendanceReport.objects.filter(student_id=student_obj, status=False).count() course_obj = Courses.objects.get(id=student_obj.course_id.id) total_subjects = Subjects.objects.filter(course_id=course_obj).count() subject_name = [] data_present = [] data_absent = [] subject_data = Subjects.objects.filter(course_id=student_obj.course_id) for subject in subject_data: attendance = Attendance.objects.filter(subject_id=subject.id) attendance_present_count = AttendanceReport.objects.filter(attendance_id__in=attendance, status=True, student_id=student_obj.id).count() attendance_absent_count = AttendanceReport.objects.filter(attendance_id__in=attendance, status=False, student_id=student_obj.id).count() subject_name.append(subject.subject_name) data_present.append(attendance_present_count) data_absent.append(attendance_absent_count) context={ \"total_attendance\": total_attendance, \"attendance_present\": attendance_present, \"attendance_absent\": attendance_absent, \"total_subjects\": total_subjects, \"subject_name\": subject_name, \"data_present\": data_present, \"data_absent\": data_absent } return render(request, \"student_template/student_home_template.html\") def student_view_attendance(request): # Getting Logged in Student Data student = Students.objects.get(admin=request.user.id) # Getting Course Enrolled of LoggedIn Student course = student.course_id # Getting the Subjects of Course Enrolled subjects = Subjects.objects.filter(course_id=course) context = { \"subjects\": subjects } return render(request, \"student_template/student_view_attendance.html\", context) def student_view_attendance_post(request): if request.method != \"POST\": messages.error(request, \"Invalid Method\") return redirect('student_view_attendance') else: # Getting all the Input Data subject_id = request.POST.get('subject') start_date = request.POST.get('start_date') end_date = request.POST.get('end_date') # Parsing the date data into Python object start_date_parse = datetime.datetime.strptime(start_date, '%Y-%m-%d').date() end_date_parse = datetime.datetime.strptime(end_date, '%Y-%m-%d').date() # Getting all the Subject Data based on Selected Subject subject_obj = Subjects.objects.get(id=subject_id) # Getting Logged In User Data user_obj = CustomUser.objects.get(id=request.user.id) # Getting Student Data Based on Logged in Data stud_obj = Students.objects.get(admin=user_obj) # Now Accessing Attendance Data based on the Range of Date # Selected and Subject Selected attendance = Attendance.objects.filter(attendance_date__range=(start_date_parse, end_date_parse), subject_id=subject_obj) # Getting Attendance Report based on the attendance # details obtained above attendance_reports = AttendanceReport.objects.filter(attendance_id__in=attendance, student_id=stud_obj) context = { \"subject_obj\": subject_obj, \"attendance_reports\": attendance_reports } return render(request, 'student_template/student_attendance_data.html', context) def student_apply_leave(request): student_obj = Students.objects.get(admin=request.user.id) leave_data = LeaveReportStudent.objects.filter(student_id=student_obj) context = { \"leave_data\": leave_data } return render(request, 'student_template/student_apply_leave.html', context) def student_apply_leave_save(request): if request.method != \"POST\": messages.error(request, \"Invalid Method\") return redirect('student_apply_leave') else: leave_date = request.POST.get('leave_date') leave_message = request.POST.get('leave_message') student_obj = Students.objects.get(admin=request.user.id) try: leave_report = LeaveReportStudent(student_id=student_obj, leave_date=leave_date, leave_message=leave_message, leave_status=0) leave_report.save() messages.success(request, \"Applied for Leave.\") return redirect('student_apply_leave') except: messages.error(request, \"Failed to Apply Leave\") return redirect('student_apply_leave') def student_feedback(request): student_obj = Students.objects.get(admin=request.user.id) feedback_data = FeedBackStudent.objects.filter(student_id=student_obj) context = { \"feedback_data\": feedback_data } return render(request, 'student_template/student_feedback.html', context) def student_feedback_save(request): if request.method != \"POST\": messages.error(request, \"Invalid Method.\") return redirect('student_feedback') else: feedback = request.POST.get('feedback_message') student_obj = Students.objects.get(admin=request.user.id) try: add_feedback = FeedBackStudent(student_id=student_obj, feedback=feedback, feedback_reply=\"\") add_feedback.save() messages.success(request, \"Feedback Sent.\") return redirect('student_feedback') except: messages.error(request, \"Failed to Send Feedback.\") return redirect('student_feedback') def student_profile(request): user = CustomUser.objects.get(id=request.user.id) student = Students.objects.get(admin=user) context={ \"user\": user, \"student\": student } return render(request, 'student_template/student_profile.html', context) def student_profile_update(request): if request.method != \"POST\": messages.error(request, \"Invalid Method!\") return redirect('student_profile') else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') password = request.POST.get('password') address = request.POST.get('address') try: customuser = CustomUser.objects.get(id=request.user.id) customuser.first_name = first_name customuser.last_name = last_name if password != None and password != \"\": customuser.set_password(password) customuser.save() student = Students.objects.get(admin=customuser.id) student.address = address student.save() messages.success(request, \"Profile Updated Successfully\") return redirect('student_profile') except: messages.error(request, \"Failed to Update Profile\") return redirect('student_profile') def student_view_result(request): student = Students.objects.get(admin=request.user.id) student_result = StudentResult.objects.filter(student_id=student.id) context = { \"student_result\": student_result, } return render(request, \"student_template/student_view_result.html\", context)", "e": 46619, "s": 38245, "text": null }, { "code": null, "e": 46701, "s": 46619, "text": "Step 10: Now add the StaffViews.py. It contains the views of the staff interface." }, { "code": null, "e": 46709, "s": 46701, "text": "Python3" }, { "code": "from django.shortcuts import render, redirectfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponsefrom django.contrib import messagesfrom django.core.files.storage import FileSystemStoragefrom django.urls import reversefrom django.views.decorators.csrf import csrf_exemptfrom django.core import serializersimport json from .models import CustomUser, Staffs, Courses, Subjects, Students, SessionYearModel, Attendance, AttendanceReport, LeaveReportStaff, FeedBackStaffs, StudentResult def staff_home(request): # Fetching All Students under Staff print(request.user.id) subjects = Subjects.objects.filter(staff_id=request.user.id) print(subjects) course_id_list = [] for subject in subjects: course = Courses.objects.get(id=subject.course_id.id) course_id_list.append(course.id) final_course = [] # Removing Duplicate Course Id for course_id in course_id_list: if course_id not in final_course: final_course.append(course_id) print(final_course) students_count = Students.objects.filter(course_id__in=final_course).count() subject_count = subjects.count() print(subject_count) print(students_count) # Fetch All Attendance Count attendance_count = Attendance.objects.filter(subject_id__in=subjects).count() # Fetch All Approve Leave # print(request.user) print(request.user.user_type) staff = Staffs.objects.get(admin=request.user.id) leave_count = LeaveReportStaff.objects.filter(staff_id=staff.id, leave_status=1).count() # Fetch Attendance Data by Subjects subject_list = [] attendance_list = [] for subject in subjects: attendance_count1 = Attendance.objects.filter(subject_id=subject.id).count() subject_list.append(subject.subject_name) attendance_list.append(attendance_count1) students_attendance = Students.objects.filter(course_id__in=final_course) student_list = [] student_list_attendance_present = [] student_list_attendance_absent = [] for student in students_attendance: attendance_present_count = AttendanceReport.objects.filter(status=True, student_id=student.id).count() attendance_absent_count = AttendanceReport.objects.filter(status=False, student_id=student.id).count() student_list.append(student.admin.first_name+\" \"+ student.admin.last_name) student_list_attendance_present.append(attendance_present_count) student_list_attendance_absent.append(attendance_absent_count) context={ \"students_count\": students_count, \"attendance_count\": attendance_count, \"leave_count\": leave_count, \"subject_count\": subject_count, \"subject_list\": subject_list, \"attendance_list\": attendance_list, \"student_list\": student_list, \"attendance_present_list\": student_list_attendance_present, \"attendance_absent_list\": student_list_attendance_absent } return render(request, \"staff_template/staff_home_template.html\", context) def staff_take_attendance(request): subjects = Subjects.objects.filter(staff_id=request.user.id) session_years = SessionYearModel.objects.all() context = { \"subjects\": subjects, \"session_years\": session_years } return render(request, \"staff_template/take_attendance_template.html\", context) def staff_apply_leave(request): print(request.user.id) staff_obj = Staffs.objects.get(admin=request.user.id) leave_data = LeaveReportStaff.objects.filter(staff_id=staff_obj) context = { \"leave_data\": leave_data } return render(request, \"staff_template/staff_apply_leave_template.html\", context) def staff_apply_leave_save(request): if request.method != \"POST\": messages.error(request, \"Invalid Method\") return redirect('staff_apply_leave') else: leave_date = request.POST.get('leave_date') leave_message = request.POST.get('leave_message') staff_obj = Staffs.objects.get(admin=request.user.id) try: leave_report = LeaveReportStaff(staff_id=staff_obj, leave_date=leave_date, leave_message=leave_message, leave_status=0) leave_report.save() messages.success(request, \"Applied for Leave.\") return redirect('staff_apply_leave') except: messages.error(request, \"Failed to Apply Leave\") return redirect('staff_apply_leave') def staff_feedback(request): return render(request, \"staff_template/staff_feedback_template.html\") def staff_feedback_save(request): if request.method != \"POST\": messages.error(request, \"Invalid Method.\") return redirect('staff_feedback') else: feedback = request.POST.get('feedback_message') staff_obj = Staffs.objects.get(admin=request.user.id) try: add_feedback = FeedBackStaffs(staff_id=staff_obj, feedback=feedback, feedback_reply=\"\") add_feedback.save() messages.success(request, \"Feedback Sent.\") return redirect('staff_feedback') except: messages.error(request, \"Failed to Send Feedback.\") return redirect('staff_feedback') @csrf_exemptdef get_students(request): subject_id = request.POST.get(\"subject\") session_year = request.POST.get(\"session_year\") # Students enroll to Course, Course has Subjects # Getting all data from subject model based on subject_id subject_model = Subjects.objects.get(id=subject_id) session_model = SessionYearModel.objects.get(id=session_year) students = Students.objects.filter(course_id=subject_model.course_id, session_year_id=session_model) # Only Passing Student Id and Student Name Only list_data = [] for student in students: data_small={\"id\":student.admin.id, \"name\":student.admin.first_name+\" \"+student.admin.last_name} list_data.append(data_small) return JsonResponse(json.dumps(list_data), content_type=\"application/json\", safe=False) @csrf_exemptdef save_attendance_data(request): # Get Values from Staf Take Attendance form via AJAX (JavaScript) # Use getlist to access HTML Array/List Input Data student_ids = request.POST.get(\"student_ids\") subject_id = request.POST.get(\"subject_id\") attendance_date = request.POST.get(\"attendance_date\") session_year_id = request.POST.get(\"session_year_id\") subject_model = Subjects.objects.get(id=subject_id) session_year_model = SessionYearModel.objects.get(id=session_year_id) json_student = json.loads(student_ids) try: # First Attendance Data is Saved on Attendance Model attendance = Attendance(subject_id=subject_model, attendance_date=attendance_date, session_year_id=session_year_model) attendance.save() for stud in json_student: # Attendance of Individual Student saved on AttendanceReport Model student = Students.objects.get(admin=stud['id']) attendance_report = AttendanceReport(student_id=student, attendance_id=attendance, status=stud['status']) attendance_report.save() return HttpResponse(\"OK\") except: return HttpResponse(\"Error\") def staff_update_attendance(request): subjects = Subjects.objects.filter(staff_id=request.user.id) session_years = SessionYearModel.objects.all() context = { \"subjects\": subjects, \"session_years\": session_years } return render(request, \"staff_template/update_attendance_template.html\", context) @csrf_exemptdef get_attendance_dates(request): # Getting Values from Ajax POST 'Fetch Student' subject_id = request.POST.get(\"subject\") session_year = request.POST.get(\"session_year_id\") # Students enroll to Course, Course has Subjects # Getting all data from subject model based on subject_id subject_model = Subjects.objects.get(id=subject_id) session_model = SessionYearModel.objects.get(id=session_year) attendance = Attendance.objects.filter(subject_id=subject_model, session_year_id=session_model) # Only Passing Student Id and Student Name Only list_data = [] for attendance_single in attendance: data_small={\"id\":attendance_single.id, \"attendance_date\":str(attendance_single.attendance_date), \"session_year_id\":attendance_single.session_year_id.id} list_data.append(data_small) return JsonResponse(json.dumps(list_data), content_type=\"application/json\", safe=False) @csrf_exemptdef get_attendance_student(request): # Getting Values from Ajax POST 'Fetch Student' attendance_date = request.POST.get('attendance_date') attendance = Attendance.objects.get(id=attendance_date) attendance_data = AttendanceReport.objects.filter(attendance_id=attendance) # Only Passing Student Id and Student Name Only list_data = [] for student in attendance_data: data_small={\"id\":student.student_id.admin.id, \"name\":student.student_id.admin.first_name+\" \"+student.student_id.admin.last_name, \"status\":student.status} list_data.append(data_small) return JsonResponse(json.dumps(list_data), content_type=\"application/json\", safe=False) @csrf_exemptdef update_attendance_data(request): student_ids = request.POST.get(\"student_ids\") attendance_date = request.POST.get(\"attendance_date\") attendance = Attendance.objects.get(id=attendance_date) json_student = json.loads(student_ids) try: for stud in json_student: # Attendance of Individual Student saved on AttendanceReport Model student = Students.objects.get(admin=stud['id']) attendance_report = AttendanceReport.objects.get(student_id=student, attendance_id=attendance) attendance_report.status=stud['status'] attendance_report.save() return HttpResponse(\"OK\") except: return HttpResponse(\"Error\") def staff_profile(request): user = CustomUser.objects.get(id=request.user.id) staff = Staffs.objects.get(admin=user) context={ \"user\": user, \"staff\": staff } return render(request, 'staff_template/staff_profile.html', context) def staff_profile_update(request): if request.method != \"POST\": messages.error(request, \"Invalid Method!\") return redirect('staff_profile') else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') password = request.POST.get('password') address = request.POST.get('address') try: customuser = CustomUser.objects.get(id=request.user.id) customuser.first_name = first_name customuser.last_name = last_name if password != None and password != \"\": customuser.set_password(password) customuser.save() staff = Staffs.objects.get(admin=customuser.id) staff.address = address staff.save() messages.success(request, \"Profile Updated Successfully\") return redirect('staff_profile') except: messages.error(request, \"Failed to Update Profile\") return redirect('staff_profile') def staff_add_result(request): subjects = Subjects.objects.filter(staff_id=request.user.id) session_years = SessionYearModel.objects.all() context = { \"subjects\": subjects, \"session_years\": session_years, } return render(request, \"staff_template/add_result_template.html\", context) def staff_add_result_save(request): if request.method != \"POST\": messages.error(request, \"Invalid Method\") return redirect('staff_add_result') else: student_admin_id = request.POST.get('student_list') assignment_marks = request.POST.get('assignment_marks') exam_marks = request.POST.get('exam_marks') subject_id = request.POST.get('subject') student_obj = Students.objects.get(admin=student_admin_id) subject_obj = Subjects.objects.get(id=subject_id) try: # Check if Students Result Already Exists or not check_exist = StudentResult.objects.filter(subject_id=subject_obj, student_id=student_obj).exists() if check_exist: result = StudentResult.objects.get(subject_id=subject_obj, student_id=student_obj) result.subject_assignment_marks = assignment_marks result.subject_exam_marks = exam_marks result.save() messages.success(request, \"Result Updated Successfully!\") return redirect('staff_add_result') else: result = StudentResult(student_id=student_obj, subject_id=subject_obj, subject_exam_marks=exam_marks, subject_assignment_marks=assignment_marks) result.save() messages.success(request, \"Result Added Successfully!\") return redirect('staff_add_result') except: messages.error(request, \"Failed to Add Result!\") return redirect('staff_add_result')", "e": 60741, "s": 46709, "text": null }, { "code": null, "e": 60819, "s": 60741, "text": "Step 11: Now add the HodViews.py. It contains the views of the HOD interface." }, { "code": null, "e": 60827, "s": 60819, "text": "Python3" }, { "code": "from django.shortcuts import render, redirectfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponsefrom django.contrib import messagesfrom django.core.files.storage import FileSystemStoragefrom django.urls import reversefrom django.views.decorators.csrf import csrf_exemptimport json from .forms import AddStudentForm, EditStudentForm from .models import CustomUser, Staffs, Courses, Subjects, Students, SessionYearModel, FeedBackStudent, FeedBackStaffs, LeaveReportStudent, LeaveReportStaff, Attendance, AttendanceReport def admin_home(request): all_student_count = Students.objects.all().count() subject_count = Subjects.objects.all().count() course_count = Courses.objects.all().count() staff_count = Staffs.objects.all().count() course_all = Courses.objects.all() course_name_list = [] subject_count_list = [] student_count_list_in_course = [] for course in course_all: subjects = Subjects.objects.filter(course_id=course.id).count() students = Students.objects.filter(course_id=course.id).count() course_name_list.append(course.course_name) subject_count_list.append(subjects) student_count_list_in_course.append(students) subject_all = Subjects.objects.all() subject_list = [] student_count_list_in_subject = [] for subject in subject_all: course = Courses.objects.get(id=subject.course_id.id) student_count = Students.objects.filter(course_id=course.id).count() subject_list.append(subject.subject_name) student_count_list_in_subject.append(student_count) # For Saffs staff_attendance_present_list=[] staff_attendance_leave_list=[] staff_name_list=[] staffs = Staffs.objects.all() for staff in staffs: subject_ids = Subjects.objects.filter(staff_id=staff.admin.id) attendance = Attendance.objects.filter(subject_id__in=subject_ids).count() leaves = LeaveReportStaff.objects.filter(staff_id=staff.id, leave_status=1).count() staff_attendance_present_list.append(attendance) staff_attendance_leave_list.append(leaves) staff_name_list.append(staff.admin.first_name) # For Students student_attendance_present_list=[] student_attendance_leave_list=[] student_name_list=[] students = Students.objects.all() for student in students: attendance = AttendanceReport.objects.filter(student_id=student.id, status=True).count() absent = AttendanceReport.objects.filter(student_id=student.id, status=False).count() leaves = LeaveReportStudent.objects.filter(student_id=student.id, leave_status=1).count() student_attendance_present_list.append(attendance) student_attendance_leave_list.append(leaves+absent) student_name_list.append(student.admin.first_name) context={ \"all_student_count\": all_student_count, \"subject_count\": subject_count, \"course_count\": course_count, \"staff_count\": staff_count, \"course_name_list\": course_name_list, \"subject_count_list\": subject_count_list, \"student_count_list_in_course\": student_count_list_in_course, \"subject_list\": subject_list, \"student_count_list_in_subject\": student_count_list_in_subject, \"staff_attendance_present_list\": staff_attendance_present_list, \"staff_attendance_leave_list\": staff_attendance_leave_list, \"staff_name_list\": staff_name_list, \"student_attendance_present_list\": student_attendance_present_list, \"student_attendance_leave_list\": student_attendance_leave_list, \"student_name_list\": student_name_list, } return render(request, \"hod_template/home_content.html\", context) def add_staff(request): return render(request, \"hod_template/add_staff_template.html\") def add_staff_save(request): if request.method != \"POST\": messages.error(request, \"Invalid Method \") return redirect('add_staff') else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') address = request.POST.get('address') try: user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=2) user.staffs.address = address user.save() messages.success(request, \"Staff Added Successfully!\") return redirect('add_staff') except: messages.error(request, \"Failed to Add Staff!\") return redirect('add_staff') def manage_staff(request): staffs = Staffs.objects.all() context = { \"staffs\": staffs } return render(request, \"hod_template/manage_staff_template.html\", context) def edit_staff(request, staff_id): staff = Staffs.objects.get(admin=staff_id) context = { \"staff\": staff, \"id\": staff_id } return render(request, \"hod_template/edit_staff_template.html\", context) def edit_staff_save(request): if request.method != \"POST\": return HttpResponse(\"<h2>Method Not Allowed</h2>\") else: staff_id = request.POST.get('staff_id') username = request.POST.get('username') email = request.POST.get('email') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') address = request.POST.get('address') try: # INSERTING into Customuser Model user = CustomUser.objects.get(id=staff_id) user.first_name = first_name user.last_name = last_name user.email = email user.username = username user.save() # INSERTING into Staff Model staff_model = Staffs.objects.get(admin=staff_id) staff_model.address = address staff_model.save() messages.success(request, \"Staff Updated Successfully.\") return redirect('/edit_staff/'+staff_id) except: messages.error(request, \"Failed to Update Staff.\") return redirect('/edit_staff/'+staff_id) def delete_staff(request, staff_id): staff = Staffs.objects.get(admin=staff_id) try: staff.delete() messages.success(request, \"Staff Deleted Successfully.\") return redirect('manage_staff') except: messages.error(request, \"Failed to Delete Staff.\") return redirect('manage_staff') def add_course(request): return render(request, \"hod_template/add_course_template.html\") def add_course_save(request): if request.method != \"POST\": messages.error(request, \"Invalid Method!\") return redirect('add_course') else: course = request.POST.get('course') try: course_model = Courses(course_name=course) course_model.save() messages.success(request, \"Course Added Successfully!\") return redirect('add_course') except: messages.error(request, \"Failed to Add Course!\") return redirect('add_course') def manage_course(request): courses = Courses.objects.all() context = { \"courses\": courses } return render(request, 'hod_template/manage_course_template.html', context) def edit_course(request, course_id): course = Courses.objects.get(id=course_id) context = { \"course\": course, \"id\": course_id } return render(request, 'hod_template/edit_course_template.html', context) def edit_course_save(request): if request.method != \"POST\": HttpResponse(\"Invalid Method\") else: course_id = request.POST.get('course_id') course_name = request.POST.get('course') try: course = Courses.objects.get(id=course_id) course.course_name = course_name course.save() messages.success(request, \"Course Updated Successfully.\") return redirect('/edit_course/'+course_id) except: messages.error(request, \"Failed to Update Course.\") return redirect('/edit_course/'+course_id) def delete_course(request, course_id): course = Courses.objects.get(id=course_id) try: course.delete() messages.success(request, \"Course Deleted Successfully.\") return redirect('manage_course') except: messages.error(request, \"Failed to Delete Course.\") return redirect('manage_course') def manage_session(request): session_years = SessionYearModel.objects.all() context = { \"session_years\": session_years } return render(request, \"hod_template/manage_session_template.html\", context) def add_session(request): return render(request, \"hod_template/add_session_template.html\") def add_session_save(request): if request.method != \"POST\": messages.error(request, \"Invalid Method\") return redirect('add_course') else: session_start_year = request.POST.get('session_start_year') session_end_year = request.POST.get('session_end_year') try: sessionyear = SessionYearModel(session_start_year=session_start_year, session_end_year=session_end_year) sessionyear.save() messages.success(request, \"Session Year added Successfully!\") return redirect(\"add_session\") except: messages.error(request, \"Failed to Add Session Year\") return redirect(\"add_session\") def edit_session(request, session_id): session_year = SessionYearModel.objects.get(id=session_id) context = { \"session_year\": session_year } return render(request, \"hod_template/edit_session_template.html\", context) def edit_session_save(request): if request.method != \"POST\": messages.error(request, \"Invalid Method!\") return redirect('manage_session') else: session_id = request.POST.get('session_id') session_start_year = request.POST.get('session_start_year') session_end_year = request.POST.get('session_end_year') try: session_year = SessionYearModel.objects.get(id=session_id) session_year.session_start_year = session_start_year session_year.session_end_year = session_end_year session_year.save() messages.success(request, \"Session Year Updated Successfully.\") return redirect('/edit_session/'+session_id) except: messages.error(request, \"Failed to Update Session Year.\") return redirect('/edit_session/'+session_id) def delete_session(request, session_id): session = SessionYearModel.objects.get(id=session_id) try: session.delete() messages.success(request, \"Session Deleted Successfully.\") return redirect('manage_session') except: messages.error(request, \"Failed to Delete Session.\") return redirect('manage_session') def add_student(request): form = AddStudentForm() context = { \"form\": form } return render(request, 'hod_template/add_student_template.html', context) def add_student_save(request): if request.method != \"POST\": messages.error(request, \"Invalid Method\") return redirect('add_student') else: form = AddStudentForm(request.POST, request.FILES) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] address = form.cleaned_data['address'] session_year_id = form.cleaned_data['session_year_id'] course_id = form.cleaned_data['course_id'] gender = form.cleaned_data['gender'] if len(request.FILES) != 0: profile_pic = request.FILES['profile_pic'] fs = FileSystemStorage() filename = fs.save(profile_pic.name, profile_pic) profile_pic_url = fs.url(filename) else: profile_pic_url = None try: user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=3) user.students.address = address course_obj = Courses.objects.get(id=course_id) user.students.course_id = course_obj session_year_obj = SessionYearModel.objects.get(id=session_year_id) user.students.session_year_id = session_year_obj user.students.gender = gender user.students.profile_pic = profile_pic_url user.save() messages.success(request, \"Student Added Successfully!\") return redirect('add_student') except: messages.error(request, \"Failed to Add Student!\") return redirect('add_student') else: return redirect('add_student') def manage_student(request): students = Students.objects.all() context = { \"students\": students } return render(request, 'hod_template/manage_student_template.html', context) def edit_student(request, student_id): # Adding Student ID into Session Variable request.session['student_id'] = student_id student = Students.objects.get(admin=student_id) form = EditStudentForm() # Filling the form with Data from Database form.fields['email'].initial = student.admin.email form.fields['username'].initial = student.admin.username form.fields['first_name'].initial = student.admin.first_name form.fields['last_name'].initial = student.admin.last_name form.fields['address'].initial = student.address form.fields['course_id'].initial = student.course_id.id form.fields['gender'].initial = student.gender form.fields['session_year_id'].initial = student.session_year_id.id context = { \"id\": student_id, \"username\": student.admin.username, \"form\": form } return render(request, \"hod_template/edit_student_template.html\", context) def edit_student_save(request): if request.method != \"POST\": return HttpResponse(\"Invalid Method!\") else: student_id = request.session.get('student_id') if student_id == None: return redirect('/manage_student') form = EditStudentForm(request.POST, request.FILES) if form.is_valid(): email = form.cleaned_data['email'] username = form.cleaned_data['username'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] address = form.cleaned_data['address'] course_id = form.cleaned_data['course_id'] gender = form.cleaned_data['gender'] session_year_id = form.cleaned_data['session_year_id'] # Getting Profile Pic first # First Check whether the file is selected or not # Upload only if file is selected if len(request.FILES) != 0: profile_pic = request.FILES['profile_pic'] fs = FileSystemStorage() filename = fs.save(profile_pic.name, profile_pic) profile_pic_url = fs.url(filename) else: profile_pic_url = None try: # First Update into Custom User Model user = CustomUser.objects.get(id=student_id) user.first_name = first_name user.last_name = last_name user.email = email user.username = username user.save() # Then Update Students Table student_model = Students.objects.get(admin=student_id) student_model.address = address course = Courses.objects.get(id=course_id) student_model.course_id = course session_year_obj = SessionYearModel.objects.get(id=session_year_id) student_model.session_year_id = session_year_obj student_model.gender = gender if profile_pic_url != None: student_model.profile_pic = profile_pic_url student_model.save() # Delete student_id SESSION after the data is updated del request.session['student_id'] messages.success(request, \"Student Updated Successfully!\") return redirect('/edit_student/'+student_id) except: messages.success(request, \"Failed to Uupdate Student.\") return redirect('/edit_student/'+student_id) else: return redirect('/edit_student/'+student_id) def delete_student(request, student_id): student = Students.objects.get(admin=student_id) try: student.delete() messages.success(request, \"Student Deleted Successfully.\") return redirect('manage_student') except: messages.error(request, \"Failed to Delete Student.\") return redirect('manage_student') def add_subject(request): courses = Courses.objects.all() staffs = CustomUser.objects.filter(user_type='2') context = { \"courses\": courses, \"staffs\": staffs } return render(request, 'hod_template/add_subject_template.html', context) def add_subject_save(request): if request.method != \"POST\": messages.error(request, \"Method Not Allowed!\") return redirect('add_subject') else: subject_name = request.POST.get('subject') course_id = request.POST.get('course') course = Courses.objects.get(id=course_id) staff_id = request.POST.get('staff') staff = CustomUser.objects.get(id=staff_id) try: subject = Subjects(subject_name=subject_name, course_id=course, staff_id=staff) subject.save() messages.success(request, \"Subject Added Successfully!\") return redirect('add_subject') except: messages.error(request, \"Failed to Add Subject!\") return redirect('add_subject') def manage_subject(request): subjects = Subjects.objects.all() context = { \"subjects\": subjects } return render(request, 'hod_template/manage_subject_template.html', context) def edit_subject(request, subject_id): subject = Subjects.objects.get(id=subject_id) courses = Courses.objects.all() staffs = CustomUser.objects.filter(user_type='2') context = { \"subject\": subject, \"courses\": courses, \"staffs\": staffs, \"id\": subject_id } return render(request, 'hod_template/edit_subject_template.html', context) def edit_subject_save(request): if request.method != \"POST\": HttpResponse(\"Invalid Method.\") else: subject_id = request.POST.get('subject_id') subject_name = request.POST.get('subject') course_id = request.POST.get('course') staff_id = request.POST.get('staff') try: subject = Subjects.objects.get(id=subject_id) subject.subject_name = subject_name course = Courses.objects.get(id=course_id) subject.course_id = course staff = CustomUser.objects.get(id=staff_id) subject.staff_id = staff subject.save() messages.success(request, \"Subject Updated Successfully.\") return HttpResponseRedirect(reverse(\"edit_subject\", kwargs={\"subject_id\":subject_id})) except: messages.error(request, \"Failed to Update Subject.\") return HttpResponseRedirect(reverse(\"edit_subject\", kwargs={\"subject_id\":subject_id})) def delete_subject(request, subject_id): subject = Subjects.objects.get(id=subject_id) try: subject.delete() messages.success(request, \"Subject Deleted Successfully.\") return redirect('manage_subject') except: messages.error(request, \"Failed to Delete Subject.\") return redirect('manage_subject') @csrf_exemptdef check_email_exist(request): email = request.POST.get(\"email\") user_obj = CustomUser.objects.filter(email=email).exists() if user_obj: return HttpResponse(True) else: return HttpResponse(False) @csrf_exemptdef check_username_exist(request): username = request.POST.get(\"username\") user_obj = CustomUser.objects.filter(username=username).exists() if user_obj: return HttpResponse(True) else: return HttpResponse(False) def student_feedback_message(request): feedbacks = FeedBackStudent.objects.all() context = { \"feedbacks\": feedbacks } return render(request, 'hod_template/student_feedback_template.html', context) @csrf_exemptdef student_feedback_message_reply(request): feedback_id = request.POST.get('id') feedback_reply = request.POST.get('reply') try: feedback = FeedBackStudent.objects.get(id=feedback_id) feedback.feedback_reply = feedback_reply feedback.save() return HttpResponse(\"True\") except: return HttpResponse(\"False\") def staff_feedback_message(request): feedbacks = FeedBackStaffs.objects.all() context = { \"feedbacks\": feedbacks } return render(request, 'hod_template/staff_feedback_template.html', context) @csrf_exemptdef staff_feedback_message_reply(request): feedback_id = request.POST.get('id') feedback_reply = request.POST.get('reply') try: feedback = FeedBackStaffs.objects.get(id=feedback_id) feedback.feedback_reply = feedback_reply feedback.save() return HttpResponse(\"True\") except: return HttpResponse(\"False\") def student_leave_view(request): leaves = LeaveReportStudent.objects.all() context = { \"leaves\": leaves } return render(request, 'hod_template/student_leave_view.html', context) def student_leave_approve(request, leave_id): leave = LeaveReportStudent.objects.get(id=leave_id) leave.leave_status = 1 leave.save() return redirect('student_leave_view') def student_leave_reject(request, leave_id): leave = LeaveReportStudent.objects.get(id=leave_id) leave.leave_status = 2 leave.save() return redirect('student_leave_view') def staff_leave_view(request): leaves = LeaveReportStaff.objects.all() context = { \"leaves\": leaves } return render(request, 'hod_template/staff_leave_view.html', context) def staff_leave_approve(request, leave_id): leave = LeaveReportStaff.objects.get(id=leave_id) leave.leave_status = 1 leave.save() return redirect('staff_leave_view') def staff_leave_reject(request, leave_id): leave = LeaveReportStaff.objects.get(id=leave_id) leave.leave_status = 2 leave.save() return redirect('staff_leave_view') def admin_view_attendance(request): subjects = Subjects.objects.all() session_years = SessionYearModel.objects.all() context = { \"subjects\": subjects, \"session_years\": session_years } return render(request, \"hod_template/admin_view_attendance.html\", context) @csrf_exemptdef admin_get_attendance_dates(request): subject_id = request.POST.get(\"subject\") session_year = request.POST.get(\"session_year_id\") # Students enroll to Course, Course has Subjects # Getting all data from subject model based on subject_id subject_model = Subjects.objects.get(id=subject_id) session_model = SessionYearModel.objects.get(id=session_year) attendance = Attendance.objects.filter(subject_id=subject_model, session_year_id=session_model) # Only Passing Student Id and Student Name Only list_data = [] for attendance_single in attendance: data_small={\"id\":attendance_single.id, \"attendance_date\":str(attendance_single.attendance_date), \"session_year_id\":attendance_single.session_year_id.id} list_data.append(data_small) return JsonResponse(json.dumps(list_data), content_type=\"application/json\", safe=False) @csrf_exemptdef admin_get_attendance_student(request): # Getting Values from Ajax POST 'Fetch Student' attendance_date = request.POST.get('attendance_date') attendance = Attendance.objects.get(id=attendance_date) attendance_data = AttendanceReport.objects.filter(attendance_id=attendance) # Only Passing Student Id and Student Name Only list_data = [] for student in attendance_data: data_small={\"id\":student.student_id.admin.id, \"name\":student.student_id.admin.first_name+\" \"+student.student_id.admin.last_name, \"status\":student.status} list_data.append(data_small) return JsonResponse(json.dumps(list_data), content_type=\"application/json\", safe=False) def admin_profile(request): user = CustomUser.objects.get(id=request.user.id) context={ \"user\": user } return render(request, 'hod_template/admin_profile.html', context) def admin_profile_update(request): if request.method != \"POST\": messages.error(request, \"Invalid Method!\") return redirect('admin_profile') else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') password = request.POST.get('password') try: customuser = CustomUser.objects.get(id=request.user.id) customuser.first_name = first_name customuser.last_name = last_name if password != None and password != \"\": customuser.set_password(password) customuser.save() messages.success(request, \"Profile Updated Successfully\") return redirect('admin_profile') except: messages.error(request, \"Failed to Update Profile\") return redirect('admin_profile') def staff_profile(request): pass def student_profile(requtest): pass", "e": 87802, "s": 60827, "text": null }, { "code": null, "e": 87905, "s": 87802, "text": "Step 12: Now add models.py to our project. It stores all the models that will be used in our project. " }, { "code": null, "e": 87913, "s": 87905, "text": "Python3" }, { "code": "from django.contrib.auth.models import AbstractUserfrom django.db import modelsfrom django.db.models.signals import post_savefrom django.dispatch import receiver class SessionYearModel(models.Model): id = models.AutoField(primary_key=True) session_start_year = models.DateField() session_end_year = models.DateField() objects = models.Manager() # Overriding the Default Django Auth# User and adding One More Field (user_type)class CustomUser(AbstractUser): HOD = '1' STAFF = '2' STUDENT = '3' EMAIL_TO_USER_TYPE_MAP = { 'hod': HOD, 'staff': STAFF, 'student': STUDENT } user_type_data = ((HOD, \"HOD\"), (STAFF, \"Staff\"), (STUDENT, \"Student\")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) class AdminHOD(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Staffs(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) address = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Courses(models.Model): id = models.AutoField(primary_key=True) course_name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Subjects(models.Model): id =models.AutoField(primary_key=True) subject_name = models.CharField(max_length=255) # need to give default course course_id = models.ForeignKey(Courses, on_delete=models.CASCADE, default=1) staff_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Students(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) gender = models.CharField(max_length=50) profile_pic = models.FileField() address = models.TextField() course_id = models.ForeignKey(Courses, on_delete=models.DO_NOTHING, default=1) session_year_id = models.ForeignKey(SessionYearModel, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Attendance(models.Model): # Subject Attendance id = models.AutoField(primary_key=True) subject_id = models.ForeignKey(Subjects, on_delete=models.DO_NOTHING) attendance_date = models.DateField() session_year_id = models.ForeignKey(SessionYearModel, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class AttendanceReport(models.Model): # Individual Student Attendance id = models.AutoField(primary_key=True) student_id = models.ForeignKey(Students, on_delete=models.DO_NOTHING) attendance_id = models.ForeignKey(Attendance, on_delete=models.CASCADE) status = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class LeaveReportStudent(models.Model): id = models.AutoField(primary_key=True) student_id = models.ForeignKey(Students, on_delete=models.CASCADE) leave_date = models.CharField(max_length=255) leave_message = models.TextField() leave_status = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class LeaveReportStaff(models.Model): id = models.AutoField(primary_key=True) staff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE) leave_date = models.CharField(max_length=255) leave_message = models.TextField() leave_status = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class FeedBackStudent(models.Model): id = models.AutoField(primary_key=True) student_id = models.ForeignKey(Students, on_delete=models.CASCADE) feedback = models.TextField() feedback_reply = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class FeedBackStaffs(models.Model): id = models.AutoField(primary_key=True) staff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE) feedback = models.TextField() feedback_reply = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class NotificationStudent(models.Model): id = models.AutoField(primary_key=True) student_id = models.ForeignKey(Students, on_delete=models.CASCADE) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class NotificationStaffs(models.Model): id = models.AutoField(primary_key=True) stafff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class StudentResult(models.Model): id = models.AutoField(primary_key=True) student_id = models.ForeignKey(Students, on_delete=models.CASCADE) subject_id = models.ForeignKey(Subjects, on_delete=models.CASCADE, default=1) subject_exam_marks = models.FloatField(default=0) subject_assignment_marks = models.FloatField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() #Creating Django Signals@receiver(post_save, sender=CustomUser) # Now Creating a Function which will# automatically insert data in HOD, Staff or Studentdef create_user_profile(sender, instance, created, **kwargs): # if Created is true (Means Data Inserted) if created: # Check the user_type and insert the data in respective tables if instance.user_type == 1: AdminHOD.objects.create(admin=instance) if instance.user_type == 2: Staffs.objects.create(admin=instance) if instance.user_type == 3: Students.objects.create(admin=instance, course_id=Courses.objects.get(id=1), session_year_id=SessionYearModel.objects.get(id=1), address=\"\", profile_pic=\"\", gender=\"\") @receiver(post_save, sender=CustomUser)def save_user_profile(sender, instance, **kwargs): if instance.user_type == 1: instance.adminhod.save() if instance.user_type == 2: instance.staffs.save() if instance.user_type == 3: instance.students.save()", "e": 95397, "s": 87913, "text": null }, { "code": null, "e": 95513, "s": 95397, "text": "Step 13: Go to student_management_project -> setting and add AUTH_USER_MODEL = ‘student_management_app.CustomUser’." }, { "code": null, "e": 95542, "s": 95513, "text": "Step 14: Now create forms.py" }, { "code": null, "e": 95550, "s": 95542, "text": "Python3" }, { "code": "from django import formsfrom .models import Courses, SessionYearModel class DateInput(forms.DateInput): input_type = \"date\" class AddStudentForm(forms.Form): email = forms.EmailField(label=\"Email\", max_length=50, widget=forms.EmailInput(attrs={\"class\":\"form-control\"})) password = forms.CharField(label=\"Password\", max_length=50, widget=forms.PasswordInput(attrs={\"class\":\"form-control\"})) first_name = forms.CharField(label=\"First Name\", max_length=50, widget=forms.TextInput(attrs={\"class\":\"form-control\"})) last_name = forms.CharField(label=\"Last Name\", max_length=50, widget=forms.TextInput(attrs={\"class\":\"form-control\"})) username = forms.CharField(label=\"Username\", max_length=50, widget=forms.TextInput(attrs={\"class\":\"form-control\"})) address = forms.CharField(label=\"Address\", max_length=50, widget=forms.TextInput(attrs={\"class\":\"form-control\"})) #For Displaying Courses try: courses = Courses.objects.all() course_list = [] for course in courses: single_course = (course.id, course.course_name) course_list.append(single_course) except: print(\"here\") course_list = [] #For Displaying Session Years try: session_years = SessionYearModel.objects.all() session_year_list = [] for session_year in session_years: single_session_year = (session_year.id, str(session_year.session_start_year)+\" to \"+str(session_year.session_end_year)) session_year_list.append(single_session_year) except: session_year_list = [] gender_list = ( ('Male','Male'), ('Female','Female') ) course_id = forms.ChoiceField(label=\"Course\", choices=course_list, widget=forms.Select(attrs={\"class\":\"form-control\"})) gender = forms.ChoiceField(label=\"Gender\", choices=gender_list, widget=forms.Select(attrs={\"class\":\"form-control\"})) session_year_id = forms.ChoiceField(label=\"Session Year\", choices=session_year_list, widget=forms.Select(attrs={\"class\":\"form-control\"})) profile_pic = forms.FileField(label=\"Profile Pic\", required=False, widget=forms.FileInput(attrs={\"class\":\"form-control\"})) class EditStudentForm(forms.Form): email = forms.EmailField(label=\"Email\", max_length=50, widget=forms.EmailInput(attrs={\"class\":\"form-control\"})) first_name = forms.CharField(label=\"First Name\", max_length=50, widget=forms.TextInput(attrs={\"class\":\"form-control\"})) last_name = forms.CharField(label=\"Last Name\", max_length=50, widget=forms.TextInput(attrs={\"class\":\"form-control\"})) username = forms.CharField(label=\"Username\", max_length=50, widget=forms.TextInput(attrs={\"class\":\"form-control\"})) address = forms.CharField(label=\"Address\", max_length=50, widget=forms.TextInput(attrs={\"class\":\"form-control\"})) # For Displaying Courses try: courses = Courses.objects.all() course_list = [] for course in courses: single_course = (course.id, course.course_name) course_list.append(single_course) except: course_list = [] # For Displaying Session Years try: session_years = SessionYearModel.objects.all() session_year_list = [] for session_year in session_years: single_session_year = (session_year.id, str(session_year.session_start_year)+\" to \"+str(session_year.session_end_year)) session_year_list.append(single_session_year) except: session_year_list = [] gender_list = ( ('Male','Male'), ('Female','Female') ) course_id = forms.ChoiceField(label=\"Course\", choices=course_list, widget=forms.Select(attrs={\"class\":\"form-control\"})) gender = forms.ChoiceField(label=\"Gender\", choices=gender_list, widget=forms.Select(attrs={\"class\":\"form-control\"})) session_year_id = forms.ChoiceField(label=\"Session Year\", choices=session_year_list, widget=forms.Select(attrs={\"class\":\"form-control\"})) profile_pic = forms.FileField(label=\"Profile Pic\", required=False, widget=forms.FileInput(attrs={\"class\":\"form-control\"}))", "e": 100837, "s": 95550, "text": null }, { "code": null, "e": 100883, "s": 100837, "text": "Step 15: Now register the models in admin.py " }, { "code": null, "e": 100891, "s": 100883, "text": "Python3" }, { "code": "from django.contrib import adminfrom django.contrib.auth.admin import UserAdminfrom .models import CustomUser, AdminHOD, Staffs, Courses, Subjects, Students, Attendance, AttendanceReport, LeaveReportStudent, LeaveReportStaff, FeedBackStudent, FeedBackStaffs, NotificationStudent, NotificationStaffs # Register your models here.class UserModel(UserAdmin): pass admin.site.register(CustomUser, UserModel) admin.site.register(AdminHOD)admin.site.register(Staffs)admin.site.register(Courses)admin.site.register(Subjects)admin.site.register(Students)admin.site.register(Attendance)admin.site.register(AttendanceReport)admin.site.register(LeaveReportStudent)admin.site.register(LeaveReportStaff)admin.site.register(FeedBackStudent)admin.site.register(FeedBackStaffs)admin.site.register(NotificationStudent)admin.site.register(NotificationStaffs)", "e": 101735, "s": 100891, "text": null }, { "code": null, "e": 102088, "s": 101735, "text": "Step 16: Now Create a new folder as templates which includes Student_template, Hod_template, Staff_template folders. It contains the different templates used in each interface.Create another folder as static which also includes some files. ( Note – All these folders must be in student_management_project ). All these files can be downloaded from here." }, { "code": null, "e": 102137, "s": 102088, "text": "Step 17: Add media, static URLs, and root path. " }, { "code": null, "e": 102277, "s": 102137, "text": "import os\n\nMEDIA_URL=\"/media/\"\nMEDIA_ROOT=os.path.join(BASE_DIR,\"media\")\n\nSTATIC_URL=\"/static/\"\nSTATIC_ROOT=os.path.join(BASE_DIR,\"static\")" }, { "code": null, "e": 102315, "s": 102277, "text": "Step 18: Now create a base.html page." }, { "code": null, "e": 102320, "s": 102315, "text": "HTML" }, { "code": "{% load static %} <!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <title>College Management System | Dashboard</title> <!-- Tell the browser to be responsive to screen width --> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Font Awesome --> <link rel=\"stylesheet\" href=\"{% static \"fontawesome-free/css/all.min.css\" %}\"> <!-- Ionicons --> <!-- Bootstrap CSS --> <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6\" crossorigin=\"anonymous\"> <link rel=\"stylesheet\" href=\"https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css\"> <!-- Tempusdominus Bbootstrap 4 --> <link rel=\"stylesheet\" href=\"{% static 'tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css' %}\"> <!-- iCheck --> <link rel=\"stylesheet\" href=\"{% static \"icheck-bootstrap/icheck-bootstrap.min.css\" %}\"> <!-- JQVMap --> <link rel=\"stylesheet\" href=\"{% static \"jqvmap/jqvmap.min.css\" %}\"> <!-- Theme style --> <link rel=\"stylesheet\" href=\"{% static 'dist/css/adminlte.min.css' %}\"> <!-- overlayScrollbars --> <link rel=\"stylesheet\" href=\"{% static \"overlayScrollbars/css/OverlayScrollbars.min.css\" %}\"> <!-- Daterange picker --> <link rel=\"stylesheet\" href=\"{% static \"daterangepicker/daterangepicker.css\" %}\"> <!-- summernote --> <link rel=\"stylesheet\" href=\"{% static \"summernote/summernote-bs4.css\" %}\"> <!-- Google Font: Source Sans Pro --> <link href=\"https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700\" rel=\"stylesheet\"> </head> {% block content %} {% endblock content %} <!-- jQuery --> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.4.1.slim.min.js\" integrity=\"sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n\" crossorigin=\"anonymous\"></script> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js\" integrity=\"sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6\" crossorigin=\"anonymous\"></script> <script src=\"{% static \"jquery/jquery.min.js\" %}\"></script><!-- jQuery UI 1.11.4 --><script src=\"{% static \"jquery-ui/jquery-ui.min.js\" %}\"></script><!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip --><script> $.widget.bridge('uibutton', $.ui.button)</script><!-- Bootstrap 4 --><script src=\"{% static \"bootstrap/js/bootstrap.bundle.min.js\" %}\"></script><!-- ChartJS --><script src=\"{% static \"chart.js/Chart.min.js\" %}\"></script><!-- Sparkline --><script src=\"{% static \"sparklines/sparkline.js\" %}\"></script><!-- JQVMap --><script src=\"{% static \"jqvmap/jquery.vmap.min.js\" %}\"></script><script src=\"{% static \"jqvmap/maps/jquery.vmap.usa.js\" %}\"></script><!-- jQuery Knob Chart --><script src=\"{% static \"jquery-knob/jquery.knob.min.js\" %}\"></script><!-- daterangepicker --><script src=\"{% static \"moment/moment.min.js\" %}\"></script><script src=\"{% static \"daterangepicker/daterangepicker.js\" %}\"></script><!-- Tempusdominus Bootstrap 4 --><script src=\"{% static \"tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js\" %}\"></script><!-- Summernote --><script src=\"{% static \"summernote/summernote-bs4.min.js\" %}\"></script><!-- overlayScrollbars --><script src=\"{% static \"overlayScrollbars/js/jquery.overlayScrollbars.min.js\" %}\"></script><!-- AdminLTE App --><script src=\"{% static 'dist/js/adminlte.js' %}\"></script><!-- AdminLTE dashboard demo (This is only for demo purposes) --><script src=\"{% static 'dist/js/pages/dashboard.js' %}\"></script><!-- AdminLTE for demo purposes --><script src=\"{% static 'dist/js/demo.js' %}\"></script></body></html>", "e": 106433, "s": 102320, "text": null }, { "code": null, "e": 106533, "s": 106433, "text": "Step 19: Now create a home.html page of our project in the student_management_app\\templates folder." }, { "code": null, "e": 106538, "s": 106533, "text": "HTML" }, { "code": "{% extends 'base.html' %}{% load static %}{% block title %}Home{% endblock title %} {% block content %}<html><head> <style>img { background-size: cover;}body {background-color: coral;} </style> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css\" integrity=\"sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ\" crossorigin=\"anonymous\"> <script src=\"https://code.jquery.com/jquery-3.1.1.slim.min.js\" integrity=\"sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n\" crossorigin=\"anonymous\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js\" integrity=\"sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn\" crossorigin=\"anonymous\"></script> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"><script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"></script><script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"></script><script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"></script> </head> <nav class=\"navbar navbar-expand-lg navbar-dark bg-dark\"> <a class=\"navbar-brand\" href=\"\"><h3>WELCOME TO CMS</h3></a> <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\"> <ul class=\"navbar-nav mr-auto\"> </ul> <form class=\"form-inline my-2 my-lg-0\"> <!--<input class=\"form-control mr-sm-2\" type=\"search\" placeholder=\"Search\" aria-label=\"Search\">--> <a href=\"/logi\" class=\"btn btn-outline-success my-1 mx-2\">Login</a> <!--<input class=\"form-control mr-sm-2\" type=\"Register\" placeholder=\"Register\" aria-label=\"Register\">--> <a href=\"/registration\" class=\"btn btn-outline-success my-1 mx-2\">Register</a> <a href=\"/contact\" class=\"btn btn-outline-danger my-1 mx-2\">Contact Us</a> </form> </div></nav> <div id=\"carouselExampleIndicators\" class=\"carousel slide\" data-ride=\"carousel\"> <ol class=\"carousel-indicators\"> </ol> <div class=\"carousel-inner\"> <div class=\"carousel-item active\"> {% comment %} <img class=\"d-block w-100\" src=\"https://images.unsplash.com/20/cambridge.JPG?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1030&q=80\" alt=\"First slide\"> {% endcomment %} <img src=\"{% static 'dist/img/111.png' %}\" class=\"d-block w-100 h-100 size-cover\" alt=\"...\"> </div> <div class=\"carousel-item\"> {% comment %} <img class=\"d-block w-100\" src=\"https://images.unsplash.com/photo-1541339907198-e08756dedf3f?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80\" alt=\"Second slide\"> {% endcomment %} <img src=\"{% static 'dist/img/re.png' %}\" class=\"d-block w-100 h-100 size-cover \" alt=\"...\"> </div> <div class=\"carousel-item\"> {% comment %} <img class=\"d-block w-100\" src=\"https://images.unsplash.com/photo-1541339907198-e08756dedf3f?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80\" alt=\"Second slide\"> {% endcomment %} <img src=\"{% static 'dist/img/e.png' %}\" class=\"d-block w-100 h-100 size-cover \" alt=\"...\"> </div> <div class=\"carousel-item\"> {% comment %} <img class=\"d-block w-100\" src=\"https://images.unsplash.com/photo-1541339907198-e08756dedf3f?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80\" alt=\"Second slide\"> {% endcomment %} <img src=\"{% static 'dist/img/22.png' %}\" class=\"d-block w-100 h-100 size-cover \" alt=\"...\"> </div> <div class=\"carousel-item\"> {% comment %} <img class=\"d-block w-100\" src=\"https://images.unsplash.com/photo-1503676260728-1c00da094a0b?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1009&q=80\" alt=\"Third slide\"> {% endcomment %} <img src=\"{% static 'dist/img/33.png' %}\" class=\"d-block w-100 h-100 size-cover\" alt=\"...\"> </div> </div> <a class=\"carousel-control-prev\" href=\"#carouselExampleIndicators\" role=\"button\" data-slide=\"prev\"> <span class=\"carousel-control-prev-icon\" aria-hidden=\"true\"></span> <span class=\"sr-only\">Previous</span> </a> <a class=\"carousel-control-next\" href=\"#carouselExampleIndicators\" role=\"button\" data-slide=\"next\"> <span class=\"carousel-control-next-icon\" aria-hidden=\"true\"></span> <span class=\"sr-only\">Next</span> </a></div> </html> {% endblock content %}", "e": 111717, "s": 106538, "text": null }, { "code": null, "e": 111726, "s": 111717, "text": "Output :" }, { "code": null, "e": 111825, "s": 111728, "text": "Step 20: Now create a registration.html page where students, staff, HOD can register themselves." }, { "code": null, "e": 111830, "s": 111825, "text": "HTML" }, { "code": "{% extends 'base.html' %}{% load static %}{% block content %}<head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Untitled</title> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css\"> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css\"> <link rel=\"stylesheet\" href=\"assets/css/style.css\"> <style> body{ height:1000px; background:#475d62; background-color: cover; font-family: sans-seriff; } .login-dark { max-width:320px; width:90%; background-color: #1e2833; padding:40px; border-radius:4px; transform: translate(-50%,-50%); position: absolute; top: 50%; left: 50%; color:#fff; box-shadow:3px 3px 4px rgba(0,0,0,0.2); } .login-dark form { max-width:320px; width:90%; background-color:#1e2833; padding:40px; border-radius:4px; transform:translate(-50%, -50%); position:absolute; top:50%; left:50%; color:#fff; box-shadow:3px 3px 4px rgba(0,0,0,0.2); } .login-dark .illustration { text-align:center; padding:15px 0 20px; font-size:100px; color:#2980ef; } .login-dark form .form-control { background:none; border:none; border-bottom:1px solid #434a52; border-radius:0; box-shadow:none; outline:none; color:inherit; } .login-dark form .btn-primary { background:#214a80; border:none; border-radius:4px; padding:11px; box-shadow:none; margin-top:26px; text-shadow:none; outline:none; } .login-dark form .btn-primary:hover, .login-dark form .btn-primary:active { background:#214a80; outline:none; } .login-dark form .forgot { display:block; text-align:center; font-size:12px; color:#6f7a85; opacity:0.9; text-decoration:none; } .login-dark form .forgot:hover, .login-dark form .forgot:active { opacity:1; text-decoration:none; } .login-dark form .btn-primary:active { transform:translateY(1px); } </style></head><nav class=\"navbar navbar-expand-lg navbar-dark bg-dark\"> <a class=\"navbar-brand\" href=\"/ \"> <h4>BACK TO HOME</h4> </a> <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\"> <ul class=\"navbar-nav mr-auto\"> </ul> <form class=\"form-inline my-2 my-lg-0\"> <!-- <input class=\"form-control mr-sm-2\" type=\"login\" placeholder=\"login\" aria-label=\"login\">--> <!--<input class=\"form-control mr-sm-2\" type=\"Register\" placeholder=\"Register\" aria-label=\"Register\">--> <a href=\"/logi\" class=\"btn btn-outline-success my-1 mx-2\">Login Here</a> <a href=\"/contact\" class=\"btn btn-outline-danger my-1 mx-2\">Contact Us</a> <!--<input class=\"form-control mr-sm-2\" type=\"register\" placeholder=\"register\" aria-label=\"register\">--> </form> </div></nav><div class=\"login-dark form-inline py-0 mx-4 my-4 pl-4 pr-4\"><form action=\"{% url 'doRegistration' %}\" method=\"get\">{% csrf_token %}<h1 class=\"text-center\">Signup</h1><div class=\"illustration\"><i class=\"icon ion-ios-locked-outline\"></i></div><div class=\"form-group\"><input class=\"form-control mb-2\" type=\"text\" name=\"first_name\" placeholder=\"First Name\"></div><div class=\"form-group\"><input class=\"form-control mb-2\" type=\"text\" name=\"last_name\" placeholder=\"Last Name\"></div><div class=\"form-group\"><input class=\"form-control mb-2\" type=\"email\" name=\"email\" placeholder=\"Email\"></div><div class=\"form-group\"><input class=\"form-control mb-2\" type=\"password\" name=\"password\" placeholder=\"Password\"></div><div class=\"form-group\"><input class=\"form-control mb-2\" type=\"password\" name=\"confirmPassword\" placeholder=\"Confirm Password\"></div><div class=\"form-group\"><button class=\"btn btn-primary btn-block mt-2 ml-2\" type=\"submit\">Register</button></div>{% comment %} Display Messages {% endcomment %}{% if messages %}<div class=\"col-12\"> {% for message in messages %} {% if message.tags == \"error\" %} <div class=\"alert alert-danger alert-dismissible fade show\" role=\"alert\" style=\"margin-top: 10px;\"> <b>{{ message }}</b> <button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"alert\" aria-label=\"Close\"></button> </div> {% endif %} {% endfor %}</div>{% endif %}<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script><script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js\"></script>{% endblock content %}", "e": 116787, "s": 111830, "text": null }, { "code": null, "e": 116795, "s": 116787, "text": "Output:" }, { "code": null, "e": 116813, "s": 116795, "text": "REGISTRATION PAGE" }, { "code": null, "e": 116905, "s": 116817, "text": "Step 21: Now create a login_page.html where students, staff, HOD can log in themselves." }, { "code": null, "e": 116910, "s": 116905, "text": "HTML" }, { "code": "{% extends 'base.html' %}{% load static %}{% block content %}<head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1; maximum-scale=1.0; user-scalable=0;\"> <title>Untitled</title> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css\"> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css\"> <link rel=\"stylesheet\" href=\"assets/css/style.css\"> <style> body{ height:1000px; background:#475d62; background-color: cover; font-family: sans-seriff; } .login-dark { max-width:320px; width:90%; background-color: #1e2833; padding:40px; border-radius:4px; transform: translate(-50%,-50%); position: absolute; top: 50%; left: 50%; color:#fff; box-shadow:3px 3px 4px rgba(0,0,0,0.2); } .login-dark form { max-width:320px; width:90%; background-color:#1e2833; padding:40px; border-radius:4px; transform:translate(-50%, -50%); position:absolute; top:50%; left:50%; color:#fff; box-shadow:3px 3px 4px rgba(0,0,0,0.2); } .login-dark .illustration { text-align:center; padding:15px 0 20px; font-size:100px; color:#2980ef; } .login-dark form .form-control { background:none; border:none; border-bottom:1px solid #434a52; border-radius:0; box-shadow:none; outline:none; color:inherit; } .login-dark form .btn-primary { background:#214a80; border:none; border-radius:4px; padding:11px; box-shadow:none; margin-top:26px; text-shadow:none; outline:none; } .login-dark form .btn-primary:hover, .login-dark form .btn-primary:active { background:#214a80; outline:none; } .login-dark form .forgot { display:block; text-align:center; font-size:12px; color:#6f7a85; opacity:0.9; text-decoration:none; } .login-dark form .forgot:hover, .login-dark form .forgot:active { opacity:1; text-decoration:none; } .login-dark form .btn-primary:active { transform:translateY(1px); } </style></head><nav class=\"navbar navbar-expand-lg navbar-dark bg-dark\"> <a class=\"navbar-brand\" href=\"/ \">BACK TO HOME</a> <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\"> <ul class=\"navbar-nav mr-auto\"> </ul> <form class=\"form-inline my-2 my-lg-0\"> <a href=\"{% url 'contact' %}\" class=\"btn btn-outline-danger my-1 mx-2\">Contact Us</a> </form> <!-- <form class=\"form-inline my-2 my-lg-0\">--> </div></nav><div class=\"login-dark form-inline py-0 mx-4 my-4 pl-4 pr-4\"> <form action=\"{% url 'doLogin' %}\" method=\"get\"> {% csrf_token %} <h1 class=\"text-center\">Login</h1> <div class=\"illustration\"><i class=\"icon ion-ios-locked-outline\"></i></div> <div class=\"form-group\"><input class=\"form-control mb-2\" type=\"email\" name=\"email\" placeholder=\"Email\"></div> <div class=\"form-group\"><input class=\"form-control mb-2\" type=\"password\" name=\"password\" placeholder=\"Password\"></div> <div class=\"form-group\"><button class=\"btn btn-primary btn-block mb-2 ml-2\" type=\"submit\">Log In</button></div> <a href=\"/registration\" class=\"forgot\">Not Registered Yet? Register Now</a> </form></div>{% comment %} Display Messages {% endcomment %}{% if messages %}<div class=\"col-12\"> {% for message in messages %} {% if message.tags == \"error\" %} {% comment %} <div class=\"alert alert-danger alert-dismissible fade show\" role=\"alert\" style=\"margin-top: 10px;\"> <b>{{ message }}</b> <button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"alert\" aria-label=\"Close\"></button> </div> {% endcomment %} <div class=\"alert alert-danger alert-dismissible fade show\" role=\"alert\"> <strong>Invalid Login Credentials!</strong> <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"> <span aria-hidden=\"true\">×</span> </button> </div> {% endif %} {% endfor %}</div>{% endif %}<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script><script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js\"></script>{% endblock content %}", "e": 121599, "s": 116910, "text": null }, { "code": null, "e": 121607, "s": 121599, "text": "Output:" }, { "code": null, "e": 121618, "s": 121607, "text": "LOGIN page" }, { "code": null, "e": 121648, "s": 121618, "text": "Step 22: Create contact.html " }, { "code": null, "e": 121653, "s": 121648, "text": "HTML" }, { "code": "{% extends 'base.html' %}{% load static %} {% block content %} <nav class=\"navbar navbar-expand-lg navbar-dark bg-dark\"> <a href=\"/ \" class=\"btn btn-outline-primary my-1 mx-2\">Go Back To Home </a> <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"collapse navbar-collapse\" id=\"navbarSupportedContent\"> <ul class=\"navbar-nav mr-auto\"> </ul> <form class=\"form-inline my-2 my-lg-0\"> <!-- <input class=\"form-control mr-sm-2\" type=\"login\" placeholder=\"login\" aria-label=\"login\">--> <!--<input class=\"form-control mr-sm-2\" type=\"Register\" placeholder=\"Register\" aria-label=\"Register\">--> <!--<input class=\"form-control mr-sm-2\" type=\"register\" placeholder=\"register\" aria-label=\"register\">--> </form> <form class=\"form-inline my-2 my-lg-0\"> </div> </nav><div class=\"container-fluid px-0\"> <img src=\"{% static 'dist/img/contact.jpg' %}\" class=\"d-block w-100 mx-0\" alt=\"...\" height=450px width=10px></div><div class=\"container\"> <h1 class=\"text-center my-3 display-2\"> <b>Contact Us</b> </h1><form action=\"/contact\" method=\"post\">{% csrf_token %} <div class=\"mb-3 py-2\"> <label for=\"exampleFormControlInput1\" class=\"form-label\"><b>Name</b></label> <input type=\"name\" class=\"form-control\" id=\"exampleFormControlInput1\" name = \"name\" placeholder=\"Enter your Name\"></div> <div class=\"mb-3 py-2\"> <label for=\"exampleFormControlInput1\" class=\"form-label\"><b>Email id</b></label> <input type=\"email\" class=\"form-control\" id=\"exampleFormControlInpu2\"name = \"email\" placeholder=\"Enter your Email\"></div> <div class=\"mb-3 py-2\"> <label for=\"exampleFormControlInput1\" class=\"form-label\"><b>Phone number</b></label> <input type=\"number\" class=\"form-control\" id=\"exampleFormControlInput3\" name = \"phone\" placeholder=\"Enter your Phone number\"></div><div class=\"mb-3 py-2\"> <label for=\"exampleFormControlTextarea1\" class=\"form-label\"><b>How can we help you ??</b></label> <textarea class=\"form-control\" id=\"exampleFormControlTextarea1\" rows=\"7\" name = \"desc\"></textarea></div> <button type=\"submit\" class=\"btn btn-primary btn-lg \">Submit</button> </form></div> {% endblock content%}", "e": 124414, "s": 121653, "text": null }, { "code": null, "e": 124564, "s": 124414, "text": "Step 23: Run these commands to migrate your models into the database. When you successfully do all the steps you will get this type of output in CMD." }, { "code": null, "e": 124596, "s": 124564, "text": "python manage.py makemigrations" }, { "code": null, "e": 124621, "s": 124596, "text": "python manage.py migrate" }, { "code": null, "e": 124641, "s": 124623, "text": "Project Overview:" }, { "code": null, "e": 124701, "s": 124641, "text": "Media error: Format(s) not supported or source(s) not found" }, { "code": null, "e": 124844, "s": 124701, "text": "This project can be used in the colleges to keep HOD, students, and staff connected with each other. The deployed project can be checked here." }, { "code": null, "e": 124874, "s": 124844, "text": "This project is developed by:" }, { "code": null, "e": 124888, "s": 124874, "text": "Nalin Goyal " }, { "code": null, "e": 124906, "s": 124888, "text": "Kanchan Jeswani " }, { "code": null, "e": 124921, "s": 124906, "text": "Vaishali Goyal" }, { "code": null, "e": 124934, "s": 124921, "text": "simmytarika5" }, { "code": null, "e": 124949, "s": 124934, "text": "sagartomar9927" }, { "code": null, "e": 124959, "s": 124949, "text": "as5853535" }, { "code": null, "e": 124967, "s": 124959, "text": "clintra" }, { "code": null, "e": 124989, "s": 124967, "text": "surajkumarguptaintern" }, { "code": null, "e": 125005, "s": 124989, "text": "Django-Projects" }, { "code": null, "e": 125018, "s": 125005, "text": "ProGeek 2021" }, { "code": null, "e": 125032, "s": 125018, "text": "Python Django" }, { "code": null, "e": 125040, "s": 125032, "text": "ProGeek" }, { "code": null, "e": 125048, "s": 125040, "text": "Project" }, { "code": null, "e": 125055, "s": 125048, "text": "Python" }, { "code": null, "e": 125153, "s": 125055, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 125162, "s": 125153, "text": "Comments" }, { "code": null, "e": 125175, "s": 125162, "text": "Old Comments" }, { "code": null, "e": 125256, "s": 125175, "text": "Project Idea - A website acting as transaction between oxygen sellers and buyers" }, { "code": null, "e": 125284, "s": 125256, "text": "Project Idea | Fuel Balance" }, { "code": null, "e": 125325, "s": 125284, "text": "Online Schooling System - Python Project" }, { "code": null, "e": 125373, "s": 125325, "text": "Project Idea | FILEit - An online filing system" }, { "code": null, "e": 125419, "s": 125373, "text": "Project Idea | Electric Vehicle Charging Lane" }, { "code": null, "e": 125468, "s": 125419, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 125490, "s": 125468, "text": "XML parsing in Python" }, { "code": null, "e": 125523, "s": 125490, "text": "Working with zip files in Python" }, { "code": null, "e": 125568, "s": 125523, "text": "Python | Simple GUI calculator using Tkinter" } ]
Program to Calculate Body Mass Index (BMI) - GeeksforGeeks
29 May, 2021 The Body Mass Index (BMI) or Quetelet index is a value derived from the mass (weight) and height of an individual, male or female. The BMI is defined as the body mass divided by the square of the body height and is universally expressed in units of kg/m2, resulting from the mass in kilograms and height in meters. The formula is: BMI = (mass or weight)/(height*height) where, mass or weight is in Kg, height is in meters Examples: Input : height(in meter): 1.79832 weight(in Kg): 70 Output : The BMI is 21.64532402096181, so Healthy. Explanation : 70/(1.79832*1.79832) Input : height(in meter): 1.58496 weight(in Kg): 85 Output : The BMI is 33.836256857260594 so Suffering from Obesity Explanation : 70/(1.58496*1.58496) Python3 #Python program to illustrate# how to calculate BMIdef BMI(height, weight): bmi = weight/(height**2) return bmi # Driver codeheight = 1.79832weight = 70 # calling the BMI functionbmi = BMI(height, weight)print("The BMI is", format(bmi), "so ", end='') # Conditions to find out BMI categoryif (bmi < 18.5): print("underweight") elif ( bmi >= 18.5 and bmi < 24.9): print("Healthy") elif ( bmi >= 24.9 and bmi < 30): print("overweight") elif ( bmi >=30): print("Suffering from Obesity") Output: The BMI is 21.64532402096181 so Healthy akshaysingh98088 Python School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Python Dictionary Arrays in C/C++ Reverse a string in Java Inheritance in C++ Constructors in C++
[ { "code": null, "e": 24331, "s": 24303, "text": "\n29 May, 2021" }, { "code": null, "e": 24664, "s": 24331, "text": "The Body Mass Index (BMI) or Quetelet index is a value derived from the mass (weight) and height of an individual, male or female. The BMI is defined as the body mass divided by the square of the body height and is universally expressed in units of kg/m2, resulting from the mass in kilograms and height in meters. The formula is: " }, { "code": null, "e": 24755, "s": 24664, "text": "BMI = (mass or weight)/(height*height)\nwhere,\nmass or weight is in Kg,\nheight is in meters" }, { "code": null, "e": 24767, "s": 24755, "text": "Examples: " }, { "code": null, "e": 25058, "s": 24767, "text": "Input : height(in meter): 1.79832\nweight(in Kg): 70\nOutput : The BMI is 21.64532402096181, so Healthy.\nExplanation : 70/(1.79832*1.79832)\n\nInput : height(in meter): 1.58496\nweight(in Kg): 85\nOutput : The BMI is 33.836256857260594 so Suffering from Obesity\nExplanation : 70/(1.58496*1.58496)" }, { "code": null, "e": 25070, "s": 25062, "text": "Python3" }, { "code": "#Python program to illustrate# how to calculate BMIdef BMI(height, weight): bmi = weight/(height**2) return bmi # Driver codeheight = 1.79832weight = 70 # calling the BMI functionbmi = BMI(height, weight)print(\"The BMI is\", format(bmi), \"so \", end='') # Conditions to find out BMI categoryif (bmi < 18.5): print(\"underweight\") elif ( bmi >= 18.5 and bmi < 24.9): print(\"Healthy\") elif ( bmi >= 24.9 and bmi < 30): print(\"overweight\") elif ( bmi >=30): print(\"Suffering from Obesity\")", "e": 25572, "s": 25070, "text": null }, { "code": null, "e": 25582, "s": 25572, "text": "Output: " }, { "code": null, "e": 25622, "s": 25582, "text": "The BMI is 21.64532402096181 so Healthy" }, { "code": null, "e": 25641, "s": 25624, "text": "akshaysingh98088" }, { "code": null, "e": 25648, "s": 25641, "text": "Python" }, { "code": null, "e": 25667, "s": 25648, "text": "School Programming" }, { "code": null, "e": 25765, "s": 25667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25774, "s": 25765, "text": "Comments" }, { "code": null, "e": 25787, "s": 25774, "text": "Old Comments" }, { "code": null, "e": 25805, "s": 25787, "text": "Python Dictionary" }, { "code": null, "e": 25840, "s": 25805, "text": "Read a file line by line in Python" }, { "code": null, "e": 25862, "s": 25840, "text": "Enumerate() in Python" }, { "code": null, "e": 25894, "s": 25862, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25924, "s": 25894, "text": "Iterate over a list in Python" }, { "code": null, "e": 25942, "s": 25924, "text": "Python Dictionary" }, { "code": null, "e": 25958, "s": 25942, "text": "Arrays in C/C++" }, { "code": null, "e": 25983, "s": 25958, "text": "Reverse a string in Java" }, { "code": null, "e": 26002, "s": 25983, "text": "Inheritance in C++" } ]
HTML - Email Links
It is not difficult to put an HTML email link on your webpage but it can cause unnecessary spamming problem for your email account. There are people, who can run programs to harvest these types of emails and later use them for spamming in various ways. You can have another option to facilitate people to send you emails. One option could be to use HTML forms to collect user data and then use PHP or CGI script to send an email. A simple example, check our Contact Us Form. We take user feedback using this form and then we are using one CGI program which is collecting this information and sending us email to the one given email ID. Note − You will learn about HTML Forms in HTML Forms and you will learn about CGI in our another tutorial Perl CGI Programming. HTML <a> tag provides you option to specify an email address to send an email. While using <a> tag as an email tag, you will use mailto: email address along with href attribute. Following is the syntax of using mailto instead of using http. <a href = "mailto: [email protected]">Send Email</a> This code will generate the following link which you can use to send email. Send Email Now, if a user clicks this link, it launches one Email Client (like Lotus Notes, Outlook Express etc. ) installed on your user's computer. There is another risk to use this option to send email because if user do not have email client installed on their computer then it would not be possible to send email. You can specify a default email subject and email body along with your email address. Following is the example to use default subject and body. <a href = "mailto:[email protected]?subject = Feedback&body = Message"> Send Feedback </a> This code will generate the following link which you can use to send email. Send Feedback 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2627, "s": 2374, "text": "It is not difficult to put an HTML email link on your webpage but it can cause unnecessary spamming problem for your email account. There are people, who can run programs to harvest these types of emails and later use them for spamming in various ways." }, { "code": null, "e": 2804, "s": 2627, "text": "You can have another option to facilitate people to send you emails. One option could be to use HTML forms to collect user data and then use PHP or CGI script to send an email." }, { "code": null, "e": 3010, "s": 2804, "text": "A simple example, check our Contact Us Form. We take user feedback using this form and then we are using one CGI program which is collecting this information and sending us email to the one given email ID." }, { "code": null, "e": 3138, "s": 3010, "text": "Note − You will learn about HTML Forms in HTML Forms and you will learn about CGI in our another tutorial Perl CGI Programming." }, { "code": null, "e": 3379, "s": 3138, "text": "HTML <a> tag provides you option to specify an email address to send an email. While using <a> tag as an email tag, you will use mailto: email address along with href attribute. Following is the syntax of using mailto instead of using http." }, { "code": null, "e": 3431, "s": 3379, "text": "<a href = \"mailto: [email protected]\">Send Email</a>\n" }, { "code": null, "e": 3507, "s": 3431, "text": "This code will generate the following link which you can use to send email." }, { "code": null, "e": 3520, "s": 3507, "text": "Send Email \n" }, { "code": null, "e": 3828, "s": 3520, "text": "Now, if a user clicks this link, it launches one Email Client (like Lotus Notes, Outlook Express etc. ) installed on your user's computer. There is another risk to use this option to send email because if user do not have email client installed on their computer then it would not be possible to send email." }, { "code": null, "e": 3972, "s": 3828, "text": "You can specify a default email subject and email body along with your email address. Following is the example to use default subject and body." }, { "code": null, "e": 4062, "s": 3972, "text": "<a href = \"mailto:[email protected]?subject = Feedback&body = Message\">\nSend Feedback\n</a>\n" }, { "code": null, "e": 4138, "s": 4062, "text": "This code will generate the following link which you can use to send email." }, { "code": null, "e": 4153, "s": 4138, "text": "Send Feedback\n" }, { "code": null, "e": 4186, "s": 4153, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 4200, "s": 4186, "text": " Anadi Sharma" }, { "code": null, "e": 4235, "s": 4200, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4249, "s": 4235, "text": " Anadi Sharma" }, { "code": null, "e": 4284, "s": 4249, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4301, "s": 4284, "text": " Frahaan Hussain" }, { "code": null, "e": 4336, "s": 4301, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4367, "s": 4336, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4400, "s": 4367, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 4431, "s": 4400, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4466, "s": 4431, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4497, "s": 4466, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4504, "s": 4497, "text": " Print" }, { "code": null, "e": 4515, "s": 4504, "text": " Add Notes" } ]
UnitTest Framework - API
This chapter discusses the classes and methods defined in the unittest module. There are five major classes in this module. Object of this class represents the smallest testable unit. It holds the test routines and provides hooks for preparing each routine and for cleaning up thereafter. The following methods are defined in the TestCase class − setUp() Method called to prepare the test fixture. This is called immediately before calling the test method tearDown() Method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception, setUpClass() A class method called before tests in an individual class run. tearDownClass() A class method called after tests in an individual class have run. run(result = None) Run the test, collecting the result into the test result object passed as result. skipTest(reason) Calling this during a test method or setUp() skips the current test. debug() Run the test without collecting the result. shortDescription() Returns a one-line description of the test. There can be numerous tests written inside a TestCase class. These test methods may need database connection, temporary files or other resources to be initialized. These are called fixtures. TestCase includes a special hook to configure and clean up any fixtures needed by your tests. To configure the fixtures, override setUp(). To clean up, override tearDown(). In the following example, two tests are written inside the TestCase class. They test result of addition and subtraction of two values. The setup() method initializes the arguments based on shortDescription() of each test. teardown() method will be executed at the end of each test. import unittest class simpleTest2(unittest.TestCase): def setUp(self): self.a = 10 self.b = 20 name = self.shortDescription() if name == "Add": self.a = 10 self.b = 20 print name, self.a, self.b if name == "sub": self.a = 50 self.b = 60 print name, self.a, self.b def tearDown(self): print '\nend of test',self.shortDescription() def testadd(self): """Add""" result = self.a+self.b self.assertTrue(result == 100) def testsub(self): """sub""" result = self.a-self.b self.assertTrue(result == -10) if __name__ == '__main__': unittest.main() Run the above code from the command line. It gives the following output − C:\Python27>python test2.py Add 10 20 F end of test Add sub 50 60 end of test sub . ================================================================ FAIL: testadd (__main__.simpleTest2) Add ---------------------------------------------------------------------- Traceback (most recent call last): File "test2.py", line 21, in testadd self.assertTrue(result == 100) AssertionError: False is not true ---------------------------------------------------------------------- Ran 2 tests in 0.015s FAILED (failures = 1) TestCase class has a setUpClass() method which can be overridden to execute before the execution of individual tests inside a TestCase class. Similarly, tearDownClass() method will be executed after all test in the class. Both the methods are class methods. Hence, they must be decorated with @classmethod directive. The following example demonstrates the use of these class methods − import unittest class TestFixtures(unittest.TestCase): @classmethod def setUpClass(cls): print 'called once before any tests in class' @classmethod def tearDownClass(cls): print '\ncalled once after all tests in class' def setUp(self): self.a = 10 self.b = 20 name = self.shortDescription() print '\n',name def tearDown(self): print '\nend of test',self.shortDescription() def test1(self): """One""" result = self.a+self.b self.assertTrue(True) def test2(self): """Two""" result = self.a-self.b self.assertTrue(False) if __name__ == '__main__': unittest.main() Python's testing framework provides a useful mechanism by which test case instances can be grouped together according to the features they test. This mechanism is made available by TestSuite class in unittest module. The following steps are involved in creating and running a test suite. Step 1 − Create an instance of TestSuite class. suite = unittest.TestSuite() Step 2 − Add tests inside a TestCase class in the suite. suite.addTest(testcase class) Step 3 − You can also use makeSuite() method to add tests from a class suite = unittest.makeSuite(test case class) Step 4 − Individual tests can also be added in the suite. suite.addTest(testcaseclass(""testmethod") Step 5 − Create an object of the TestTestRunner class. runner = unittest.TextTestRunner() Step 6 − Call the run() method to run all the tests in the suite runner.run (suite) The following methods are defined in TestSuite class − addTest() Adds a test method in the test suite. addTests() Adds tests from multiple TestCase classes. run() Runs the tests associated with this suite, collecting the result into the test result object debug() Runs the tests associated with this suite without collecting the result. countTestCases() Returns the number of tests represented by this test object The following example shows how to use TestSuite class − import unittest class suiteTest(unittest.TestCase): def setUp(self): self.a = 10 self.b = 20 def testadd(self): """Add""" result = self.a+self.b self.assertTrue(result == 100) def testsub(self): """sub""" result = self.a-self.b self.assertTrue(result == -10) def suite(): suite = unittest.TestSuite() ## suite.addTest (simpleTest3("testadd")) ## suite.addTest (simpleTest3("testsub")) suite.addTest(unittest.makeSuite(simpleTest3)) return suite if __name__ == '__main__': runner = unittest.TextTestRunner() test_suite = suite() runner.run (test_suite) You can experiment with the addTest() method by uncommenting the lines and comment statement having makeSuite() method. The unittest package has the TestLoader class which is used to create test suites from classes and modules. By default, the unittest.defaultTestLoader instance is automatically created when the unittest.main(0 method is called. An explicit instance, however enables the customization of certain properties. In the following code, tests from two classes are collected in a List by using the TestLoader object. import unittest testList = [Test1, Test2] testLoad = unittest.TestLoader() TestList = [] for testCase in testList: testSuite = testLoad.loadTestsFromTestCase(testCase) TestList.append(testSuite) newSuite = unittest.TestSuite(TestList) runner = unittest.TextTestRunner() runner.run(newSuite) The following table shows a list of methods in the TestLoader class − loadTestsFromTestCase() Return a suite of all tests cases contained in a TestCase class loadTestsFromModule() Return a suite of all tests cases contained in the given module. loadTestsFromName() Return a suite of all tests cases given a string specifier. discover() Find all the test modules by recursing into subdirectories from the specified start directory, and return a TestSuite object This class is used to compile information about the tests that have been successful and the tests that have met failure. A TestResult object stores the results of a set of tests. A TestResult instance is returned by the TestRunner.run() method. TestResult instances have the following attributes − Errors A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents a test which raised an unexpected exception. Failures A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents a test where a failure was explicitly signalled using the TestCase.assert*() methods. Skipped A list containing 2-tuples of TestCase instances and strings holding the reason for skipping the test. wasSuccessful() Return True if all tests run so far have passed, otherwise returns False. stop() This method can be called to signal that the set of tests being run should be aborted. startTestRun() Called once before any tests are executed. stopTestRun() Called once after all tests are executed. testsRun The total number of tests run so far. Buffer If set to true, sys.stdout and sys.stderr will be buffered in between startTest() and stopTest() being called. The following code executes a test suite − if __name__ == '__main__': runner = unittest.TextTestRunner() test_suite = suite() result = runner.run (test_suite) print "---- START OF TEST RESULTS" print result print "result::errors" print result.errors print "result::failures" print result.failures print "result::skipped" print result.skipped print "result::successful" print result.wasSuccessful() print "result::test-run" print result.testsRun print "---- END OF TEST RESULTS" The code when executed displays the following output − ---- START OF TEST RESULTS <unittest.runner.TextTestResult run = 2 errors = 0 failures = 1> result::errors [] result::failures [(<__main__.suiteTest testMethod = testadd>, 'Traceback (most recent call last):\n File "test3.py", line 10, in testadd\n self.assertTrue(result == 100)\nAssert ionError: False is not true\n')] result::skipped [] result::successful False result::test-run 2 ---- END OF TEST RESULTS Print Add Notes Bookmark this page
[ { "code": null, "e": 2222, "s": 2098, "text": "This chapter discusses the classes and methods defined in the unittest module. There are five major classes in this module." }, { "code": null, "e": 2387, "s": 2222, "text": "Object of this class represents the smallest testable unit. It holds the test routines and provides hooks for preparing each routine and for cleaning up thereafter." }, { "code": null, "e": 2445, "s": 2387, "text": "The following methods are defined in the TestCase class −" }, { "code": null, "e": 2453, "s": 2445, "text": "setUp()" }, { "code": null, "e": 2554, "s": 2453, "text": "Method called to prepare the test fixture. This is called immediately before calling the test method" }, { "code": null, "e": 2565, "s": 2554, "text": "tearDown()" }, { "code": null, "e": 2714, "s": 2565, "text": "Method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception," }, { "code": null, "e": 2727, "s": 2714, "text": "setUpClass()" }, { "code": null, "e": 2790, "s": 2727, "text": "A class method called before tests in an individual class run." }, { "code": null, "e": 2806, "s": 2790, "text": "tearDownClass()" }, { "code": null, "e": 2873, "s": 2806, "text": "A class method called after tests in an individual class have run." }, { "code": null, "e": 2892, "s": 2873, "text": "run(result = None)" }, { "code": null, "e": 2974, "s": 2892, "text": "Run the test, collecting the result into the test result object passed as result." }, { "code": null, "e": 2991, "s": 2974, "text": "skipTest(reason)" }, { "code": null, "e": 3060, "s": 2991, "text": "Calling this during a test method or setUp() skips the current test." }, { "code": null, "e": 3068, "s": 3060, "text": "debug()" }, { "code": null, "e": 3112, "s": 3068, "text": "Run the test without collecting the result." }, { "code": null, "e": 3131, "s": 3112, "text": "shortDescription()" }, { "code": null, "e": 3175, "s": 3131, "text": "Returns a one-line description of the test." }, { "code": null, "e": 3539, "s": 3175, "text": "There can be numerous tests written inside a TestCase class. These test methods may need database connection, temporary files or other resources to be initialized. These are called fixtures. TestCase includes a special hook to configure and clean up any fixtures needed by your tests. To configure the fixtures, override setUp(). To clean up, override tearDown()." }, { "code": null, "e": 3821, "s": 3539, "text": "In the following example, two tests are written inside the TestCase class. They test result of addition and subtraction of two values. The setup() method initializes the arguments based on shortDescription() of each test. teardown() method will be executed at the end of each test." }, { "code": null, "e": 4510, "s": 3821, "text": "import unittest\n\nclass simpleTest2(unittest.TestCase):\n def setUp(self):\n self.a = 10\n self.b = 20\n name = self.shortDescription()\n if name == \"Add\":\n self.a = 10\n self.b = 20\n print name, self.a, self.b\n if name == \"sub\":\n self.a = 50\n self.b = 60\n print name, self.a, self.b\n def tearDown(self):\n print '\\nend of test',self.shortDescription()\n\n def testadd(self):\n \"\"\"Add\"\"\"\n result = self.a+self.b\n self.assertTrue(result == 100)\n def testsub(self):\n \"\"\"sub\"\"\"\n result = self.a-self.b\n self.assertTrue(result == -10)\n \nif __name__ == '__main__':\n unittest.main()" }, { "code": null, "e": 4584, "s": 4510, "text": "Run the above code from the command line. It gives the following output −" }, { "code": null, "e": 5108, "s": 4584, "text": "C:\\Python27>python test2.py\nAdd 10 20\nF\nend of test Add\nsub 50 60\nend of test sub\n.\n================================================================\nFAIL: testadd (__main__.simpleTest2)\nAdd\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"test2.py\", line 21, in testadd\n self.assertTrue(result == 100)\nAssertionError: False is not true\n----------------------------------------------------------------------\nRan 2 tests in 0.015s\n\nFAILED (failures = 1)\n" }, { "code": null, "e": 5425, "s": 5108, "text": "TestCase class has a setUpClass() method which can be overridden to execute before the execution of individual tests inside a TestCase class. Similarly, tearDownClass() method will be executed after all test in the class. Both the methods are class methods. Hence, they must be decorated with @classmethod directive." }, { "code": null, "e": 5493, "s": 5425, "text": "The following example demonstrates the use of these class methods −" }, { "code": null, "e": 6168, "s": 5493, "text": "import unittest\n\nclass TestFixtures(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n print 'called once before any tests in class'\n\n @classmethod\n def tearDownClass(cls):\n print '\\ncalled once after all tests in class'\n\n def setUp(self):\n self.a = 10\n self.b = 20\n name = self.shortDescription()\n print '\\n',name\n def tearDown(self):\n print '\\nend of test',self.shortDescription()\n\n def test1(self):\n \"\"\"One\"\"\"\n result = self.a+self.b\n self.assertTrue(True)\n def test2(self):\n \"\"\"Two\"\"\"\n result = self.a-self.b\n self.assertTrue(False)\n \nif __name__ == '__main__':\nunittest.main()" }, { "code": null, "e": 6385, "s": 6168, "text": "Python's testing framework provides a useful mechanism by which test case instances can be grouped together according to the features they test. This mechanism is made available by TestSuite class in unittest module." }, { "code": null, "e": 6456, "s": 6385, "text": "The following steps are involved in creating and running a test suite." }, { "code": null, "e": 6504, "s": 6456, "text": "Step 1 − Create an instance of TestSuite class." }, { "code": null, "e": 6533, "s": 6504, "text": "suite = unittest.TestSuite()" }, { "code": null, "e": 6590, "s": 6533, "text": "Step 2 − Add tests inside a TestCase class in the suite." }, { "code": null, "e": 6620, "s": 6590, "text": "suite.addTest(testcase class)" }, { "code": null, "e": 6691, "s": 6620, "text": "Step 3 − You can also use makeSuite() method to add tests from a class" }, { "code": null, "e": 6735, "s": 6691, "text": "suite = unittest.makeSuite(test case class)" }, { "code": null, "e": 6793, "s": 6735, "text": "Step 4 − Individual tests can also be added in the suite." }, { "code": null, "e": 6836, "s": 6793, "text": "suite.addTest(testcaseclass(\"\"testmethod\")" }, { "code": null, "e": 6891, "s": 6836, "text": "Step 5 − Create an object of the TestTestRunner class." }, { "code": null, "e": 6926, "s": 6891, "text": "runner = unittest.TextTestRunner()" }, { "code": null, "e": 6991, "s": 6926, "text": "Step 6 − Call the run() method to run all the tests in the suite" }, { "code": null, "e": 7010, "s": 6991, "text": "runner.run (suite)" }, { "code": null, "e": 7065, "s": 7010, "text": "The following methods are defined in TestSuite class −" }, { "code": null, "e": 7075, "s": 7065, "text": "addTest()" }, { "code": null, "e": 7113, "s": 7075, "text": "Adds a test method in the test suite." }, { "code": null, "e": 7124, "s": 7113, "text": "addTests()" }, { "code": null, "e": 7167, "s": 7124, "text": "Adds tests from multiple TestCase classes." }, { "code": null, "e": 7173, "s": 7167, "text": "run()" }, { "code": null, "e": 7266, "s": 7173, "text": "Runs the tests associated with this suite, collecting the result into the test result object" }, { "code": null, "e": 7274, "s": 7266, "text": "debug()" }, { "code": null, "e": 7347, "s": 7274, "text": "Runs the tests associated with this suite without collecting the result." }, { "code": null, "e": 7364, "s": 7347, "text": "countTestCases()" }, { "code": null, "e": 7424, "s": 7364, "text": "Returns the number of tests represented by this test object" }, { "code": null, "e": 7481, "s": 7424, "text": "The following example shows how to use TestSuite class −" }, { "code": null, "e": 8130, "s": 7481, "text": "import unittest\nclass suiteTest(unittest.TestCase):\n def setUp(self):\n self.a = 10\n self.b = 20\n \n def testadd(self):\n \"\"\"Add\"\"\"\n result = self.a+self.b\n self.assertTrue(result == 100)\n def testsub(self):\n \"\"\"sub\"\"\"\n result = self.a-self.b\n self.assertTrue(result == -10)\n \ndef suite():\n suite = unittest.TestSuite()\n## suite.addTest (simpleTest3(\"testadd\"))\n## suite.addTest (simpleTest3(\"testsub\"))\n suite.addTest(unittest.makeSuite(simpleTest3))\n return suite\n \nif __name__ == '__main__':\n runner = unittest.TextTestRunner()\n test_suite = suite()\n runner.run (test_suite)" }, { "code": null, "e": 8250, "s": 8130, "text": "You can experiment with the addTest() method by uncommenting the lines and comment statement having makeSuite() method." }, { "code": null, "e": 8557, "s": 8250, "text": "The unittest package has the TestLoader class which is used to create test suites from classes and modules. By default, the unittest.defaultTestLoader instance is automatically created when the unittest.main(0 method is called. An explicit instance, however enables the customization of certain properties." }, { "code": null, "e": 8659, "s": 8557, "text": "In the following code, tests from two classes are collected in a List by using the TestLoader object." }, { "code": null, "e": 8961, "s": 8659, "text": "import unittest\ntestList = [Test1, Test2]\ntestLoad = unittest.TestLoader()\n\nTestList = []\nfor testCase in testList:\n testSuite = testLoad.loadTestsFromTestCase(testCase)\n TestList.append(testSuite)\n \nnewSuite = unittest.TestSuite(TestList)\nrunner = unittest.TextTestRunner()\nrunner.run(newSuite)" }, { "code": null, "e": 9031, "s": 8961, "text": "The following table shows a list of methods in the TestLoader class −" }, { "code": null, "e": 9055, "s": 9031, "text": "loadTestsFromTestCase()" }, { "code": null, "e": 9119, "s": 9055, "text": "Return a suite of all tests cases contained in a TestCase class" }, { "code": null, "e": 9141, "s": 9119, "text": "loadTestsFromModule()" }, { "code": null, "e": 9206, "s": 9141, "text": "Return a suite of all tests cases contained in the given module." }, { "code": null, "e": 9226, "s": 9206, "text": "loadTestsFromName()" }, { "code": null, "e": 9286, "s": 9226, "text": "Return a suite of all tests cases given a string specifier." }, { "code": null, "e": 9297, "s": 9286, "text": "discover()" }, { "code": null, "e": 9422, "s": 9297, "text": "Find all the test modules by recursing into subdirectories from the specified start directory, and return a TestSuite object" }, { "code": null, "e": 9667, "s": 9422, "text": "This class is used to compile information about the tests that have been successful and the tests that have met failure. A TestResult object stores the results of a set of tests. A TestResult instance is returned by the TestRunner.run() method." }, { "code": null, "e": 9720, "s": 9667, "text": "TestResult instances have the following attributes −" }, { "code": null, "e": 9727, "s": 9720, "text": "Errors" }, { "code": null, "e": 9885, "s": 9727, "text": "A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents a test which raised an unexpected exception." }, { "code": null, "e": 9894, "s": 9885, "text": "Failures" }, { "code": null, "e": 10093, "s": 9894, "text": "A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents a test where a failure was explicitly signalled using the TestCase.assert*() methods." }, { "code": null, "e": 10101, "s": 10093, "text": "Skipped" }, { "code": null, "e": 10204, "s": 10101, "text": "A list containing 2-tuples of TestCase instances and strings holding the reason for skipping the test." }, { "code": null, "e": 10220, "s": 10204, "text": "wasSuccessful()" }, { "code": null, "e": 10294, "s": 10220, "text": "Return True if all tests run so far have passed, otherwise returns False." }, { "code": null, "e": 10301, "s": 10294, "text": "stop()" }, { "code": null, "e": 10388, "s": 10301, "text": "This method can be called to signal that the set of tests being run should be aborted." }, { "code": null, "e": 10403, "s": 10388, "text": "startTestRun()" }, { "code": null, "e": 10446, "s": 10403, "text": "Called once before any tests are executed." }, { "code": null, "e": 10460, "s": 10446, "text": "stopTestRun()" }, { "code": null, "e": 10502, "s": 10460, "text": "Called once after all tests are executed." }, { "code": null, "e": 10511, "s": 10502, "text": "testsRun" }, { "code": null, "e": 10549, "s": 10511, "text": "The total number of tests run so far." }, { "code": null, "e": 10556, "s": 10549, "text": "Buffer" }, { "code": null, "e": 10667, "s": 10556, "text": "If set to true, sys.stdout and sys.stderr will be buffered in between startTest() and stopTest() being called." }, { "code": null, "e": 10710, "s": 10667, "text": "The following code executes a test suite −" }, { "code": null, "e": 11205, "s": 10710, "text": "if __name__ == '__main__':\n runner = unittest.TextTestRunner()\n test_suite = suite()\n result = runner.run (test_suite)\n \n print \"---- START OF TEST RESULTS\"\n print result\n\n print \"result::errors\"\n print result.errors\n\n print \"result::failures\"\n print result.failures\n\n print \"result::skipped\"\n print result.skipped\n\n print \"result::successful\"\n print result.wasSuccessful()\n \n print \"result::test-run\"\n print result.testsRun\n print \"---- END OF TEST RESULTS\"" }, { "code": null, "e": 11260, "s": 11205, "text": "The code when executed displays the following output −" }, { "code": null, "e": 11680, "s": 11260, "text": "---- START OF TEST RESULTS\n<unittest.runner.TextTestResult run = 2 errors = 0 failures = 1>\nresult::errors\n[]\nresult::failures\n[(<__main__.suiteTest testMethod = testadd>, 'Traceback (most recent call last):\\n\n File \"test3.py\", line 10, in testadd\\n \n self.assertTrue(result == 100)\\nAssert\n ionError: False is not true\\n')]\nresult::skipped\n[]\nresult::successful\nFalse\nresult::test-run\n2\n---- END OF TEST RESULTS\n" }, { "code": null, "e": 11687, "s": 11680, "text": " Print" }, { "code": null, "e": 11698, "s": 11687, "text": " Add Notes" } ]
HBase - Count & Truncate
You can count the number of rows of a table using the count command. Its syntax is as follows: count ‘<table name>’ After deleting the first row, emp table will have two rows. Verify it as shown below. hbase(main):023:0> count 'emp' 2 row(s) in 0.090 seconds ⇒ 2 This command disables drops and recreates a table. The syntax of truncate is as follows: hbase> truncate 'table name' Given below is the example of truncate command. Here we have truncated the emp table. hbase(main):011:0> truncate 'emp' Truncating 'one' table (it may take a while): - Disabling table... - Truncating table... 0 row(s) in 1.5950 seconds After truncating the table, use the scan command to verify. You will get a table with zero rows. hbase(main):017:0> scan ‘emp’ ROW COLUMN + CELL 0 row(s) in 0.3110 seconds Print Add Notes Bookmark this page
[ { "code": null, "e": 2132, "s": 2037, "text": "You can count the number of rows of a table using the count command. Its syntax is as follows:" }, { "code": null, "e": 2155, "s": 2132, "text": "count ‘<table name>’ \n" }, { "code": null, "e": 2241, "s": 2155, "text": "After deleting the first row, emp table will have two rows. Verify it as shown below." }, { "code": null, "e": 2304, "s": 2241, "text": "hbase(main):023:0> count 'emp'\n2 row(s) in 0.090 seconds\n⇒ 2 \n" }, { "code": null, "e": 2393, "s": 2304, "text": "This command disables drops and recreates a table. The syntax of truncate is as follows:" }, { "code": null, "e": 2423, "s": 2393, "text": "hbase> truncate 'table name'\n" }, { "code": null, "e": 2509, "s": 2423, "text": "Given below is the example of truncate command. Here we have truncated the emp table." }, { "code": null, "e": 2669, "s": 2509, "text": "hbase(main):011:0> truncate 'emp'\nTruncating 'one' table (it may take a while):\n - Disabling table...\n - Truncating table...\n 0 row(s) in 1.5950 seconds\n" }, { "code": null, "e": 2766, "s": 2669, "text": "After truncating the table, use the scan command to verify. You will get a table with zero rows." }, { "code": null, "e": 2859, "s": 2766, "text": "hbase(main):017:0> scan ‘emp’\nROW COLUMN + CELL\n0 row(s) in 0.3110 seconds\n" }, { "code": null, "e": 2866, "s": 2859, "text": " Print" }, { "code": null, "e": 2877, "s": 2866, "text": " Add Notes" } ]
Clone a Binary Tree | Practice | GeeksforGeeks
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree. Example 1: Input: Output: 1 Explanation: The tree was cloned successfully. Your Task: No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree. Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0. Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1 ≤ Number of nodes ≤ 100 1 ≤ Data of a node ≤ 1000 +1 wolfofsv4 days ago Single traversal create and store root (if not created before) create and store the random node (if not created before) clone left subtree clone right subtree Node* Inorder(Node* root, unordered_map<Node*, Node*>& origToDup){ if(root){ if(origToDup.find(root) == origToDup.end()){ Node* newNode = new Node(root -> data); origToDup[root] = newNode; } if(root -> random && origToDup.find(root -> random) == origToDup.end()){ Node* newNode = new Node(root -> random -> data); origToDup[root -> random] = newNode; } origToDup[root] -> random = origToDup[root -> random]; origToDup[root] -> left = Inorder(root -> left, origToDup); origToDup[root] -> right = Inorder(root -> right, origToDup); return origToDup[root]; } return NULL; } Node* cloneTree(Node* tree) { //Your code here unordered_map<Node*, Node*>origToDup; return Inorder(tree, origToDup); } +1 aryangarg1999 This comment was deleted. 0 amit092 weeks ago class Solution{ std::map<Node*, Node*> cloneMap; public: /* The function should clone the passed tree and return root of the cloned tree */ void mapRandomNode(Node * tree){ if(!tree) return; cloneMap[tree]->random = cloneMap[tree->random]; mapRandomNode(tree->left); mapRandomNode(tree->right); } Node * cloneTreeHelper(Node * tree) { if(tree == NULL) return tree; Node * cloneNode = new Node(tree->data); cloneMap[tree] = cloneNode; cloneNode->left = cloneTreeHelper(tree->left); cloneNode->right = cloneTreeHelper(tree->right); } Node* cloneTree(Node* tree) { //Your code here if(!tree) return nullptr; Node * retTree = cloneTreeHelper(tree); mapRandomNode(tree); return retTree; } }; +1 prasannathapa3 weeks ago Node* cloneTree(Node* tree) { if(!tree) return NULL; Node* newNode = new Node(tree->data); newNode->left = cloneTree(tree->left); newNode->right = cloneTree(tree->right); newNode->random = tree->random; return newNode; } 0 roopsaisurampudi1 month ago Java Solution using HashMap public void solve(Tree root, HashMap<Tree, Tree> hm) { if (root == null) return; hm.put(root, new Tree(root.data)); solve(root.left, hm); solve(root.right, hm); } public void solveTree(Tree root, HashMap<Tree, Tree> hm) { if (root == null) return; Tree node = hm.get(root); node.left = hm.get(root.left); node.right = hm.get(root.right); node.random = hm.get(root.random); solveTree(root.left, hm); solveTree(root.right, hm); } public Tree cloneTree(Tree tree){ // add code here. HashMap<Tree, Tree> hm = new HashMap<>(); solve(tree, hm); solveTree(tree, hm); return hm.get(tree); } 0 shulabhgill2 months ago Node* create_copy(Node* root,unordered_map<Node *, Node *> &mp){ if(!root) return NULL; mp[root]=new Node(root->data); mp[root]->left=create_copy(root->left,mp); mp[root]->right=create_copy(root->right,mp); return mp[root]; } void create_random(Node* tree,unordered_map<Node *, Node *> &mp){ if(!tree) return NULL; mp[tree]->random=mp[tree->random]; create_random(tree->left,mp); create_random(tree->right,mp); } Node* cloneTree(Node* tree) { if(!tree) return NULL; unordered_map<Node *, Node *>mp; Node * root=create_copy(tree,mp); create_random(tree,mp); return root; }}; 0 madhukartemba2 months ago EASY JAVA SOLUTION USING HASHMAP: class Solution { private Tree rec(Tree node, HashMap<Integer, Tree> map) { if(node==null) return null; Tree root; if(map.containsKey(node.data)) { //The node already exists so we don't create a new node. root = map.get(node.data); } else { //The node does not exist so we create a new node and add it to the HashMap. root = new Tree(node.data); map.put(root.data, root); } if(node.random!=null) { //If the node's random pointer is not null if(map.containsKey(node.random.data)) { //If the map contains node.random root.random = map.get(node.random.data); } else { //Else create a new node and add it to the map. root.random = new Tree(node.random.data); map.put(root.random.data, root.random); } } //Recursively travel left and right; root.left = rec(node.left, map); root.right = rec(node.right, map); //Return the root; return root; } public Tree cloneTree(Tree tree) { Tree root = rec(tree, new HashMap<>()); return root; } } +4 harshit68rocking2 months ago Node* cloneTree(Node* tree) { //Your code here if(tree== NULL) return NULL; Node *root = new Node(tree->data); root->data = tree->data; root->random = tree->random; root->left = cloneTree(tree->left); root->right = cloneTree(tree->right); return root; } +1 greatwhite2 months ago C++ solution class Solution{ public: unordered_map<Node*, Node*> dp; Node* copyTree(Node* root) { if(!root) return NULL; Node* newRoot = new Node(root->data); dp[root] = newRoot; newRoot->left = copyTree(root->left); newRoot->right = copyTree(root->right); return newRoot; } void copyRandom(Node* root, Node* newRoot) { if(!root) return; newRoot->random = dp[root->random]; copyRandom(root->left, newRoot->left); copyRandom(root->right, newRoot->right); } Node* cloneTree(Node* tree) { Node* newRoot = copyTree(tree); copyRandom(tree, newRoot); return newRoot; } }; 0 hamidnourashraf2 months ago def simple_clone(self, root): if root is None: return None else: new_root = Node(root.data) if root.random: new_root.random = Node(root.random.data) new_root.left = self.simple_clone(root.left) new_root.right = self.simple_clone(root.right) return new_root def cloneTree(self, root): new_root = self.simple_clone(root) return new_root There is a problem in the way the original tree is created. The parent node in random field is not exactly the object of parent. So the random field is not referring to parent node object but a new object has been created with the same data as data in parent. We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 357, "s": 238, "text": "Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree." }, { "code": null, "e": 369, "s": 357, "text": "\nExample 1:" }, { "code": null, "e": 435, "s": 369, "text": "Input:\n\nOutput: 1\nExplanation: The tree was cloned successfully.\n" }, { "code": null, "e": 618, "s": 435, "text": "\nYour Task:\nNo need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree. " }, { "code": null, "e": 699, "s": 618, "text": "Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0." }, { "code": null, "e": 764, "s": 699, "text": "\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 830, "s": 764, "text": "\nConstraints:\n1 ≤ Number of nodes ≤ 100\n1 ≤ Data of a node ≤ 1000" }, { "code": null, "e": 833, "s": 830, "text": "+1" }, { "code": null, "e": 852, "s": 833, "text": "wolfofsv4 days ago" }, { "code": null, "e": 869, "s": 852, "text": "Single traversal" }, { "code": null, "e": 915, "s": 869, "text": "create and store root (if not created before)" }, { "code": null, "e": 972, "s": 915, "text": "create and store the random node (if not created before)" }, { "code": null, "e": 991, "s": 972, "text": "clone left subtree" }, { "code": null, "e": 1011, "s": 991, "text": "clone right subtree" }, { "code": null, "e": 1970, "s": 1011, "text": "Node* Inorder(Node* root, unordered_map<Node*, Node*>& origToDup){\n if(root){\n if(origToDup.find(root) == origToDup.end()){\n Node* newNode = new Node(root -> data);\n origToDup[root] = newNode;\n }\n \n if(root -> random && origToDup.find(root -> random) == origToDup.end()){\n Node* newNode = new Node(root -> random -> data);\n origToDup[root -> random] = newNode;\n }\n \n origToDup[root] -> random = origToDup[root -> random];\n origToDup[root] -> left = Inorder(root -> left, origToDup);\n origToDup[root] -> right = Inorder(root -> right, origToDup);\n \n return origToDup[root];\n }\n return NULL;\n }\n \n Node* cloneTree(Node* tree)\n {\n //Your code here\n unordered_map<Node*, Node*>origToDup;\n return Inorder(tree, origToDup);\n }" }, { "code": null, "e": 1973, "s": 1970, "text": "+1" }, { "code": null, "e": 1987, "s": 1973, "text": "aryangarg1999" }, { "code": null, "e": 2013, "s": 1987, "text": "This comment was deleted." }, { "code": null, "e": 2015, "s": 2013, "text": "0" }, { "code": null, "e": 2033, "s": 2015, "text": "amit092 weeks ago" }, { "code": null, "e": 2873, "s": 2033, "text": "class Solution{\n std::map<Node*, Node*> cloneMap;\n public:\n /* The function should clone the passed tree and return \n root of the cloned tree */\n void mapRandomNode(Node * tree){\n if(!tree) return;\n \n cloneMap[tree]->random = cloneMap[tree->random];\n mapRandomNode(tree->left);\n mapRandomNode(tree->right);\n }\n Node * cloneTreeHelper(Node * tree)\n {\n if(tree == NULL) return tree;\n \n Node * cloneNode = new Node(tree->data);\n cloneMap[tree] = cloneNode;\n cloneNode->left = cloneTreeHelper(tree->left);\n cloneNode->right = cloneTreeHelper(tree->right);\n }\n Node* cloneTree(Node* tree)\n {\n //Your code here\n if(!tree) return nullptr;\n Node * retTree = cloneTreeHelper(tree);\n mapRandomNode(tree);\n \n return retTree;\n }\n};" }, { "code": null, "e": 2876, "s": 2873, "text": "+1" }, { "code": null, "e": 2901, "s": 2876, "text": "prasannathapa3 weeks ago" }, { "code": null, "e": 3164, "s": 2901, "text": "Node* cloneTree(Node* tree)\n {\n if(!tree) return NULL;\n Node* newNode = new Node(tree->data);\n newNode->left = cloneTree(tree->left);\n newNode->right = cloneTree(tree->right);\n newNode->random = tree->random;\n return newNode;\n }" }, { "code": null, "e": 3166, "s": 3164, "text": "0" }, { "code": null, "e": 3194, "s": 3166, "text": "roopsaisurampudi1 month ago" }, { "code": null, "e": 3222, "s": 3194, "text": "Java Solution using HashMap" }, { "code": null, "e": 3955, "s": 3222, "text": " public void solve(Tree root, HashMap<Tree, Tree> hm) {\n if (root == null) return;\n hm.put(root, new Tree(root.data));\n solve(root.left, hm);\n solve(root.right, hm);\n }\n \n public void solveTree(Tree root, HashMap<Tree, Tree> hm) {\n if (root == null) return;\n Tree node = hm.get(root);\n node.left = hm.get(root.left);\n node.right = hm.get(root.right);\n node.random = hm.get(root.random);\n solveTree(root.left, hm);\n solveTree(root.right, hm);\n }\n public Tree cloneTree(Tree tree){\n // add code here.\n HashMap<Tree, Tree> hm = new HashMap<>();\n solve(tree, hm);\n solveTree(tree, hm);\n return hm.get(tree);\n }" }, { "code": null, "e": 3957, "s": 3955, "text": "0" }, { "code": null, "e": 3981, "s": 3957, "text": "shulabhgill2 months ago" }, { "code": null, "e": 4782, "s": 3981, "text": " Node* create_copy(Node* root,unordered_map<Node *, Node *> &mp){ if(!root) return NULL; mp[root]=new Node(root->data); mp[root]->left=create_copy(root->left,mp); mp[root]->right=create_copy(root->right,mp); return mp[root]; } void create_random(Node* tree,unordered_map<Node *, Node *> &mp){ if(!tree) return NULL; mp[tree]->random=mp[tree->random]; create_random(tree->left,mp); create_random(tree->right,mp); } Node* cloneTree(Node* tree) { if(!tree) return NULL; unordered_map<Node *, Node *>mp; Node * root=create_copy(tree,mp); create_random(tree,mp); return root; }};" }, { "code": null, "e": 4784, "s": 4782, "text": "0" }, { "code": null, "e": 4810, "s": 4784, "text": "madhukartemba2 months ago" }, { "code": null, "e": 4844, "s": 4810, "text": "EASY JAVA SOLUTION USING HASHMAP:" }, { "code": null, "e": 6224, "s": 4844, "text": "class Solution\n{\n private Tree rec(Tree node, HashMap<Integer, Tree> map)\n {\n if(node==null) return null;\n \n Tree root;\n \n if(map.containsKey(node.data))\n {\n //The node already exists so we don't create a new node.\n root = map.get(node.data);\n }\n else\n {\n //The node does not exist so we create a new node and add it to the HashMap.\n root = new Tree(node.data);\n map.put(root.data, root);\n }\n \n \n if(node.random!=null)\n {\n //If the node's random pointer is not null\n if(map.containsKey(node.random.data))\n {\n //If the map contains node.random\n root.random = map.get(node.random.data);\n }\n else\n {\n //Else create a new node and add it to the map.\n root.random = new Tree(node.random.data);\n map.put(root.random.data, root.random);\n }\n }\n \n //Recursively travel left and right;\n root.left = rec(node.left, map);\n root.right = rec(node.right, map);\n \n //Return the root;\n return root;\n }\n \n public Tree cloneTree(Tree tree)\n {\n Tree root = rec(tree, new HashMap<>());\n return root;\n }\n}" }, { "code": null, "e": 6227, "s": 6224, "text": "+4" }, { "code": null, "e": 6256, "s": 6227, "text": "harshit68rocking2 months ago" }, { "code": null, "e": 6602, "s": 6256, "text": " Node* cloneTree(Node* tree)\n {\n \n //Your code here\n if(tree== NULL) return NULL;\n \n Node *root = new Node(tree->data);\n root->data = tree->data;\n root->random = tree->random;\n root->left = cloneTree(tree->left);\n root->right = cloneTree(tree->right);\n return root;\n }" }, { "code": null, "e": 6605, "s": 6602, "text": "+1" }, { "code": null, "e": 6628, "s": 6605, "text": "greatwhite2 months ago" }, { "code": null, "e": 6641, "s": 6628, "text": "C++ solution" }, { "code": null, "e": 7343, "s": 6641, "text": "class Solution{\n public:\n unordered_map<Node*, Node*> dp;\n \n Node* copyTree(Node* root) {\n if(!root) return NULL;\n Node* newRoot = new Node(root->data);\n dp[root] = newRoot;\n newRoot->left = copyTree(root->left);\n newRoot->right = copyTree(root->right);\n return newRoot;\n }\n \n void copyRandom(Node* root, Node* newRoot) {\n if(!root) return;\n newRoot->random = dp[root->random];\n copyRandom(root->left, newRoot->left);\n copyRandom(root->right, newRoot->right);\n }\n \n Node* cloneTree(Node* tree) {\n Node* newRoot = copyTree(tree);\n copyRandom(tree, newRoot);\n return newRoot;\n }\n};" }, { "code": null, "e": 7345, "s": 7343, "text": "0" }, { "code": null, "e": 7373, "s": 7345, "text": "hamidnourashraf2 months ago" }, { "code": null, "e": 7863, "s": 7373, "text": " def simple_clone(self, root):\n if root is None:\n return None\n else:\n new_root = Node(root.data)\n if root.random:\n new_root.random = Node(root.random.data)\n new_root.left = self.simple_clone(root.left)\n new_root.right = self.simple_clone(root.right)\n \n return new_root\n \n def cloneTree(self, root):\n new_root = self.simple_clone(root)\n \n return new_root" }, { "code": null, "e": 8126, "s": 7865, "text": "There is a problem in the way the original tree is created. The parent node in random field is not exactly the object of parent. So the random field is not referring to parent node object but a new object has been created with the same data as data in parent. " }, { "code": null, "e": 8272, "s": 8126, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 8308, "s": 8272, "text": " Login to access your submissions. " }, { "code": null, "e": 8318, "s": 8308, "text": "\nProblem\n" }, { "code": null, "e": 8328, "s": 8318, "text": "\nContest\n" }, { "code": null, "e": 8391, "s": 8328, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8539, "s": 8391, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8747, "s": 8539, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 8853, "s": 8747, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
TypeScript - String replace()
This method finds a match between a regular expression and a string, and replaces the matched substring with a new substring. The replacement string can include the following special replacement patterns − string.replace(regexp/substr, newSubStr/function[, flags]); regexp − A RegExp object. The match is replaced by the return value of parameter #2. regexp − A RegExp object. The match is replaced by the return value of parameter #2. substr − A String that is to be replaced by newSubStr. substr − A String that is to be replaced by newSubStr. newSubStr − The String that replaces the substring received from parameter #1. newSubStr − The String that replaces the substring received from parameter #1. function − A function to be invoked to create the new substring. function − A function to be invoked to create the new substring. flags − A String containing any combination of the RegExp flags: g flags − A String containing any combination of the RegExp flags: g It simply returns a new changed string. var re = /apples/gi; var str = "Apples are round, and apples are juicy."; var newstr = str.replace(re, "oranges"); console.log(newstr) On compiling, it will generate the same code in JavaScript. Its output is as follows − oranges are round, and oranges are juicy. var re = /(\w+)\s(\w+)/; var str = "zara ali"; var newstr = str.replace(re, "$2, $1"); console.log(newstr); On compiling, it will generate the same code in JavaScript. Its output is as follows − ali, zara 45 Lectures 4 hours Antonio Papa 41 Lectures 7 hours Haider Malik 60 Lectures 2.5 hours Skillbakerystudios 77 Lectures 8 hours Sean Bradley 77 Lectures 3.5 hours TELCOMA Global 19 Lectures 3 hours Christopher Frewin Print Add Notes Bookmark this page
[ { "code": null, "e": 2174, "s": 2048, "text": "This method finds a match between a regular expression and a string, and replaces the matched substring with a new substring." }, { "code": null, "e": 2254, "s": 2174, "text": "The replacement string can include the following special replacement patterns −" }, { "code": null, "e": 2315, "s": 2254, "text": "string.replace(regexp/substr, newSubStr/function[, flags]);\n" }, { "code": null, "e": 2400, "s": 2315, "text": "regexp − A RegExp object. The match is replaced by the return value of parameter #2." }, { "code": null, "e": 2485, "s": 2400, "text": "regexp − A RegExp object. The match is replaced by the return value of parameter #2." }, { "code": null, "e": 2540, "s": 2485, "text": "substr − A String that is to be replaced by newSubStr." }, { "code": null, "e": 2595, "s": 2540, "text": "substr − A String that is to be replaced by newSubStr." }, { "code": null, "e": 2674, "s": 2595, "text": "newSubStr − The String that replaces the substring received from parameter #1." }, { "code": null, "e": 2753, "s": 2674, "text": "newSubStr − The String that replaces the substring received from parameter #1." }, { "code": null, "e": 2818, "s": 2753, "text": "function − A function to be invoked to create the new substring." }, { "code": null, "e": 2883, "s": 2818, "text": "function − A function to be invoked to create the new substring." }, { "code": null, "e": 2950, "s": 2883, "text": "flags − A String containing any combination of the RegExp flags: g" }, { "code": null, "e": 3017, "s": 2950, "text": "flags − A String containing any combination of the RegExp flags: g" }, { "code": null, "e": 3057, "s": 3017, "text": "It simply returns a new changed string." }, { "code": null, "e": 3195, "s": 3057, "text": "var re = /apples/gi; \nvar str = \"Apples are round, and apples are juicy.\";\nvar newstr = str.replace(re, \"oranges\"); \nconsole.log(newstr)\n" }, { "code": null, "e": 3255, "s": 3195, "text": "On compiling, it will generate the same code in JavaScript." }, { "code": null, "e": 3282, "s": 3255, "text": "Its output is as follows −" }, { "code": null, "e": 3325, "s": 3282, "text": "oranges are round, and oranges are juicy.\n" }, { "code": null, "e": 3437, "s": 3325, "text": "var re = /(\\w+)\\s(\\w+)/; \nvar str = \"zara ali\"; \nvar newstr = str.replace(re, \"$2, $1\"); \nconsole.log(newstr);\n" }, { "code": null, "e": 3497, "s": 3437, "text": "On compiling, it will generate the same code in JavaScript." }, { "code": null, "e": 3524, "s": 3497, "text": "Its output is as follows −" }, { "code": null, "e": 3535, "s": 3524, "text": "ali, zara\n" }, { "code": null, "e": 3568, "s": 3535, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 3582, "s": 3568, "text": " Antonio Papa" }, { "code": null, "e": 3615, "s": 3582, "text": "\n 41 Lectures \n 7 hours \n" }, { "code": null, "e": 3629, "s": 3615, "text": " Haider Malik" }, { "code": null, "e": 3664, "s": 3629, "text": "\n 60 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3684, "s": 3664, "text": " Skillbakerystudios" }, { "code": null, "e": 3717, "s": 3684, "text": "\n 77 Lectures \n 8 hours \n" }, { "code": null, "e": 3731, "s": 3717, "text": " Sean Bradley" }, { "code": null, "e": 3766, "s": 3731, "text": "\n 77 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3782, "s": 3766, "text": " TELCOMA Global" }, { "code": null, "e": 3815, "s": 3782, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 3835, "s": 3815, "text": " Christopher Frewin" }, { "code": null, "e": 3842, "s": 3835, "text": " Print" }, { "code": null, "e": 3853, "s": 3842, "text": " Add Notes" } ]
Auto-Transcribe : Google Speech API Time Offsets in Python | by Soham Sil | Towards Data Science
Transcribing audio files or speech is vital for many companies around the world and as we know, the old school technique of Listen — Transcribe by humans may cause fatal errors and eats up lot of your resources(humans). It requires painstaking attention to transcribe every word that’s being recorded and sometimes, you have to deal with multiple audio files. ‘What a drag’, is exactly what Shikamaru would say if he was given the job of transcribing and here’s where Google Speech API and it’s latest addition, Time offsets (timestamps) comes to the rescue, for us Shikamarus. What is Google Speech API ? Apply powerful neural network models to convert speech to text Recognises more than 110 languages and variants Text results in Real-Time Successful noise handling Supports devices which can send a REST or gRPC request API includes time offset values(timestamps) for the beginning and end of each word spoken in the recognised audio Sign Up for a Free Tier Account in Google CloudAccount is required to get an API key and you can for a free tier plan (365days). Generate an API Key in Google CloudFollow these steps to generate an API key: Sign-in to Google Cloud Console Go to APIs and Services Click on Credentials Click on Create Credentials Select Service Account Key Select New service account in Service Account Enter Service account name Select Role as Project > Owner Leave JSON option selected Click on Create Save generated API key file Rename file to api-key.json api-key.json will be downloaded to your computer Install required Python modules Install Google Speech packagepip3 install -U google-cloud-speech Install Google API packagepip3 install -U google-api-python-client The Google Speech API supports a number of different encodings. The following table lists supported audio codecs: All encodings support only 1 channel(mono) audio and the audio should be transmitted using a lossless encoding (FLAC or LINEAR16). Audacity hasbeen working well for me and with the simple UI, it’s very easy to convertyour audio files to mono in FLAC. Click on Stereo to Mono using Audacity, to learn how to convert audio files. Click on Audio Encoding for more information. In this Python script, we will be using Google Speech API’s latest addition,Time Offsets and include time offset values(timestamps) for the beginningand end of each spoken in the recognised audio. A time offset value represents the amount of time that has elapsed from thebeginning of the audio, in increments of 100ms. Click on Transcribe with time offsets in Python for full code. Let’s start with importing necessary libraries and create credentials to getthe Speech API credentials from the api-key.json we saved earlier. Transcribe audio file from local storage Here, we will define transcribe_file_with_word_time_offsets().It passes the audio and language of the audio as parameters and prints the recognisedwords with their time offset values(timestamps). Import the necessary google.cloud libraries and verify credentials withGoogle Cloud using method SpeechClient(). Next we read the audio file and pass it through theRecognitionAudio()method to store audio data to `audio` as per the encoding specified in theRecognitionConfig() method. Assigning TRUE to the parameter enable_word_time_offsetsenables theRecognitionConfig() method to record the time offset vales (timestamps) for each word. response contains the message returned to the client by speech.recognize(),if successful. The result is either stored as zero or sequential messages asshown below. Note: confidence in the output shows the accuracy of speech recognition. The value is from 0.0 to 1.0, for low to high confidence, respectively. The value of confidence:0.93 shows the Google Speech API has done avery good job in recognising the words. Now we iterate through results and print the words along with their time offset values (timestamps). Transcribe audio file from Google Cloud Storage The only difference in this section of the code is that we have to pass theGoogle Cloud URL of the audio file to gsc_uri, the first parameter of themethod transcribe_file_with_word_time_offsets() and the rest works the same. The words get printed along with their time offset values (timestamps) asoutput. Time to call the __main__ functionargparse library is being used to parse through the parameters passed in thecommand-line during execution. We are running an if else loop to call the appropriate method for locally and cloud stored audio files. Mention the language type by typing –s “en-US” and the path of the file to execute the file.python3 transcribe_time_offsets_with_language_change.py -s “en-US” Sample.flac For google cloud type \gs://cloud-samples-tests/speech/Sample.flac as path,python3 transcribe_time_offsets_with_language_change.py -s “en-US” \gs://cloud-samples-tests/speech/Sample.flac` Click on Google Cloud Shell to learn basic operations in Cloud Shell. Install virtualenv globally in Cloud Shell,pip install –upgrade vitrualenv After installing virtualenv, use the — python flag to tell virtualenv whichPython version to use:virtualenv –python python3 env Next, we need to activate the virtuale. It tells the shell to use virtualenv’spath for Python,source env/bin/activate Cloud shell is now ready to execute our Python program using commandsmentioned in under Invocation in Terminal. Congratulations! Here’s your transcribed data along with time offset values(timestamps) for each word. We can improve these models by changing the parameters in configuration ofthe file. Speech recognition can be improved by changing the parameters ofthe configuration. Click on Cloud Speech API to know more on Synchronous, Asynchronous andStreaming recognition, and how to improve or change the models.
[ { "code": null, "e": 532, "s": 172, "text": "Transcribing audio files or speech is vital for many companies around the world and as we know, the old school technique of Listen — Transcribe by humans may cause fatal errors and eats up lot of your resources(humans). It requires painstaking attention to transcribe every word that’s being recorded and sometimes, you have to deal with multiple audio files." }, { "code": null, "e": 750, "s": 532, "text": "‘What a drag’, is exactly what Shikamaru would say if he was given the job of transcribing and here’s where Google Speech API and it’s latest addition, Time offsets (timestamps) comes to the rescue, for us Shikamarus." }, { "code": null, "e": 778, "s": 750, "text": "What is Google Speech API ?" }, { "code": null, "e": 841, "s": 778, "text": "Apply powerful neural network models to convert speech to text" }, { "code": null, "e": 889, "s": 841, "text": "Recognises more than 110 languages and variants" }, { "code": null, "e": 915, "s": 889, "text": "Text results in Real-Time" }, { "code": null, "e": 941, "s": 915, "text": "Successful noise handling" }, { "code": null, "e": 996, "s": 941, "text": "Supports devices which can send a REST or gRPC request" }, { "code": null, "e": 1110, "s": 996, "text": "API includes time offset values(timestamps) for the beginning and end of each word spoken in the recognised audio" }, { "code": null, "e": 1239, "s": 1110, "text": "Sign Up for a Free Tier Account in Google CloudAccount is required to get an API key and you can for a free tier plan (365days)." }, { "code": null, "e": 1317, "s": 1239, "text": "Generate an API Key in Google CloudFollow these steps to generate an API key:" }, { "code": null, "e": 1349, "s": 1317, "text": "Sign-in to Google Cloud Console" }, { "code": null, "e": 1373, "s": 1349, "text": "Go to APIs and Services" }, { "code": null, "e": 1394, "s": 1373, "text": "Click on Credentials" }, { "code": null, "e": 1422, "s": 1394, "text": "Click on Create Credentials" }, { "code": null, "e": 1449, "s": 1422, "text": "Select Service Account Key" }, { "code": null, "e": 1495, "s": 1449, "text": "Select New service account in Service Account" }, { "code": null, "e": 1522, "s": 1495, "text": "Enter Service account name" }, { "code": null, "e": 1553, "s": 1522, "text": "Select Role as Project > Owner" }, { "code": null, "e": 1580, "s": 1553, "text": "Leave JSON option selected" }, { "code": null, "e": 1596, "s": 1580, "text": "Click on Create" }, { "code": null, "e": 1624, "s": 1596, "text": "Save generated API key file" }, { "code": null, "e": 1652, "s": 1624, "text": "Rename file to api-key.json" }, { "code": null, "e": 1701, "s": 1652, "text": "api-key.json will be downloaded to your computer" }, { "code": null, "e": 1733, "s": 1701, "text": "Install required Python modules" }, { "code": null, "e": 1798, "s": 1733, "text": "Install Google Speech packagepip3 install -U google-cloud-speech" }, { "code": null, "e": 1865, "s": 1798, "text": "Install Google API packagepip3 install -U google-api-python-client" }, { "code": null, "e": 1979, "s": 1865, "text": "The Google Speech API supports a number of different encodings. The following table lists supported audio codecs:" }, { "code": null, "e": 2230, "s": 1979, "text": "All encodings support only 1 channel(mono) audio and the audio should be transmitted using a lossless encoding (FLAC or LINEAR16). Audacity hasbeen working well for me and with the simple UI, it’s very easy to convertyour audio files to mono in FLAC." }, { "code": null, "e": 2307, "s": 2230, "text": "Click on Stereo to Mono using Audacity, to learn how to convert audio files." }, { "code": null, "e": 2353, "s": 2307, "text": "Click on Audio Encoding for more information." }, { "code": null, "e": 2550, "s": 2353, "text": "In this Python script, we will be using Google Speech API’s latest addition,Time Offsets and include time offset values(timestamps) for the beginningand end of each spoken in the recognised audio." }, { "code": null, "e": 2673, "s": 2550, "text": "A time offset value represents the amount of time that has elapsed from thebeginning of the audio, in increments of 100ms." }, { "code": null, "e": 2736, "s": 2673, "text": "Click on Transcribe with time offsets in Python for full code." }, { "code": null, "e": 2879, "s": 2736, "text": "Let’s start with importing necessary libraries and create credentials to getthe Speech API credentials from the api-key.json we saved earlier." }, { "code": null, "e": 2920, "s": 2879, "text": "Transcribe audio file from local storage" }, { "code": null, "e": 3116, "s": 2920, "text": "Here, we will define transcribe_file_with_word_time_offsets().It passes the audio and language of the audio as parameters and prints the recognisedwords with their time offset values(timestamps)." }, { "code": null, "e": 3229, "s": 3116, "text": "Import the necessary google.cloud libraries and verify credentials withGoogle Cloud using method SpeechClient()." }, { "code": null, "e": 3400, "s": 3229, "text": "Next we read the audio file and pass it through theRecognitionAudio()method to store audio data to `audio` as per the encoding specified in theRecognitionConfig() method." }, { "code": null, "e": 3554, "s": 3400, "text": "Assigning TRUE to the parameter enable_word_time_offsetsenables theRecognitionConfig() method to record the time offset vales (timestamps) for each word." }, { "code": null, "e": 3718, "s": 3554, "text": "response contains the message returned to the client by speech.recognize(),if successful. The result is either stored as zero or sequential messages asshown below." }, { "code": null, "e": 3864, "s": 3718, "text": " Note: confidence in the output shows the accuracy of speech recognition. The value is from 0.0 to 1.0, for low to high confidence, respectively." }, { "code": null, "e": 4072, "s": 3864, "text": "The value of confidence:0.93 shows the Google Speech API has done avery good job in recognising the words. Now we iterate through results and print the words along with their time offset values (timestamps)." }, { "code": null, "e": 4120, "s": 4072, "text": "Transcribe audio file from Google Cloud Storage" }, { "code": null, "e": 4345, "s": 4120, "text": "The only difference in this section of the code is that we have to pass theGoogle Cloud URL of the audio file to gsc_uri, the first parameter of themethod transcribe_file_with_word_time_offsets() and the rest works the same." }, { "code": null, "e": 4426, "s": 4345, "text": "The words get printed along with their time offset values (timestamps) asoutput." }, { "code": null, "e": 4567, "s": 4426, "text": "Time to call the __main__ functionargparse library is being used to parse through the parameters passed in thecommand-line during execution." }, { "code": null, "e": 4671, "s": 4567, "text": "We are running an if else loop to call the appropriate method for locally and cloud stored audio files." }, { "code": null, "e": 4842, "s": 4671, "text": "Mention the language type by typing –s “en-US” and the path of the file to execute the file.python3 transcribe_time_offsets_with_language_change.py -s “en-US” Sample.flac" }, { "code": null, "e": 5030, "s": 4842, "text": "For google cloud type \\gs://cloud-samples-tests/speech/Sample.flac as path,python3 transcribe_time_offsets_with_language_change.py -s “en-US” \\gs://cloud-samples-tests/speech/Sample.flac`" }, { "code": null, "e": 5100, "s": 5030, "text": "Click on Google Cloud Shell to learn basic operations in Cloud Shell." }, { "code": null, "e": 5175, "s": 5100, "text": "Install virtualenv globally in Cloud Shell,pip install –upgrade vitrualenv" }, { "code": null, "e": 5303, "s": 5175, "text": "After installing virtualenv, use the — python flag to tell virtualenv whichPython version to use:virtualenv –python python3 env" }, { "code": null, "e": 5421, "s": 5303, "text": "Next, we need to activate the virtuale. It tells the shell to use virtualenv’spath for Python,source env/bin/activate" }, { "code": null, "e": 5533, "s": 5421, "text": "Cloud shell is now ready to execute our Python program using commandsmentioned in under Invocation in Terminal." }, { "code": null, "e": 5636, "s": 5533, "text": "Congratulations! Here’s your transcribed data along with time offset values(timestamps) for each word." }, { "code": null, "e": 5803, "s": 5636, "text": "We can improve these models by changing the parameters in configuration ofthe file. Speech recognition can be improved by changing the parameters ofthe configuration." } ]
Find the difference between current date and the date records from a MySQL table
To find the difference, use the DATEDIFF() method. Let us first create a table − mysql> create table DemoTable1446 -> ( -> DueDate date -> ); Query OK, 0 rows affected (1.42 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1446 values('2019-01-21'); Query OK, 1 row affected (0.69 sec) mysql> insert into DemoTable1446 values('2019-02-01'); Query OK, 1 row affected (0.44 sec) mysql> insert into DemoTable1446 values('2019-09-30'); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement − mysql> select * from DemoTable1446; This will produce the following output − +------------+ | DueDate | +------------+ | 2019-01-21 | | 2019-02-01 | | 2019-09-30 | +------------+ 3 rows in set (0.10 sec) The current date is as follows − mysql> select curdate(); +------------+ | curdate() | +------------+ | 2019-10-01 | +------------+ 1 row in set (0.12 sec) Following is the query get the difference between current date and date records in the table − mysql> select datediff(curdate(),DueDate) from DemoTable1446; This will produce the following output − +-----------------------------+ | datediff(curdate(),DueDate) | +-----------------------------+ | 253 | | 242 | | 1 | +-----------------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1143, "s": 1062, "text": "To find the difference, use the DATEDIFF() method. Let us first create a table −" }, { "code": null, "e": 1250, "s": 1143, "text": "mysql> create table DemoTable1446\n -> (\n -> DueDate date\n -> );\nQuery OK, 0 rows affected (1.42 sec)" }, { "code": null, "e": 1306, "s": 1250, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1579, "s": 1306, "text": "mysql> insert into DemoTable1446 values('2019-01-21');\nQuery OK, 1 row affected (0.69 sec)\nmysql> insert into DemoTable1446 values('2019-02-01');\nQuery OK, 1 row affected (0.44 sec)\nmysql> insert into DemoTable1446 values('2019-09-30');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 1639, "s": 1579, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1675, "s": 1639, "text": "mysql> select * from DemoTable1446;" }, { "code": null, "e": 1716, "s": 1675, "text": "This will produce the following output −" }, { "code": null, "e": 1846, "s": 1716, "text": "+------------+\n| DueDate |\n+------------+\n| 2019-01-21 |\n| 2019-02-01 |\n| 2019-09-30 |\n+------------+\n3 rows in set (0.10 sec)" }, { "code": null, "e": 1879, "s": 1846, "text": "The current date is as follows −" }, { "code": null, "e": 2003, "s": 1879, "text": "mysql> select curdate();\n+------------+\n| curdate() |\n+------------+\n| 2019-10-01 |\n+------------+\n1 row in set (0.12 sec)" }, { "code": null, "e": 2098, "s": 2003, "text": "Following is the query get the difference between current date and date records in the table −" }, { "code": null, "e": 2160, "s": 2098, "text": "mysql> select datediff(curdate(),DueDate) from DemoTable1446;" }, { "code": null, "e": 2201, "s": 2160, "text": "This will produce the following output −" }, { "code": null, "e": 2450, "s": 2201, "text": "+-----------------------------+\n| datediff(curdate(),DueDate) |\n+-----------------------------+\n| 253 |\n| 242 |\n| 1 |\n+-----------------------------+\n3 rows in set (0.00 sec)" } ]
F# - Data Types
The data types in F# can be classified as follows − Integral types Floating point types Text types Other types The following table provides the integral data types of F#. These are basically integer data types. 42y -11y 42uy 200uy 42s -11s 42us 200us 42 -11 42u 200u 42L -11L 42UL 200UL 42I 1499999 9999999 9999999 9999999 9999I (* single byte integer *) let x = 268.97f let y = 312.58f let z = x + y printfn "x: %f" x printfn "y: %f" y printfn "z: %f" z (* unsigned 8-bit natural number *) let p = 2uy let q = 4uy let r = p + q printfn "p: %i" p printfn "q: %i" q printfn "r: %i" r (* signed 16-bit integer *) let a = 12s let b = 24s let c = a + b printfn "a: %i" a printfn "b: %i" b printfn "c: %i" c (* signed 32-bit integer *) let d = 212l let e = 504l let f = d + e printfn "d: %i" d printfn "e: %i" e printfn "f: %i" f When you compile and execute the program, it yields the following output − x: 1 y: 2 z: 3 p: 2 q: 4 r: 6 a: 12 b: 24 c: 36 d: 212 e: 504 f: 716 The following table provides the floating point data types of F#. 42.0F -11.0F 42.0 -11.0 42.0M -11.0M 42N -11N (* 32-bit signed floating point number *) (* 7 significant digits *) let d = 212.098f let e = 504.768f let f = d + e printfn "d: %f" d printfn "e: %f" e printfn "f: %f" f (* 64-bit signed floating point number *) (* 15-16 significant digits *) let x = 21290.098 let y = 50446.768 let z = x + y printfn "x: %g" x printfn "y: %g" y printfn "z: %g" z When you compile and execute the program, it yields the following output − d: 212.098000 e: 504.768000 f: 716.866000 x: 21290.1 y: 50446.8 z: 71736.9 The following table provides the text data types of F#. 'x' '\t' "Hello" "World" let choice = 'y' let name = "Zara Ali" let org = "Tutorials Point" printfn "Choice: %c" choice printfn "Name: %s" name printfn "Organisation: %s" org When you compile and execute the program, it yields the following output − Choice: y Name: Zara Ali Organisation: Tutorials Point The following table provides some other data types of F#. true false let trueVal = true let falseVal = false printfn "True Value: %b" (trueVal) printfn "False Value: %b" (falseVal) When you compile and execute the program, it yields the following output − True Value: true False Value: false Print Add Notes Bookmark this page
[ { "code": null, "e": 2213, "s": 2161, "text": "The data types in F# can be classified as follows −" }, { "code": null, "e": 2228, "s": 2213, "text": "Integral types" }, { "code": null, "e": 2249, "s": 2228, "text": "Floating point types" }, { "code": null, "e": 2260, "s": 2249, "text": "Text types" }, { "code": null, "e": 2272, "s": 2260, "text": "Other types" }, { "code": null, "e": 2372, "s": 2272, "text": "The following table provides the integral data types of F#. These are basically integer data types." }, { "code": null, "e": 2376, "s": 2372, "text": "42y" }, { "code": null, "e": 2381, "s": 2376, "text": "-11y" }, { "code": null, "e": 2386, "s": 2381, "text": "42uy" }, { "code": null, "e": 2392, "s": 2386, "text": "200uy" }, { "code": null, "e": 2396, "s": 2392, "text": "42s" }, { "code": null, "e": 2401, "s": 2396, "text": "-11s" }, { "code": null, "e": 2406, "s": 2401, "text": "42us" }, { "code": null, "e": 2412, "s": 2406, "text": "200us" }, { "code": null, "e": 2415, "s": 2412, "text": "42" }, { "code": null, "e": 2419, "s": 2415, "text": "-11" }, { "code": null, "e": 2423, "s": 2419, "text": "42u" }, { "code": null, "e": 2428, "s": 2423, "text": "200u" }, { "code": null, "e": 2432, "s": 2428, "text": "42L" }, { "code": null, "e": 2437, "s": 2432, "text": "-11L" }, { "code": null, "e": 2442, "s": 2437, "text": "42UL" }, { "code": null, "e": 2448, "s": 2442, "text": "200UL" }, { "code": null, "e": 2452, "s": 2448, "text": "42I" }, { "code": null, "e": 2460, "s": 2452, "text": "1499999" }, { "code": null, "e": 2468, "s": 2460, "text": "9999999" }, { "code": null, "e": 2476, "s": 2468, "text": "9999999" }, { "code": null, "e": 2484, "s": 2476, "text": "9999999" }, { "code": null, "e": 2490, "s": 2484, "text": "9999I" }, { "code": null, "e": 2996, "s": 2490, "text": "(* single byte integer *)\nlet x = 268.97f\nlet y = 312.58f\nlet z = x + y\n\nprintfn \"x: %f\" x\nprintfn \"y: %f\" y\nprintfn \"z: %f\" z\n\n(* unsigned 8-bit natural number *)\n\nlet p = 2uy\nlet q = 4uy\nlet r = p + q\n\nprintfn \"p: %i\" p\nprintfn \"q: %i\" q\nprintfn \"r: %i\" r\n\n(* signed 16-bit integer *)\n\nlet a = 12s\nlet b = 24s\nlet c = a + b\n\nprintfn \"a: %i\" a\nprintfn \"b: %i\" b\nprintfn \"c: %i\" c\n\n(* signed 32-bit integer *)\n\nlet d = 212l\nlet e = 504l\nlet f = d + e\n\nprintfn \"d: %i\" d\nprintfn \"e: %i\" e\nprintfn \"f: %i\" f" }, { "code": null, "e": 3071, "s": 2996, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 3141, "s": 3071, "text": "x: 1\ny: 2\nz: 3\np: 2\nq: 4\nr: 6\na: 12\nb: 24\nc: 36\nd: 212\ne: 504\nf: 716\n" }, { "code": null, "e": 3207, "s": 3141, "text": "The following table provides the floating point data types of F#." }, { "code": null, "e": 3213, "s": 3207, "text": "42.0F" }, { "code": null, "e": 3220, "s": 3213, "text": "-11.0F" }, { "code": null, "e": 3225, "s": 3220, "text": "42.0" }, { "code": null, "e": 3231, "s": 3225, "text": "-11.0" }, { "code": null, "e": 3237, "s": 3231, "text": "42.0M" }, { "code": null, "e": 3244, "s": 3237, "text": "-11.0M" }, { "code": null, "e": 3248, "s": 3244, "text": "42N" }, { "code": null, "e": 3253, "s": 3248, "text": "-11N" }, { "code": null, "e": 3605, "s": 3253, "text": "(* 32-bit signed floating point number *)\n(* 7 significant digits *)\n\nlet d = 212.098f\nlet e = 504.768f\nlet f = d + e\n\nprintfn \"d: %f\" d\nprintfn \"e: %f\" e\nprintfn \"f: %f\" f\n\n(* 64-bit signed floating point number *)\n(* 15-16 significant digits *)\nlet x = 21290.098\nlet y = 50446.768\nlet z = x + y\n\nprintfn \"x: %g\" x\nprintfn \"y: %g\" y\nprintfn \"z: %g\" z" }, { "code": null, "e": 3680, "s": 3605, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 3756, "s": 3680, "text": "d: 212.098000\ne: 504.768000\nf: 716.866000\nx: 21290.1\ny: 50446.8\nz: 71736.9\n" }, { "code": null, "e": 3812, "s": 3756, "text": "The following table provides the text data types of F#." }, { "code": null, "e": 3816, "s": 3812, "text": "'x'" }, { "code": null, "e": 3821, "s": 3816, "text": "'\\t'" }, { "code": null, "e": 3829, "s": 3821, "text": "\"Hello\"" }, { "code": null, "e": 3837, "s": 3829, "text": "\"World\"" }, { "code": null, "e": 3988, "s": 3837, "text": "let choice = 'y'\nlet name = \"Zara Ali\"\nlet org = \"Tutorials Point\"\n\nprintfn \"Choice: %c\" choice\nprintfn \"Name: %s\" name\nprintfn \"Organisation: %s\" org" }, { "code": null, "e": 4063, "s": 3988, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 4119, "s": 4063, "text": "Choice: y\nName: Zara Ali\nOrganisation: Tutorials Point\n" }, { "code": null, "e": 4177, "s": 4119, "text": "The following table provides some other data types of F#." }, { "code": null, "e": 4182, "s": 4177, "text": "true" }, { "code": null, "e": 4188, "s": 4182, "text": "false" }, { "code": null, "e": 4301, "s": 4188, "text": "let trueVal = true\nlet falseVal = false\n\nprintfn \"True Value: %b\" (trueVal)\nprintfn \"False Value: %b\" (falseVal)" }, { "code": null, "e": 4376, "s": 4301, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 4413, "s": 4376, "text": "True Value: true\nFalse Value: false\n" }, { "code": null, "e": 4420, "s": 4413, "text": " Print" }, { "code": null, "e": 4431, "s": 4420, "text": " Add Notes" } ]
RegEx in ReactJS
In this article, we are going to see how to handle the strings with RegEx handling in a React application. A RegEx or Regular Expression is a sequence of characters that forms a search pattern and is used to check if a string contains a specified search pattern or not. It is also used to validate strings which consist of email, passwords etc. new RegExp(pattern[, flags]) In this example, we will build an authentication React application that takes an email and password from the user and checks if they are validated or not. We have Regex.js which contains all the regular expressions to validate the email and password for our application. Regex.jsx export const validEmail = new RegExp( '^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]$' ); export const validPassword = new RegExp('^(?=.*?[A-Za-z])(?=.*?[0-9]).{6,}$'); App.jsx import React, { useState } from 'react'; import { validEmail, validPassword } from './regex.js'; const App = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [emailErr, setEmailErr] = useState(false); const [pwdError, setPwdError] = useState(false); const validate = () => { if (!validEmail.test(email)) { setEmailErr(true); } if (!validPassword.test(password)) { setPwdError(true); } }; return ( <div> <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} /> <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} /> <div> <button onClick={validate}>Validate </div> {emailErr && <p>Your email is invalid</p>} {pwdError && <p>Your password is invalid</p>} </div> ); }; export default App; In the above example, when the user clicks the Validate button, it checks for the validity of the email and password and displays the result accordingly. This will produce the following result.
[ { "code": null, "e": 1169, "s": 1062, "text": "In this article, we are going to see how to handle the strings with RegEx handling in a React application." }, { "code": null, "e": 1407, "s": 1169, "text": "A RegEx or Regular Expression is a sequence of characters that forms a search pattern and is used to check if a string contains a specified search pattern or not. It is also used to validate strings which consist of email, passwords etc." }, { "code": null, "e": 1436, "s": 1407, "text": "new RegExp(pattern[, flags])" }, { "code": null, "e": 1591, "s": 1436, "text": "In this example, we will build an authentication React application that takes an email and password from the user and checks if they are validated or not." }, { "code": null, "e": 1707, "s": 1591, "text": "We have Regex.js which contains all the regular expressions to validate the email and password for our application." }, { "code": null, "e": 1717, "s": 1707, "text": "Regex.jsx" }, { "code": null, "e": 1888, "s": 1717, "text": "export const validEmail = new RegExp(\n '^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]$'\n);\nexport const validPassword = new RegExp('^(?=.*?[A-Za-z])(?=.*?[0-9]).{6,}$');" }, { "code": null, "e": 1896, "s": 1888, "text": "App.jsx" }, { "code": null, "e": 2992, "s": 1896, "text": "import React, { useState } from 'react';\nimport { validEmail, validPassword } from './regex.js';\n\nconst App = () => {\n const [email, setEmail] = useState('');\n const [password, setPassword] = useState('');\n const [emailErr, setEmailErr] = useState(false);\n const [pwdError, setPwdError] = useState(false);\n const validate = () => {\n if (!validEmail.test(email)) {\n setEmailErr(true);\n }\n if (!validPassword.test(password)) {\n setPwdError(true);\n }\n };\n return (\n <div>\n <input\n type=\"email\"\n placeholder=\"Email\"\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n />\n <input\n type=\"password\"\n placeholder=\"Password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n />\n <div>\n <button onClick={validate}>Validate\n </div>\n {emailErr && <p>Your email is invalid</p>}\n {pwdError && <p>Your password is invalid</p>}\n </div>\n );\n};\nexport default App;" }, { "code": null, "e": 3146, "s": 2992, "text": "In the above example, when the user clicks the Validate button, it checks for the validity of the email and password and displays the result accordingly." }, { "code": null, "e": 3186, "s": 3146, "text": "This will produce the following result." } ]
Plotting dates on the X-axis with Python's Matplotlib
Using Pandas, we can create a dataframe and can set the index for datetime. Using gcf().autofmt_xdate(), we will adjust the date on the X-axis. Make the list of date_time and convert into it in date_time using pd.to_datetime(). Make the list of date_time and convert into it in date_time using pd.to_datetime(). Consider data = [1, 2, 3] Consider data = [1, 2, 3] Instantiate DataFrame() object, i.e., DF. Instantiate DataFrame() object, i.e., DF. Set the DF[‘value’] with data from step 2. Set the DF[‘value’] with data from step 2. Set DF.index() using date_time from step 1. Set DF.index() using date_time from step 1. Now plot the data frame i.e., plt.plot(DF). Now plot the data frame i.e., plt.plot(DF). Get the current figure and make it autofmt_xdate(). Get the current figure and make it autofmt_xdate(). Using plt.show() method, show the figure. Using plt.show() method, show the figure. import pandas as pd import matplotlib.pyplot as plt date_time = ["2021-01-01", "2021-01-02", "2021-01-03"] date_time = pd.to_datetime(date_time) data = [1, 2, 3] DF = pd.DataFrame() DF['value'] = data DF = DF.set_index(date_time) plt.plot(DF) plt.gcf().autofmt_xdate() plt.show()
[ { "code": null, "e": 1331, "s": 1187, "text": "Using Pandas, we can create a dataframe and can set the index for datetime. Using gcf().autofmt_xdate(), we will adjust the date on the X-axis." }, { "code": null, "e": 1415, "s": 1331, "text": "Make the list of date_time and convert into it in date_time using pd.to_datetime()." }, { "code": null, "e": 1499, "s": 1415, "text": "Make the list of date_time and convert into it in date_time using pd.to_datetime()." }, { "code": null, "e": 1525, "s": 1499, "text": "Consider data = [1, 2, 3]" }, { "code": null, "e": 1551, "s": 1525, "text": "Consider data = [1, 2, 3]" }, { "code": null, "e": 1593, "s": 1551, "text": "Instantiate DataFrame() object, i.e., DF." }, { "code": null, "e": 1635, "s": 1593, "text": "Instantiate DataFrame() object, i.e., DF." }, { "code": null, "e": 1678, "s": 1635, "text": "Set the DF[‘value’] with data from step 2." }, { "code": null, "e": 1721, "s": 1678, "text": "Set the DF[‘value’] with data from step 2." }, { "code": null, "e": 1765, "s": 1721, "text": "Set DF.index() using date_time from step 1." }, { "code": null, "e": 1809, "s": 1765, "text": "Set DF.index() using date_time from step 1." }, { "code": null, "e": 1853, "s": 1809, "text": "Now plot the data frame i.e., plt.plot(DF)." }, { "code": null, "e": 1897, "s": 1853, "text": "Now plot the data frame i.e., plt.plot(DF)." }, { "code": null, "e": 1949, "s": 1897, "text": "Get the current figure and make it autofmt_xdate()." }, { "code": null, "e": 2001, "s": 1949, "text": "Get the current figure and make it autofmt_xdate()." }, { "code": null, "e": 2043, "s": 2001, "text": "Using plt.show() method, show the figure." }, { "code": null, "e": 2085, "s": 2043, "text": "Using plt.show() method, show the figure." }, { "code": null, "e": 2367, "s": 2085, "text": "import pandas as pd\nimport matplotlib.pyplot as plt\n\ndate_time = [\"2021-01-01\", \"2021-01-02\", \"2021-01-03\"]\ndate_time = pd.to_datetime(date_time)\ndata = [1, 2, 3]\n\nDF = pd.DataFrame()\nDF['value'] = data\nDF = DF.set_index(date_time)\nplt.plot(DF)\nplt.gcf().autofmt_xdate()\nplt.show()" } ]
PUT method – Python requests
22 Sep, 2021 Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make PUT request to a specified URL using requests.put() method. Before checking out the PUT method, let’s figure out what a Http PUT request is – PUT is a request method supported by HTTP used by the World Wide Web. The PUT method requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified and if the URI does not point to an existing resource, then the server can create the resource with that URI. Python’s requests module provides in-built method called put() for making a PUT request to a specified URI.Syntax – requests.put(url, params={key: value}, args) Example – Let’s try making a request to httpbin’s APIs for example purposes. Python3 import requests # Making a PUT requestr = requests.put('https://httpbin.org / put', data ={'key':'value'}) # check status code for response received# success code - 200print(r) # print content of requestprint(r.content) save this file as request.py and through terminal run, python request.py Output – PUT request is made to a particular resource. If the Request-URI refers to an already existing resource, an update operation will happen, otherwise create operation should happen if Request-URI is a valid resource URI (assuming client is allowed to determine resource identifier). Example – PUT /article/{article-id} POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. It essentially means that POST request-URI should be of a collection URI. Example – POST /articles clintra sooda367 Python-requests Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Sep, 2021" }, { "code": null, "e": 322, "s": 28, "text": "Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make PUT request to a specified URL using requests.put() method. Before checking out the PUT method, let’s figure out what a Http PUT request is – " }, { "code": null, "e": 653, "s": 322, "text": "PUT is a request method supported by HTTP used by the World Wide Web. The PUT method requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified and if the URI does not point to an existing resource, then the server can create the resource with that URI. " }, { "code": null, "e": 771, "s": 653, "text": "Python’s requests module provides in-built method called put() for making a PUT request to a specified URI.Syntax – " }, { "code": null, "e": 816, "s": 771, "text": "requests.put(url, params={key: value}, args)" }, { "code": null, "e": 895, "s": 816, "text": "Example – Let’s try making a request to httpbin’s APIs for example purposes. " }, { "code": null, "e": 903, "s": 895, "text": "Python3" }, { "code": "import requests # Making a PUT requestr = requests.put('https://httpbin.org / put', data ={'key':'value'}) # check status code for response received# success code - 200print(r) # print content of requestprint(r.content)", "e": 1123, "s": 903, "text": null }, { "code": null, "e": 1180, "s": 1123, "text": "save this file as request.py and through terminal run, " }, { "code": null, "e": 1198, "s": 1180, "text": "python request.py" }, { "code": null, "e": 1208, "s": 1198, "text": "Output – " }, { "code": null, "e": 1505, "s": 1212, "text": "PUT request is made to a particular resource. If the Request-URI refers to an already existing resource, an update operation will happen, otherwise create operation should happen if Request-URI is a valid resource URI (assuming client is allowed to determine resource identifier). Example – " }, { "code": null, "e": 1531, "s": 1505, "text": "PUT /article/{article-id}" }, { "code": null, "e": 1803, "s": 1533, "text": "POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. It essentially means that POST request-URI should be of a collection URI. Example – " }, { "code": null, "e": 1818, "s": 1803, "text": "POST /articles" }, { "code": null, "e": 1830, "s": 1822, "text": "clintra" }, { "code": null, "e": 1839, "s": 1830, "text": "sooda367" }, { "code": null, "e": 1855, "s": 1839, "text": "Python-requests" }, { "code": null, "e": 1862, "s": 1855, "text": "Python" } ]
Group by clause in MS SQL Server
24 Aug, 2020 Group by clause will be discussed in detail in this article. There are tons of data present in the database system. Even though the data is arranged in form of a table in a proper order, the user at times wants the data in the query to be grouped for easier access. To arrange the data(columns) in form of groups, a clause named group by has to be used in the query. The group by clause arranges the data according to the columns specified in the query. The basic syntax is- Syntax : select select_list from table_name group by column_1 column_2 An example is given below-Student table : select name from student group by roll number Output – This way, the table can be grouped using group by clause. In real-time production, group by clause is used for generating calculations by applying aggregate functions(maximum, minimum, etc). The users often confuse group by and order by clauses. Order by clause is used to arrange the data in chronological order. Group by clause is used to arrange the data in form of groups. For better understanding, an example is given below. Queries using order by and group by – select roll number from student order by name ASC Output – select roll number from student group by name Output – From the example, we can clearly notice the difference between group by and order by clauses. In case of order by, the names are arranged in an alphabetical order(A-Z). In case the user has to arrange from Z-A, it can be done as follows. select roll number from student order by name DESC The output will be arranged as follows : SQL-Server DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS MySQL | Regular expressions (Regexp) What is Temporary Table in SQL? Difference between OLAP and OLTP in DBMS Difference between Where and Having Clause in SQL SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? MySQL | Group_CONCAT() Function
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Aug, 2020" }, { "code": null, "e": 89, "s": 28, "text": "Group by clause will be discussed in detail in this article." }, { "code": null, "e": 503, "s": 89, "text": "There are tons of data present in the database system. Even though the data is arranged in form of a table in a proper order, the user at times wants the data in the query to be grouped for easier access. To arrange the data(columns) in form of groups, a clause named group by has to be used in the query. The group by clause arranges the data according to the columns specified in the query. The basic syntax is-" }, { "code": null, "e": 512, "s": 503, "text": "Syntax :" }, { "code": null, "e": 577, "s": 512, "text": "select select_list \nfrom table_name \ngroup by column_1 column_2 " }, { "code": null, "e": 619, "s": 577, "text": "An example is given below-Student table :" }, { "code": null, "e": 667, "s": 619, "text": "select name\nfrom student \ngroup by roll number " }, { "code": null, "e": 676, "s": 667, "text": "Output –" }, { "code": null, "e": 1053, "s": 676, "text": "This way, the table can be grouped using group by clause. In real-time production, group by clause is used for generating calculations by applying aggregate functions(maximum, minimum, etc). The users often confuse group by and order by clauses. Order by clause is used to arrange the data in chronological order. Group by clause is used to arrange the data in form of groups." }, { "code": null, "e": 1106, "s": 1053, "text": "For better understanding, an example is given below." }, { "code": null, "e": 1144, "s": 1106, "text": "Queries using order by and group by –" }, { "code": null, "e": 1197, "s": 1144, "text": "select roll number\nfrom student \norder by name ASC " }, { "code": null, "e": 1206, "s": 1197, "text": "Output –" }, { "code": null, "e": 1255, "s": 1206, "text": "select roll number\nfrom student \ngroup by name " }, { "code": null, "e": 1264, "s": 1255, "text": "Output –" }, { "code": null, "e": 1502, "s": 1264, "text": "From the example, we can clearly notice the difference between group by and order by clauses. In case of order by, the names are arranged in an alphabetical order(A-Z). In case the user has to arrange from Z-A, it can be done as follows." }, { "code": null, "e": 1557, "s": 1502, "text": "select \nroll number \nfrom \nstudent\norder by\nname DESC\n" }, { "code": null, "e": 1598, "s": 1557, "text": "The output will be arranged as follows :" }, { "code": null, "e": 1609, "s": 1598, "text": "SQL-Server" }, { "code": null, "e": 1614, "s": 1609, "text": "DBMS" }, { "code": null, "e": 1618, "s": 1614, "text": "SQL" }, { "code": null, "e": 1623, "s": 1618, "text": "DBMS" }, { "code": null, "e": 1627, "s": 1623, "text": "SQL" }, { "code": null, "e": 1725, "s": 1627, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1766, "s": 1725, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 1803, "s": 1766, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 1835, "s": 1803, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 1876, "s": 1835, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 1926, "s": 1876, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 1968, "s": 1926, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 2012, "s": 1968, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 2033, "s": 2012, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 2099, "s": 2033, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
Python | Creating a button in tkinter
16 Feb, 2021 Tkinter is Python’s standard GUI (Graphical User Interface) package. It is one of the most commonly used packages for GUI applications which comes with Python itself. Let’s see how to create a button using Tkinter. Follow the below steps: Import tkinter module # Tkinter in Python 2.x. (Note Capital T)Create main window (root = Tk())Add as many widgets as you want. Import tkinter module # Tkinter in Python 2.x. (Note Capital T) Create main window (root = Tk()) Add as many widgets as you want. Importing tkinter module is same as importing any other module. import tkinter # In Python 3.x import Tkinter # In python 2.x. (Note Capital T) The tkinter.ttk module provides access to the Tk-themed widget set, introduced in Tk 8.5. If Python has not been compiled against Tk 8.5, this module can still be accessed if Tile has been installed. The former method using Tk 8.5 provides additional benefits including anti-aliased font rendering under X11 and window transparency.The basic idea for tkinter.ttk is to separate, to the extent possible, the code implementing a widget’s behavior from the code implementing its appearance. tkinter.ttk is used to create modern GUI (Graphical User Interface) applications that cannot be achieved by tkinter itself. Code #1: Creating button using Tkinter. Python3 # import everything from tkinter modulefrom tkinter import * # create a tkinter windowroot = Tk() # Open window having dimension 100x100root.geometry('100x100') # Create a Buttonbtn = Button(root, text = 'Click me !', bd = '5', command = root.destroy) # Set the position of button on the top of window. btn.pack(side = 'top') root.mainloop() Output: Creation of Button without using tk themed widget. Creation of Button using tk themed widget (tkinter.ttk). This will give you the effects of modern graphics. Effects will change from one OS to another because it is basically for the appearance. Code #2: Python3 # import tkinter modulefrom tkinter import * # Following will import tkinter.ttk module and# automatically override all the widgets# which are present in tkinter module.from tkinter.ttk import * # Create Objectroot = Tk() # Initialize tkinter window with dimensions 100x100 root.geometry('100x100') btn = Button(root, text = 'Click me !', command = root.destroy) # Set the position of button on the top of windowbtn.pack(side = 'top') root.mainloop() Output: Note: See in the Output of both the code, BORDER is not present in 2nd output because tkinter.ttk does not support border. Also, when you hover the mouse over both the buttons ttk.Button will change its color and become light blue (effects may change from one OS to another) because it supports modern graphics while in the case of a simple Button it won’t change color as it does not support modern graphics. abhigoya Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe 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 ? Iterate over a list in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Feb, 2021" }, { "code": null, "e": 269, "s": 53, "text": "Tkinter is Python’s standard GUI (Graphical User Interface) package. It is one of the most commonly used packages for GUI applications which comes with Python itself. Let’s see how to create a button using Tkinter. " }, { "code": null, "e": 294, "s": 269, "text": "Follow the below steps: " }, { "code": null, "e": 424, "s": 294, "text": "Import tkinter module # Tkinter in Python 2.x. (Note Capital T)Create main window (root = Tk())Add as many widgets as you want. " }, { "code": null, "e": 488, "s": 424, "text": "Import tkinter module # Tkinter in Python 2.x. (Note Capital T)" }, { "code": null, "e": 521, "s": 488, "text": "Create main window (root = Tk())" }, { "code": null, "e": 556, "s": 521, "text": "Add as many widgets as you want. " }, { "code": null, "e": 622, "s": 556, "text": "Importing tkinter module is same as importing any other module. " }, { "code": null, "e": 707, "s": 622, "text": "import tkinter # In Python 3.x\n\nimport Tkinter # In python 2.x. (Note Capital T)" }, { "code": null, "e": 1320, "s": 707, "text": "The tkinter.ttk module provides access to the Tk-themed widget set, introduced in Tk 8.5. If Python has not been compiled against Tk 8.5, this module can still be accessed if Tile has been installed. The former method using Tk 8.5 provides additional benefits including anti-aliased font rendering under X11 and window transparency.The basic idea for tkinter.ttk is to separate, to the extent possible, the code implementing a widget’s behavior from the code implementing its appearance. tkinter.ttk is used to create modern GUI (Graphical User Interface) applications that cannot be achieved by tkinter itself. " }, { "code": null, "e": 1361, "s": 1320, "text": "Code #1: Creating button using Tkinter. " }, { "code": null, "e": 1369, "s": 1361, "text": "Python3" }, { "code": "# import everything from tkinter modulefrom tkinter import * # create a tkinter windowroot = Tk() # Open window having dimension 100x100root.geometry('100x100') # Create a Buttonbtn = Button(root, text = 'Click me !', bd = '5', command = root.destroy) # Set the position of button on the top of window. btn.pack(side = 'top') root.mainloop()", "e": 1756, "s": 1369, "text": null }, { "code": null, "e": 1765, "s": 1756, "text": "Output: " }, { "code": null, "e": 1822, "s": 1767, "text": " Creation of Button without using tk themed widget. " }, { "code": null, "e": 2018, "s": 1822, "text": "Creation of Button using tk themed widget (tkinter.ttk). This will give you the effects of modern graphics. Effects will change from one OS to another because it is basically for the appearance. " }, { "code": null, "e": 2029, "s": 2018, "text": "Code #2: " }, { "code": null, "e": 2037, "s": 2029, "text": "Python3" }, { "code": "# import tkinter modulefrom tkinter import * # Following will import tkinter.ttk module and# automatically override all the widgets# which are present in tkinter module.from tkinter.ttk import * # Create Objectroot = Tk() # Initialize tkinter window with dimensions 100x100 root.geometry('100x100') btn = Button(root, text = 'Click me !', command = root.destroy) # Set the position of button on the top of windowbtn.pack(side = 'top') root.mainloop()", "e": 2529, "s": 2037, "text": null }, { "code": null, "e": 2538, "s": 2529, "text": "Output: " }, { "code": null, "e": 2951, "s": 2540, "text": "Note: See in the Output of both the code, BORDER is not present in 2nd output because tkinter.ttk does not support border. Also, when you hover the mouse over both the buttons ttk.Button will change its color and become light blue (effects may change from one OS to another) because it supports modern graphics while in the case of a simple Button it won’t change color as it does not support modern graphics. " }, { "code": null, "e": 2960, "s": 2951, "text": "abhigoya" }, { "code": null, "e": 2967, "s": 2960, "text": "Python" }, { "code": null, "e": 3065, "s": 2967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3093, "s": 3065, "text": "Read JSON file using Python" }, { "code": null, "e": 3143, "s": 3093, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3165, "s": 3143, "text": "Python map() function" }, { "code": null, "e": 3209, "s": 3165, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 3251, "s": 3209, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3273, "s": 3251, "text": "Enumerate() in Python" }, { "code": null, "e": 3308, "s": 3273, "text": "Read a file line by line in Python" }, { "code": null, "e": 3334, "s": 3308, "text": "Python String | replace()" }, { "code": null, "e": 3366, "s": 3334, "text": "How to Install PIP on Windows ?" } ]
TypeScript | Array map() Method
17 Feb, 2021 The Array.map() is an inbuilt TypeScript function that is used to create a new array with the results of calling a provided function on every element in this array. Syntax: array.map(callback[, thisObject]) Parameter: This method accepts two parameters as mentioned above and described below: callback : This parameter is the function that produces an element of the new Array from an element of the current one. thisObject : This parameter is the Object to use as this when executing callback. Return Value: This method returns the created array. Below examples illustrate the Array map() method in TypeScript.Example 1: JavaScript // language is TypeScript // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // use of map() method var val = arr.map(Math.log) // printing element console.log( val ); Output: [ 2.3978952727983707, 4.48863636973214, 3.1354942159291497, 1.9459101490553132, 4.584967478670572 ] Example 2: JavaScript // language is TypeScript // Driver code var arr = [2, 5, 6, 3, 8, 9]; // use of map() method var newArr = arr.map(function(val, index){ // printing element console.log("key : ",index, "value : ",val*val); }) Output: key : 0 value : 4 key : 1 value : 25 key : 2 value : 36 key : 3 value : 9 key : 4 value : 64 key : 5 value : 81 pratikraut0000 TypeScript 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": "\n17 Feb, 2021" }, { "code": null, "e": 193, "s": 28, "text": "The Array.map() is an inbuilt TypeScript function that is used to create a new array with the results of calling a provided function on every element in this array." }, { "code": null, "e": 202, "s": 193, "text": "Syntax: " }, { "code": null, "e": 236, "s": 202, "text": "array.map(callback[, thisObject])" }, { "code": null, "e": 323, "s": 236, "text": "Parameter: This method accepts two parameters as mentioned above and described below: " }, { "code": null, "e": 443, "s": 323, "text": "callback : This parameter is the function that produces an element of the new Array from an element of the current one." }, { "code": null, "e": 525, "s": 443, "text": "thisObject : This parameter is the Object to use as this when executing callback." }, { "code": null, "e": 579, "s": 525, "text": "Return Value: This method returns the created array. " }, { "code": null, "e": 654, "s": 579, "text": "Below examples illustrate the Array map() method in TypeScript.Example 1: " }, { "code": null, "e": 665, "s": 654, "text": "JavaScript" }, { "code": "// language is TypeScript // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // use of map() method var val = arr.map(Math.log) // printing element console.log( val );", "e": 856, "s": 665, "text": null }, { "code": null, "e": 865, "s": 856, "text": "Output: " }, { "code": null, "e": 973, "s": 865, "text": "[ 2.3978952727983707,\n 4.48863636973214,\n 3.1354942159291497,\n 1.9459101490553132,\n 4.584967478670572 ]" }, { "code": null, "e": 985, "s": 973, "text": "Example 2: " }, { "code": null, "e": 996, "s": 985, "text": "JavaScript" }, { "code": "// language is TypeScript // Driver code var arr = [2, 5, 6, 3, 8, 9]; // use of map() method var newArr = arr.map(function(val, index){ // printing element console.log(\"key : \",index, \"value : \",val*val); })", "e": 1237, "s": 996, "text": null }, { "code": null, "e": 1246, "s": 1237, "text": "Output: " }, { "code": null, "e": 1370, "s": 1246, "text": "key : 0 value : 4\nkey : 1 value : 25\nkey : 2 value : 36\nkey : 3 value : 9\nkey : 4 value : 64\nkey : 5 value : 81" }, { "code": null, "e": 1385, "s": 1370, "text": "pratikraut0000" }, { "code": null, "e": 1396, "s": 1385, "text": "TypeScript" }, { "code": null, "e": 1407, "s": 1396, "text": "JavaScript" }, { "code": null, "e": 1424, "s": 1407, "text": "Web Technologies" } ]
Shared ViewModel in Android
14 Feb, 2022 In android, we can use ViewModel to share data between various fragments or activities by sharing the same ViewModel among all the fragments and they can access everything defined in the ViewModel. This is one way to have communication between fragments or activities. Almost every application has some communication between various activities or fragments. In the article, we are going to learn about Shared ViewModel in Android to communicate with other fragments. We will develop an application containing two fragments in which one fragment updates the data within the ViewModel which is shared between both the fragments and another fragment observes the changes on that data and displays the updated one on the screen. Application’s work is to send->receive->display a message. A sample GIF is given below to get an idea about what we are going to do in this article. 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 Kotlin as the programming language. Step 2: Create a class SharedViewModel Go to the SharedViewModel.kt file and refer to the following code. Below is the code for the SharedViewModel.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import androidx.lifecycle.MutableLiveDataimport androidx.lifecycle.ViewModel class SharedViewModel : ViewModel() { // variable to contain message whenever // it gets changed/modified(mutable) val message = MutableLiveData<String>() // function to send message fun sendMessage(text: String) { message.value = text }} Step 3: Create two fragments and they are – MessageSenderFragment & MessageReceiverFragment MessageSenderFragment – To send the message which will be received by MessageReceiverFragment. It will have a Button to send the message after clicking it. Go to the MessageSenderFragment.kt file and refer to the following code. Below is the code for the MessageSenderFragment.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.EditTextimport androidx.lifecycle.ViewModelProvider class MessageSenderFragment : Fragment() { // to send message lateinit var btn: Button // to write message lateinit var writeMSg: EditText override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_message_sender, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // reference for button and EditText btn = view.findViewById(R.id.button) writeMSg = view.findViewById(R.id.writeMessage) // create object of SharedViewModel val model = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java) // call function "sendMessage" defined in SharedVieModel // to store the value in message. btn.setOnClickListener { model.sendMessage(writeMSg.text.toString()) } }} Navigate to the app > res > fragment_message_sender.xml and add the below code to that file. Below is the code for the fragment_message_sender.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/writeMessage" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Write your message" android:textAlignment="center" app:layout_constraintBottom_toTopOf="@+id/button" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="100dp" android:text="Share Your Message" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> MessageReceiverFragment – To receive the message sent by MessageSenderFragment. It will have a TextView to show the updated message on the screen. Go to the MessageReceiverFragment.kt file and refer to the following code. Below is the code for the MessageReceiverFragment.kt file. Comments are added inside the code to understand the code in more detail. Kotlin class MessageReceiverFragment : Fragment() { // to contain and display shared message lateinit var displayMsg: TextView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // inflate the fragment layout return inflater.inflate(R.layout.fragment_message_receiver, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // reference for the container declared above displayMsg = view.findViewById(R.id.textViewReceiver) // create object of SharedViewModel val model = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java) // observing the change in the message declared in SharedViewModel model.message.observe(viewLifecycleOwner, Observer { // updating data in displayMsg displayMsg.text = it }) }} Navigate to the app > res > fragment_message_receiver.xml and add the below code to that file. Below is the code for the fragment_message_receiver.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textViewReceiver" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:textColor="@color/black" android:textAlignment="center" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> We have created the object of SharedViewModel which is the same object as we are using the same single activity as an owner. This is the reason it is shared. Notice that we have used the requireActivity() in both the fragments. . . . ViewModelProvider(requireActivity()).get(SharedViewModel::class.java) . . . Step 3: Update the activity_main.xml The activity consists of two fragments and is the host for both the fragments. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <fragment android:id="@+id/receiverFragment" android:name="com.gfg.article.sharedviewmodel.MessageReceiverFragment" android:layout_width="match_parent" android:layout_height="0dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:layout_marginEnd="8dp" android:layout_marginBottom="8dp" app:layout_constraintBottom_toTopOf="@+id/senderFragment" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <fragment android:id="@+id/senderFragment" android:name="com.gfg.article.sharedviewmodel.MessageSenderFragment" android:layout_width="match_parent" android:layout_height="0dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:layout_marginEnd="8dp" android:layout_marginBottom="8dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/receiverFragment" /> </androidx.constraintlayout.widget.ConstraintLayout> MainActivity.kt remains as it is. Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) }} Now, Run the app. Output: Source Code: Click Here varshagumber28 Blogathon-2021 Picked Android Blogathon Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference Between Implicit Intent and Explicit Intent in Android How to Create and Add Data to SQLite Database in Android? Android Projects - From Basic to Advanced Level Retrofit with Kotlin Coroutine in Android Navigation Drawer in Android How to Call or Consume External API in Spring Boot? Re-rendering Components in ReactJS SQL Query to Insert Multiple Rows How to Connect Python with SQL Database? Top 10 Fastest Programming Languages
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Feb, 2022" }, { "code": null, "e": 411, "s": 52, "text": "In android, we can use ViewModel to share data between various fragments or activities by sharing the same ViewModel among all the fragments and they can access everything defined in the ViewModel. This is one way to have communication between fragments or activities. Almost every application has some communication between various activities or fragments. " }, { "code": null, "e": 927, "s": 411, "text": "In the article, we are going to learn about Shared ViewModel in Android to communicate with other fragments. We will develop an application containing two fragments in which one fragment updates the data within the ViewModel which is shared between both the fragments and another fragment observes the changes on that data and displays the updated one on the screen. Application’s work is to send->receive->display a message. A sample GIF is given below to get an idea about what we are going to do in this article." }, { "code": null, "e": 956, "s": 927, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1120, "s": 956, "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 Kotlin as the programming language." }, { "code": null, "e": 1159, "s": 1120, "text": "Step 2: Create a class SharedViewModel" }, { "code": null, "e": 1351, "s": 1159, "text": "Go to the SharedViewModel.kt file and refer to the following code. Below is the code for the SharedViewModel.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 1358, "s": 1351, "text": "Kotlin" }, { "code": "import androidx.lifecycle.MutableLiveDataimport androidx.lifecycle.ViewModel class SharedViewModel : ViewModel() { // variable to contain message whenever // it gets changed/modified(mutable) val message = MutableLiveData<String>() // function to send message fun sendMessage(text: String) { message.value = text }}", "e": 1703, "s": 1358, "text": null }, { "code": null, "e": 1799, "s": 1707, "text": "Step 3: Create two fragments and they are – MessageSenderFragment & MessageReceiverFragment" }, { "code": null, "e": 2161, "s": 1801, "text": "MessageSenderFragment – To send the message which will be received by MessageReceiverFragment. It will have a Button to send the message after clicking it. Go to the MessageSenderFragment.kt file and refer to the following code. Below is the code for the MessageSenderFragment.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 2170, "s": 2163, "text": "Kotlin" }, { "code": "import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.EditTextimport androidx.lifecycle.ViewModelProvider class MessageSenderFragment : Fragment() { // to send message lateinit var btn: Button // to write message lateinit var writeMSg: EditText override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_message_sender, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // reference for button and EditText btn = view.findViewById(R.id.button) writeMSg = view.findViewById(R.id.writeMessage) // create object of SharedViewModel val model = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java) // call function \"sendMessage\" defined in SharedVieModel // to store the value in message. btn.setOnClickListener { model.sendMessage(writeMSg.text.toString()) } }}", "e": 3436, "s": 2170, "text": null }, { "code": null, "e": 3593, "s": 3440, "text": "Navigate to the app > res > fragment_message_sender.xml and add the below code to that file. Below is the code for the fragment_message_sender.xml file." }, { "code": null, "e": 3599, "s": 3595, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <EditText android:id=\"@+id/writeMessage\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"Write your message\" android:textAlignment=\"center\" app:layout_constraintBottom_toTopOf=\"@+id/button\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginBottom=\"100dp\" android:text=\"Share Your Message\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 4742, "s": 3599, "text": null }, { "code": null, "e": 5101, "s": 4746, "text": "MessageReceiverFragment – To receive the message sent by MessageSenderFragment. It will have a TextView to show the updated message on the screen. Go to the MessageReceiverFragment.kt file and refer to the following code. Below is the code for the MessageReceiverFragment.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 5110, "s": 5103, "text": "Kotlin" }, { "code": "class MessageReceiverFragment : Fragment() { // to contain and display shared message lateinit var displayMsg: TextView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // inflate the fragment layout return inflater.inflate(R.layout.fragment_message_receiver, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // reference for the container declared above displayMsg = view.findViewById(R.id.textViewReceiver) // create object of SharedViewModel val model = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java) // observing the change in the message declared in SharedViewModel model.message.observe(viewLifecycleOwner, Observer { // updating data in displayMsg displayMsg.text = it }) }}", "e": 6103, "s": 5110, "text": null }, { "code": null, "e": 6264, "s": 6107, "text": "Navigate to the app > res > fragment_message_receiver.xml and add the below code to that file. Below is the code for the fragment_message_receiver.xml file." }, { "code": null, "e": 6270, "s": 6266, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <TextView android:id=\"@+id/textViewReceiver\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textSize=\"20sp\" android:textColor=\"@color/black\" android:textAlignment=\"center\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 7070, "s": 6270, "text": null }, { "code": null, "e": 7302, "s": 7074, "text": "We have created the object of SharedViewModel which is the same object as we are using the same single activity as an owner. This is the reason it is shared. Notice that we have used the requireActivity() in both the fragments." }, { "code": null, "e": 7310, "s": 7304, "text": ". . ." }, { "code": null, "e": 7380, "s": 7310, "text": "ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)" }, { "code": null, "e": 7386, "s": 7380, "text": ". . ." }, { "code": null, "e": 7425, "s": 7388, "text": "Step 3: Update the activity_main.xml" }, { "code": null, "e": 7506, "s": 7427, "text": "The activity consists of two fragments and is the host for both the fragments." }, { "code": null, "e": 7512, "s": 7508, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <fragment android:id=\"@+id/receiverFragment\" android:name=\"com.gfg.article.sharedviewmodel.MessageReceiverFragment\" android:layout_width=\"match_parent\" android:layout_height=\"0dp\" android:layout_marginStart=\"8dp\" android:layout_marginTop=\"8dp\" android:layout_marginEnd=\"8dp\" android:layout_marginBottom=\"8dp\" app:layout_constraintBottom_toTopOf=\"@+id/senderFragment\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.5\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <fragment android:id=\"@+id/senderFragment\" android:name=\"com.gfg.article.sharedviewmodel.MessageSenderFragment\" android:layout_width=\"match_parent\" android:layout_height=\"0dp\" android:layout_marginStart=\"8dp\" android:layout_marginTop=\"8dp\" android:layout_marginEnd=\"8dp\" android:layout_marginBottom=\"8dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.5\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/receiverFragment\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 9214, "s": 7512, "text": null }, { "code": null, "e": 9252, "s": 9218, "text": "MainActivity.kt remains as it is." }, { "code": null, "e": 9261, "s": 9254, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) }}", "e": 9526, "s": 9261, "text": null }, { "code": null, "e": 9548, "s": 9530, "text": "Now, Run the app." }, { "code": null, "e": 9558, "s": 9550, "text": "Output:" }, { "code": null, "e": 9586, "s": 9562, "text": "Source Code: Click Here" }, { "code": null, "e": 9603, "s": 9588, "text": "varshagumber28" }, { "code": null, "e": 9618, "s": 9603, "text": "Blogathon-2021" }, { "code": null, "e": 9625, "s": 9618, "text": "Picked" }, { "code": null, "e": 9633, "s": 9625, "text": "Android" }, { "code": null, "e": 9643, "s": 9633, "text": "Blogathon" }, { "code": null, "e": 9650, "s": 9643, "text": "Kotlin" }, { "code": null, "e": 9658, "s": 9650, "text": "Android" }, { "code": null, "e": 9756, "s": 9658, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9822, "s": 9756, "text": "Difference Between Implicit Intent and Explicit Intent in Android" }, { "code": null, "e": 9880, "s": 9822, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 9928, "s": 9880, "text": "Android Projects - From Basic to Advanced Level" }, { "code": null, "e": 9970, "s": 9928, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 9999, "s": 9970, "text": "Navigation Drawer in Android" }, { "code": null, "e": 10051, "s": 9999, "text": "How to Call or Consume External API in Spring Boot?" }, { "code": null, "e": 10086, "s": 10051, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 10120, "s": 10086, "text": "SQL Query to Insert Multiple Rows" }, { "code": null, "e": 10161, "s": 10120, "text": "How to Connect Python with SQL Database?" } ]
Different Types of Functions in Dart
31 Oct, 2021 The function is a set of statements that take inputs, do some specific computation, and produce output. Functions are created when certain statements are repeatedly occurring in the program and a function is created to replace them. Functions make it easy to divide the complex program into smaller sub-groups and increase the code reusability of the program. Basically, there are four types of functions in Dart. These are as follows: No arguments and no return type With arguments and no return type No arguments and return type With arguments and with return type Basically in this function, we do not give any argument and expect no return type. It can be better understood by an example. Dart void myName(){ print("GeeksForGeeks");} void main(){ print("This is the best website for developers:"); myName();} So myName is the function which is void means it is not returning and anything and the empty pair of parentheses suggest that there is no argument that is passed to the function. Basically in this function, we are giving an argument and expect no return type. Dart int myPrice(){ int price = 0; return price;} void main(){ int Price = myPrice(); print("GeeksforGeeks is the best website for developers which costs : ${Price}/-");} So myPrice is the function which is int means it is returning int type and the empty pair of parentheses suggests that there is no argument which is passed to the function. Basically in this function, we do not give any argument but expect a return type. Dart myPrice(int price){ print(price);}void main(){ print("GeeksforGeeks is the best website for developers which costs : "); myPrice(0);} So myPrice is the function which is void means it is not returning anything and the pair of parentheses is not empty this time that suggests that it accept an argument. Basically in this function, we are giving an argument and expect return type. It can we better understand by an example. Dart int mySum(int firstNumber, int secondNumber){ return (firstNumber + secondNumber);}void main(){ int additionOfTwoNumber = mySum(100, 500); print(additionOfTwoNumber);} So mySum is the function which is int means it is returning int type and the pair of parentheses is having two arguments which are used further in this function and then in the main function we are printing the addition of two numbers. nosenselesstalks Dart Function Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - Row and Column Widgets ListView Class in Flutter Dart Tutorial Flutter - Stack Widget Flutter - Search Bar How to Append or Concatenate Strings in Dart? Container class in Flutter
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Oct, 2021" }, { "code": null, "e": 415, "s": 54, "text": "The function is a set of statements that take inputs, do some specific computation, and produce output. Functions are created when certain statements are repeatedly occurring in the program and a function is created to replace them. Functions make it easy to divide the complex program into smaller sub-groups and increase the code reusability of the program. " }, { "code": null, "e": 491, "s": 415, "text": "Basically, there are four types of functions in Dart. These are as follows:" }, { "code": null, "e": 524, "s": 491, "text": "No arguments and no return type " }, { "code": null, "e": 559, "s": 524, "text": "With arguments and no return type " }, { "code": null, "e": 589, "s": 559, "text": "No arguments and return type " }, { "code": null, "e": 625, "s": 589, "text": "With arguments and with return type" }, { "code": null, "e": 752, "s": 625, "text": "Basically in this function, we do not give any argument and expect no return type. It can be better understood by an example. " }, { "code": null, "e": 757, "s": 752, "text": "Dart" }, { "code": "void myName(){ print(\"GeeksForGeeks\");} void main(){ print(\"This is the best website for developers:\"); myName();}", "e": 875, "s": 757, "text": null }, { "code": null, "e": 1057, "s": 875, "text": " So myName is the function which is void means it is not returning and anything and the empty pair of parentheses suggest that there is no argument that is passed to the function. " }, { "code": null, "e": 1139, "s": 1057, "text": "Basically in this function, we are giving an argument and expect no return type. " }, { "code": null, "e": 1144, "s": 1139, "text": "Dart" }, { "code": "int myPrice(){ int price = 0; return price;} void main(){ int Price = myPrice(); print(\"GeeksforGeeks is the best website for developers which costs : ${Price}/-\");}", "e": 1314, "s": 1144, "text": null }, { "code": null, "e": 1489, "s": 1314, "text": " So myPrice is the function which is int means it is returning int type and the empty pair of parentheses suggests that there is no argument which is passed to the function." }, { "code": null, "e": 1572, "s": 1489, "text": "Basically in this function, we do not give any argument but expect a return type. " }, { "code": null, "e": 1577, "s": 1572, "text": "Dart" }, { "code": "myPrice(int price){ print(price);}void main(){ print(\"GeeksforGeeks is the best website for developers which costs : \"); myPrice(0);}", "e": 1715, "s": 1577, "text": null }, { "code": null, "e": 1887, "s": 1715, "text": " So myPrice is the function which is void means it is not returning anything and the pair of parentheses is not empty this time that suggests that it accept an argument. " }, { "code": null, "e": 2009, "s": 1887, "text": "Basically in this function, we are giving an argument and expect return type. It can we better understand by an example. " }, { "code": null, "e": 2014, "s": 2009, "text": "Dart" }, { "code": "int mySum(int firstNumber, int secondNumber){ return (firstNumber + secondNumber);}void main(){ int additionOfTwoNumber = mySum(100, 500); print(additionOfTwoNumber);}", "e": 2185, "s": 2014, "text": null }, { "code": null, "e": 2422, "s": 2185, "text": " So mySum is the function which is int means it is returning int type and the pair of parentheses is having two arguments which are used further in this function and then in the main function we are printing the addition of two numbers." }, { "code": null, "e": 2439, "s": 2422, "text": "nosenselesstalks" }, { "code": null, "e": 2453, "s": 2439, "text": "Dart Function" }, { "code": null, "e": 2458, "s": 2453, "text": "Dart" }, { "code": null, "e": 2556, "s": 2458, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2588, "s": 2556, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 2627, "s": 2588, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 2653, "s": 2627, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 2686, "s": 2653, "text": "Flutter - Row and Column Widgets" }, { "code": null, "e": 2712, "s": 2686, "text": "ListView Class in Flutter" }, { "code": null, "e": 2726, "s": 2712, "text": "Dart Tutorial" }, { "code": null, "e": 2749, "s": 2726, "text": "Flutter - Stack Widget" }, { "code": null, "e": 2770, "s": 2749, "text": "Flutter - Search Bar" }, { "code": null, "e": 2816, "s": 2770, "text": "How to Append or Concatenate Strings in Dart?" } ]
Rotation of a point about another point in C++
22 Jun, 2022 We have already discussed the rotation of a point P about the origin in the Set 1 and Set 2. The rotation of point P about origin with an angle θ in the anti-clockwise direction is given as under: Rotation of P about origin: P * polar(1.0, θ) Rotation of P about point Q Now, we have to rotate the point P not about origin but about a general point Q. This can be easily understood by the method of translation which is quite a common technique adopted in geometric analysis. What is Translation? In Euclidean geometry, translation is a geometric transformation that moves every point of a figure or a space by the same amount in a given direction. How to Perform Translation? Translation can also be interpreted as the addition of a constant vector to every point, or as shifting the origin of the coordinate system. After the translation, required computations are made and the translation is nullified by subtracting the constant vector to every point or shifting the origin back. So, for rotating P about Q, we shift the origin at Q i.e. we subtract the vector equivalent of Q from every point of the coordinate plane. Now the new point P – Q has to be rotated about the origin and then translation has to be nullified. These steps can be described as under: Translation (Shifting origin at Q): Subtract Q from all points. Thus, P becomes P – QRotation of (P – Q) about origin: (P – Q) * polar(1.0, θ)Restoring back the Origin: Add Q to all the points. Translation (Shifting origin at Q): Subtract Q from all points. Thus, P becomes P – Q Rotation of (P – Q) about origin: (P – Q) * polar(1.0, θ) Restoring back the Origin: Add Q to all the points. Thus, Rotation of P about Q : (P – Q) * polar(1.0, θ) + Q CPP // CPP example to illustrate the rotation// of a point about another point#include <iostream>#include <complex> using namespace std; typedef complex<double> point;#define x real()#define y imag() // Constant PI for providing angles in radians#define PI 3.1415926535897932384626 // Function used to display X and Y coordinates of a pointvoid displayPoint(point P){ cout << "(" << P.x << ", " << P.y << ")" << endl;} //Function for Rotation of P about Q by angle thetapoint rotate(point P, point Q, double theta){ return (P-Q) * polar(1.0, theta) + Q;} int main(){ // Rotate P about Q point P(4.0, 3.0); point Q(2.0, 2.0); // Angle of rotation = 90 degrees double theta = PI/2; point P_rotated = rotate(P, Q, theta); cout << "The point P on rotating 90 degrees anti-clockwise about Q becomes:"; cout << "P_rotated"; displayPoint(P_rotated); return 0;} Output: The point P on rotating 90 degrees anti-clockwise about Q becomes: P_rotated(1, 4) Time Complexity: O(1) Auxiliary Space: O(1) This article is contributed by Aanya Jindal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. mailaruyashaswi cpp-numerics-library STL C++ Geometric Mathematical Mathematical Geometric STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2022" }, { "code": null, "e": 225, "s": 28, "text": "We have already discussed the rotation of a point P about the origin in the Set 1 and Set 2. The rotation of point P about origin with an angle θ in the anti-clockwise direction is given as under:" }, { "code": null, "e": 271, "s": 225, "text": "Rotation of P about origin: P * polar(1.0, θ)" }, { "code": null, "e": 299, "s": 271, "text": "Rotation of P about point Q" }, { "code": null, "e": 1292, "s": 299, "text": "Now, we have to rotate the point P not about origin but about a general point Q. This can be easily understood by the method of translation which is quite a common technique adopted in geometric analysis. What is Translation? In Euclidean geometry, translation is a geometric transformation that moves every point of a figure or a space by the same amount in a given direction. How to Perform Translation? Translation can also be interpreted as the addition of a constant vector to every point, or as shifting the origin of the coordinate system. After the translation, required computations are made and the translation is nullified by subtracting the constant vector to every point or shifting the origin back. So, for rotating P about Q, we shift the origin at Q i.e. we subtract the vector equivalent of Q from every point of the coordinate plane. Now the new point P – Q has to be rotated about the origin and then translation has to be nullified. These steps can be described as under:" }, { "code": null, "e": 1486, "s": 1292, "text": "Translation (Shifting origin at Q): Subtract Q from all points. Thus, P becomes P – QRotation of (P – Q) about origin: (P – Q) * polar(1.0, θ)Restoring back the Origin: Add Q to all the points." }, { "code": null, "e": 1572, "s": 1486, "text": "Translation (Shifting origin at Q): Subtract Q from all points. Thus, P becomes P – Q" }, { "code": null, "e": 1630, "s": 1572, "text": "Rotation of (P – Q) about origin: (P – Q) * polar(1.0, θ)" }, { "code": null, "e": 1682, "s": 1630, "text": "Restoring back the Origin: Add Q to all the points." }, { "code": null, "e": 1688, "s": 1682, "text": "Thus," }, { "code": null, "e": 1741, "s": 1688, "text": " Rotation of P about Q : (P – Q) * polar(1.0, θ) + Q" }, { "code": null, "e": 1745, "s": 1741, "text": "CPP" }, { "code": "// CPP example to illustrate the rotation// of a point about another point#include <iostream>#include <complex> using namespace std; typedef complex<double> point;#define x real()#define y imag() // Constant PI for providing angles in radians#define PI 3.1415926535897932384626 // Function used to display X and Y coordinates of a pointvoid displayPoint(point P){ cout << \"(\" << P.x << \", \" << P.y << \")\" << endl;} //Function for Rotation of P about Q by angle thetapoint rotate(point P, point Q, double theta){ return (P-Q) * polar(1.0, theta) + Q;} int main(){ // Rotate P about Q point P(4.0, 3.0); point Q(2.0, 2.0); // Angle of rotation = 90 degrees double theta = PI/2; point P_rotated = rotate(P, Q, theta); cout << \"The point P on rotating 90 degrees anti-clockwise about Q becomes:\"; cout << \"P_rotated\"; displayPoint(P_rotated); return 0;}", "e": 2635, "s": 1745, "text": null }, { "code": null, "e": 2643, "s": 2635, "text": "Output:" }, { "code": null, "e": 2726, "s": 2643, "text": "The point P on rotating 90 degrees anti-clockwise about Q becomes: P_rotated(1, 4)" }, { "code": null, "e": 2748, "s": 2726, "text": "Time Complexity: O(1)" }, { "code": null, "e": 2770, "s": 2748, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3191, "s": 2770, "text": "This article is contributed by Aanya Jindal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3207, "s": 3191, "text": "mailaruyashaswi" }, { "code": null, "e": 3228, "s": 3207, "text": "cpp-numerics-library" }, { "code": null, "e": 3232, "s": 3228, "text": "STL" }, { "code": null, "e": 3236, "s": 3232, "text": "C++" }, { "code": null, "e": 3246, "s": 3236, "text": "Geometric" }, { "code": null, "e": 3259, "s": 3246, "text": "Mathematical" }, { "code": null, "e": 3272, "s": 3259, "text": "Mathematical" }, { "code": null, "e": 3282, "s": 3272, "text": "Geometric" }, { "code": null, "e": 3286, "s": 3282, "text": "STL" }, { "code": null, "e": 3290, "s": 3286, "text": "CPP" } ]
How to connect WiFi using Python?
23 Aug, 2021 Seeing a computer without an active internet connection today is next to impossible. The Internet has been of the utmost importance in the 21st Century. There are multiple ways one can connect their machine to the Internet. The first being, the traditional cables, i.e. the Ethernet, and the other being, the modern Wireless Fidelity Systems or Wi-Fi as we all know it. Wi-Fi has made life easier and faster for all of us. With a touch of the thumb or a click of the mouse, we get connected to a limitless ocean of information and resources almost instantaneously. In this article, we will accomplish the same task with a High-Level modern programming language, like Python Here we are going to connect to a previously connected WiFi network. Approach: The approach of the program will be simple: Import the necessary libraries. Displaying all the available SSIDs with the help of cmd commands and a python library named os. Selecting the known Wi-Fi you want to connect to. Wait for it to Connect successfully. Now, let’s get coding. We will make use of a couple of Windows Command Prompt commands to access the list of available Wi-Fi networks and to connect to a previously connected network. But, how do we write and execute Window Command Prompt commands in a Python script? Umm... The os library helps us communicate with the operating system directly through python with several methods like path(), getcwd(), system(), etc. We can even run CMD commands using os functions. Implementation: Python3 # import moduleimport os # scan available Wifi networksos.system('cmd /c "netsh wlan show networks"') # input Wifi namename_of_router = input('Enter Name/SSID of the Wifi Network you wish to connect to: ') # connect to the given wifi networkos.system(f'''cmd /c "netsh wlan connect name={name_of_router}"''') print("If you're not yet connected, try connecting to a previously connected SSID again!") Output: Explanation: Here, first, we fetch the os library using the import keyword. Then, we use the system() method from the os library with helps us run the cmd command 'cmd /c "netsh wlan show networks"' The above command scans all the available SSIDs and displays them as output along with their Infrastructure, Authentication, and Encryption type. We proceed by taking a string input of the SSID, the user wishes to connect to and save them in the variable named, name_of_router. This string variable is then substituted in the place of another cmd command where we are supposed to enter the name of the SSID. f'''cmd /c "netsh wlan connect name={name_of_router}"''' We will now be successfully connected to the particular SSID. Now, connecting to a new Wi-Fi involves a couple of more steps. To connect to a new network, we must first add this new Wi-Fi Network profile to our system using an .XML file. This makes that Wi-Fi network, a known SSID, and we can now successfully connect to it using the above steps. Approach: Step 1: Import the os library Step 2: Set up the new Wi-Fi Network’s XML configuration Step 3: Select the Wi-Fi Network Step 4: Add this profile to your system Step 5: Connect to the Wi-Fi network Implementation: Python3 # import moduleimport os # function to establish a new connectiondef createNewConnection(name, SSID, password): config = """<?xml version=\"1.0\"?><WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1"> <name>"""+name+"""</name> <SSIDConfig> <SSID> <name>"""+SSID+"""</name> </SSID> </SSIDConfig> <connectionType>ESS</connectionType> <connectionMode>auto</connectionMode> <MSM> <security> <authEncryption> <authentication>WPA2PSK</authentication> <encryption>AES</encryption> <useOneX>false</useOneX> </authEncryption> <sharedKey> <keyType>passPhrase</keyType> <protected>false</protected> <keyMaterial>"""+password+"""</keyMaterial> </sharedKey> </security> </MSM></WLANProfile>""" command = "netsh wlan add profile filename=\""+name+".xml\""+" interface=Wi-Fi" with open(name+".xml", 'w') as file: file.write(config) os.system(command) # function to connect to a network def connect(name, SSID): command = "netsh wlan connect name=\""+name+"\" ssid=\""+SSID+"\" interface=Wi-Fi" os.system(command) # function to display avavilabe Wifi networks def displayAvailableNetworks(): command = "netsh wlan show networks interface=Wi-Fi" os.system(command) # display available netwroksdisplayAvailableNetworks() # input wifi name and passwordname = input("Name of Wi-Fi: ")password = input("Password: ") # establish new connectioncreateNewConnection(name, name, password) # connect to the wifi networkconnect(name, name)print("If you aren't connected to this network, try connecting with the correct password!") Output: Explanation: First, we define the createNewConnection function which takes the parameters name, SSID, and password, which are all strings that we used to complete to config variable. The config variable is a string that helps us define the XML configuration for a new Wi-Fi Network. Then, we take the input from the user for the SSID name and Password. They are then fed into XML code which is then added as a profile using the following lines of code: command = "netsh wlan add profile filename=\""+name+".xml\""+" interface=Wi-Fi" with open(name+".xml", 'w') as file: file.write(config) os.system(command) We can now connect to the Wi-Fi using the same commands we used earlier in this article and connect to the network as if it was a known one. abhishek0719kadiyan Picked python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Aug, 2021" }, { "code": null, "e": 728, "s": 54, "text": "Seeing a computer without an active internet connection today is next to impossible. The Internet has been of the utmost importance in the 21st Century. There are multiple ways one can connect their machine to the Internet. The first being, the traditional cables, i.e. the Ethernet, and the other being, the modern Wireless Fidelity Systems or Wi-Fi as we all know it. Wi-Fi has made life easier and faster for all of us. With a touch of the thumb or a click of the mouse, we get connected to a limitless ocean of information and resources almost instantaneously. In this article, we will accomplish the same task with a High-Level modern programming language, like Python" }, { "code": null, "e": 797, "s": 728, "text": "Here we are going to connect to a previously connected WiFi network." }, { "code": null, "e": 807, "s": 797, "text": "Approach:" }, { "code": null, "e": 851, "s": 807, "text": "The approach of the program will be simple:" }, { "code": null, "e": 883, "s": 851, "text": "Import the necessary libraries." }, { "code": null, "e": 979, "s": 883, "text": "Displaying all the available SSIDs with the help of cmd commands and a python library named os." }, { "code": null, "e": 1029, "s": 979, "text": "Selecting the known Wi-Fi you want to connect to." }, { "code": null, "e": 1066, "s": 1029, "text": "Wait for it to Connect successfully." }, { "code": null, "e": 1341, "s": 1066, "text": "Now, let’s get coding. We will make use of a couple of Windows Command Prompt commands to access the list of available Wi-Fi networks and to connect to a previously connected network. But, how do we write and execute Window Command Prompt commands in a Python script? Umm..." }, { "code": null, "e": 1536, "s": 1341, "text": "The os library helps us communicate with the operating system directly through python with several methods like path(), getcwd(), system(), etc. We can even run CMD commands using os functions. " }, { "code": null, "e": 1552, "s": 1536, "text": "Implementation:" }, { "code": null, "e": 1560, "s": 1552, "text": "Python3" }, { "code": "# import moduleimport os # scan available Wifi networksos.system('cmd /c \"netsh wlan show networks\"') # input Wifi namename_of_router = input('Enter Name/SSID of the Wifi Network you wish to connect to: ') # connect to the given wifi networkos.system(f'''cmd /c \"netsh wlan connect name={name_of_router}\"''') print(\"If you're not yet connected, try connecting to a previously connected SSID again!\")", "e": 1960, "s": 1560, "text": null }, { "code": null, "e": 1970, "s": 1960, "text": " Output:" }, { "code": null, "e": 1983, "s": 1970, "text": "Explanation:" }, { "code": null, "e": 2134, "s": 1983, "text": "Here, first, we fetch the os library using the import keyword. Then, we use the system() method from the os library with helps us run the cmd command " }, { "code": null, "e": 2171, "s": 2134, "text": "'cmd /c \"netsh wlan show networks\"' " }, { "code": null, "e": 2450, "s": 2171, "text": "The above command scans all the available SSIDs and displays them as output along with their Infrastructure, Authentication, and Encryption type. We proceed by taking a string input of the SSID, the user wishes to connect to and save them in the variable named, name_of_router. " }, { "code": null, "e": 2581, "s": 2450, "text": "This string variable is then substituted in the place of another cmd command where we are supposed to enter the name of the SSID. " }, { "code": null, "e": 2639, "s": 2581, "text": "f'''cmd /c \"netsh wlan connect name={name_of_router}\"''' " }, { "code": null, "e": 2702, "s": 2639, "text": "We will now be successfully connected to the particular SSID. " }, { "code": null, "e": 2988, "s": 2702, "text": "Now, connecting to a new Wi-Fi involves a couple of more steps. To connect to a new network, we must first add this new Wi-Fi Network profile to our system using an .XML file. This makes that Wi-Fi network, a known SSID, and we can now successfully connect to it using the above steps." }, { "code": null, "e": 2998, "s": 2988, "text": "Approach:" }, { "code": null, "e": 3028, "s": 2998, "text": "Step 1: Import the os library" }, { "code": null, "e": 3085, "s": 3028, "text": "Step 2: Set up the new Wi-Fi Network’s XML configuration" }, { "code": null, "e": 3118, "s": 3085, "text": "Step 3: Select the Wi-Fi Network" }, { "code": null, "e": 3158, "s": 3118, "text": "Step 4: Add this profile to your system" }, { "code": null, "e": 3195, "s": 3158, "text": "Step 5: Connect to the Wi-Fi network" }, { "code": null, "e": 3212, "s": 3195, "text": " Implementation:" }, { "code": null, "e": 3220, "s": 3212, "text": "Python3" }, { "code": "# import moduleimport os # function to establish a new connectiondef createNewConnection(name, SSID, password): config = \"\"\"<?xml version=\\\"1.0\\\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"> <name>\"\"\"+name+\"\"\"</name> <SSIDConfig> <SSID> <name>\"\"\"+SSID+\"\"\"</name> </SSID> </SSIDConfig> <connectionType>ESS</connectionType> <connectionMode>auto</connectionMode> <MSM> <security> <authEncryption> <authentication>WPA2PSK</authentication> <encryption>AES</encryption> <useOneX>false</useOneX> </authEncryption> <sharedKey> <keyType>passPhrase</keyType> <protected>false</protected> <keyMaterial>\"\"\"+password+\"\"\"</keyMaterial> </sharedKey> </security> </MSM></WLANProfile>\"\"\" command = \"netsh wlan add profile filename=\\\"\"+name+\".xml\\\"\"+\" interface=Wi-Fi\" with open(name+\".xml\", 'w') as file: file.write(config) os.system(command) # function to connect to a network def connect(name, SSID): command = \"netsh wlan connect name=\\\"\"+name+\"\\\" ssid=\\\"\"+SSID+\"\\\" interface=Wi-Fi\" os.system(command) # function to display avavilabe Wifi networks def displayAvailableNetworks(): command = \"netsh wlan show networks interface=Wi-Fi\" os.system(command) # display available netwroksdisplayAvailableNetworks() # input wifi name and passwordname = input(\"Name of Wi-Fi: \")password = input(\"Password: \") # establish new connectioncreateNewConnection(name, name, password) # connect to the wifi networkconnect(name, name)print(\"If you aren't connected to this network, try connecting with the correct password!\")", "e": 4973, "s": 3220, "text": null }, { "code": null, "e": 4981, "s": 4973, "text": "Output:" }, { "code": null, "e": 4994, "s": 4981, "text": "Explanation:" }, { "code": null, "e": 5264, "s": 4994, "text": "First, we define the createNewConnection function which takes the parameters name, SSID, and password, which are all strings that we used to complete to config variable. The config variable is a string that helps us define the XML configuration for a new Wi-Fi Network." }, { "code": null, "e": 5434, "s": 5264, "text": "Then, we take the input from the user for the SSID name and Password. They are then fed into XML code which is then added as a profile using the following lines of code:" }, { "code": null, "e": 5605, "s": 5434, "text": "command = \"netsh wlan add profile filename=\\\"\"+name+\".xml\\\"\"+\" interface=Wi-Fi\"\n with open(name+\".xml\", 'w') as file:\n file.write(config)\n os.system(command)" }, { "code": null, "e": 5747, "s": 5605, "text": "We can now connect to the Wi-Fi using the same commands we used earlier in this article and connect to the network as if it was a known one. " }, { "code": null, "e": 5767, "s": 5747, "text": "abhishek0719kadiyan" }, { "code": null, "e": 5774, "s": 5767, "text": "Picked" }, { "code": null, "e": 5789, "s": 5774, "text": "python-utility" }, { "code": null, "e": 5796, "s": 5789, "text": "Python" } ]
How to download a file using Node.js?
29 Jan, 2021 Downloading a file using node js can be done using inbuilt packages or with third party libraries. Method 1: Using ‘https’ and ‘fs’ module GET method is used on HTTPS to fetch the file which is to be downloaded. createWriteStream() is a method that is used to create a writable stream and receives only one argument, the location where the file is to be saved. pipe() is a method that reads the data from the readable stream and writes it onto the writable stream. Javascript const fs = require('fs');const https = require('https'); // URL of the imageconst url = 'GFG.jpeg'; https.get(url,(res) => { // Image will be stored at this path const path = `${__dirname}/files/img.jpeg`; const filePath = fs.createWriteStream(path); res.pipe(filePath); filePath.on('finish',() => { filePath.close(); console.log('Download Completed'); })}) Method 2: Using third party libraries‘node-downloader-helper’ LibraryInstallation: npm install node-helper-libraryBelow is the code for downloading an image from a website. An object dl is created of class DownloadHelper which receives two arguments:The image which is to be downloaded.The path where the image has to be saved after downloading.The file variable contains the URL of the image which will be downloaded and filePath variables contain the path where the file will be saved.JavascriptJavascriptconst { DownloaderHelper } = require('node-downloader-helper'); // URL of the imageconst file = 'GFG.jpeg';// Path at which image will be downloadedconst filePath = `${__dirname}/files`; const dl = new DownloaderHelper(file , filePath); dl.on('end', () => console.log('Download Completed'))dl.start();‘download’ LibraryInstallation:npm install downloadBelow is the code for downloading an image from a website. The download function receives the file and path of fileJavascriptJavascriptconst download = require('download'); // Url of the imageconst file = 'GFG.jpeg';// Path at which image will get downloadedconst filePath = `${__dirname}/files`; download(file,filePath).then(() => { console.log('Download Completed');})console output of all the above three codes Method 2: Using third party libraries ‘node-downloader-helper’ LibraryInstallation: npm install node-helper-libraryBelow is the code for downloading an image from a website. An object dl is created of class DownloadHelper which receives two arguments:The image which is to be downloaded.The path where the image has to be saved after downloading.The file variable contains the URL of the image which will be downloaded and filePath variables contain the path where the file will be saved.JavascriptJavascriptconst { DownloaderHelper } = require('node-downloader-helper'); // URL of the imageconst file = 'GFG.jpeg';// Path at which image will be downloadedconst filePath = `${__dirname}/files`; const dl = new DownloaderHelper(file , filePath); dl.on('end', () => console.log('Download Completed'))dl.start(); Installation: npm install node-helper-library Below is the code for downloading an image from a website. An object dl is created of class DownloadHelper which receives two arguments: The image which is to be downloaded. The path where the image has to be saved after downloading. The file variable contains the URL of the image which will be downloaded and filePath variables contain the path where the file will be saved. Javascript const { DownloaderHelper } = require('node-downloader-helper'); // URL of the imageconst file = 'GFG.jpeg';// Path at which image will be downloadedconst filePath = `${__dirname}/files`; const dl = new DownloaderHelper(file , filePath); dl.on('end', () => console.log('Download Completed'))dl.start(); ‘download’ LibraryInstallation:npm install downloadBelow is the code for downloading an image from a website. The download function receives the file and path of fileJavascriptJavascriptconst download = require('download'); // Url of the imageconst file = 'GFG.jpeg';// Path at which image will get downloadedconst filePath = `${__dirname}/files`; download(file,filePath).then(() => { console.log('Download Completed');})console output of all the above three codes Installation: npm install download Below is the code for downloading an image from a website. The download function receives the file and path of file Javascript const download = require('download'); // Url of the imageconst file = 'GFG.jpeg';// Path at which image will get downloadedconst filePath = `${__dirname}/files`; download(file,filePath).then(() => { console.log('Download Completed');}) console output of all the above three codes NodeJS-Questions Picked Technical Scripter 2020 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JWT Authentication with Node.js Installation of Node.js on Windows Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jan, 2021" }, { "code": null, "e": 127, "s": 28, "text": "Downloading a file using node js can be done using inbuilt packages or with third party libraries." }, { "code": null, "e": 167, "s": 127, "text": "Method 1: Using ‘https’ and ‘fs’ module" }, { "code": null, "e": 493, "s": 167, "text": "GET method is used on HTTPS to fetch the file which is to be downloaded. createWriteStream() is a method that is used to create a writable stream and receives only one argument, the location where the file is to be saved. pipe() is a method that reads the data from the readable stream and writes it onto the writable stream." }, { "code": null, "e": 504, "s": 493, "text": "Javascript" }, { "code": "const fs = require('fs');const https = require('https'); // URL of the imageconst url = 'GFG.jpeg'; https.get(url,(res) => { // Image will be stored at this path const path = `${__dirname}/files/img.jpeg`; const filePath = fs.createWriteStream(path); res.pipe(filePath); filePath.on('finish',() => { filePath.close(); console.log('Download Completed'); })})", "e": 898, "s": 504, "text": null }, { "code": null, "e": 2180, "s": 898, "text": "Method 2: Using third party libraries‘node-downloader-helper’ LibraryInstallation: npm install node-helper-libraryBelow is the code for downloading an image from a website. An object dl is created of class DownloadHelper which receives two arguments:The image which is to be downloaded.The path where the image has to be saved after downloading.The file variable contains the URL of the image which will be downloaded and filePath variables contain the path where the file will be saved.JavascriptJavascriptconst { DownloaderHelper } = require('node-downloader-helper'); // URL of the imageconst file = 'GFG.jpeg';// Path at which image will be downloadedconst filePath = `${__dirname}/files`; const dl = new DownloaderHelper(file , filePath); dl.on('end', () => console.log('Download Completed'))dl.start();‘download’ LibraryInstallation:npm install downloadBelow is the code for downloading an image from a website. The download function receives the file and path of fileJavascriptJavascriptconst download = require('download'); // Url of the imageconst file = 'GFG.jpeg';// Path at which image will get downloadedconst filePath = `${__dirname}/files`; download(file,filePath).then(() => { console.log('Download Completed');})console output of all the above three codes" }, { "code": null, "e": 2218, "s": 2180, "text": "Method 2: Using third party libraries" }, { "code": null, "e": 2994, "s": 2218, "text": "‘node-downloader-helper’ LibraryInstallation: npm install node-helper-libraryBelow is the code for downloading an image from a website. An object dl is created of class DownloadHelper which receives two arguments:The image which is to be downloaded.The path where the image has to be saved after downloading.The file variable contains the URL of the image which will be downloaded and filePath variables contain the path where the file will be saved.JavascriptJavascriptconst { DownloaderHelper } = require('node-downloader-helper'); // URL of the imageconst file = 'GFG.jpeg';// Path at which image will be downloadedconst filePath = `${__dirname}/files`; const dl = new DownloaderHelper(file , filePath); dl.on('end', () => console.log('Download Completed'))dl.start();" }, { "code": null, "e": 3009, "s": 2994, "text": "Installation: " }, { "code": null, "e": 3041, "s": 3009, "text": "npm install node-helper-library" }, { "code": null, "e": 3178, "s": 3041, "text": "Below is the code for downloading an image from a website. An object dl is created of class DownloadHelper which receives two arguments:" }, { "code": null, "e": 3215, "s": 3178, "text": "The image which is to be downloaded." }, { "code": null, "e": 3275, "s": 3215, "text": "The path where the image has to be saved after downloading." }, { "code": null, "e": 3418, "s": 3275, "text": "The file variable contains the URL of the image which will be downloaded and filePath variables contain the path where the file will be saved." }, { "code": null, "e": 3429, "s": 3418, "text": "Javascript" }, { "code": "const { DownloaderHelper } = require('node-downloader-helper'); // URL of the imageconst file = 'GFG.jpeg';// Path at which image will be downloadedconst filePath = `${__dirname}/files`; const dl = new DownloaderHelper(file , filePath); dl.on('end', () => console.log('Download Completed'))dl.start();", "e": 3735, "s": 3429, "text": null }, { "code": null, "e": 4205, "s": 3735, "text": "‘download’ LibraryInstallation:npm install downloadBelow is the code for downloading an image from a website. The download function receives the file and path of fileJavascriptJavascriptconst download = require('download'); // Url of the imageconst file = 'GFG.jpeg';// Path at which image will get downloadedconst filePath = `${__dirname}/files`; download(file,filePath).then(() => { console.log('Download Completed');})console output of all the above three codes" }, { "code": null, "e": 4219, "s": 4205, "text": "Installation:" }, { "code": null, "e": 4240, "s": 4219, "text": "npm install download" }, { "code": null, "e": 4356, "s": 4240, "text": "Below is the code for downloading an image from a website. The download function receives the file and path of file" }, { "code": null, "e": 4367, "s": 4356, "text": "Javascript" }, { "code": "const download = require('download'); // Url of the imageconst file = 'GFG.jpeg';// Path at which image will get downloadedconst filePath = `${__dirname}/files`; download(file,filePath).then(() => { console.log('Download Completed');})", "e": 4608, "s": 4367, "text": null }, { "code": null, "e": 4652, "s": 4608, "text": "console output of all the above three codes" }, { "code": null, "e": 4669, "s": 4652, "text": "NodeJS-Questions" }, { "code": null, "e": 4676, "s": 4669, "text": "Picked" }, { "code": null, "e": 4700, "s": 4676, "text": "Technical Scripter 2020" }, { "code": null, "e": 4708, "s": 4700, "text": "Node.js" }, { "code": null, "e": 4727, "s": 4708, "text": "Technical Scripter" }, { "code": null, "e": 4744, "s": 4727, "text": "Web Technologies" }, { "code": null, "e": 4842, "s": 4744, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4874, "s": 4842, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 4909, "s": 4874, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 4979, "s": 4909, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 5006, "s": 4979, "text": "Mongoose Populate() Method" }, { "code": null, "e": 5031, "s": 5006, "text": "Mongoose find() Function" }, { "code": null, "e": 5093, "s": 5031, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5154, "s": 5093, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5204, "s": 5154, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5247, "s": 5204, "text": "How to fetch data from an API in ReactJS ?" } ]
WebAssembly - WASM
WebAssembly is also called wasm, which is an improvement to Javascript. It is designed to run inside browsers just like javascript and also with nodejs. You happen to get wasm output, when any high level language like C, C++, Rust is compiled. Consider the following C program − int factorial(int n) { if (n == 0) return 1; else return n * factorial(n-1); } Make use of WasmExplorer, which is available at https://mbebenita.github.io/WasmExplorer/ to get the compiled code as shown below − The WebAssembly text format for factorial program is as stated below − (module (table 0 anyfunc) (memory $0 1) (export "memory" (memory $0)) (export "factorial" (func $factorial)) (func $factorial (; 0 ;) (param $0 i32) (result i32) (local $1 i32) (local $2 i32) (block $label$0 (br_if $label$0 (i32.eqz (get_local $0) ) ) (set_local $2 (i32.const 1) ) (loop $label$1 (set_local $2 (i32.mul (get_local $0) (get_local $2) ) ) (set_local $0 (tee_local $1 (i32.add (get_local $0) (i32.const -1) ) ) ) (br_if $label$1 (get_local $1) ) ) (return (get_local $2) ) ) (i32.const 1) ) ) Using the Wat2Wasm tool, you can view the WASM code, just like how it is mentioned below − Developers are not supposed to write code in wasm or learn to code in it, as it is mostly generated when you compile high level languages. In WASM, all the instructions are pushed on to the stack. The arguments are popped and the result is pushed back to the stack. Consider the following WebAssembly Text format that adds 2 numbers − (module (func $add (param $a i32) (param $b i32) (result i32) get_local $a get_local $b i32.add ) (export "add" (func $add)) ) The name of the function is $add, it takes in 2 params $a and $b. The result is a type 32-bit integer. The local variables are accessed using get_local and the add operation is performed using i32.add. The stack representation to add 2 numbers while execution will be as follows − In step 1 − The execution of get_local $a instruction, the first parameters i.e., $a is pushed on the stack. In step 2 − During execution of get_local $b instruction, the second parameters i.e., $b is pushed on the stack. In step 3 − The execution of i32.add will pop the elements from the stack and will push the result back to the stack. The value that remains in the end inside the stack is the result of the function $add. Print Add Notes Bookmark this page
[ { "code": null, "e": 2477, "s": 2233, "text": "WebAssembly is also called wasm, which is an improvement to Javascript. It is designed to run inside browsers just like javascript and also with nodejs. You happen to get wasm output, when any high level language like C, C++, Rust is compiled." }, { "code": null, "e": 2512, "s": 2477, "text": "Consider the following C program −" }, { "code": null, "e": 2614, "s": 2512, "text": "int factorial(int n) {\n if (n == 0) \n return 1; \n else \n return n * factorial(n-1); \n}\n" }, { "code": null, "e": 2746, "s": 2614, "text": "Make use of WasmExplorer, which is available at https://mbebenita.github.io/WasmExplorer/ to get the compiled code as shown below −" }, { "code": null, "e": 2817, "s": 2746, "text": "The WebAssembly text format for factorial program is as stated below −" }, { "code": null, "e": 3731, "s": 2817, "text": "(module \n (table 0 anyfunc) \n (memory $0 1) \n (export \"memory\" (memory $0)) (export \"factorial\" (func $factorial)) \n (func $factorial (; 0 ;) (param $0 i32) (result i32)\n (local $1 i32) \n (local $2 i32) \n (block $label$0 \n (br_if $label$0 \n (i32.eqz \n (get_local $0) \n )\n )\n (set_local $2 \n (i32.const 1) \n ) \n (loop $label$1 \n (set_local $2 \n (i32.mul \n (get_local $0) (get_local $2) \n ) \n ) \n (set_local $0 \n (tee_local $1 (i32.add \n (get_local $0) (i32.const -1) \n ) \n ) \n ) \n (br_if $label$1 (get_local $1) \n ) \n ) \n (return \n (get_local $2)\n ) \n ) \n (i32.const 1) \n )\n)" }, { "code": null, "e": 3822, "s": 3731, "text": "Using the Wat2Wasm tool, you can view the WASM code, just like how it is mentioned below −" }, { "code": null, "e": 3961, "s": 3822, "text": "Developers are not supposed to write code in wasm or learn to code in it, as it is mostly generated when you compile high level languages." }, { "code": null, "e": 4088, "s": 3961, "text": "In WASM, all the instructions are pushed on to the stack. The arguments are popped and the result is pushed back to the stack." }, { "code": null, "e": 4157, "s": 4088, "text": "Consider the following WebAssembly Text format that adds 2 numbers −" }, { "code": null, "e": 4314, "s": 4157, "text": "(module\n (func $add (param $a i32) (param $b i32) (result i32) \n get_local $a \n get_local $b \n i32.add\n )\n (export \"add\" (func $add))\n)" }, { "code": null, "e": 4516, "s": 4314, "text": "The name of the function is $add, it takes in 2 params $a and $b. The result is a type 32-bit integer. The local variables are accessed using get_local and the add operation is performed using i32.add." }, { "code": null, "e": 4595, "s": 4516, "text": "The stack representation to add 2 numbers while execution will be as follows −" }, { "code": null, "e": 4704, "s": 4595, "text": "In step 1 − The execution of get_local $a instruction, the first parameters i.e., $a is pushed on the stack." }, { "code": null, "e": 4817, "s": 4704, "text": "In step 2 − During execution of get_local $b instruction, the second parameters i.e., $b is pushed on the stack." }, { "code": null, "e": 5022, "s": 4817, "text": "In step 3 − The execution of i32.add will pop the elements from the stack and will push the result back to the stack. The value that remains in the end inside the stack is the result of the function $add." }, { "code": null, "e": 5029, "s": 5022, "text": " Print" }, { "code": null, "e": 5040, "s": 5029, "text": " Add Notes" } ]
jQuery - ajaxStart( callback ) Method
The ajaxStart( callback ) method attaches a function to be executed whenever an AJAX request begins and there is none already active. This is an Ajax Event. Here is the simple syntax to use this method − $(document).ajaxStart( callback ) Here is the description of all the parameters used by this method − callback − The function to execute. callback − The function to execute. Assuming we have following HTML content in result.html file − <h1>THIS IS RESULT...</h1> Following is a simple example a simple showing the usage of this method. <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { /* Global variable */ var count = 0; $("#driver").click(function(event){ $('#stage1').load('result.html'); }); /* Gets called when request starts */ $(document).ajaxStart(function(){ count++; $("#stage2").html("<h1>Starts, Count :" + count + "</h1>"); }); /* Gets called when request complete */ $(document).ajaxComplete(function(event,request,set){ count++; $("#stage3").html("<h1>Completes,Count:" + count + "</h1>"); }); }); </script> </head> <body> <p>Click on the button to load result.html file:</p> <div id = "stage1" style = "background-color:blue;"> STAGE - 1 </div> <div id = "stage2" style = "background-color:blue;"> STAGE - 2 </div> <div id = "stage3" style = "background-color:blue;"> STAGE - 3 </div> <input type = "button" id = "driver" value = "Load Data" /> </body> </html> This will produce following result − Click on the button to load result.html file − 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2479, "s": 2322, "text": "The ajaxStart( callback ) method attaches a function to be executed whenever an AJAX request begins and there is none already active. This is an Ajax Event." }, { "code": null, "e": 2526, "s": 2479, "text": "Here is the simple syntax to use this method −" }, { "code": null, "e": 2561, "s": 2526, "text": "$(document).ajaxStart( callback )\n" }, { "code": null, "e": 2629, "s": 2561, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 2665, "s": 2629, "text": "callback − The function to execute." }, { "code": null, "e": 2701, "s": 2665, "text": "callback − The function to execute." }, { "code": null, "e": 2763, "s": 2701, "text": "Assuming we have following HTML content in result.html file −" }, { "code": null, "e": 2791, "s": 2763, "text": "<h1>THIS IS RESULT...</h1>\n" }, { "code": null, "e": 2864, "s": 2791, "text": "Following is a simple example a simple showing the usage of this method." }, { "code": null, "e": 4288, "s": 2864, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n /* Global variable */\n var count = 0;\n\n $(\"#driver\").click(function(event){\n $('#stage1').load('result.html');\n });\n\t\t\t\t\n /* Gets called when request starts */\n\t\t\t\t\n $(document).ajaxStart(function(){\n count++;\n $(\"#stage2\").html(\"<h1>Starts, Count :\" + count + \"</h1>\");\n });\n\t\t\t\t\n /* Gets called when request complete */\n $(document).ajaxComplete(function(event,request,set){\n count++;\n $(\"#stage3\").html(\"<h1>Completes,Count:\" + count + \"</h1>\");\n });\n\t\t\t\t\n });\n </script>\n </head>\n\t\n <body>\n <p>Click on the button to load result.html file:</p>\n\t\t\n <div id = \"stage1\" style = \"background-color:blue;\">\n STAGE - 1\n </div>\n\t\t\n <div id = \"stage2\" style = \"background-color:blue;\">\n STAGE - 2\n </div>\n\t\t\n <div id = \"stage3\" style = \"background-color:blue;\">\n STAGE - 3\n </div>\n\t\t\n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n </body>\n</html>" }, { "code": null, "e": 4325, "s": 4288, "text": "This will produce following result −" }, { "code": null, "e": 4372, "s": 4325, "text": "Click on the button to load result.html file −" }, { "code": null, "e": 4405, "s": 4372, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 4419, "s": 4405, "text": " Mahesh Kumar" }, { "code": null, "e": 4454, "s": 4419, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4468, "s": 4454, "text": " Pratik Singh" }, { "code": null, "e": 4503, "s": 4468, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4520, "s": 4503, "text": " Frahaan Hussain" }, { "code": null, "e": 4553, "s": 4520, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 4581, "s": 4553, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4614, "s": 4581, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 4635, "s": 4614, "text": " Sandip Bhattacharya" }, { "code": null, "e": 4667, "s": 4635, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 4684, "s": 4667, "text": " Laurence Svekis" }, { "code": null, "e": 4691, "s": 4684, "text": " Print" }, { "code": null, "e": 4702, "s": 4691, "text": " Add Notes" } ]
Adaptive Software Development (ASD) - GeeksforGeeks
20 Nov, 2021 Adaptive Software Development is a method to build complex software and system. ASD focuses on human collaboration and self-organization. ASD “life cycle” incorporates three phases namely: 1. Speculation 2. Collaboration 3. Learning These are explained as following below. 1. Speculation: During this phase project is initiated and planning is conducted. The project plan uses project initiation information like project requirements, user needs, customer mission statement, etc, to define set of release cycles that the project wants. 2. Collaboration: It is the difficult part of ASD as it needs the workers to be motivated. It collaborates communication and teamwork but emphasizes individualism as individual creativity plays a major role in creative thinking. People working together must trust each others to Criticize without animosity, Assist without resentment, Work as hard as possible, Possession of skill set, Communicate problems to find effective solution. 3. Learning: The workers may have a overestimate of their own understanding of the technology which may not lead to the desired result. Learning helps the workers to increase their level of understanding over the project. Learning process is of 3 ways: Focus groupsTechnical reviewsProject postmortem Focus groups Technical reviews Project postmortem ASD’s overall emphasis on the dynamics of self-organizing teams, interpersonal collaboration, and individual and team learning yield software project teams that have a much higher likelihood of success. singghakshay Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Software Engineering | Classical Waterfall Model Functional vs Non Functional Requirements Software Requirement Specification (SRS) Format Software Engineering | Requirements Engineering Process Differences between Verification and Validation Software Engineering | SDLC V-Model Levels in Data Flow Diagrams (DFD) Software Testing Life Cycle (STLC) Class Diagram for Library Management System Software Engineering | Iterative Waterfall Model
[ { "code": null, "e": 24205, "s": 24177, "text": "\n20 Nov, 2021" }, { "code": null, "e": 24395, "s": 24205, "text": "Adaptive Software Development is a method to build complex software and system. ASD focuses on human collaboration and self-organization. ASD “life cycle” incorporates three phases namely: " }, { "code": null, "e": 24440, "s": 24395, "text": "1. Speculation\n2. Collaboration\n3. Learning " }, { "code": null, "e": 24481, "s": 24440, "text": "These are explained as following below. " }, { "code": null, "e": 24745, "s": 24481, "text": "1. Speculation: During this phase project is initiated and planning is conducted. The project plan uses project initiation information like project requirements, user needs, customer mission statement, etc, to define set of release cycles that the project wants. " }, { "code": null, "e": 25026, "s": 24745, "text": "2. Collaboration: It is the difficult part of ASD as it needs the workers to be motivated. It collaborates communication and teamwork but emphasizes individualism as individual creativity plays a major role in creative thinking. People working together must trust each others to " }, { "code": null, "e": 25055, "s": 25026, "text": "Criticize without animosity," }, { "code": null, "e": 25082, "s": 25055, "text": "Assist without resentment," }, { "code": null, "e": 25108, "s": 25082, "text": "Work as hard as possible," }, { "code": null, "e": 25133, "s": 25108, "text": "Possession of skill set," }, { "code": null, "e": 25182, "s": 25133, "text": "Communicate problems to find effective solution." }, { "code": null, "e": 25436, "s": 25182, "text": "3. Learning: The workers may have a overestimate of their own understanding of the technology which may not lead to the desired result. Learning helps the workers to increase their level of understanding over the project. Learning process is of 3 ways: " }, { "code": null, "e": 25484, "s": 25436, "text": "Focus groupsTechnical reviewsProject postmortem" }, { "code": null, "e": 25497, "s": 25484, "text": "Focus groups" }, { "code": null, "e": 25515, "s": 25497, "text": "Technical reviews" }, { "code": null, "e": 25534, "s": 25515, "text": "Project postmortem" }, { "code": null, "e": 25738, "s": 25534, "text": "ASD’s overall emphasis on the dynamics of self-organizing teams, interpersonal collaboration, and individual and team learning yield software project teams that have a much higher likelihood of success. " }, { "code": null, "e": 25751, "s": 25738, "text": "singghakshay" }, { "code": null, "e": 25772, "s": 25751, "text": "Software Engineering" }, { "code": null, "e": 25870, "s": 25772, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25879, "s": 25870, "text": "Comments" }, { "code": null, "e": 25892, "s": 25879, "text": "Old Comments" }, { "code": null, "e": 25941, "s": 25892, "text": "Software Engineering | Classical Waterfall Model" }, { "code": null, "e": 25983, "s": 25941, "text": "Functional vs Non Functional Requirements" }, { "code": null, "e": 26031, "s": 25983, "text": "Software Requirement Specification (SRS) Format" }, { "code": null, "e": 26087, "s": 26031, "text": "Software Engineering | Requirements Engineering Process" }, { "code": null, "e": 26135, "s": 26087, "text": "Differences between Verification and Validation" }, { "code": null, "e": 26171, "s": 26135, "text": "Software Engineering | SDLC V-Model" }, { "code": null, "e": 26206, "s": 26171, "text": "Levels in Data Flow Diagrams (DFD)" }, { "code": null, "e": 26241, "s": 26206, "text": "Software Testing Life Cycle (STLC)" }, { "code": null, "e": 26285, "s": 26241, "text": "Class Diagram for Library Management System" } ]
Python - Extract Emails from Text
To extract emails form text, we can take of regular expression. In the below example we take help of the regular expression package to define the pattern of an email ID and then use the findall() function to retrieve those text which match this pattern. import re text = "Please contact us at [email protected] for further information."+\ " You can also give feedbacl at [email protected]" emails = re.findall(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+", text) print emails When we run the above program, we get the following output − ['[email protected]', '[email protected]'] 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2841, "s": 2587, "text": "To extract emails form text, we can take of regular expression. In the below example we take help of the regular expression package to define the pattern of an email ID and then use the findall() function to retrieve those text which match this pattern." }, { "code": null, "e": 3078, "s": 2841, "text": "import re\ntext = \"Please contact us at [email protected] for further information.\"+\\\n \" You can also give feedbacl at [email protected]\"\n\n\nemails = re.findall(r\"[a-z0-9\\.\\-+_]+@[a-z0-9\\.\\-+_]+\\.[a-z]+\", text)\nprint emails\n" }, { "code": null, "e": 3139, "s": 3078, "text": "When we run the above program, we get the following output −" }, { "code": null, "e": 3190, "s": 3139, "text": "['[email protected]', '[email protected]']\n" }, { "code": null, "e": 3227, "s": 3190, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3243, "s": 3227, "text": " Malhar Lathkar" }, { "code": null, "e": 3276, "s": 3243, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3295, "s": 3276, "text": " Arnab Chakraborty" }, { "code": null, "e": 3330, "s": 3295, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3352, "s": 3330, "text": " In28Minutes Official" }, { "code": null, "e": 3386, "s": 3352, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3414, "s": 3386, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3449, "s": 3414, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3463, "s": 3449, "text": " Lets Kode It" }, { "code": null, "e": 3496, "s": 3463, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3513, "s": 3496, "text": " Abhilash Nelson" }, { "code": null, "e": 3520, "s": 3513, "text": " Print" }, { "code": null, "e": 3531, "s": 3520, "text": " Add Notes" } ]
Tryit Editor v3.7
CSS Attr Selectors Tryit: The [attribute] selector
[ { "code": null, "e": 28, "s": 9, "text": "CSS Attr Selectors" } ]
Validate the first name and last name with Java Regular Expressions
In order to match the first name and last name using regular expression, we use the matches method in Java. The java.lang.String.matches() method returns a boolean value which depends on the matching of the String with the regular expression. Declaration −The java.lang.String.matches() method is declared as follows − public boolean matches(String regex) Let us see a program to validate the first name and last name with regular expressions − Live Demo public class Example { public static void main( String[] args ) { System.out.println(firstName("Tom")); System.out.println(lastName("hanks")); } // validate first name public static boolean firstName( String firstName ) { return firstName.matches( "[A-Z][a-z]*" ); } // validate last name public static boolean lastName( String lastName ) { return lastName.matches( "[A-Z]+([ '-][a-zA-Z]+)*" ); } } true false
[ { "code": null, "e": 1305, "s": 1062, "text": "In order to match the first name and last name using regular expression, we use the matches method in Java. The java.lang.String.matches() method returns a boolean value which depends on the matching of the String with the regular expression." }, { "code": null, "e": 1381, "s": 1305, "text": "Declaration −The java.lang.String.matches() method is declared as follows −" }, { "code": null, "e": 1418, "s": 1381, "text": "public boolean matches(String regex)" }, { "code": null, "e": 1507, "s": 1418, "text": "Let us see a program to validate the first name and last name with regular expressions −" }, { "code": null, "e": 1518, "s": 1507, "text": " Live Demo" }, { "code": null, "e": 1965, "s": 1518, "text": "public class Example {\n public static void main( String[] args ) {\n System.out.println(firstName(\"Tom\"));\n System.out.println(lastName(\"hanks\"));\n }\n // validate first name\n public static boolean firstName( String firstName ) {\n return firstName.matches( \"[A-Z][a-z]*\" );\n }\n // validate last name\n public static boolean lastName( String lastName ) {\n return lastName.matches( \"[A-Z]+([ '-][a-zA-Z]+)*\" );\n }\n}" }, { "code": null, "e": 1976, "s": 1965, "text": "true\nfalse" } ]
Create Different Types of Cells
How to create different types of cells in a spreadsheet using Java. Following is the program to create different types of cells in a spreadsheet using Java. import java.io.File; import java.io.FileOutputStream; import java.util.Date; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class TypesOfCellsInExcel { public static void main(String[] args)throws Exception { //Creating a Workbook XSSFWorkbook workbook = new XSSFWorkbook(); //Creating a Spread sheet XSSFSheet spreadsheet = workbook.createSheet("cell types"); XSSFRow row = spreadsheet.createRow((short) 2); row.createCell(0).setCellValue("Type of Cell"); row.createCell(1).setCellValue("cell value"); row = spreadsheet.createRow((short) 3); row.createCell(0).setCellValue("set cell type BLANK"); row.createCell(1); row = spreadsheet.createRow((short) 4); row.createCell(0).setCellValue("set cell type BOOLEAN"); row.createCell(1).setCellValue(true); row = spreadsheet.createRow((short) 5); row.createCell(0).setCellValue("set cell type ERROR"); row.createCell(1).setCellValue(XSSFCell.CELL_TYPE_ERROR ); row = spreadsheet.createRow((short) 6); row.createCell(0).setCellValue("set cell type date"); row.createCell(1).setCellValue(new Date()); row = spreadsheet.createRow((short) 7); row.createCell(0).setCellValue("set cell type numeric" ); row.createCell(1).setCellValue(20 ); row = spreadsheet.createRow((short) 8); row.createCell(0).setCellValue("set cell type string"); row.createCell(1).setCellValue("A String"); FileOutputStream out = new FileOutputStream(new File("typesofcells.xlsx")); workbook.write(out); out.close(); System.out.println("typesofcells.xlsx written successfully"); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2136, "s": 2068, "text": "How to create different types of cells in a spreadsheet using Java." }, { "code": null, "e": 2225, "s": 2136, "text": "Following is the program to create different types of cells in a spreadsheet using Java." }, { "code": null, "e": 4106, "s": 2225, "text": "import java.io.File;\nimport java.io.FileOutputStream;\n\nimport java.util.Date;\nimport org.apache.poi.xssf.usermodel.XSSFCell;\nimport org.apache.poi.xssf.usermodel.XSSFRow;\nimport org.apache.poi.xssf.usermodel.XSSFSheet;\nimport org.apache.poi.xssf.usermodel.XSSFWorkbook;\n\npublic class TypesOfCellsInExcel {\n public static void main(String[] args)throws Exception {\n\n //Creating a Workbook\n XSSFWorkbook workbook = new XSSFWorkbook();\n\n //Creating a Spread sheet\n XSSFSheet spreadsheet = workbook.createSheet(\"cell types\");\n XSSFRow row = spreadsheet.createRow((short) 2);\n\n row.createCell(0).setCellValue(\"Type of Cell\");\n row.createCell(1).setCellValue(\"cell value\");\n row = spreadsheet.createRow((short) 3);\n \n row.createCell(0).setCellValue(\"set cell type BLANK\");\n row.createCell(1);\n row = spreadsheet.createRow((short) 4);\n \n row.createCell(0).setCellValue(\"set cell type BOOLEAN\");\n row.createCell(1).setCellValue(true);\n row = spreadsheet.createRow((short) 5);\n \n row.createCell(0).setCellValue(\"set cell type ERROR\");\n row.createCell(1).setCellValue(XSSFCell.CELL_TYPE_ERROR );\n row = spreadsheet.createRow((short) 6);\n \n row.createCell(0).setCellValue(\"set cell type date\");\n row.createCell(1).setCellValue(new Date());\n row = spreadsheet.createRow((short) 7);\n \n row.createCell(0).setCellValue(\"set cell type numeric\" );\n row.createCell(1).setCellValue(20 );\n row = spreadsheet.createRow((short) 8);\n \n row.createCell(0).setCellValue(\"set cell type string\");\n row.createCell(1).setCellValue(\"A String\");\n \n FileOutputStream out = new FileOutputStream(new File(\"typesofcells.xlsx\"));\n workbook.write(out);\n out.close();\n System.out.println(\"typesofcells.xlsx written successfully\");\n }\n}" }, { "code": null, "e": 4113, "s": 4106, "text": " Print" }, { "code": null, "e": 4124, "s": 4113, "text": " Add Notes" } ]
ROC Curve explained using a COVID-19 hypothetical example: Binary & Multi-Class Classification tutorial | by Serafeim Loukas | Towards Data Science
In 99% of the cases where a machine learning classification model is used, people report its ROC curve plot (as well as the AUC: area under the ROC) along with other metrics such as the accuracy of the model or the confusion matrix. But what is a ROC curve? What does it tell us? Why everyone is using them? How is it connected to the confusion matrix? Continue reading and you will be able to answer all these questions. A receiver operating characteristic curve (ROC) curve is a plot that shows the diagnostic ability of a binary classifier as its discrimination threshold is varied. Before I dig into the details, we need to understand that this discrimination threshold is not the same across different models but instead it is model-specific. For instance, if we have a Support Vector Machine (SVC) then this threshold is nothing more than the bias term of the decision boundary equation. By varying the bias in a SVM model, we actually just change the position of the decision boundary. Have a look at my previously published SVM article for more details about the SVM models. The ROC curve is created by plotting the true positive rate (TPR) against the false positive rate (FPR) at various threshold settings. The true-positive rate is also known as sensitivity, recall or probability of detection in machine learning. The false-positive rate is also known as the probability of false alarm and can be calculated as (1−specificity). It tells us how well our model can distinguish the classes. A lot of terminology, right? Hold on a second, I will explain all these terms in the next section using an example that will make you always remember all these terms. Let’s imagine that we have a COVID-19 test that is able within seconds to tell us if one individual is affected by the virus or not. So the output of the test can be either Positive (affected) or Negative (not affected) — we have a binary classification case. Let’s also suppose that we know the ground truth and that we have 2 populations: a) people that are really affected (TP: True Positives, blue distribution in the figure below) and b) people that are not affected (TN: True Negatives, red distribution in the figure below) — binary classification case. So, as said before, we assume that we know the ground truth i.e. we really know who is sick and who is not. Next, we use our covid test and we define a threshold (let’s say 20). If the test value if above the threshold then the denote this person as affected (positive, covid-affected). On the other hand, if test value if below the threshold we then denote this person as non-affected (negative, covid-free). So, based on the output of the test, we can denote a person as affected (positive, blue population) or not affected (negative, red population). To digest all these, have a look at the figure below. But there is a catch! Our test cannot be perfect! Some people will be wrongly miss-classified as positive (covid-affected, we call this False Positives (FP)) or negative (covid-free, we call this False Negatives (FN)). True Positives (TP, blue distribution) are the people that truly have the COVID-19 virus. True Negatives (TN, red distribution) are the people that truly DO NOT have the COVID-19 virus. False Positives (FP) are the people that are truly NOT sick but based on the test, they were falsely (False) denoted as sick (Positives). False Negatives (FN) are the people that are truly sick but based on the test, they were falsely (False) denoted as NOT sick (Negative). For the perfect case, we would want high values TP and TN and zero FP and FN — this would be the perfect model with the perfect ROC curve. Now that we have understood the terms TP, TN, FP, FN let’s look back again at the definition of the ROC curve. The ROC curve is created by plotting the true positive rate (TPR) against the false positive rate (FPR) at various threshold settings. In other words, the ROC curve shows the trade-off of TPR and FPR for different threshold settings of the underlying model. If the curve is above the diagonal, the model is good and above chance (chance is 50% for a binary case). If the curve is below the diagonal, the model is bad. The AUC (area under the curve) indicates if the curve is above or below the diagonal (chance level). AUC ranges in value from 0 to 1. A model whose predictions are 100% wrong has an AUC of 0.0 and one whose predictions are 100% correct has an AUC of 1.0. Using all the above terms, we can also construct the famous confusion matrix that consists of these metrics and then we can compute the True Positive Rate and the False Positive Rate as shown in the figure below for a binary classification case. Having estimated the True Positive Rate and the False Positive Rate (using the formulas from the above table), we can now plot the ROC curve. But one moment! The True Positive Rate and the False Positive Rate are just 2 scalars. How can we really have a curve in the ROC plot? This is achieved by varying some threshold settings. The ROC curve shows the trade-off of TPR and FPR for different thresholds. For instance, in the case of a Support Vector Machine (SVC) this threshold is nothing more that the bias term in the decision boundary equation. So, we would vary this bias (this would change the position of the decision boundary) and estimate the FPR and TPR for the given values of the bias. To learn everything about SVMs have a look at this post. The ROC curve is only defined for binary classification problems. However, there is a way to integrate it into multi-class classification problems. To do so, if we have N classes then we will need to define several models. For example, if we have N=3 classes then we will need to define the following cases: case/model 1 for class 1 vs class 2, case/model 2 for class 1 vs class 2, and case/model 3 for class 1 vs class 3. Remember that in our Covid-19 test example, we had 2 possible outcomes i.e. affected by the virus (Positives) and not affected (Negatives). Similarly, in the multi-class cases, we again have to define the Positive and Negative outcomes. In the multi-class case, for each case the positive class is the second one: for case 1: “class 1 vs class 2”, the positive class is class 2 for case 2: “class 2 vs class 3”, the positive class is class 3 for case 3: “class 1 vs class 3”, the positive class is class 3 In other words, we can think of this as follows: We ask the classifier “Is this sample Positive or Negative?” and the classifier will predict the label (positive or negative). The ROC will be estimated for each case 1,2,3 independently. The same holds for the confusion matrix. We would have one Confusion Matrix for each case. Now, you should know everything about the ROC curve and the confusion matrix as well as you should be familiar with the terminology such as TP, TN, FP, FN, TPR, FPR. Let’s now build a python working example. In a previous post, I explained what an SVC is so here we will use such a model. In the iris dataset, we have 3 classes of flowers and 4 features in total. So the classification problem is not a binary case anymore since we have 3 classes. However, the following code will estimate and plot the ROC curve for our multi-class classification problem. To this end, the model will be used for class 1 vs class 2, class 2 vs class 3 and class 1 vs class 3. So, we have 3 cases at the end and within each case, the bias will be varied in order to get the ROC curve of the given case — so, 3 ROC curves as output. import matplotlib.pyplot as pltfrom sklearn import svm, datasetsfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import label_binarizefrom sklearn.metrics import roc_curve, aucfrom sklearn.multiclass import OneVsRestClassifierfrom itertools import cycleplt.style.use('ggplot') Let’s load the dataset, binarize the labels and split the data into training and test sets (to avoid ovefitting): # Load the iris datairis = datasets.load_iris()X = iris.datay = iris.target# Binarize the outputy_bin = label_binarize(y, classes=[0, 1, 2])n_classes = y_bin.shape[1]# We split the data into training and test setsX_train, X_test, y_train, y_test = train_test_split(X, y_bin, test_size= 0.5, random_state=0) Finally, we build our model (SVC) and we estimate the ROC curve for the 3 cases: class 1 vs class 2, class 2 vs class 3 and class 1 vs class 3. Each time the positive class is the second one i.e. for case 1: “class 1 vs class 2”, the positive class is class 2, for case 2: “class 2 vs class 3”, the positive class is class 3 etc. #We define the model as an SVC in OneVsRestClassifier setting.#this means that the model will be used for class 1 vs class 2, #class 2vs class 3 and class 1 vs class 3. So, we have 3 cases at #the end and within each case, the bias will be varied in order to #get the ROC curve of the given case - 3 ROC curves as output.classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True, random_state=0))y_score = classifier.fit(X_train, y_train).decision_function(X_test)# Plotting and estimation of FPR, TPRfpr = dict()tpr = dict()roc_auc = dict()for i in range(n_classes): fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i]) roc_auc[i] = auc(fpr[i], tpr[i])colors = cycle(['blue', 'red', 'green'])for i, color in zip(range(n_classes), colors): plt.plot(fpr[i], tpr[i], color=color, lw=1.5, label='ROC curve of class {0} (area = {1:0.2f})' ''.format(i+1, roc_auc[i]))plt.plot([0, 1], [0, 1], 'k-', lw=1.5)plt.xlim([-0.05, 1.0])plt.ylim([0.0, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver operating characteristic for multi-class data')plt.legend(loc="lower right")plt.show() Reminder: The ROC curve shows the trade-off of TPR and FPR for different threshold settings of the underlying model. If the curve is above the diagonal, the model is good and above chance (chance is 50% for a binary case). If the curve is below the diagonal, the model is bad. The AUC (area under the curve) indicates if the curve is above or below the diagonal (chance level). Now let’s also estimate the confusion matrix. from sklearn import svm, datasetsfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrix# Load the iris datairis = datasets.load_iris()X = iris.datay = iris.target# We split the data into training and test setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.5, random_state=0)# the modelclassifier_svc = svm.SVC(kernel='linear',random_state=0)# fit the model using the training setclassifier_svc.fit(X_train, y_train)# predict the labels/classes of the test sety_pred = classifier_svc.predict(X_test) Having the predicted y_predand the ground truth labels y_test, estimate the confusion matrix: # build the confusion matrixcnf_matrix = confusion_matrix(y_test, y_pred)print(cnf_matrix)#[[21 0 0]# [ 0 29 1]# [ 0 1 23]] We can see that we can really predict the labels/class of all 3 groups (values mostly on the diagonal meaning high True Positive (TP) rates). Reminder: The confusion matrix shows you the TN, TP, FN, FP. Values on the diagonal is the counting of TP so the higher these values the better the predictive ability of the model. That’s all folks! Hope you liked this article! towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com If you liked and found this article useful, follow me! Questions? Post them as a comment and I will reply as soon as possible. [1] https://en.wikipedia.org/wiki/Confusion_matrix [2] https://en.wikipedia.org/wiki/Support_vector_machine [3] https://en.wikipedia.org/wiki/Receiver_operating_characteristic [4] https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html LinkedIn: https://www.linkedin.com/in/serafeim-loukas/ ResearchGate: https://www.researchgate.net/profile/Serafeim_Loukas EPFL profile: https://people.epfl.ch/serafeim.loukas Stack Overflow: https://stackoverflow.com/users/5025009/seralouk
[ { "code": null, "e": 405, "s": 172, "text": "In 99% of the cases where a machine learning classification model is used, people report its ROC curve plot (as well as the AUC: area under the ROC) along with other metrics such as the accuracy of the model or the confusion matrix." }, { "code": null, "e": 594, "s": 405, "text": "But what is a ROC curve? What does it tell us? Why everyone is using them? How is it connected to the confusion matrix? Continue reading and you will be able to answer all these questions." }, { "code": null, "e": 758, "s": 594, "text": "A receiver operating characteristic curve (ROC) curve is a plot that shows the diagnostic ability of a binary classifier as its discrimination threshold is varied." }, { "code": null, "e": 1255, "s": 758, "text": "Before I dig into the details, we need to understand that this discrimination threshold is not the same across different models but instead it is model-specific. For instance, if we have a Support Vector Machine (SVC) then this threshold is nothing more than the bias term of the decision boundary equation. By varying the bias in a SVM model, we actually just change the position of the decision boundary. Have a look at my previously published SVM article for more details about the SVM models." }, { "code": null, "e": 1673, "s": 1255, "text": "The ROC curve is created by plotting the true positive rate (TPR) against the false positive rate (FPR) at various threshold settings. The true-positive rate is also known as sensitivity, recall or probability of detection in machine learning. The false-positive rate is also known as the probability of false alarm and can be calculated as (1−specificity). It tells us how well our model can distinguish the classes." }, { "code": null, "e": 1840, "s": 1673, "text": "A lot of terminology, right? Hold on a second, I will explain all these terms in the next section using an example that will make you always remember all these terms." }, { "code": null, "e": 2100, "s": 1840, "text": "Let’s imagine that we have a COVID-19 test that is able within seconds to tell us if one individual is affected by the virus or not. So the output of the test can be either Positive (affected) or Negative (not affected) — we have a binary classification case." }, { "code": null, "e": 2181, "s": 2100, "text": "Let’s also suppose that we know the ground truth and that we have 2 populations:" }, { "code": null, "e": 2280, "s": 2181, "text": "a) people that are really affected (TP: True Positives, blue distribution in the figure below) and" }, { "code": null, "e": 2401, "s": 2280, "text": "b) people that are not affected (TN: True Negatives, red distribution in the figure below) — binary classification case." }, { "code": null, "e": 2509, "s": 2401, "text": "So, as said before, we assume that we know the ground truth i.e. we really know who is sick and who is not." }, { "code": null, "e": 2955, "s": 2509, "text": "Next, we use our covid test and we define a threshold (let’s say 20). If the test value if above the threshold then the denote this person as affected (positive, covid-affected). On the other hand, if test value if below the threshold we then denote this person as non-affected (negative, covid-free). So, based on the output of the test, we can denote a person as affected (positive, blue population) or not affected (negative, red population)." }, { "code": null, "e": 3009, "s": 2955, "text": "To digest all these, have a look at the figure below." }, { "code": null, "e": 3059, "s": 3009, "text": "But there is a catch! Our test cannot be perfect!" }, { "code": null, "e": 3228, "s": 3059, "text": "Some people will be wrongly miss-classified as positive (covid-affected, we call this False Positives (FP)) or negative (covid-free, we call this False Negatives (FN))." }, { "code": null, "e": 3318, "s": 3228, "text": "True Positives (TP, blue distribution) are the people that truly have the COVID-19 virus." }, { "code": null, "e": 3414, "s": 3318, "text": "True Negatives (TN, red distribution) are the people that truly DO NOT have the COVID-19 virus." }, { "code": null, "e": 3552, "s": 3414, "text": "False Positives (FP) are the people that are truly NOT sick but based on the test, they were falsely (False) denoted as sick (Positives)." }, { "code": null, "e": 3689, "s": 3552, "text": "False Negatives (FN) are the people that are truly sick but based on the test, they were falsely (False) denoted as NOT sick (Negative)." }, { "code": null, "e": 3828, "s": 3689, "text": "For the perfect case, we would want high values TP and TN and zero FP and FN — this would be the perfect model with the perfect ROC curve." }, { "code": null, "e": 3939, "s": 3828, "text": "Now that we have understood the terms TP, TN, FP, FN let’s look back again at the definition of the ROC curve." }, { "code": null, "e": 4197, "s": 3939, "text": "The ROC curve is created by plotting the true positive rate (TPR) against the false positive rate (FPR) at various threshold settings. In other words, the ROC curve shows the trade-off of TPR and FPR for different threshold settings of the underlying model." }, { "code": null, "e": 4357, "s": 4197, "text": "If the curve is above the diagonal, the model is good and above chance (chance is 50% for a binary case). If the curve is below the diagonal, the model is bad." }, { "code": null, "e": 4612, "s": 4357, "text": "The AUC (area under the curve) indicates if the curve is above or below the diagonal (chance level). AUC ranges in value from 0 to 1. A model whose predictions are 100% wrong has an AUC of 0.0 and one whose predictions are 100% correct has an AUC of 1.0." }, { "code": null, "e": 4858, "s": 4612, "text": "Using all the above terms, we can also construct the famous confusion matrix that consists of these metrics and then we can compute the True Positive Rate and the False Positive Rate as shown in the figure below for a binary classification case." }, { "code": null, "e": 5016, "s": 4858, "text": "Having estimated the True Positive Rate and the False Positive Rate (using the formulas from the above table), we can now plot the ROC curve. But one moment!" }, { "code": null, "e": 5135, "s": 5016, "text": "The True Positive Rate and the False Positive Rate are just 2 scalars. How can we really have a curve in the ROC plot?" }, { "code": null, "e": 5263, "s": 5135, "text": "This is achieved by varying some threshold settings. The ROC curve shows the trade-off of TPR and FPR for different thresholds." }, { "code": null, "e": 5557, "s": 5263, "text": "For instance, in the case of a Support Vector Machine (SVC) this threshold is nothing more that the bias term in the decision boundary equation. So, we would vary this bias (this would change the position of the decision boundary) and estimate the FPR and TPR for the given values of the bias." }, { "code": null, "e": 5614, "s": 5557, "text": "To learn everything about SVMs have a look at this post." }, { "code": null, "e": 5837, "s": 5614, "text": "The ROC curve is only defined for binary classification problems. However, there is a way to integrate it into multi-class classification problems. To do so, if we have N classes then we will need to define several models." }, { "code": null, "e": 6037, "s": 5837, "text": "For example, if we have N=3 classes then we will need to define the following cases: case/model 1 for class 1 vs class 2, case/model 2 for class 1 vs class 2, and case/model 3 for class 1 vs class 3." }, { "code": null, "e": 6274, "s": 6037, "text": "Remember that in our Covid-19 test example, we had 2 possible outcomes i.e. affected by the virus (Positives) and not affected (Negatives). Similarly, in the multi-class cases, we again have to define the Positive and Negative outcomes." }, { "code": null, "e": 6351, "s": 6274, "text": "In the multi-class case, for each case the positive class is the second one:" }, { "code": null, "e": 6415, "s": 6351, "text": "for case 1: “class 1 vs class 2”, the positive class is class 2" }, { "code": null, "e": 6479, "s": 6415, "text": "for case 2: “class 2 vs class 3”, the positive class is class 3" }, { "code": null, "e": 6543, "s": 6479, "text": "for case 3: “class 1 vs class 3”, the positive class is class 3" }, { "code": null, "e": 6780, "s": 6543, "text": "In other words, we can think of this as follows: We ask the classifier “Is this sample Positive or Negative?” and the classifier will predict the label (positive or negative). The ROC will be estimated for each case 1,2,3 independently." }, { "code": null, "e": 6871, "s": 6780, "text": "The same holds for the confusion matrix. We would have one Confusion Matrix for each case." }, { "code": null, "e": 7079, "s": 6871, "text": "Now, you should know everything about the ROC curve and the confusion matrix as well as you should be familiar with the terminology such as TP, TN, FP, FN, TPR, FPR. Let’s now build a python working example." }, { "code": null, "e": 7160, "s": 7079, "text": "In a previous post, I explained what an SVC is so here we will use such a model." }, { "code": null, "e": 7428, "s": 7160, "text": "In the iris dataset, we have 3 classes of flowers and 4 features in total. So the classification problem is not a binary case anymore since we have 3 classes. However, the following code will estimate and plot the ROC curve for our multi-class classification problem." }, { "code": null, "e": 7686, "s": 7428, "text": "To this end, the model will be used for class 1 vs class 2, class 2 vs class 3 and class 1 vs class 3. So, we have 3 cases at the end and within each case, the bias will be varied in order to get the ROC curve of the given case — so, 3 ROC curves as output." }, { "code": null, "e": 7993, "s": 7686, "text": "import matplotlib.pyplot as pltfrom sklearn import svm, datasetsfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import label_binarizefrom sklearn.metrics import roc_curve, aucfrom sklearn.multiclass import OneVsRestClassifierfrom itertools import cycleplt.style.use('ggplot')" }, { "code": null, "e": 8107, "s": 7993, "text": "Let’s load the dataset, binarize the labels and split the data into training and test sets (to avoid ovefitting):" }, { "code": null, "e": 8414, "s": 8107, "text": "# Load the iris datairis = datasets.load_iris()X = iris.datay = iris.target# Binarize the outputy_bin = label_binarize(y, classes=[0, 1, 2])n_classes = y_bin.shape[1]# We split the data into training and test setsX_train, X_test, y_train, y_test = train_test_split(X, y_bin, test_size= 0.5, random_state=0)" }, { "code": null, "e": 8558, "s": 8414, "text": "Finally, we build our model (SVC) and we estimate the ROC curve for the 3 cases: class 1 vs class 2, class 2 vs class 3 and class 1 vs class 3." }, { "code": null, "e": 8744, "s": 8558, "text": "Each time the positive class is the second one i.e. for case 1: “class 1 vs class 2”, the positive class is class 2, for case 2: “class 2 vs class 3”, the positive class is class 3 etc." }, { "code": null, "e": 9891, "s": 8744, "text": "#We define the model as an SVC in OneVsRestClassifier setting.#this means that the model will be used for class 1 vs class 2, #class 2vs class 3 and class 1 vs class 3. So, we have 3 cases at #the end and within each case, the bias will be varied in order to #get the ROC curve of the given case - 3 ROC curves as output.classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True, random_state=0))y_score = classifier.fit(X_train, y_train).decision_function(X_test)# Plotting and estimation of FPR, TPRfpr = dict()tpr = dict()roc_auc = dict()for i in range(n_classes): fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i]) roc_auc[i] = auc(fpr[i], tpr[i])colors = cycle(['blue', 'red', 'green'])for i, color in zip(range(n_classes), colors): plt.plot(fpr[i], tpr[i], color=color, lw=1.5, label='ROC curve of class {0} (area = {1:0.2f})' ''.format(i+1, roc_auc[i]))plt.plot([0, 1], [0, 1], 'k-', lw=1.5)plt.xlim([-0.05, 1.0])plt.ylim([0.0, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver operating characteristic for multi-class data')plt.legend(loc=\"lower right\")plt.show()" }, { "code": null, "e": 10168, "s": 9891, "text": "Reminder: The ROC curve shows the trade-off of TPR and FPR for different threshold settings of the underlying model. If the curve is above the diagonal, the model is good and above chance (chance is 50% for a binary case). If the curve is below the diagonal, the model is bad." }, { "code": null, "e": 10269, "s": 10168, "text": "The AUC (area under the curve) indicates if the curve is above or below the diagonal (chance level)." }, { "code": null, "e": 10315, "s": 10269, "text": "Now let’s also estimate the confusion matrix." }, { "code": null, "e": 10880, "s": 10315, "text": "from sklearn import svm, datasetsfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrix# Load the iris datairis = datasets.load_iris()X = iris.datay = iris.target# We split the data into training and test setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.5, random_state=0)# the modelclassifier_svc = svm.SVC(kernel='linear',random_state=0)# fit the model using the training setclassifier_svc.fit(X_train, y_train)# predict the labels/classes of the test sety_pred = classifier_svc.predict(X_test)" }, { "code": null, "e": 10974, "s": 10880, "text": "Having the predicted y_predand the ground truth labels y_test, estimate the confusion matrix:" }, { "code": null, "e": 11102, "s": 10974, "text": "# build the confusion matrixcnf_matrix = confusion_matrix(y_test, y_pred)print(cnf_matrix)#[[21 0 0]# [ 0 29 1]# [ 0 1 23]]" }, { "code": null, "e": 11244, "s": 11102, "text": "We can see that we can really predict the labels/class of all 3 groups (values mostly on the diagonal meaning high True Positive (TP) rates)." }, { "code": null, "e": 11425, "s": 11244, "text": "Reminder: The confusion matrix shows you the TN, TP, FN, FP. Values on the diagonal is the counting of TP so the higher these values the better the predictive ability of the model." }, { "code": null, "e": 11472, "s": 11425, "text": "That’s all folks! Hope you liked this article!" }, { "code": null, "e": 11495, "s": 11472, "text": "towardsdatascience.com" }, { "code": null, "e": 11518, "s": 11495, "text": "towardsdatascience.com" }, { "code": null, "e": 11541, "s": 11518, "text": "towardsdatascience.com" }, { "code": null, "e": 11564, "s": 11541, "text": "towardsdatascience.com" }, { "code": null, "e": 11587, "s": 11564, "text": "towardsdatascience.com" }, { "code": null, "e": 11642, "s": 11587, "text": "If you liked and found this article useful, follow me!" }, { "code": null, "e": 11714, "s": 11642, "text": "Questions? Post them as a comment and I will reply as soon as possible." }, { "code": null, "e": 11765, "s": 11714, "text": "[1] https://en.wikipedia.org/wiki/Confusion_matrix" }, { "code": null, "e": 11822, "s": 11765, "text": "[2] https://en.wikipedia.org/wiki/Support_vector_machine" }, { "code": null, "e": 11890, "s": 11822, "text": "[3] https://en.wikipedia.org/wiki/Receiver_operating_characteristic" }, { "code": null, "e": 11965, "s": 11890, "text": "[4] https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html" }, { "code": null, "e": 12020, "s": 11965, "text": "LinkedIn: https://www.linkedin.com/in/serafeim-loukas/" }, { "code": null, "e": 12087, "s": 12020, "text": "ResearchGate: https://www.researchgate.net/profile/Serafeim_Loukas" }, { "code": null, "e": 12140, "s": 12087, "text": "EPFL profile: https://people.epfl.ch/serafeim.loukas" } ]
How to animate a scatter plot in Matplotlib?
Using the FuncAnimation method of matplotlib, we can animate the diagram. We can pass a user defined method where we will be changing the position of the particles, and at the end, we will return plot type. Get the particle's initial position, velocity, force, and size. Get the particle's initial position, velocity, force, and size. Create a new figure, or activate an existing figure with figsize = (7, 7). Create a new figure, or activate an existing figure with figsize = (7, 7). Add an axes to the current figure and make it the current axes, with xlim and ylim. Add an axes to the current figure and make it the current axes, with xlim and ylim. Plot scatter for initial position of the particles. Plot scatter for initial position of the particles. Make an animation by repeatedly calling a function *func*. We can pass a user-defined method that helps to change the position of particles, into the FuncAnimation class. Make an animation by repeatedly calling a function *func*. We can pass a user-defined method that helps to change the position of particles, into the FuncAnimation class. Using plt.show(), show the figure. Using plt.show(), show the figure. import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import numpy as np dt = 0.005 n=20 L = 1 particles=np.zeros(n,dtype=[("position", float , 2), ("velocity", float ,2), ("force", float ,2), ("size", float , 1)]) particles["position"]=np.random.uniform(0,L,(n,2)); particles["velocity"]=np.zeros((n,2)); particles["size"]=0.5*np.ones(n); fig = plt.figure(figsize=(7,7)) ax = plt.axes(xlim=(0,L),ylim=(0,L)) scatter=ax.scatter(particles["position"][:,0], particles["position"][:,1]) def update(frame_number): particles["force"]=np.random.uniform(-2,2.,(n,2)); particles["velocity"] = particles["velocity"] + particles["force"]*dt particles["position"] = particles["position"] + particles["velocity"]*dt particles["position"] = particles["position"]%L scatter.set_offsets(particles["position"]) return scatter, anim = FuncAnimation(fig, update, interval=10) plt.show()
[ { "code": null, "e": 1269, "s": 1062, "text": "Using the FuncAnimation method of matplotlib, we can animate the diagram. We can pass a user defined method where we will be changing the position of the particles, and at the end, we will return plot type." }, { "code": null, "e": 1333, "s": 1269, "text": "Get the particle's initial position, velocity, force, and size." }, { "code": null, "e": 1397, "s": 1333, "text": "Get the particle's initial position, velocity, force, and size." }, { "code": null, "e": 1472, "s": 1397, "text": "Create a new figure, or activate an existing figure with figsize = (7, 7)." }, { "code": null, "e": 1547, "s": 1472, "text": "Create a new figure, or activate an existing figure with figsize = (7, 7)." }, { "code": null, "e": 1631, "s": 1547, "text": "Add an axes to the current figure and make it the current axes, with xlim and ylim." }, { "code": null, "e": 1715, "s": 1631, "text": "Add an axes to the current figure and make it the current axes, with xlim and ylim." }, { "code": null, "e": 1767, "s": 1715, "text": "Plot scatter for initial position of the particles." }, { "code": null, "e": 1819, "s": 1767, "text": "Plot scatter for initial position of the particles." }, { "code": null, "e": 1990, "s": 1819, "text": "Make an animation by repeatedly calling a function *func*. We can pass a user-defined method that helps to change the position of particles, into the FuncAnimation class." }, { "code": null, "e": 2161, "s": 1990, "text": "Make an animation by repeatedly calling a function *func*. We can pass a user-defined method that helps to change the position of particles, into the FuncAnimation class." }, { "code": null, "e": 2196, "s": 2161, "text": "Using plt.show(), show the figure." }, { "code": null, "e": 2231, "s": 2196, "text": "Using plt.show(), show the figure." }, { "code": null, "e": 3230, "s": 2231, "text": "import matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nimport numpy as np\n\ndt = 0.005\nn=20\nL = 1\nparticles=np.zeros(n,dtype=[(\"position\", float , 2),\n (\"velocity\", float ,2),\n (\"force\", float ,2),\n (\"size\", float , 1)])\n\nparticles[\"position\"]=np.random.uniform(0,L,(n,2));\nparticles[\"velocity\"]=np.zeros((n,2));\nparticles[\"size\"]=0.5*np.ones(n);\n\nfig = plt.figure(figsize=(7,7))\nax = plt.axes(xlim=(0,L),ylim=(0,L))\nscatter=ax.scatter(particles[\"position\"][:,0], particles[\"position\"][:,1])\n\ndef update(frame_number):\n particles[\"force\"]=np.random.uniform(-2,2.,(n,2));\n particles[\"velocity\"] = particles[\"velocity\"] + particles[\"force\"]*dt\n particles[\"position\"] = particles[\"position\"] + particles[\"velocity\"]*dt\n\n particles[\"position\"] = particles[\"position\"]%L\n scatter.set_offsets(particles[\"position\"])\n return scatter,\n\nanim = FuncAnimation(fig, update, interval=10)\nplt.show()" } ]
MomentJS - Checking current locale
We can check the current locale using moment.locale(). moment.locale(); moment.locale('fr'); var k = moment.locale(); moment.locale('fr'); var k = moment.locale(); moment.locale('ja'); var s = moment.locale(); moment.locales() gives the list of all the locales available for use or which are loaded. Observe the following line of code and its output − moment.locales() In the above example, we are using thelocale.min.js with all locales, so moment.locales() displays all the locales as shown above. Print Add Notes Bookmark this page
[ { "code": null, "e": 2015, "s": 1960, "text": "We can check the current locale using moment.locale()." }, { "code": null, "e": 2033, "s": 2015, "text": "moment.locale();\n" }, { "code": null, "e": 2079, "s": 2033, "text": "moment.locale('fr');\nvar k = moment.locale();" }, { "code": null, "e": 2171, "s": 2079, "text": "moment.locale('fr');\nvar k = moment.locale();\nmoment.locale('ja');\nvar s = moment.locale();" }, { "code": null, "e": 2313, "s": 2171, "text": "moment.locales() gives the list of all the locales available for use or which are loaded. Observe the following line of code and its output −" }, { "code": null, "e": 2330, "s": 2313, "text": "moment.locales()" }, { "code": null, "e": 2461, "s": 2330, "text": "In the above example, we are using thelocale.min.js with all locales, so moment.locales() displays all the locales as shown above." }, { "code": null, "e": 2468, "s": 2461, "text": " Print" }, { "code": null, "e": 2479, "s": 2468, "text": " Add Notes" } ]
Most Frequent Number in Intervals in C++
Suppose we have a list of lists of integers intervals where each element has interval like [start, end]. We have to find the most frequently occurred number in the intervals. If there are ties, then return the smallest number. So, if the input is like [[2, 5],[4, 6],[7, 10],[8, 10]], then the output will be 4 To solve this, we will follow these steps − Define one map m Define one map m cnt := 0, val := 0 cnt := 0, val := 0 for each value it in x −(increase m[it[0]] by 1)decrease m[it[1] + 1] by 1 for each value it in x − (increase m[it[0]] by 1) (increase m[it[0]] by 1) decrease m[it[1] + 1] by 1 decrease m[it[1] + 1] by 1 last := 0 last := 0 for each key it in mlast := last + value of itif last > cnt, then:cnt := lastval := it for each key it in m last := last + value of it last := last + value of it if last > cnt, then:cnt := lastval := it if last > cnt, then: cnt := last cnt := last val := it val := it return val return val Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int solve(vector<vector<int>>& x) { map <int, int> m; int cnt = 0; int val = 0; for(auto& it : x){ m[it[0]]++; m[it[1] + 1]--; } int last = 0; for(auto& it : m){ last += it.second; if(last > cnt){ cnt = last; val = it.first; } } return val; } }; main() { Solution ob; vector<vector<int>> v = {{2, 5},{4, 6},{7, 10},{8, 10}}; cout << ob.solve(v); } {{2, 5},{4, 6},{7, 10},{8, 10}} 4
[ { "code": null, "e": 1289, "s": 1062, "text": "Suppose we have a list of lists of integers intervals where each element has interval like [start, end]. We have to find the most frequently occurred number in the intervals. If there are ties, then return the smallest number." }, { "code": null, "e": 1373, "s": 1289, "text": "So, if the input is like [[2, 5],[4, 6],[7, 10],[8, 10]], then the output will be 4" }, { "code": null, "e": 1417, "s": 1373, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1434, "s": 1417, "text": "Define one map m" }, { "code": null, "e": 1451, "s": 1434, "text": "Define one map m" }, { "code": null, "e": 1470, "s": 1451, "text": "cnt := 0, val := 0" }, { "code": null, "e": 1489, "s": 1470, "text": "cnt := 0, val := 0" }, { "code": null, "e": 1564, "s": 1489, "text": "for each value it in x −(increase m[it[0]] by 1)decrease m[it[1] + 1] by 1" }, { "code": null, "e": 1589, "s": 1564, "text": "for each value it in x −" }, { "code": null, "e": 1614, "s": 1589, "text": "(increase m[it[0]] by 1)" }, { "code": null, "e": 1639, "s": 1614, "text": "(increase m[it[0]] by 1)" }, { "code": null, "e": 1666, "s": 1639, "text": "decrease m[it[1] + 1] by 1" }, { "code": null, "e": 1693, "s": 1666, "text": "decrease m[it[1] + 1] by 1" }, { "code": null, "e": 1703, "s": 1693, "text": "last := 0" }, { "code": null, "e": 1713, "s": 1703, "text": "last := 0" }, { "code": null, "e": 1800, "s": 1713, "text": "for each key it in mlast := last + value of itif last > cnt, then:cnt := lastval := it" }, { "code": null, "e": 1821, "s": 1800, "text": "for each key it in m" }, { "code": null, "e": 1848, "s": 1821, "text": "last := last + value of it" }, { "code": null, "e": 1875, "s": 1848, "text": "last := last + value of it" }, { "code": null, "e": 1916, "s": 1875, "text": "if last > cnt, then:cnt := lastval := it" }, { "code": null, "e": 1937, "s": 1916, "text": "if last > cnt, then:" }, { "code": null, "e": 1949, "s": 1937, "text": "cnt := last" }, { "code": null, "e": 1961, "s": 1949, "text": "cnt := last" }, { "code": null, "e": 1971, "s": 1961, "text": "val := it" }, { "code": null, "e": 1981, "s": 1971, "text": "val := it" }, { "code": null, "e": 1992, "s": 1981, "text": "return val" }, { "code": null, "e": 2003, "s": 1992, "text": "return val" }, { "code": null, "e": 2073, "s": 2003, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2084, "s": 2073, "text": " Live Demo" }, { "code": null, "e": 2644, "s": 2084, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int solve(vector<vector<int>>& x) {\n map <int, int> m;\n int cnt = 0;\n int val = 0;\n for(auto& it : x){\n m[it[0]]++;\n m[it[1] + 1]--;\n }\n int last = 0;\n for(auto& it : m){\n last += it.second;\n if(last > cnt){\n cnt = last;\n val = it.first;\n }\n }\n return val;\n }\n};\nmain() {\n Solution ob;\n vector<vector<int>> v = {{2, 5},{4, 6},{7, 10},{8, 10}};\n cout << ob.solve(v);\n}" }, { "code": null, "e": 2676, "s": 2644, "text": "{{2, 5},{4, 6},{7, 10},{8, 10}}" }, { "code": null, "e": 2678, "s": 2676, "text": "4" } ]
Transform nested array into normal array with JavaScript?
Let’s say the following is our nested array − const arrayObject = [ [ { Name: "John" }, { countryName: "US" } ], [ { subjectName: "JavaScript" }, { teacherName: "Mike" } ] ]; To transform nested array into normal array, use the concept of flat() as in the below code − const arrayObject = [ [ { Name: "John" }, { countryName: "US" } ], [ { subjectName: "JavaScript" }, { teacherName: "Mike" } ] ]; const output = arrayObject.flat(); console.log(output); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo50.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo50.js [ { Name: 'John' }, { countryName: 'US' }, { subjectName: 'JavaScript' }, { teacherName: 'Mike' } ]
[ { "code": null, "e": 1108, "s": 1062, "text": "Let’s say the following is our nested array −" }, { "code": null, "e": 1333, "s": 1108, "text": "const arrayObject = [\n [\n {\n Name: \"John\"\n },\n {\n countryName: \"US\"\n }\n ],\n [\n {\n subjectName: \"JavaScript\"\n },\n {\n teacherName: \"Mike\"\n }\n ]\n];" }, { "code": null, "e": 1427, "s": 1333, "text": "To transform nested array into normal array, use the concept of flat() as in the below code −" }, { "code": null, "e": 1708, "s": 1427, "text": "const arrayObject = [\n [\n {\n Name: \"John\"\n },\n {\n countryName: \"US\"\n }\n ],\n [\n {\n subjectName: \"JavaScript\"\n },\n {\n teacherName: \"Mike\"\n }\n ]\n];\nconst output = arrayObject.flat();\nconsole.log(output);" }, { "code": null, "e": 1774, "s": 1708, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1792, "s": 1774, "text": "node fileName.js." }, { "code": null, "e": 1825, "s": 1792, "text": "Here, my file name is demo50.js." }, { "code": null, "e": 1866, "s": 1825, "text": "This will produce the following output −" }, { "code": null, "e": 2027, "s": 1866, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo50.js\n[\n { Name: 'John' },\n { countryName: 'US' },\n { subjectName: 'JavaScript' },\n { teacherName: 'Mike' }\n]" } ]
How to MySQL SELECT by month?
To select by month, use MONTH() function. Let us first create a table − mysql> create table DemoTable1599 -> ( -> Shippingdate datetime -> ); Query OK, 0 rows affected (0.78 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1599 values('2019-10-21'); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable1599 values('2018-12-12'); Query OK, 1 row affected (0.35 sec) mysql> insert into DemoTable1599 values('2015-11-21'); Query OK, 1 row affected (0.34 sec) mysql> insert into DemoTable1599 values('2017-12-31'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable1599 values('2018-12-26'); Query OK, 1 row affected (0.17 sec) Display all records from the table using select statement − mysql> select * from DemoTable1599; This will produce the following output − +---------------------+ | Shippingdate | +---------------------+ | 2019-10-21 00:00:00 | | 2018-12-12 00:00:00 | | 2015-11-21 00:00:00 | | 2017-12-31 00:00:00 | | 2018-12-26 00:00:00 | +---------------------+ 5 rows in set (0.00 sec) Following is the query to SELECT by month − mysql> select * from DemoTable1599 -> where month(Shippingdate)=12; This will produce the following output − +---------------------+ | Shippingdate | +---------------------+ | 2018-12-12 00:00:00 | | 2017-12-31 00:00:00 | | 2018-12-26 00:00:00 | +---------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1134, "s": 1062, "text": "To select by month, use MONTH() function. Let us first create a table −" }, { "code": null, "e": 1250, "s": 1134, "text": "mysql> create table DemoTable1599\n -> (\n -> Shippingdate datetime\n -> );\nQuery OK, 0 rows affected (0.78 sec)" }, { "code": null, "e": 1306, "s": 1250, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1761, "s": 1306, "text": "mysql> insert into DemoTable1599 values('2019-10-21');\nQuery OK, 1 row affected (0.28 sec)\nmysql> insert into DemoTable1599 values('2018-12-12');\nQuery OK, 1 row affected (0.35 sec)\nmysql> insert into DemoTable1599 values('2015-11-21');\nQuery OK, 1 row affected (0.34 sec)\nmysql> insert into DemoTable1599 values('2017-12-31');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable1599 values('2018-12-26');\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 1821, "s": 1761, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1857, "s": 1821, "text": "mysql> select * from DemoTable1599;" }, { "code": null, "e": 1898, "s": 1857, "text": "This will produce the following output −" }, { "code": null, "e": 2139, "s": 1898, "text": "+---------------------+\n| Shippingdate |\n+---------------------+\n| 2019-10-21 00:00:00 |\n| 2018-12-12 00:00:00 |\n| 2015-11-21 00:00:00 |\n| 2017-12-31 00:00:00 |\n| 2018-12-26 00:00:00 |\n+---------------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2183, "s": 2139, "text": "Following is the query to SELECT by month −" }, { "code": null, "e": 2254, "s": 2183, "text": "mysql> select * from DemoTable1599\n -> where month(Shippingdate)=12;" }, { "code": null, "e": 2295, "s": 2254, "text": "This will produce the following output −" }, { "code": null, "e": 2488, "s": 2295, "text": "+---------------------+\n| Shippingdate |\n+---------------------+\n| 2018-12-12 00:00:00 |\n| 2017-12-31 00:00:00 |\n| 2018-12-26 00:00:00 |\n+---------------------+\n3 rows in set (0.00 sec)" } ]
C# program to count number of bytes in an array
Set a byte array − byte[] b = { 5, 9, 19, 23, 29, 35, 55, 78 }; To count number of bytes − Buffer.ByteLength(b) The following is the code − Live Demo using System; class Program { static void Main() { byte[] b = { 5, 9, 19, 23, 29, 35, 55, 78 }; int len = Buffer.ByteLength(b); for (int i = 0; i < len; i++) { Console.WriteLine(b[i]); } Console.WriteLine("Length of byte array = "+len); } } 5 9 19 23 29 35 55 78 Length of byte array = 8
[ { "code": null, "e": 1081, "s": 1062, "text": "Set a byte array −" }, { "code": null, "e": 1126, "s": 1081, "text": "byte[] b = { 5, 9, 19, 23, 29, 35, 55, 78 };" }, { "code": null, "e": 1153, "s": 1126, "text": "To count number of bytes −" }, { "code": null, "e": 1174, "s": 1153, "text": "Buffer.ByteLength(b)" }, { "code": null, "e": 1202, "s": 1174, "text": "The following is the code −" }, { "code": null, "e": 1213, "s": 1202, "text": " Live Demo" }, { "code": null, "e": 1499, "s": 1213, "text": "using System;\nclass Program {\n static void Main() {\n byte[] b = { 5, 9, 19, 23, 29, 35, 55, 78 };\n int len = Buffer.ByteLength(b);\n for (int i = 0; i < len; i++) {\n Console.WriteLine(b[i]);\n }\n Console.WriteLine(\"Length of byte array = \"+len);\n }\n}" }, { "code": null, "e": 1546, "s": 1499, "text": "5\n9\n19\n23\n29\n35\n55\n78\nLength of byte array = 8" } ]
Reinforcement Learning in a few lines of code | by Maarten Grootendorst | Towards Data Science
Reinforcement learning has seen major improvements over the last year with state-of-the-art methods coming out on a bi-monthly basis. We have seen AlphaGo beat world champion Go player Ke Jie, Multi-Agents play Hide and Seek, and even AlphaStar competitively hold its own in Starcraft. Implementing these algorithms can be quite challenging as it requires a good understanding of both Deep Learning and Reinforcement Learning. The purpose of this article is to give you a quick start using some neat packages such that you can easily start with Reinforcement Learning. For in-depth tutorials on how to implement SOTA Deep Reinforcement Learning algorithms, please see this and this. They are highly recommended! Before we can start implementing these algorithms we first need to create an environment to work in, namely the games. It is important for the algorithm to understand what is action and observation space. For that, we will go into several packages that can be used for selecting interesting environments. Gym is a toolkit for developing and comparing reinforcement learning algorithms. It is typically used for experimentation and research purposes as it provides a simple to use interface for working with environments. Simply install the package with: pip install gym. After doing so, you can create an environment using the following code: import gymenv = gym.make(‘CartPole-v0’) In the CartPole environment, you are tasked with preventing a pole, attached by an un-actuated joint to a cart, from falling over. The env variable contains information about the environment (the game). To understand what the action space is of CartPole, simply run env.action_space which will yield Discrete(2). This means that there are two discrete actions possible. To view the observation space you run env.observation_spacewhich yields Box(4). This box represents theCartesian product of n (4) closed intervals. To render the game, run the following piece of code: We can see that the cart is constantly failing if we choose to take random actions. Eventually, the goal will be to run a Reinforcement Learning algorithm that will learn how to solve this problem. For a full list of environments in Gym, please see this. NOTE: If you have a problem running the atari games, please see this. Another option for creating interesting environments is to use Retro. This package is developed by OpenAI and allows you to use ROMS to emulate games such as Airstriker-Genesis. Simply install the package with pip install gym-retro. Then, we can create and view environments with: import retroenv = retro.make(game='Airstriker-Genesis') Again, to render the game, run the following piece of code: To install ROMS you need to find the corresponding .sha files and then run: python3 -m retro.import /path/to/your/ROMs/directory/ NOTE: For a full list of readily available environments, run retro.data.list_games(). A typical problem with Reinforcement Learning is that the resulting algorithms often work very well with specific environments, but fail to learn any generalizable skills. For example, what if we were to change how a game looks or how the enemy responds? To solve this problem OpenAI developed a package called Procgen, which allows creating procedurally-generated environments. We can use this package to measure how quickly a Reinforcement Learning Agent learns generalizable skills. Rendering the game is straightforward: This will generate a single level on which the algorithm can be trained. There are several options available to procedurally generate many different versions of the same environment: num_levels - The number of unique levels that can be generated distribution_mode - What variant of the levels to use, the options are "easy", "hard", "extreme", "memory", "exploration". All games support "easy" and "hard", while other options are game-specific. Now, it is finally time for the actual Reinforcement Learning. Although there are many packages available that can be used to train the algorithms, I will be mostly going into Stable Baselines due to their solid implementations. Note that I will not be explaining how the RL-algorithms actually work in this post as that would require an entirely new post in itself. For an overview of state-of-the-art algorithms such as PPO, SAC, and TD3 please see this or this. Stable Baselines (SB) is based upon OpenAI Baselines and is meant to make it easier for the research community and industry to replicate, refine, and identify new ideas. They improved upon on Baselines to make a more stable and simple tool that allows beginners to experiment with Reinforcement Learning without being buried in implementation details. SB is often used due to its easy and quick application of state-of-the-art Reinforcement Learning Algorithms. Moreover, only a few lines of code are necessary to create and train RL-models. Installation can simply be done with: pip install stable-baselines. Then, to create and learn an RL-model, for example, PPO2, we run the following lines of code: There are a few things that might need some explanation: total_timesteps - The total number of samples to train on MlpPolicy - The Policy object that implements actor-critic. In this case, a Multi-layer Perceptron with 2 layers of 64. There are also policies for visual information such as a CnnPolicy or even CnnLstmPolicy In order to apply this model to the CartPole example, we need to wrap our environment in a Dummy to make it available to SB. The full example of training PPO2 on the CartPole environment is then as follows: As we can see in the image above, in only 50,000 steps PPO2 has managed to find out a way to keep the pole stable. This required only a few lines of code and a couple of minutes of processing! If you want to apply this to Procgen or Retro, make sure to select a policy that allows for a Convolution-based network as the observation space is likely to be the image of the current state of the environment. Finally, the CartPole example is an extremely simple one which makes it possible to train it only 50,000 steps. Most other environments typically take tens of millions of steps before showing significant improvements. NOTE: The authors of Stable Baselines warn beginners to get a good understanding when it comes to Reinforcement Learning before using the package in productions. There are many crucial components of Reinforcement Learning that if any of them go wrong, the algorithm will fail and likely leaves very little explanation. There are several other packages that are frequently used to apply RL-algorithms: TF-Agents - Requires significant more coding than Stable-Baselines, but is often the go-to package for research in Reinforcement Learning. MinimalRL - State-of-the-art RL-algorithms implemented in Pytorch with very minimal code. It definitely helps in understanding the algorithms. DeepRL - Another Pytorch implementation, but this version also has additional environments implemented to be used. MlAgents - An open-source Unity plugin that enables games and simulations to serve as environments for training agents. Reinforcement Learning can be a tricky subject as it is difficult to debug if and when something is going wrong in your code. Hopefully, this post helped you get started with Reinforcement Learning. All code can be found in: github.com If you are, like me, passionate about AI, Data Science or Psychology, please feel free to add me on LinkedIn.
[ { "code": null, "e": 332, "s": 46, "text": "Reinforcement learning has seen major improvements over the last year with state-of-the-art methods coming out on a bi-monthly basis. We have seen AlphaGo beat world champion Go player Ke Jie, Multi-Agents play Hide and Seek, and even AlphaStar competitively hold its own in Starcraft." }, { "code": null, "e": 615, "s": 332, "text": "Implementing these algorithms can be quite challenging as it requires a good understanding of both Deep Learning and Reinforcement Learning. The purpose of this article is to give you a quick start using some neat packages such that you can easily start with Reinforcement Learning." }, { "code": null, "e": 758, "s": 615, "text": "For in-depth tutorials on how to implement SOTA Deep Reinforcement Learning algorithms, please see this and this. They are highly recommended!" }, { "code": null, "e": 1063, "s": 758, "text": "Before we can start implementing these algorithms we first need to create an environment to work in, namely the games. It is important for the algorithm to understand what is action and observation space. For that, we will go into several packages that can be used for selecting interesting environments." }, { "code": null, "e": 1279, "s": 1063, "text": "Gym is a toolkit for developing and comparing reinforcement learning algorithms. It is typically used for experimentation and research purposes as it provides a simple to use interface for working with environments." }, { "code": null, "e": 1401, "s": 1279, "text": "Simply install the package with: pip install gym. After doing so, you can create an environment using the following code:" }, { "code": null, "e": 1441, "s": 1401, "text": "import gymenv = gym.make(‘CartPole-v0’)" }, { "code": null, "e": 1572, "s": 1441, "text": "In the CartPole environment, you are tasked with preventing a pole, attached by an un-actuated joint to a cart, from falling over." }, { "code": null, "e": 1959, "s": 1572, "text": "The env variable contains information about the environment (the game). To understand what the action space is of CartPole, simply run env.action_space which will yield Discrete(2). This means that there are two discrete actions possible. To view the observation space you run env.observation_spacewhich yields Box(4). This box represents theCartesian product of n (4) closed intervals." }, { "code": null, "e": 2012, "s": 1959, "text": "To render the game, run the following piece of code:" }, { "code": null, "e": 2210, "s": 2012, "text": "We can see that the cart is constantly failing if we choose to take random actions. Eventually, the goal will be to run a Reinforcement Learning algorithm that will learn how to solve this problem." }, { "code": null, "e": 2267, "s": 2210, "text": "For a full list of environments in Gym, please see this." }, { "code": null, "e": 2337, "s": 2267, "text": "NOTE: If you have a problem running the atari games, please see this." }, { "code": null, "e": 2515, "s": 2337, "text": "Another option for creating interesting environments is to use Retro. This package is developed by OpenAI and allows you to use ROMS to emulate games such as Airstriker-Genesis." }, { "code": null, "e": 2618, "s": 2515, "text": "Simply install the package with pip install gym-retro. Then, we can create and view environments with:" }, { "code": null, "e": 2674, "s": 2618, "text": "import retroenv = retro.make(game='Airstriker-Genesis')" }, { "code": null, "e": 2734, "s": 2674, "text": "Again, to render the game, run the following piece of code:" }, { "code": null, "e": 2810, "s": 2734, "text": "To install ROMS you need to find the corresponding .sha files and then run:" }, { "code": null, "e": 2864, "s": 2810, "text": "python3 -m retro.import /path/to/your/ROMs/directory/" }, { "code": null, "e": 2950, "s": 2864, "text": "NOTE: For a full list of readily available environments, run retro.data.list_games()." }, { "code": null, "e": 3205, "s": 2950, "text": "A typical problem with Reinforcement Learning is that the resulting algorithms often work very well with specific environments, but fail to learn any generalizable skills. For example, what if we were to change how a game looks or how the enemy responds?" }, { "code": null, "e": 3436, "s": 3205, "text": "To solve this problem OpenAI developed a package called Procgen, which allows creating procedurally-generated environments. We can use this package to measure how quickly a Reinforcement Learning Agent learns generalizable skills." }, { "code": null, "e": 3475, "s": 3436, "text": "Rendering the game is straightforward:" }, { "code": null, "e": 3658, "s": 3475, "text": "This will generate a single level on which the algorithm can be trained. There are several options available to procedurally generate many different versions of the same environment:" }, { "code": null, "e": 3721, "s": 3658, "text": "num_levels - The number of unique levels that can be generated" }, { "code": null, "e": 3920, "s": 3721, "text": "distribution_mode - What variant of the levels to use, the options are \"easy\", \"hard\", \"extreme\", \"memory\", \"exploration\". All games support \"easy\" and \"hard\", while other options are game-specific." }, { "code": null, "e": 4149, "s": 3920, "text": "Now, it is finally time for the actual Reinforcement Learning. Although there are many packages available that can be used to train the algorithms, I will be mostly going into Stable Baselines due to their solid implementations." }, { "code": null, "e": 4385, "s": 4149, "text": "Note that I will not be explaining how the RL-algorithms actually work in this post as that would require an entirely new post in itself. For an overview of state-of-the-art algorithms such as PPO, SAC, and TD3 please see this or this." }, { "code": null, "e": 4737, "s": 4385, "text": "Stable Baselines (SB) is based upon OpenAI Baselines and is meant to make it easier for the research community and industry to replicate, refine, and identify new ideas. They improved upon on Baselines to make a more stable and simple tool that allows beginners to experiment with Reinforcement Learning without being buried in implementation details." }, { "code": null, "e": 4927, "s": 4737, "text": "SB is often used due to its easy and quick application of state-of-the-art Reinforcement Learning Algorithms. Moreover, only a few lines of code are necessary to create and train RL-models." }, { "code": null, "e": 5089, "s": 4927, "text": "Installation can simply be done with: pip install stable-baselines. Then, to create and learn an RL-model, for example, PPO2, we run the following lines of code:" }, { "code": null, "e": 5146, "s": 5089, "text": "There are a few things that might need some explanation:" }, { "code": null, "e": 5204, "s": 5146, "text": "total_timesteps - The total number of samples to train on" }, { "code": null, "e": 5413, "s": 5204, "text": "MlpPolicy - The Policy object that implements actor-critic. In this case, a Multi-layer Perceptron with 2 layers of 64. There are also policies for visual information such as a CnnPolicy or even CnnLstmPolicy" }, { "code": null, "e": 5620, "s": 5413, "text": "In order to apply this model to the CartPole example, we need to wrap our environment in a Dummy to make it available to SB. The full example of training PPO2 on the CartPole environment is then as follows:" }, { "code": null, "e": 5813, "s": 5620, "text": "As we can see in the image above, in only 50,000 steps PPO2 has managed to find out a way to keep the pole stable. This required only a few lines of code and a couple of minutes of processing!" }, { "code": null, "e": 6025, "s": 5813, "text": "If you want to apply this to Procgen or Retro, make sure to select a policy that allows for a Convolution-based network as the observation space is likely to be the image of the current state of the environment." }, { "code": null, "e": 6243, "s": 6025, "text": "Finally, the CartPole example is an extremely simple one which makes it possible to train it only 50,000 steps. Most other environments typically take tens of millions of steps before showing significant improvements." }, { "code": null, "e": 6562, "s": 6243, "text": "NOTE: The authors of Stable Baselines warn beginners to get a good understanding when it comes to Reinforcement Learning before using the package in productions. There are many crucial components of Reinforcement Learning that if any of them go wrong, the algorithm will fail and likely leaves very little explanation." }, { "code": null, "e": 6644, "s": 6562, "text": "There are several other packages that are frequently used to apply RL-algorithms:" }, { "code": null, "e": 6783, "s": 6644, "text": "TF-Agents - Requires significant more coding than Stable-Baselines, but is often the go-to package for research in Reinforcement Learning." }, { "code": null, "e": 6926, "s": 6783, "text": "MinimalRL - State-of-the-art RL-algorithms implemented in Pytorch with very minimal code. It definitely helps in understanding the algorithms." }, { "code": null, "e": 7041, "s": 6926, "text": "DeepRL - Another Pytorch implementation, but this version also has additional environments implemented to be used." }, { "code": null, "e": 7161, "s": 7041, "text": "MlAgents - An open-source Unity plugin that enables games and simulations to serve as environments for training agents." }, { "code": null, "e": 7360, "s": 7161, "text": "Reinforcement Learning can be a tricky subject as it is difficult to debug if and when something is going wrong in your code. Hopefully, this post helped you get started with Reinforcement Learning." }, { "code": null, "e": 7386, "s": 7360, "text": "All code can be found in:" }, { "code": null, "e": 7397, "s": 7386, "text": "github.com" } ]
Python Program for Binary Insertion Sort
In this article, we will learn about the solution to the problem statement given below. Problem statement − We are given an array, we need to sort it using the concept of binary insertion sort. Here as the name suggests, we use the concept of the binary search along with the insertion sort algorithm. Now let’s observe the solution in the implementation below − Live Demo # sort def insertion_sort(arr): for i in range(1, len(arr)): temp = arr[i] pos = binary_search(arr, temp, 0, i) + 1 for k in range(i, pos, -1): arr[k] = arr[k - 1] arr[pos] = temp def binary_search(arr, key, start, end): #key if end - start <= 1: if key < arr[start]: return start - 1 else: return start mid = (start + end)//2 if arr[mid] < key: return binary_search(arr, key, mid, end) elif arr[mid] > key: return binary_search(arr, key, start, mid) else: return mid # main arr = [1,5,3,4,8,6,3,4] n = len(arr) insertion_sort(arr) print("Sorted array is:") for i in range(n): print(arr[i],end=" ") Sorted array is : 1 3 3 4 4 5 5 6 8 All the variables are declared in the local scope and their references are seen in the figure above. In this article, we have learned about how we can make a Python Program for Binary Insertion Sort
[ { "code": null, "e": 1150, "s": 1062, "text": "In this article, we will learn about the solution to the problem statement given below." }, { "code": null, "e": 1256, "s": 1150, "text": "Problem statement − We are given an array, we need to sort it using the concept of binary insertion sort." }, { "code": null, "e": 1364, "s": 1256, "text": "Here as the name suggests, we use the concept of the binary search along with the insertion sort algorithm." }, { "code": null, "e": 1425, "s": 1364, "text": "Now let’s observe the solution in the implementation below −" }, { "code": null, "e": 1436, "s": 1425, "text": " Live Demo" }, { "code": null, "e": 2140, "s": 1436, "text": "# sort\ndef insertion_sort(arr):\n for i in range(1, len(arr)):\n temp = arr[i]\n pos = binary_search(arr, temp, 0, i) + 1\n for k in range(i, pos, -1):\n arr[k] = arr[k - 1]\n arr[pos] = temp\ndef binary_search(arr, key, start, end):\n #key\n if end - start <= 1:\n if key < arr[start]:\n return start - 1\n else:\n return start\n mid = (start + end)//2\n if arr[mid] < key:\n return binary_search(arr, key, mid, end)\n elif arr[mid] > key:\n return binary_search(arr, key, start, mid)\n else:\n return mid\n# main\narr = [1,5,3,4,8,6,3,4]\nn = len(arr)\ninsertion_sort(arr)\nprint(\"Sorted array is:\")\nfor i in range(n):\n print(arr[i],end=\" \")" }, { "code": null, "e": 2176, "s": 2140, "text": "Sorted array is :\n1 3 3 4 4 5 5 6 8" }, { "code": null, "e": 2277, "s": 2176, "text": "All the variables are declared in the local scope and their references are seen in the figure above." }, { "code": null, "e": 2375, "s": 2277, "text": "In this article, we have learned about how we can make a Python Program for Binary Insertion Sort" } ]
Anomaly Detection for Dummies. Unsupervised Anomaly Detection for... | by Susan Li | Towards Data Science
Anomaly detection is the process of identifying unexpected items or events in data sets, which differ from the norm. And anomaly detection is often applied on unlabeled data which is known as unsupervised anomaly detection. Anomaly detection has two basic assumptions: Anomalies only occur very rarely in the data. Their features differ from the normal instances significantly. Before we get to Multivariate anomaly detection, I think its necessary to work through a simple example of Univariate anomaly detection method in which we detect outliers from a distribution of values in a single feature space. We are using the Super Store Sales data set that can be downloaded from here, and we are going to find patterns in Sales and Profit separately that do not conform to expected behavior. That is, spotting outliers for one variable at a time. import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport matplotlibfrom sklearn.ensemble import IsolationForest df = pd.read_excel("Superstore.xls")df['Sales'].describe() plt.scatter(range(df.shape[0]), np.sort(df['Sales'].values))plt.xlabel('index')plt.ylabel('Sales')plt.title("Sales distribution")sns.despine() sns.distplot(df['Sales'])plt.title("Distribution of Sales")sns.despine() print("Skewness: %f" % df['Sales'].skew())print("Kurtosis: %f" % df['Sales'].kurt()) The Superstore’s sales distribution is far from a normal distribution, and it has a positive long thin tail, the mass of the distribution is concentrated on the left of the figure. And the tail sales distribution far exceeds the tails of the normal distribution. There are one region where the data has low probability to appear which is on the right side of the distribution. df['Profit'].describe() plt.scatter(range(df.shape[0]), np.sort(df['Profit'].values))plt.xlabel('index')plt.ylabel('Profit')plt.title("Profit distribution")sns.despine() sns.distplot(df['Profit'])plt.title("Distribution of Profit")sns.despine() print("Skewness: %f" % df['Profit'].skew())print("Kurtosis: %f" % df['Profit'].kurt()) The Superstore’s Profit distribution has both a positive tail and negative tail. However, the positive tail is longer than the negative tail. So the distribution is positive skewed, and the data are heavy-tailed or profusion of outliers. There are two regions where the data has low probability to appear: one on the right side of the distribution, another one on the left. Isolation Forest is an algorithm to detect outliers that returns the anomaly score of each sample using the IsolationForest algorithm which is based on the fact that anomalies are data points that are few and different. Isolation Forest is a tree-based model. In these trees, partitions are created by first randomly selecting a feature and then selecting a random split value between the minimum and maximum value of the selected feature. The following process shows how IsolationForest behaves in the case of the Susperstore’s sales, and the algorithm was implemented in Sklearn and the code was largely borrowed from this tutorial Trained IsolationForest using the Sales data. Store the Sales in the NumPy array for using in our models later. Computed the anomaly score for each observation. The anomaly score of an input sample is computed as the mean anomaly score of the trees in the forest. Classified each observation as an outlier or non-outlier. The visualization highlights the regions where the outliers fall. According to the above results and visualization, It seems that Sales that exceeds 1000 would be definitely considered as an outlier. df.iloc[10] This purchase seems normal to me expect it was a larger amount of sales compared with the other orders in the data. Trained IsolationForest using the Profit variable. Store the Profit in the NumPy array for using in our models later. Computed the anomaly score for each observation. The anomaly score of an input sample is computed as the mean anomaly score of the trees in the forest. Classified each observation as an outlier or non-outlier. The visualization highlights the regions where the outliers fall. According to the above results and visualization, It seems that Profit that below -100 or exceeds 100 would be considered as an outlier, let’s visually examine one example each that determined by our model and to see whether they make sense. df.iloc[3] Any negative profit would be an anomaly and should be further investigate, this goes without saying df.iloc[1] Our model determined that this order with a large profit is an anomaly. However, when we investigate this order, it could be just a product that has a relatively high margin. The above two visualizations show the anomaly scores and highlighted the regions where the outliers are. As expected, the anomaly score reflects the shape of the underlying distribution and the outlier regions correspond to low probability areas. However, Univariate analysis can only get us thus far. We may realize that some of these anomalies that determined by our models are not the anomalies we expected. When our data is multidimensional as opposed to univariate, the approaches to anomaly detection become more computationally intensive and more mathematically complex. Most of the analysis that we end up doing are multivariate due to complexity of the world we are living in. In multivariate anomaly detection, outlier is a combined unusual score on at least two variables. So, using the Sales and Profit variables, we are going to build an unsupervised multivariate anomaly detection method based on several models. We are using PyOD which is a Python library for detecting anomalies in multivariate data. The library was developed by Yue Zhao. When we are in business, we expect that Sales & Profit are positive correlated. If some of the Sales data points and Profit data points are not positive correlated, they would be considered as outliers and need to be further investigated. sns.regplot(x="Sales", y="Profit", data=df)sns.despine(); From the above correlation chart, we can see that some of the data points are obvious outliers such as extreme low and extreme high values. The CBLOF calculates the outlier score based on cluster-based local outlier factor. An anomaly score is computed by the distance of each instance to its cluster center multiplied by the instances belonging to its cluster. PyOD library includes the CBLOF implementation. The following code are borrowed from PyOD tutorial combined with this article. Scaling Sales and Profit to between zero and one. Arbitrarily set outliers fraction as 1% based on trial and best guess. Fit the data to the CBLOF model and predict the results. Use threshold value to consider a data point is inlier or outlier. Use decision function to calculate the anomaly score for every point. HBOS assumes the feature independence and calculates the degree of anomalies by building histograms. In multivariate anomaly detection, a histogram for each single feature can be computed, scored individually and combined at the end. When using PyOD library, the code are very similar with the CBLOF. Isolation Forest is similar in principle to Random Forest and is built on the basis of decision trees. Isolation Forest isolates observations by randomly selecting a feature and then randomly selecting a split value between the maximum and minimum values of that selected feature. The PyOD Isolation Forest module is a wrapper of Scikit-learn Isolation Forest with more functionalities. KNN is one of the simplest methods in anomaly detection. For a data point, its distance to its kth nearest neighbor could be viewed as the outlier score. The anomalies predicted by the above four algorithms were not very different. We may want to investigate each of the outliers that determined by our model, for example, let’s look in details for a couple of outliers that determined by KNN, and try to understand what make them anomalies. df.iloc[1995] For this particular order, a customer purchased 5 products with total price at 294.62 and profit at lower than -766, with 80% discount. It seems like a clearance. We should be aware of the loss for each product we sell. df.iloc[9649] For this purchase, it seems to me that the profit at around 4.7% is too small and the model determined that this order is an anomaly. df.iloc[9270] For the above order, a customer purchased 6 product at 4305 in total price, after 20% discount, we still get over 33% of the profit. We would love to have more of these kind of anomalies. Jupyter notebook for the above analysis can be found on Github. Enjoy the rest of the week.
[ { "code": null, "e": 440, "s": 171, "text": "Anomaly detection is the process of identifying unexpected items or events in data sets, which differ from the norm. And anomaly detection is often applied on unlabeled data which is known as unsupervised anomaly detection. Anomaly detection has two basic assumptions:" }, { "code": null, "e": 486, "s": 440, "text": "Anomalies only occur very rarely in the data." }, { "code": null, "e": 549, "s": 486, "text": "Their features differ from the normal instances significantly." }, { "code": null, "e": 777, "s": 549, "text": "Before we get to Multivariate anomaly detection, I think its necessary to work through a simple example of Univariate anomaly detection method in which we detect outliers from a distribution of values in a single feature space." }, { "code": null, "e": 1017, "s": 777, "text": "We are using the Super Store Sales data set that can be downloaded from here, and we are going to find patterns in Sales and Profit separately that do not conform to expected behavior. That is, spotting outliers for one variable at a time." }, { "code": null, "e": 1168, "s": 1017, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport matplotlibfrom sklearn.ensemble import IsolationForest" }, { "code": null, "e": 1227, "s": 1168, "text": "df = pd.read_excel(\"Superstore.xls\")df['Sales'].describe()" }, { "code": null, "e": 1370, "s": 1227, "text": "plt.scatter(range(df.shape[0]), np.sort(df['Sales'].values))plt.xlabel('index')plt.ylabel('Sales')plt.title(\"Sales distribution\")sns.despine()" }, { "code": null, "e": 1443, "s": 1370, "text": "sns.distplot(df['Sales'])plt.title(\"Distribution of Sales\")sns.despine()" }, { "code": null, "e": 1528, "s": 1443, "text": "print(\"Skewness: %f\" % df['Sales'].skew())print(\"Kurtosis: %f\" % df['Sales'].kurt())" }, { "code": null, "e": 1791, "s": 1528, "text": "The Superstore’s sales distribution is far from a normal distribution, and it has a positive long thin tail, the mass of the distribution is concentrated on the left of the figure. And the tail sales distribution far exceeds the tails of the normal distribution." }, { "code": null, "e": 1905, "s": 1791, "text": "There are one region where the data has low probability to appear which is on the right side of the distribution." }, { "code": null, "e": 1929, "s": 1905, "text": "df['Profit'].describe()" }, { "code": null, "e": 2075, "s": 1929, "text": "plt.scatter(range(df.shape[0]), np.sort(df['Profit'].values))plt.xlabel('index')plt.ylabel('Profit')plt.title(\"Profit distribution\")sns.despine()" }, { "code": null, "e": 2150, "s": 2075, "text": "sns.distplot(df['Profit'])plt.title(\"Distribution of Profit\")sns.despine()" }, { "code": null, "e": 2237, "s": 2150, "text": "print(\"Skewness: %f\" % df['Profit'].skew())print(\"Kurtosis: %f\" % df['Profit'].kurt())" }, { "code": null, "e": 2475, "s": 2237, "text": "The Superstore’s Profit distribution has both a positive tail and negative tail. However, the positive tail is longer than the negative tail. So the distribution is positive skewed, and the data are heavy-tailed or profusion of outliers." }, { "code": null, "e": 2611, "s": 2475, "text": "There are two regions where the data has low probability to appear: one on the right side of the distribution, another one on the left." }, { "code": null, "e": 3051, "s": 2611, "text": "Isolation Forest is an algorithm to detect outliers that returns the anomaly score of each sample using the IsolationForest algorithm which is based on the fact that anomalies are data points that are few and different. Isolation Forest is a tree-based model. In these trees, partitions are created by first randomly selecting a feature and then selecting a random split value between the minimum and maximum value of the selected feature." }, { "code": null, "e": 3245, "s": 3051, "text": "The following process shows how IsolationForest behaves in the case of the Susperstore’s sales, and the algorithm was implemented in Sklearn and the code was largely borrowed from this tutorial" }, { "code": null, "e": 3291, "s": 3245, "text": "Trained IsolationForest using the Sales data." }, { "code": null, "e": 3357, "s": 3291, "text": "Store the Sales in the NumPy array for using in our models later." }, { "code": null, "e": 3509, "s": 3357, "text": "Computed the anomaly score for each observation. The anomaly score of an input sample is computed as the mean anomaly score of the trees in the forest." }, { "code": null, "e": 3567, "s": 3509, "text": "Classified each observation as an outlier or non-outlier." }, { "code": null, "e": 3633, "s": 3567, "text": "The visualization highlights the regions where the outliers fall." }, { "code": null, "e": 3767, "s": 3633, "text": "According to the above results and visualization, It seems that Sales that exceeds 1000 would be definitely considered as an outlier." }, { "code": null, "e": 3779, "s": 3767, "text": "df.iloc[10]" }, { "code": null, "e": 3895, "s": 3779, "text": "This purchase seems normal to me expect it was a larger amount of sales compared with the other orders in the data." }, { "code": null, "e": 3946, "s": 3895, "text": "Trained IsolationForest using the Profit variable." }, { "code": null, "e": 4013, "s": 3946, "text": "Store the Profit in the NumPy array for using in our models later." }, { "code": null, "e": 4165, "s": 4013, "text": "Computed the anomaly score for each observation. The anomaly score of an input sample is computed as the mean anomaly score of the trees in the forest." }, { "code": null, "e": 4223, "s": 4165, "text": "Classified each observation as an outlier or non-outlier." }, { "code": null, "e": 4289, "s": 4223, "text": "The visualization highlights the regions where the outliers fall." }, { "code": null, "e": 4531, "s": 4289, "text": "According to the above results and visualization, It seems that Profit that below -100 or exceeds 100 would be considered as an outlier, let’s visually examine one example each that determined by our model and to see whether they make sense." }, { "code": null, "e": 4542, "s": 4531, "text": "df.iloc[3]" }, { "code": null, "e": 4642, "s": 4542, "text": "Any negative profit would be an anomaly and should be further investigate, this goes without saying" }, { "code": null, "e": 4653, "s": 4642, "text": "df.iloc[1]" }, { "code": null, "e": 4828, "s": 4653, "text": "Our model determined that this order with a large profit is an anomaly. However, when we investigate this order, it could be just a product that has a relatively high margin." }, { "code": null, "e": 5075, "s": 4828, "text": "The above two visualizations show the anomaly scores and highlighted the regions where the outliers are. As expected, the anomaly score reflects the shape of the underlying distribution and the outlier regions correspond to low probability areas." }, { "code": null, "e": 5406, "s": 5075, "text": "However, Univariate analysis can only get us thus far. We may realize that some of these anomalies that determined by our models are not the anomalies we expected. When our data is multidimensional as opposed to univariate, the approaches to anomaly detection become more computationally intensive and more mathematically complex." }, { "code": null, "e": 5612, "s": 5406, "text": "Most of the analysis that we end up doing are multivariate due to complexity of the world we are living in. In multivariate anomaly detection, outlier is a combined unusual score on at least two variables." }, { "code": null, "e": 5755, "s": 5612, "text": "So, using the Sales and Profit variables, we are going to build an unsupervised multivariate anomaly detection method based on several models." }, { "code": null, "e": 5884, "s": 5755, "text": "We are using PyOD which is a Python library for detecting anomalies in multivariate data. The library was developed by Yue Zhao." }, { "code": null, "e": 6123, "s": 5884, "text": "When we are in business, we expect that Sales & Profit are positive correlated. If some of the Sales data points and Profit data points are not positive correlated, they would be considered as outliers and need to be further investigated." }, { "code": null, "e": 6181, "s": 6123, "text": "sns.regplot(x=\"Sales\", y=\"Profit\", data=df)sns.despine();" }, { "code": null, "e": 6321, "s": 6181, "text": "From the above correlation chart, we can see that some of the data points are obvious outliers such as extreme low and extreme high values." }, { "code": null, "e": 6591, "s": 6321, "text": "The CBLOF calculates the outlier score based on cluster-based local outlier factor. An anomaly score is computed by the distance of each instance to its cluster center multiplied by the instances belonging to its cluster. PyOD library includes the CBLOF implementation." }, { "code": null, "e": 6670, "s": 6591, "text": "The following code are borrowed from PyOD tutorial combined with this article." }, { "code": null, "e": 6720, "s": 6670, "text": "Scaling Sales and Profit to between zero and one." }, { "code": null, "e": 6791, "s": 6720, "text": "Arbitrarily set outliers fraction as 1% based on trial and best guess." }, { "code": null, "e": 6848, "s": 6791, "text": "Fit the data to the CBLOF model and predict the results." }, { "code": null, "e": 6915, "s": 6848, "text": "Use threshold value to consider a data point is inlier or outlier." }, { "code": null, "e": 6985, "s": 6915, "text": "Use decision function to calculate the anomaly score for every point." }, { "code": null, "e": 7286, "s": 6985, "text": "HBOS assumes the feature independence and calculates the degree of anomalies by building histograms. In multivariate anomaly detection, a histogram for each single feature can be computed, scored individually and combined at the end. When using PyOD library, the code are very similar with the CBLOF." }, { "code": null, "e": 7567, "s": 7286, "text": "Isolation Forest is similar in principle to Random Forest and is built on the basis of decision trees. Isolation Forest isolates observations by randomly selecting a feature and then randomly selecting a split value between the maximum and minimum values of that selected feature." }, { "code": null, "e": 7673, "s": 7567, "text": "The PyOD Isolation Forest module is a wrapper of Scikit-learn Isolation Forest with more functionalities." }, { "code": null, "e": 7827, "s": 7673, "text": "KNN is one of the simplest methods in anomaly detection. For a data point, its distance to its kth nearest neighbor could be viewed as the outlier score." }, { "code": null, "e": 7905, "s": 7827, "text": "The anomalies predicted by the above four algorithms were not very different." }, { "code": null, "e": 8115, "s": 7905, "text": "We may want to investigate each of the outliers that determined by our model, for example, let’s look in details for a couple of outliers that determined by KNN, and try to understand what make them anomalies." }, { "code": null, "e": 8129, "s": 8115, "text": "df.iloc[1995]" }, { "code": null, "e": 8349, "s": 8129, "text": "For this particular order, a customer purchased 5 products with total price at 294.62 and profit at lower than -766, with 80% discount. It seems like a clearance. We should be aware of the loss for each product we sell." }, { "code": null, "e": 8363, "s": 8349, "text": "df.iloc[9649]" }, { "code": null, "e": 8497, "s": 8363, "text": "For this purchase, it seems to me that the profit at around 4.7% is too small and the model determined that this order is an anomaly." }, { "code": null, "e": 8511, "s": 8497, "text": "df.iloc[9270]" }, { "code": null, "e": 8699, "s": 8511, "text": "For the above order, a customer purchased 6 product at 4305 in total price, after 20% discount, we still get over 33% of the profit. We would love to have more of these kind of anomalies." } ]
Generate random string/characters in JavaScript?
To generate random string/ characters in JavaScript, use Math.random(). We are generating 6 random characters here from the following characters − 'ABCDEFGHIJKLMNOabcdefghijklmnopqrstuvwxyzPQRSTUVWXYZ'; Following is the code − function generateRandomNumber(numberOfCharacters) { var randomValues = ''; var stringValues = 'ABCDEFGHIJKLMNOabcdefghijklmnopqrstuvwxyzPQRSTUVWXYZ'; var sizeOfCharacter = stringValues.length; for (var i = 0; i < numberOfCharacters; i++) { randomValues = randomValues+stringValues.charAt(Math.floor(Math.random() * sizeOfCharacter)); } return randomValues; } console.log(generateRandomNumber(6)); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo270.js. This will produce the following output on console − PS C:\Users\Amit\javascript-code> node demo270.js qIcoCT
[ { "code": null, "e": 1209, "s": 1062, "text": "To generate random string/ characters in JavaScript, use Math.random(). We are generating 6 random characters here from the following characters −" }, { "code": null, "e": 1265, "s": 1209, "text": "'ABCDEFGHIJKLMNOabcdefghijklmnopqrstuvwxyzPQRSTUVWXYZ';" }, { "code": null, "e": 1289, "s": 1265, "text": "Following is the code −" }, { "code": null, "e": 1712, "s": 1289, "text": "function generateRandomNumber(numberOfCharacters) {\n var randomValues = '';\n var stringValues = 'ABCDEFGHIJKLMNOabcdefghijklmnopqrstuvwxyzPQRSTUVWXYZ'; \n var sizeOfCharacter = stringValues.length; \nfor (var i = 0; i < numberOfCharacters; i++) {\n randomValues = randomValues+stringValues.charAt(Math.floor(Math.random() * sizeOfCharacter));\n }\n return randomValues;\n} \nconsole.log(generateRandomNumber(6));" }, { "code": null, "e": 1778, "s": 1712, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1796, "s": 1778, "text": "node fileName.js." }, { "code": null, "e": 1830, "s": 1796, "text": "Here, my file name is demo270.js." }, { "code": null, "e": 1882, "s": 1830, "text": "This will produce the following output on console −" }, { "code": null, "e": 1939, "s": 1882, "text": "PS C:\\Users\\Amit\\javascript-code> node demo270.js\nqIcoCT" } ]
sympy.stats.FDistribution() in python - GeeksforGeeks
05 Jun, 2020 With the help of sympy.stats.FDistribution() method, we can get the continuous random variable representing the F distribution. Syntax : sympy.stats.FDistribution(name, d1, d2)Where, d1 and d2 denotes the degree of freedom.Return : Return continuous random variable. Example #1 :In this example we can see that by using sympy.stats.FDistribution() method, we are able to get the continuous random variable which represents the F distribution by using this method. # Import sympy and FDistributionfrom sympy.stats import FDistribution, densityfrom sympy import Symbol d1 = Symbol("d1", integer = True, positive = True)d2 = Symbol("d2", integer = True, positive = True)z = Symbol("z") # Using sympy.stats.FDistribution() methodX = FDistribution("x", d1, d2)gfg = density(X)(z) pprint(gfg) Output : d2— ______________________________2 / d1 -d1 – d2d2 *\/ (d1*z) *(d1*z + d2)————————————–/d1 d2\z*B|–, –|\2 2 / Example #2 : # Import sympy and FDistributionfrom sympy.stats import FDistribution, densityfrom sympy import Symbol d1 = 5d2 = 6z = 1 # Using sympy.stats.FDistribution() methodX = FDistribution("x", d1, d2)gfg = density(X)(z) pprint(gfg) Output : ____5400*\/ 55—————–1771561*B(5/2, 3) Python SymPy-Stats SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25045, "s": 25017, "text": "\n05 Jun, 2020" }, { "code": null, "e": 25173, "s": 25045, "text": "With the help of sympy.stats.FDistribution() method, we can get the continuous random variable representing the F distribution." }, { "code": null, "e": 25312, "s": 25173, "text": "Syntax : sympy.stats.FDistribution(name, d1, d2)Where, d1 and d2 denotes the degree of freedom.Return : Return continuous random variable." }, { "code": null, "e": 25509, "s": 25312, "text": "Example #1 :In this example we can see that by using sympy.stats.FDistribution() method, we are able to get the continuous random variable which represents the F distribution by using this method." }, { "code": "# Import sympy and FDistributionfrom sympy.stats import FDistribution, densityfrom sympy import Symbol d1 = Symbol(\"d1\", integer = True, positive = True)d2 = Symbol(\"d2\", integer = True, positive = True)z = Symbol(\"z\") # Using sympy.stats.FDistribution() methodX = FDistribution(\"x\", d1, d2)gfg = density(X)(z) pprint(gfg)", "e": 25835, "s": 25509, "text": null }, { "code": null, "e": 25844, "s": 25835, "text": "Output :" }, { "code": null, "e": 25955, "s": 25844, "text": "d2— ______________________________2 / d1 -d1 – d2d2 *\\/ (d1*z) *(d1*z + d2)————————————–/d1 d2\\z*B|–, –|\\2 2 /" }, { "code": null, "e": 25968, "s": 25955, "text": "Example #2 :" }, { "code": "# Import sympy and FDistributionfrom sympy.stats import FDistribution, densityfrom sympy import Symbol d1 = 5d2 = 6z = 1 # Using sympy.stats.FDistribution() methodX = FDistribution(\"x\", d1, d2)gfg = density(X)(z) pprint(gfg)", "e": 26196, "s": 25968, "text": null }, { "code": null, "e": 26205, "s": 26196, "text": "Output :" }, { "code": null, "e": 26243, "s": 26205, "text": "____5400*\\/ 55—————–1771561*B(5/2, 3)" }, { "code": null, "e": 26262, "s": 26243, "text": "Python SymPy-Stats" }, { "code": null, "e": 26268, "s": 26262, "text": "SymPy" }, { "code": null, "e": 26275, "s": 26268, "text": "Python" }, { "code": null, "e": 26373, "s": 26275, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26391, "s": 26373, "text": "Python Dictionary" }, { "code": null, "e": 26426, "s": 26391, "text": "Read a file line by line in Python" }, { "code": null, "e": 26458, "s": 26426, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26480, "s": 26458, "text": "Enumerate() in Python" }, { "code": null, "e": 26522, "s": 26480, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26552, "s": 26522, "text": "Iterate over a list in Python" }, { "code": null, "e": 26578, "s": 26552, "text": "Python String | replace()" }, { "code": null, "e": 26622, "s": 26578, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26651, "s": 26622, "text": "*args and **kwargs in Python" } ]
Git Getting Started
You can download Git for free from the following website: https://www.git-scm.com/ To start using Git, we are first going to open up our Command shell. For Windows, you can use Git bash, which comes included in Git for Windows. For Mac and Linux you can use the built-in terminal. The first thing we need to do, is to check if Git is properly installed: git --version git version 2.30.2.windows.1 If Git is installed, it should show something like git version X.Y Now let Git know who you are. This is important for version control systems, as each Git commit uses this information: git config --global user.name "w3schools-test" git config --global user.email "[email protected]" Change the user name and e-mail address to your own. You will probably also want to use this when registering to GitHub later on. Note: Use global to set the username and e-mail for every repository on your computer. If you want to set the username/e-mail for just the current repo, you can remove global Now, let's create a new folder for our project: mkdir myproject cd myproject mkdir makes a new directory. cd changes the current working directory. Now that we are in the correct directory. We can start by initializing Git! Note: If you already have a folder/directory you would like to use for Git: Navigate to it in command line, or open it in your file explorer, right-click and select "Git Bash here" Once you have navigated to the correct folder, you can initialize Git on that folder: git init Initialized empty Git repository in /Users/user/myproject/.git/ You just created your first Git Repository! Note: Git now knows that it should watch the folder you initiated it on. Git creates a hidden folder to keep track of changes. Insert the missing part of the command to check which version of Git (if any) is installed. git 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: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 83, "s": 0, "text": "You can download Git for free from the following website: https://www.git-scm.com/" }, { "code": null, "e": 152, "s": 83, "text": "To start using Git, we are first going to open up our Command shell." }, { "code": null, "e": 282, "s": 152, "text": "For Windows, you can use Git bash, which comes included in Git for Windows. \nFor Mac and Linux you can use the built-in terminal." }, { "code": null, "e": 355, "s": 282, "text": "The first thing we need to do, is to check if Git is properly installed:" }, { "code": null, "e": 398, "s": 355, "text": "git --version\ngit version 2.30.2.windows.1" }, { "code": null, "e": 465, "s": 398, "text": "If Git is installed, it should show something like git version X.Y" }, { "code": null, "e": 585, "s": 465, "text": "Now let Git know who you are. This is important for version control systems, \nas each Git commit uses this information:" }, { "code": null, "e": 684, "s": 585, "text": "git config --global user.name \"w3schools-test\"\ngit config --global user.email \"[email protected]\"" }, { "code": null, "e": 815, "s": 684, "text": "Change the user name and e-mail address to your own. You will probably also want to use this when registering to GitHub \nlater on." }, { "code": null, "e": 902, "s": 815, "text": "Note: Use global to set the username and e-mail for every repository on your computer." }, { "code": null, "e": 990, "s": 902, "text": "If you want to set the username/e-mail for just the current repo, you can remove global" }, { "code": null, "e": 1038, "s": 990, "text": "Now, let's create a new folder for our project:" }, { "code": null, "e": 1067, "s": 1038, "text": "mkdir myproject\ncd myproject" }, { "code": null, "e": 1096, "s": 1067, "text": "mkdir makes a new directory." }, { "code": null, "e": 1138, "s": 1096, "text": "cd changes the current working directory." }, { "code": null, "e": 1214, "s": 1138, "text": "Now that we are in the correct directory. We can start by initializing Git!" }, { "code": null, "e": 1293, "s": 1214, "text": "Note: If you already have a folder/directory you would \n like to use for Git:" }, { "code": null, "e": 1398, "s": 1293, "text": "Navigate to it in command line, or open it in your file explorer, right-click and select \"Git Bash here\"" }, { "code": null, "e": 1485, "s": 1398, "text": "Once you have navigated to the correct folder, you can initialize Git on that \nfolder:" }, { "code": null, "e": 1559, "s": 1485, "text": "git init \nInitialized empty Git repository in /Users/user/myproject/.git/" }, { "code": null, "e": 1603, "s": 1559, "text": "You just created your first Git Repository!" }, { "code": null, "e": 1679, "s": 1603, "text": "Note: Git now knows that it should watch the folder you \n initiated it on." }, { "code": null, "e": 1733, "s": 1679, "text": "Git creates a hidden folder to keep track of changes." }, { "code": null, "e": 1826, "s": 1733, "text": "Insert the missing part of the command to check which version of Git (if any) \nis installed." }, { "code": null, "e": 1832, "s": 1826, "text": "git \n" }, { "code": null, "e": 1852, "s": 1832, "text": "\nStart the Exercise" }, { "code": null, "e": 1885, "s": 1852, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1927, "s": 1885, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2034, "s": 1927, "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": 2053, "s": 2034, "text": "[email protected]" } ]
How to take care of SSL certificate issues in chrome browser in Selenium?
We can face SSL certificate issue because of the reasons listed below − While the website was developed, its SSL certificate was not proper. While the website was developed, its SSL certificate was not proper. The site may have a self-signed certificate. The site may have a self-signed certificate. SSL not configured properly at the server level. SSL not configured properly at the server level. import org.openqa.selenium.Capabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; public class SSLCert { public static void main(String[] args) { // TODO Auto-generated method stub //Desired capabilities for general chrome profile DesiredCapabilities c=DesiredCapabilities.chrome(); c.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true); c.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); //ChromeOptions for local browser ChromeOptions ch= new ChromeOptions(); ch.merge(c); System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver=new ChromeDriver(ch); } }
[ { "code": null, "e": 1134, "s": 1062, "text": "We can face SSL certificate issue because of the reasons listed below −" }, { "code": null, "e": 1203, "s": 1134, "text": "While the website was developed, its SSL certificate was not proper." }, { "code": null, "e": 1272, "s": 1203, "text": "While the website was developed, its SSL certificate was not proper." }, { "code": null, "e": 1317, "s": 1272, "text": "The site may have a self-signed certificate." }, { "code": null, "e": 1362, "s": 1317, "text": "The site may have a self-signed certificate." }, { "code": null, "e": 1411, "s": 1362, "text": "SSL not configured properly at the server level." }, { "code": null, "e": 1460, "s": 1411, "text": "SSL not configured properly at the server level." }, { "code": null, "e": 2362, "s": 1460, "text": "import org.openqa.selenium.Capabilities;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.chrome.ChromeOptions;\nimport org.openqa.selenium.remote.CapabilityType;\nimport org.openqa.selenium.remote.DesiredCapabilities;\npublic class SSLCert {\n public static void main(String[] args) {\n // TODO Auto-generated method stub\n //Desired capabilities for general chrome profile\n DesiredCapabilities c=DesiredCapabilities.chrome();\n c.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);\n c.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);\n //ChromeOptions for local browser\n ChromeOptions ch= new ChromeOptions();\n ch.merge(c);\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver=new ChromeDriver(ch);\n }\n}" } ]
Convert.ToDecimal(String, IFormatProvider) Method in C#
The Convert.ToDecimal() method in C# converts the specified string representation of a number to an equivalent decimal number, using the specified culture-specific formatting information. Following is the syntax − public static decimal ToDecimal (string val, IFormatProvider provider); Above, Val is a string that contains a number to convert, whereas the provider is an object that supplies culture-specific formatting information. Let us now see an example to implement the Convert.ToDecimal() method − using System; using System.Globalization; public class Demo { public static void Main() { CultureInfo cultures = new CultureInfo("en-US"); String val = "8787"; Console.WriteLine("Converted Decimal value..."); decimal res = Convert.ToDecimal(val, cultures); Console.Write("{0}", res); } } This will produce the following output − Converted Decimal value... 8787
[ { "code": null, "e": 1250, "s": 1062, "text": "The Convert.ToDecimal() method in C# converts the specified string representation of a number to an equivalent decimal number, using the specified culture-specific formatting information." }, { "code": null, "e": 1276, "s": 1250, "text": "Following is the syntax −" }, { "code": null, "e": 1348, "s": 1276, "text": "public static decimal ToDecimal (string val, IFormatProvider provider);" }, { "code": null, "e": 1495, "s": 1348, "text": "Above, Val is a string that contains a number to convert, whereas the provider is an object that supplies culture-specific formatting information." }, { "code": null, "e": 1567, "s": 1495, "text": "Let us now see an example to implement the Convert.ToDecimal() method −" }, { "code": null, "e": 1891, "s": 1567, "text": "using System;\nusing System.Globalization;\npublic class Demo {\n public static void Main() {\n CultureInfo cultures = new CultureInfo(\"en-US\");\n String val = \"8787\";\n Console.WriteLine(\"Converted Decimal value...\");\n decimal res = Convert.ToDecimal(val, cultures);\n Console.Write(\"{0}\", res);\n }\n}" }, { "code": null, "e": 1932, "s": 1891, "text": "This will produce the following output −" }, { "code": null, "e": 1964, "s": 1932, "text": "Converted Decimal value...\n8787" } ]
How to write files to asset folder in android?
This example demonstrates how do I write files to asset folder in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/btnReadFile" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_above="@id/textView" android:layout_marginBottom="15dp" android:text="Read File"/> <TextView android:id="@+id/textView" android:layout_centerInParent="true" android:textSize="16sp" android:textStyle="bold|italic" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> Step 3 – Create a new Assets folder and write a new text file in it. To write a text file, Right click, select New >> file (Quote.txt) Step 4 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.io.IOException; import java.io.InputStream; public class MainActivity extends AppCompatActivity { TextView textView; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); button = findViewById(R.id.btnReadFile); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = ""; InputStream inputStream = null; try { inputStream = getAssets().open("Quotes.txt"); int size = inputStream.available(); byte[] buffer = new byte[size]; inputStream.read(buffer); string = new String(buffer); } catch (IOException e) { e.printStackTrace(); } textView.setText(string); } }); } } Step 5 – Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1137, "s": 1062, "text": "This example demonstrates how do I write files to asset folder in android." }, { "code": null, "e": 1266, "s": 1137, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1331, "s": 1266, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2162, "s": 1331, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/btnReadFile\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:layout_above=\"@id/textView\"\n android:layout_marginBottom=\"15dp\"\n android:text=\"Read File\"/>\n <TextView\n android:id=\"@+id/textView\"\n android:layout_centerInParent=\"true\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold|italic\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</RelativeLayout>" }, { "code": null, "e": 2231, "s": 2162, "text": "Step 3 – Create a new Assets folder and write a new text file in it." }, { "code": null, "e": 2297, "s": 2231, "text": "To write a text file, Right click, select New >> file (Quote.txt)" }, { "code": null, "e": 2354, "s": 2297, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3528, "s": 2354, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport java.io.IOException;\nimport java.io.InputStream;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n Button button;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n button = findViewById(R.id.btnReadFile);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String string = \"\";\n InputStream inputStream = null;\n try {\n inputStream = getAssets().open(\"Quotes.txt\");\n int size = inputStream.available();\n byte[] buffer = new byte[size];\n inputStream.read(buffer);\n string = new String(buffer);\n } catch (IOException e) {\n e.printStackTrace();\n }\n textView.setText(string);\n }\n });\n }\n}" }, { "code": null, "e": 3583, "s": 3528, "text": "Step 5 – Add the following code to androidManifest.xml" }, { "code": null, "e": 4253, "s": 3583, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4600, "s": 4253, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 4641, "s": 4600, "text": "Click here to download the project code." } ]
Communication between components using $emit and props in Vue.js - GeeksforGeeks
12 Dec, 2021 Components in Vue.js need to share data with each other sometimes in order to give the desired output. Components in a webpage are in a hierarchical order like a tree. The most basic way of interacting and passing data between components is using $emit and props. $emit and props: In Vue.js, we use $emit to generate custom events for our component. Meaning just like a mouse click or scrolling generates an onclick and onwheel events we can generate events from our component methods and name them according to our convention. Not only this, we can also pass data as arguments to this event. this.$emit('setevent',someVariable); Props are used to pass data to components as custom attributes. Props are added to components as follows – Vue.component('exampleComponent',{ props: ['sometext'], template : `<p>This is the prop data - {{sometext}}</p>` }); How does it work? So how this works is parent component listens to the event of first child component and then executes a method band to it. This method gets the data of the event as an argument and then passes on this data to props of the second child component. Example: The following example illustrates how this mechanism works. It’s a very basic webpage which displays how many times a button has been clicked. It has 3 components – A parent component and 2 child components within it. HTML Javascript <!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <!-- Including Vue using CDN--> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> </script> <!-- Javascript code --> <script src="script.js"></script> <style> .component1 { display: block; background-color: green; height: 15em; text-align: center; color: white; padding-top: 5em; } .component2 { display: block; background-color: grey; height: 15em; text-align: center; padding-top: 5em; } </style></head> <body> <div id="root"> <parentcomponent></parentcomponent> </div></body> </html> /* First component has a heading element in the template which shows how many times the button in 2nd component has been clicked. It uses props. */Vue.component('component1', { props: ['labeltext'], // This props is then used in template // to have dynamic values. template: `<div class="component1"> <h1>You have clicked {{labeltext}} times</h1> </div>`}); /* Second component has a button which whenclicked upon executes the count method. Acustom event namely ‘setevent’ is triggeredby this method. */Vue.component('component2', { data() { return { nclick: 0 } }, template: `<div class="component2"> <button @click = "count">Click</button> </div>`, methods: { count() { this.nclick += 1; // Emitting a custom-event this.$emit('setevent', this.nclick); } }}); // This is just a div element component which// contains the two child components in it.Vue.component('parentcomponent', { data() { return { text: 0 } }, // Set method is binded to the 'setevent' // event and labeltext is the prop. template: `<div> <component1 :labeltext = "text"></component1> <component2 @setevent = "set"></component2> </div>`, methods: { set(n) { // Updates the variable text which // is the value of prop attribute this.text = n; } }}); new Vue({ el: '#root', data: { }}) Applications and scope: Components in a Vue.js web app are in a hierarchical order with many levels like a tree with components inside components. Using above method, it is possible to chain multiple events and climb up this tree and then pass on data to below levels using prop. Hence, this method is very suitable when we require component interaction within 2 or 3 levels but as soon as our web app requires interaction among components which are on very different levels this process becomes increasingly complex as you can imagine. That’s when state management libraries like Vuex come into play. But for basic interactions we use $emit and props, so as not to chuck every little thing into our Vuex store. saurabh1990aror HTML-Misc JavaScript-Misc HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Angular File Upload Form validation using jQuery How to auto-resize an image to fit a div container using CSS? Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React File uploading in React.js
[ { "code": null, "e": 24894, "s": 24866, "text": "\n12 Dec, 2021" }, { "code": null, "e": 25158, "s": 24894, "text": "Components in Vue.js need to share data with each other sometimes in order to give the desired output. Components in a webpage are in a hierarchical order like a tree. The most basic way of interacting and passing data between components is using $emit and props." }, { "code": null, "e": 25487, "s": 25158, "text": "$emit and props: In Vue.js, we use $emit to generate custom events for our component. Meaning just like a mouse click or scrolling generates an onclick and onwheel events we can generate events from our component methods and name them according to our convention. Not only this, we can also pass data as arguments to this event." }, { "code": null, "e": 25524, "s": 25487, "text": "this.$emit('setevent',someVariable);" }, { "code": null, "e": 25631, "s": 25524, "text": "Props are used to pass data to components as custom attributes. Props are added to components as follows –" }, { "code": null, "e": 25762, "s": 25631, "text": "Vue.component('exampleComponent',{\n props: ['sometext'],\n \n template : `<p>This is the prop data - {{sometext}}</p>`\n\n});" }, { "code": null, "e": 25781, "s": 25762, "text": "How does it work? " }, { "code": null, "e": 26027, "s": 25781, "text": "So how this works is parent component listens to the event of first child component and then executes a method band to it. This method gets the data of the event as an argument and then passes on this data to props of the second child component." }, { "code": null, "e": 26254, "s": 26027, "text": "Example: The following example illustrates how this mechanism works. It’s a very basic webpage which displays how many times a button has been clicked. It has 3 components – A parent component and 2 child components within it." }, { "code": null, "e": 26259, "s": 26254, "text": "HTML" }, { "code": null, "e": 26270, "s": 26259, "text": "Javascript" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <!-- Including Vue using CDN--> <script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"> </script> <!-- Javascript code --> <script src=\"script.js\"></script> <style> .component1 { display: block; background-color: green; height: 15em; text-align: center; color: white; padding-top: 5em; } .component2 { display: block; background-color: grey; height: 15em; text-align: center; padding-top: 5em; } </style></head> <body> <div id=\"root\"> <parentcomponent></parentcomponent> </div></body> </html>", "e": 27101, "s": 26270, "text": null }, { "code": "/* First component has a heading element in the template which shows how many times the button in 2nd component has been clicked. It uses props. */Vue.component('component1', { props: ['labeltext'], // This props is then used in template // to have dynamic values. template: `<div class=\"component1\"> <h1>You have clicked {{labeltext}} times</h1> </div>`}); /* Second component has a button which whenclicked upon executes the count method. Acustom event namely ‘setevent’ is triggeredby this method. */Vue.component('component2', { data() { return { nclick: 0 } }, template: `<div class=\"component2\"> <button @click = \"count\">Click</button> </div>`, methods: { count() { this.nclick += 1; // Emitting a custom-event this.$emit('setevent', this.nclick); } }}); // This is just a div element component which// contains the two child components in it.Vue.component('parentcomponent', { data() { return { text: 0 } }, // Set method is binded to the 'setevent' // event and labeltext is the prop. template: `<div> <component1 :labeltext = \"text\"></component1> <component2 @setevent = \"set\"></component2> </div>`, methods: { set(n) { // Updates the variable text which // is the value of prop attribute this.text = n; } }}); new Vue({ el: '#root', data: { }})", "e": 28602, "s": 27101, "text": null }, { "code": null, "e": 28882, "s": 28602, "text": "Applications and scope: Components in a Vue.js web app are in a hierarchical order with many levels like a tree with components inside components. Using above method, it is possible to chain multiple events and climb up this tree and then pass on data to below levels using prop." }, { "code": null, "e": 29314, "s": 28882, "text": "Hence, this method is very suitable when we require component interaction within 2 or 3 levels but as soon as our web app requires interaction among components which are on very different levels this process becomes increasingly complex as you can imagine. That’s when state management libraries like Vuex come into play. But for basic interactions we use $emit and props, so as not to chuck every little thing into our Vuex store." }, { "code": null, "e": 29330, "s": 29314, "text": "saurabh1990aror" }, { "code": null, "e": 29340, "s": 29330, "text": "HTML-Misc" }, { "code": null, "e": 29356, "s": 29340, "text": "JavaScript-Misc" }, { "code": null, "e": 29361, "s": 29356, "text": "HTML" }, { "code": null, "e": 29372, "s": 29361, "text": "JavaScript" }, { "code": null, "e": 29389, "s": 29372, "text": "Web Technologies" }, { "code": null, "e": 29394, "s": 29389, "text": "HTML" }, { "code": null, "e": 29492, "s": 29394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29501, "s": 29492, "text": "Comments" }, { "code": null, "e": 29514, "s": 29501, "text": "Old Comments" }, { "code": null, "e": 29538, "s": 29514, "text": "REST API (Introduction)" }, { "code": null, "e": 29575, "s": 29538, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29595, "s": 29575, "text": "Angular File Upload" }, { "code": null, "e": 29624, "s": 29595, "text": "Form validation using jQuery" }, { "code": null, "e": 29686, "s": 29624, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 29731, "s": 29686, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29800, "s": 29731, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 29861, "s": 29800, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29933, "s": 29861, "text": "Differences between Functional Components and Class Components in React" } ]
Word Wrap | Practice | GeeksforGeeks
Given an array nums[] of size n, where nums[i] denotes the number of characters in one word. Let K be the limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly. Assume that the length of each word is smaller than the line width. When line breaks are inserted there is a possibility that extra spaces are present in each line. The extra spaces include spaces put at the end of every line except the last one. You have to minimize the following total cost where total cost = Sum of cost of all lines, where cost of line is = (Number of extra spaces in the line)2. Example 1: Input: nums = {3,2,2,5}, k = 6 Output: 10 Explanation: Given a line can have 6 characters, Line number 1: From word no. 1 to 1 Line number 2: From word no. 2 to 3 Line number 3: From word no. 4 to 4 So total cost = (6-3)2 + (6-2-2-1)2 = 32+12 = 10. As in the first line word length = 3 thus extra spaces = 6 - 3 = 3 and in the second line there are two word of length 2 and there already 1 space between two word thus extra spaces = 6 - 2 -2 -1 = 1. As mentioned in the problem description there will be no extra spaces in the last line. Placing first and second word in first line and third word on second line would take a cost of 02 + 42 = 16 (zero spaces on first line and 6-2 = 4 spaces on second), which isn't the minimum possible cost. Example 2: Input: nums = {3,2,2}, k = 4 Output: 5 Explanation: Given a line can have 4 characters, Line number 1: From word no. 1 to 1 Line number 2: From word no. 2 to 2 Line number 3: From word no. 3 to 3 Same explaination as above total cost = (4 - 3)2 + (4 - 2)2 = 5. Your Task: You don't need to read or print anyhting. Your task is to complete the function solveWordWrap() which takes nums and k as input paramater and returns the minimized total cost. Expected Time Complexity: O(n2) Expected Space Complexity: O(n) Constraints: 1 ≤ n ≤ 500 1 ≤ nums[i] ≤ 1000 max(nums[i]) ≤ k ≤ 2000 +2 hacky32441 week ago int dp[501]; int n; int k; int recur(int i,int j,vector<int>&nums){ if(i>=n){ return 0; } if(dp[i]!=-1)return dp[i]; int su=0; int ans=INT_MAX; for(int j=i; j<n;j++){ su+=nums[j]; if(k-su<0)break; if(j<n-1) ans=min(ans,(k-su)*(k-su)+recur(j+1,j-i+1,nums)); else ans=0+recur(j+1,j-i+1,nums); su++; } return dp[i]=ans; } int solveWordWrap(vector<int>nums, int K) { // Code here n=nums.size(); k=K; memset(dp,-1,sizeof(dp)); int ans=recur(0,0,nums); return ans; } +4 rushabhrbs1 week ago class Solution { int solve(int ind ,int n , vector<int>& nums , int k , vector<int>& dp){ if(ind >= n ) return 0; if(dp[ind] != -1) return dp[ind]; int ans = INT_MAX; int sum = 0 ; for(int i = ind ; i < n ; i++){ sum += nums[i]; if(sum + (i - ind) <=k){ int cost = 0; if(i != n - 1){ cost = pow(k - sum - i + ind , 2); } ans = min(ans ,cost + solve(i + 1, n , nums , k , dp)); } } return dp[ind] = ans; }public: int solveWordWrap(vector<int>nums, int k) { // Code here int n = nums.size() ; vector<int>dp(n , -1); return solve(0 , n , nums , k , dp); } }; 0 anuragshubham341 week ago class Solution{ public int solveWordWrap (int[] nums, int k) { int n=nums.length; int[] dp=new int[n]; int cost=0,currlen; dp[n-1]=0; for(int i=n-2;i>=0;i--){ currlen=-1; dp[i]=Integer.MAX_VALUE; for(int j=i;j<n;j++){ currlen+=(nums[j]+1); if(currlen>k) break; if(j==n-1) cost=0; else cost=(k-currlen)*(k-currlen)+dp[j+1]; if(cost<dp[i]) dp[i]=cost; } } // for(int x:dp) // System.out.println(x); return dp[0]; }} 0 harshidsahare201 week ago int solve(int ind ,int n , vector<int>& nums , int k , vector<int>& dp){ if(ind >= n ) return 0; if(dp[ind] != -1) return dp[ind]; int ans = INT_MAX; int sum = 0 ; for(int i = ind ; i < n ; i++){ sum += nums[i]; if(sum + (i - ind) <=k){ int cost = 0; if(i != n - 1){ cost = pow(k - sum - i + ind , 2); } ans = min(ans ,cost + solve(i + 1, n , nums , k , dp)); } } return dp[ind] = ans; } int solveWordWrap(vector<int>nums, int k) { // Code here int n = nums.size() ; vector<int>dp(n , -1); return solve(0 , n , nums , k , dp); } 0 satiitmadras1231 week ago class Solution {public: int dp[501][2001]; int helper(vector<int>&nums,int idx,int k,int currCount) { if(idx >= nums.size()) return 0; if(dp[idx][currCount]!=-1) return dp[idx][currCount]; if(idx == nums.size()-1) { if(currCount+nums[idx] <= k) return 0; int isLeft = pow(k-currCount+1,2); return isLeft; } if(currCount+nums[idx] <= k) { int ifleft = pow(k-currCount+1,2); return dp[idx][currCount] = min(helper(nums,idx+1,k,currCount+nums[idx]+1),ifleft + helper(nums,idx+1,k,nums[idx]+1)); } else { int ifleft = pow(k-currCount+1,2); return dp[idx][currCount] = ifleft + helper(nums,idx+1,k,nums[idx]+1); } } int solveWordWrap(vector<int>nums, int k) { // Code here memset(dp,-1,sizeof(dp)); return helper(nums,0,k,0); } }; 0 sksirajsj2 weeks ago class Solution { public: //rec(i,k,v) returns min cost in range [0,i]; int dp[510]; int n; int rec(int i,int k,vector<int>& v){ //base case if(i<0)return 0; //check if already calculated if(dp[i]!=-1)return dp[i]; int cost = 0,ans=1e9,pref=0; //transitions for(int j=i;j>=0;j--){ pref+=v[j]; if((pref+(i-j))<=k){ if(i!=(n-1)){ cost = (k-(pref+i-j))*(k-(pref+i-j)); } ans = min(ans,rec(j-1,k,v)+cost); } } return dp[i] = ans; } int solveWordWrap(vector<int>nums, int k) { // Code here memset(dp,-1,sizeof(dp)); n = nums.size(); return rec(n-1,k,nums); } }; +7 spideyyy1092 weeks ago difficulty level should be hard . 0 sandeepgattani2 weeks ago JAVA solution: private int getCost(int[] nums, int from, int to, int k){ if(to == nums.length-1) return 0; int used = 0; for(int i=from; i<=to; i++){ if(used > 0) used++; used += nums[i]; } return (k-used)*(k-used); } public int solveWordWrapRec (int[] nums, int k, int idx, Map<Integer, Integer> cache){ if(idx >= (nums.length-1)){ return 0; } Integer value = cache.get(idx); if(value != null) return value; int cost = Integer.MAX_VALUE; int used = 0; for(int i=idx; i<nums.length; i++){ if(used+nums[i] > k) break; if(i+1 < nums.length){ cost = Math.min(cost, solveWordWrapRec(nums, k, i+1, cache) + getCost(nums, idx, i, k)); }else{ cost = Math.min(cost, getCost(nums, idx, i, k)); } used += nums[i] + 1; } value = cost; cache.put(idx, value); return value; } public int solveWordWrap (int[] nums, int k) { return solveWordWrapRec(nums, k, 0, new HashMap<>()); } +1 sourav1919sharma2 weeks ago int square(int n){ return n * n; } int helper(vector<int>&word, int n, int length, int wordIndex, int remLength, vector<vector<int>>&dp){ //We are at the last word if(wordIndex == n - 1){ //If there is required space left in the currline if(word[wordIndex] < remLength){ return 0; } //Otherwise insert it in the next line and return the cost which is square of white space return square(remLength); } if(dp[wordIndex][remLength] != -1) return dp[wordIndex][remLength]; int currWord = word[wordIndex]; //If word can fit in the remaining line if(currWord < remLength){ /* Case 1: Insert it in the same line (remLength == length) ==> whether we are putting the first word in the line -> If this is the case then we dont need to add one extra space or we are putting next word in the same line -> If this is the case then we need to insert extra space between the two words. */ int insert = helper(word, n, length, wordIndex + 1, remLength == length ? remLength - currWord : remLength - currWord - 1, dp); //Case 2: Insert it in the next line. int dontInsert = square(remLength) + helper(word, n, length, wordIndex + 1, length - currWord, dp); return dp[wordIndex][remLength] = min(insert, dontInsert); } //We don't have any choice so insert the word in the next line. return dp[wordIndex][remLength] = square(remLength) + helper(word, n, length, wordIndex + 1, length - currWord, dp); } int solveWordWrap(vector<int>nums, int k){ vector<vector<int>>dp(nums.size(), vector<int>(k + 1, -1)); return helper(nums, nums.size(), k, 0, k, dp); } +8 pritamkr2122 weeks ago THIS IS A BEAUTIFUL QUESTION OF DP DONT FORGET TO BOOKMARK TO GET THE INTUTION U KNOW THE GAP METHOD(DIAGONAL TRAVERSAL) WHICH IS A BEST TOOL IN DP QUESTIONS . SO STEPS TO GRAPS THIS QUESTION 1-→https://youtu.be/lvRdFCMD_Ew WATCH AT(1.75X) 2-→https://youtu.be/FiQY3K4_xPo NICE EXPLANTION(WATCH FOR INTUTION) OTHER DOCUMENTATION -→https://www.geeksforgeeks.org/word-wrap-problem-space-optimized-solution/ best solution class Solution { public int solveWordWrap (int[] a, int k) { int[][]dp=new int[a.length][a.length]; for(int gap=0;gap<dp.length;gap++){ for(int i=0,j=gap;j<dp.length;j++,i++){ if(gap==0){ dp[i][j]=k-a[i]; } else{ dp[i][j]=dp[i][j-1]-a[j]-1; } } } for(int i=0;i<dp.length;i++) { for(int j=i;j<dp.length;j++) { if(dp[i][j] < 0)dp[i][j] = Integer.MAX_VALUE; else if(j== a.length-1)dp[i][j]=0; else dp[i][j] = (int)Math.pow(dp[i][j], 2); } } int[]ans=new int[a.length]; for(int i=dp.length-1;i>=0;i--){ ans[i]=dp[i][dp.length-1]; for(int j=dp.length-1;j>i;j--){ if(dp[i][j-1]==Integer.MAX_VALUE)continue; else if(ans[i]>ans[j]+dp[i][j-1]){ ans[i]=ans[j]+dp[i][j-1]; } } } return ans[0]; } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 746, "s": 238, "text": "Given an array nums[] of size n, where nums[i] denotes the number of characters in one word. Let K be the limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly.\nAssume that the length of each word is smaller than the line width. When line breaks are inserted there is a possibility that extra spaces are present in each line. The extra spaces include spaces put at the end of every line except the last one. " }, { "code": null, "e": 900, "s": 746, "text": "You have to minimize the following total cost where total cost = Sum of cost of all lines, where cost of line is = (Number of extra spaces in the line)2." }, { "code": null, "e": 911, "s": 900, "text": "Example 1:" }, { "code": null, "e": 1655, "s": 911, "text": "Input: nums = {3,2,2,5}, k = 6\nOutput: 10\nExplanation: Given a line can have 6\ncharacters,\nLine number 1: From word no. 1 to 1\nLine number 2: From word no. 2 to 3\nLine number 3: From word no. 4 to 4\nSo total cost = (6-3)2 + (6-2-2-1)2 = 32+12 = 10.\nAs in the first line word length = 3 thus\nextra spaces = 6 - 3 = 3 and in the second line\nthere are two word of length 2 and there already\n1 space between two word thus extra spaces\n= 6 - 2 -2 -1 = 1. As mentioned in the problem\ndescription there will be no extra spaces in\nthe last line. Placing first and second word\nin first line and third word on second line\nwould take a cost of 02 + 42 = 16 (zero spaces\non first line and 6-2 = 4 spaces on second),\nwhich isn't the minimum possible cost.\n" }, { "code": null, "e": 1666, "s": 1655, "text": "Example 2:" }, { "code": null, "e": 1929, "s": 1666, "text": "Input: nums = {3,2,2}, k = 4\nOutput: 5\nExplanation: Given a line can have 4 \ncharacters,\nLine number 1: From word no. 1 to 1\nLine number 2: From word no. 2 to 2\nLine number 3: From word no. 3 to 3\nSame explaination as above total cost\n= (4 - 3)2 + (4 - 2)2 = 5.\n" }, { "code": null, "e": 2119, "s": 1929, "text": "\nYour Task:\nYou don't need to read or print anyhting. Your task is to complete the function solveWordWrap() which takes nums and k as input paramater and returns the minimized total cost.\n " }, { "code": null, "e": 2185, "s": 2119, "text": "Expected Time Complexity: O(n2)\nExpected Space Complexity: O(n)\n " }, { "code": null, "e": 2253, "s": 2185, "text": "Constraints:\n1 ≤ n ≤ 500\n1 ≤ nums[i] ≤ 1000\nmax(nums[i]) ≤ k ≤ 2000" }, { "code": null, "e": 2256, "s": 2253, "text": "+2" }, { "code": null, "e": 2276, "s": 2256, "text": "hacky32441 week ago" }, { "code": null, "e": 2925, "s": 2276, "text": "int dp[501]; int n; int k; int recur(int i,int j,vector<int>&nums){ if(i>=n){ return 0; } if(dp[i]!=-1)return dp[i]; int su=0; int ans=INT_MAX; for(int j=i; j<n;j++){ su+=nums[j]; if(k-su<0)break; if(j<n-1) ans=min(ans,(k-su)*(k-su)+recur(j+1,j-i+1,nums)); else ans=0+recur(j+1,j-i+1,nums); su++; } return dp[i]=ans; } int solveWordWrap(vector<int>nums, int K) { // Code here n=nums.size(); k=K; memset(dp,-1,sizeof(dp)); int ans=recur(0,0,nums); return ans; } " }, { "code": null, "e": 2928, "s": 2925, "text": "+4" }, { "code": null, "e": 2949, "s": 2928, "text": "rushabhrbs1 week ago" }, { "code": null, "e": 3713, "s": 2949, "text": "class Solution { int solve(int ind ,int n , vector<int>& nums , int k , vector<int>& dp){ if(ind >= n ) return 0; if(dp[ind] != -1) return dp[ind]; int ans = INT_MAX; int sum = 0 ; for(int i = ind ; i < n ; i++){ sum += nums[i]; if(sum + (i - ind) <=k){ int cost = 0; if(i != n - 1){ cost = pow(k - sum - i + ind , 2); } ans = min(ans ,cost + solve(i + 1, n , nums , k , dp)); } } return dp[ind] = ans; }public: int solveWordWrap(vector<int>nums, int k) { // Code here int n = nums.size() ; vector<int>dp(n , -1); return solve(0 , n , nums , k , dp); } }; " }, { "code": null, "e": 3715, "s": 3713, "text": "0" }, { "code": null, "e": 3741, "s": 3715, "text": "anuragshubham341 week ago" }, { "code": null, "e": 4405, "s": 3741, "text": "class Solution{ public int solveWordWrap (int[] nums, int k) { int n=nums.length; int[] dp=new int[n]; int cost=0,currlen; dp[n-1]=0; for(int i=n-2;i>=0;i--){ currlen=-1; dp[i]=Integer.MAX_VALUE; for(int j=i;j<n;j++){ currlen+=(nums[j]+1); if(currlen>k) break; if(j==n-1) cost=0; else cost=(k-currlen)*(k-currlen)+dp[j+1]; if(cost<dp[i]) dp[i]=cost; } } // for(int x:dp) // System.out.println(x); return dp[0]; }}" }, { "code": null, "e": 4407, "s": 4405, "text": "0" }, { "code": null, "e": 4433, "s": 4407, "text": "harshidsahare201 week ago" }, { "code": null, "e": 5221, "s": 4433, "text": "int solve(int ind ,int n , vector<int>& nums , int k , vector<int>& dp){\n if(ind >= n )\n return 0;\n if(dp[ind] != -1)\n return dp[ind];\n int ans = INT_MAX;\n int sum = 0 ;\n for(int i = ind ; i < n ; i++){\n sum += nums[i];\n if(sum + (i - ind) <=k){\n int cost = 0;\n if(i != n - 1){\n cost = pow(k - sum - i + ind , 2);\n }\n ans = min(ans ,cost + solve(i + 1, n , nums , k , dp));\n \n }\n }\n return dp[ind] = ans;\n }\n\n int solveWordWrap(vector<int>nums, int k) \n { \n // Code here\n int n = nums.size() ;\n vector<int>dp(n , -1);\n return solve(0 , n , nums , k , dp);\n } " }, { "code": null, "e": 5227, "s": 5225, "text": "0" }, { "code": null, "e": 5253, "s": 5227, "text": "satiitmadras1231 week ago" }, { "code": null, "e": 6178, "s": 5253, "text": "class Solution {public: int dp[501][2001]; int helper(vector<int>&nums,int idx,int k,int currCount) { if(idx >= nums.size()) return 0; if(dp[idx][currCount]!=-1) return dp[idx][currCount]; if(idx == nums.size()-1) { if(currCount+nums[idx] <= k) return 0; int isLeft = pow(k-currCount+1,2); return isLeft; } if(currCount+nums[idx] <= k) { int ifleft = pow(k-currCount+1,2); return dp[idx][currCount] = min(helper(nums,idx+1,k,currCount+nums[idx]+1),ifleft + helper(nums,idx+1,k,nums[idx]+1)); } else { int ifleft = pow(k-currCount+1,2); return dp[idx][currCount] = ifleft + helper(nums,idx+1,k,nums[idx]+1); } } int solveWordWrap(vector<int>nums, int k) { // Code here memset(dp,-1,sizeof(dp)); return helper(nums,0,k,0); } };" }, { "code": null, "e": 6180, "s": 6178, "text": "0" }, { "code": null, "e": 6201, "s": 6180, "text": "sksirajsj2 weeks ago" }, { "code": null, "e": 6974, "s": 6201, "text": "class Solution {\npublic:\n //rec(i,k,v) returns min cost in range [0,i];\n int dp[510];\n int n;\n int rec(int i,int k,vector<int>& v){\n \t\t//base case\n if(i<0)return 0;\n //check if already calculated\n if(dp[i]!=-1)return dp[i];\n int cost = 0,ans=1e9,pref=0;\n //transitions\n for(int j=i;j>=0;j--){\n pref+=v[j];\n if((pref+(i-j))<=k){\n if(i!=(n-1)){\n cost = (k-(pref+i-j))*(k-(pref+i-j));\n }\n ans = min(ans,rec(j-1,k,v)+cost);\n }\n }\n return dp[i] = ans;\n }\n \n int solveWordWrap(vector<int>nums, int k) \n { \n // Code here\n memset(dp,-1,sizeof(dp));\n n = nums.size();\n return rec(n-1,k,nums);\n } \n};" }, { "code": null, "e": 6977, "s": 6974, "text": "+7" }, { "code": null, "e": 7000, "s": 6977, "text": "spideyyy1092 weeks ago" }, { "code": null, "e": 7035, "s": 7000, "text": "difficulty level should be hard . " }, { "code": null, "e": 7037, "s": 7035, "text": "0" }, { "code": null, "e": 7063, "s": 7037, "text": "sandeepgattani2 weeks ago" }, { "code": null, "e": 7078, "s": 7063, "text": "JAVA solution:" }, { "code": null, "e": 8125, "s": 7078, "text": " private int getCost(int[] nums, int from, int to, int k){ if(to == nums.length-1) return 0; int used = 0; for(int i=from; i<=to; i++){ if(used > 0) used++; used += nums[i]; } return (k-used)*(k-used); } public int solveWordWrapRec (int[] nums, int k, int idx, Map<Integer, Integer> cache){ if(idx >= (nums.length-1)){ return 0; } Integer value = cache.get(idx); if(value != null) return value; int cost = Integer.MAX_VALUE; int used = 0; for(int i=idx; i<nums.length; i++){ if(used+nums[i] > k) break; if(i+1 < nums.length){ cost = Math.min(cost, solveWordWrapRec(nums, k, i+1, cache) + getCost(nums, idx, i, k)); }else{ cost = Math.min(cost, getCost(nums, idx, i, k)); } used += nums[i] + 1; } value = cost; cache.put(idx, value); return value; }" }, { "code": null, "e": 8244, "s": 8127, "text": " public int solveWordWrap (int[] nums, int k) { return solveWordWrapRec(nums, k, 0, new HashMap<>()); }" }, { "code": null, "e": 8249, "s": 8246, "text": "+1" }, { "code": null, "e": 8277, "s": 8249, "text": "sourav1919sharma2 weeks ago" }, { "code": null, "e": 10324, "s": 8277, "text": "int square(int n){\n return n * n;\n }\n \n int helper(vector<int>&word, int n, int length, int wordIndex, int remLength, vector<vector<int>>&dp){\n //We are at the last word\n if(wordIndex == n - 1){\n //If there is required space left in the currline\n if(word[wordIndex] < remLength){\n return 0;\n }\n //Otherwise insert it in the next line and return the cost which is square of white space\n return square(remLength);\n }\n \n if(dp[wordIndex][remLength] != -1)\n return dp[wordIndex][remLength];\n \n int currWord = word[wordIndex];\n \n //If word can fit in the remaining line\n if(currWord < remLength){\n /*\n Case 1: Insert it in the same line\n (remLength == length) ==> \n whether we are putting the first word in the line\n -> If this is the case then we dont need to add one extra space\n or we are putting next word in the same line\n -> If this is the case then we need to insert extra space between\n the two words.\n */\n int insert = helper(word, n, length, wordIndex + 1, remLength == length \n ? remLength - currWord : remLength - currWord - 1, dp);\n \n //Case 2: Insert it in the next line.\n int dontInsert = square(remLength) + helper(word, n, length, wordIndex + 1, length - currWord, dp);\n \n return dp[wordIndex][remLength] = min(insert, dontInsert);\n }\n \n //We don't have any choice so insert the word in the next line.\n return dp[wordIndex][remLength] = square(remLength) + helper(word, n, length, wordIndex + 1, length - currWord, dp);\n }\n\n int solveWordWrap(vector<int>nums, int k){\n vector<vector<int>>dp(nums.size(), vector<int>(k + 1, -1));\n return helper(nums, nums.size(), k, 0, k, dp);\n } " }, { "code": null, "e": 10327, "s": 10324, "text": "+8" }, { "code": null, "e": 10350, "s": 10327, "text": "pritamkr2122 weeks ago" }, { "code": null, "e": 10409, "s": 10350, "text": "THIS IS A BEAUTIFUL QUESTION OF DP DONT FORGET TO BOOKMARK" }, { "code": null, "e": 10543, "s": 10409, "text": "TO GET THE INTUTION U KNOW THE GAP METHOD(DIAGONAL TRAVERSAL) WHICH IS A BEST TOOL IN DP QUESTIONS . SO STEPS TO GRAPS THIS QUESTION " }, { "code": null, "e": 10592, "s": 10543, "text": " 1-→https://youtu.be/lvRdFCMD_Ew WATCH AT(1.75X)" }, { "code": null, "e": 10661, "s": 10592, "text": " 2-→https://youtu.be/FiQY3K4_xPo NICE EXPLANTION(WATCH FOR INTUTION)" }, { "code": null, "e": 10771, "s": 10661, "text": "OTHER DOCUMENTATION -→https://www.geeksforgeeks.org/word-wrap-problem-space-optimized-solution/ best solution" }, { "code": null, "e": 11877, "s": 10773, "text": "class Solution\n{\n public int solveWordWrap (int[] a, int k)\n {\n int[][]dp=new int[a.length][a.length];\n for(int gap=0;gap<dp.length;gap++){\n for(int i=0,j=gap;j<dp.length;j++,i++){\n if(gap==0){\n dp[i][j]=k-a[i];\n }\n else{\n dp[i][j]=dp[i][j-1]-a[j]-1;\n }\n }\n }\n for(int i=0;i<dp.length;i++)\n {\n for(int j=i;j<dp.length;j++)\n {\n if(dp[i][j] < 0)dp[i][j] = Integer.MAX_VALUE;\n else if(j== a.length-1)dp[i][j]=0;\n else dp[i][j] = (int)Math.pow(dp[i][j], 2);\n }\n }\n \n int[]ans=new int[a.length];\n for(int i=dp.length-1;i>=0;i--){\n ans[i]=dp[i][dp.length-1];\n for(int j=dp.length-1;j>i;j--){\n if(dp[i][j-1]==Integer.MAX_VALUE)continue;\n else if(ans[i]>ans[j]+dp[i][j-1]){\n ans[i]=ans[j]+dp[i][j-1];\n }\n }\n }\n return ans[0];\n }\n}" }, { "code": null, "e": 12025, "s": 11879, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 12061, "s": 12025, "text": " Login to access your submissions. " }, { "code": null, "e": 12071, "s": 12061, "text": "\nProblem\n" }, { "code": null, "e": 12081, "s": 12071, "text": "\nContest\n" }, { "code": null, "e": 12144, "s": 12081, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 12292, "s": 12144, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 12500, "s": 12292, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 12606, "s": 12500, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C# Program to convert Digits to Words
Firstly, declare the words from 0 to 9 − // words for every digits from 0 to 9 string[] digits_words = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; The following are the digits to be converted to words − // number to be converted into words val = 4677; Console.WriteLine("Number: " + val); Use the loop to check for every digit in the given number and convert into words − do { next = val % 10; a[num_digits] = next; num_digits++; val = val / 10; } while(val > 0); You can try to run the following code to converts digits to words. Live Demo using System; using System.Collections.Generic; using System.Text; namespace Demo { class MyApplication { static void Main(string[] args) { int val, next, num_digits; int[] a = new int[10]; // words for every digits from 0 to 9 string[] digits_words = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; // number to be converted into words val = 4677; Console.WriteLine("Number: " + val); Console.Write("Number (words): "); next = 0; num_digits = 0; do { next = val % 10; a[num_digits] = next; num_digits++; val = val / 10; } while (val > 0); num_digits--; for (; num_digits >= 0; num_digits--) Console.Write(digits_words[a[num_digits]] + " "); Console.ReadLine(); } } } Number: 4677 Number (words): four six seven seven
[ { "code": null, "e": 1103, "s": 1062, "text": "Firstly, declare the words from 0 to 9 −" }, { "code": null, "e": 1258, "s": 1103, "text": "// words for every digits from 0 to 9\nstring[] digits_words = { \"zero\", \"one\", \"two\",\n \"three\", \"four\", \"five\",\n \"six\", \"seven\", \"eight\",\n \"nine\"\n};" }, { "code": null, "e": 1314, "s": 1258, "text": "The following are the digits to be converted to words −" }, { "code": null, "e": 1400, "s": 1314, "text": "// number to be converted into words\nval = 4677;\nConsole.WriteLine(\"Number: \" + val);" }, { "code": null, "e": 1483, "s": 1400, "text": "Use the loop to check for every digit in the given number and convert into words −" }, { "code": null, "e": 1587, "s": 1483, "text": "do {\n next = val % 10;\n a[num_digits] = next;\n num_digits++;\n val = val / 10;\n} while(val > 0);" }, { "code": null, "e": 1654, "s": 1587, "text": "You can try to run the following code to converts digits to words." }, { "code": null, "e": 1664, "s": 1654, "text": "Live Demo" }, { "code": null, "e": 2707, "s": 1664, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nnamespace Demo {\n class MyApplication {\n static void Main(string[] args) {\n int val, next, num_digits;\n int[] a = new int[10];\n // words for every digits from 0 to 9\n string[] digits_words = {\n \"zero\",\n \"one\",\n \"two\",\n \"three\",\n \"four\",\n \"five\",\n \"six\",\n \"seven\",\n \"eight\",\n \"nine\"\n };\n // number to be converted into words\n val = 4677;\n Console.WriteLine(\"Number: \" + val);\n Console.Write(\"Number (words): \");\n next = 0;\n num_digits = 0;\n do {\n next = val % 10;\n a[num_digits] = next;\n num_digits++;\n val = val / 10;\n } while (val > 0);\n num_digits--;\n for (; num_digits >= 0; num_digits--)\n Console.Write(digits_words[a[num_digits]] + \" \");\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2758, "s": 2707, "text": "Number: 4677\nNumber (words): four six seven seven " } ]
Program to Implement NFA with epsilon move to DFA Conversion - GeeksforGeeks
20 Feb, 2018 Non-determinestic Finite Automata (NFA) : NFA is a finite automaton where for some cases when a single input is given to a single state, the machine goes to more than 1 states, i.e. some of the moves cannot be uniquely determined by the present state and the present input symbol. An NFA can be represented as M = { Q, ∑, ∂, q0, F} Q → Finite non-empty set of states.∑ → Finite non-empty set of input symbols.∂ → Transitional Function.q0 → Beginning state.F → Final State NFA with (null) or ∈ move : If any finite automata contains ε (null) move or transaction, then that finite automata is called NFA with ∈ moves Example :Consider the following figure of NFA with ∈ move : Transition state table for the above NFA Epsilon (∈) – closure : Epsilon closure for a given state X is a set of states which can be reached from the states X with only (null) or ε moves including the state X itself. In other words, ε-closure for a state can be obtained by union operation of the ε-closure of the states which can be reached from X with a single ε move in recursive manner. For the above example ∈ closure are as follows : ∈ closure(A) : {A, B, C} ∈ closure(B) : {B, C} ∈ closure(C) : {C} Deterministic Finite Automata (DFA) : DFA is a finite automata where, for all cases, when a single input is given to a single state, the machine goes to a single state, i.e., all the moves of the machine can be uniquely determined by the present state and the present input symbol. Step 1 : Take ∈ closure for the beginning state of NFA as beginning state of DFA.Step 2 : Find the states that can be traversed from the present for each input symbol(union of transition value and their closures for each states of NFA present in current state of DFA). Step 3 : If any new state is found take it as current state and repeat step 2.Step 4 : Do repeat Step 2 and Step 3 until no new state present in DFA transition table.Step 5 : Mark the states of DFA which contains final state of NFA as final states of DFA. Transition State Table for DFA corresponding to above NFA DFA STATE DIAGRAM Examples : Input : 6 2 FC - BF - C - - - D E A - A - BF - - - Output : STATES OF NFA : A, B, C, D, E, F, GIVEN SYMBOLS FOR NFA: 0, 1, eps NFA STATE TRANSITION TABLE STATES |0 |1 eps --------+------------------------------------ A |FC |- |BF B |- |C |- C |- |- |D D |E |A |- E |A |- |BF F |- |- |- e-Closure (A) : ABF e-Closure (B) : B e-Closure (C) : CD e-Closure (D) : D e-Closure (E) : BEF e-Closure (F) : F ******************************************************** DFA TRANSITION STATE TABLE STATES OF DFA : ABF, CDF, CD, BEF, GIVEN SYMBOLS FOR DFA: 0, 1, STATES |0 |1 --------+----------------------- ABF |CDF |CD CDF |BEF |ABF CD |BEF |ABF BEF |ABF |CD Input : 9 2 - - BH - - CE D - - - - G - F - - - G - - BH I - - - - - Output : STATES OF NFA : A, B, C, D, E, F, G, H, I, GIVEN SYMBOLS FOR NFA: 0, 1, eps NFA STATE TRANSITION TABLE STATES |0 |1 eps --------+------------------------------------ A |- |- |BH B |- |- |CE C |D |- |- D |- |- |G E |- |F |- F |- |- |G G |- |- |BH H |I |- |- I |- |- |- e-Closure (A) : ABCEH e-Closure (B) : BCE e-Closure (C) : C e-Closure (D) : BCDEGH e-Closure (E) : E e-Closure (F) : BCEFGH e-Closure (G) : BCEGH e-Closure (H) : H e-Closure (I) : I ******************************************************** DFA TRANSITION STATE TABLE STATES OF DFA : ABCEH, BCDEGHI, BCEFGH, GIVEN SYMBOLS FOR DFA: 0, 1, STATES |0 |1 --------+----------------------- ABCEH |BCDEGHI |BCEFGH BCDEGHI |BCDEGHI |BCEFGH BCEFGH |BCDEGHI |BCEFGH Explanation :First line of the input contains the number of states (N) of NFA. Second line of the input says the number of input symbols (S). In example1 number of states of NFA is 6 i.e.( A, B, C, D, E, F) and 2 input symbols i.e. ( 0, 1). Since we are working on NFA with ∈ move, ∈ will be added as an extra input symbol. The next N lines contains the transition values for every state of NFA. The value of ith row, jth column indicates transition value for ith state on jth input symbol. Here in example1 transition(A, 0) : FC. Output contains the NFA, ∈ closure for every states of the corresponding NFA and DFA obtained by converting the input NFA. States and input symbols of the DFA are also specified. Below is the implementation of above approach : // C Program to illustrate how to convert e-nfa to DFA #include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX_LEN 100 char NFA_FILE[MAX_LEN];char buffer[MAX_LEN];int zz = 0; // Structure to store DFA states and their// status ( i.e new entry or already present)struct DFA { char *states; int count;} dfa; int last_index = 0;FILE *fp;int symbols; /* reset the hash map*/void reset(int ar[], int size) { int i; // reset all the values of // the mapping array to zero for (i = 0; i < size; i++) { ar[i] = 0; }} // Check which States are present in the e-closure /* map the states of NFA to a hash set*/void check(int ar[], char S[]) { int i, j; // To parse the individual states of NFA int len = strlen(S); for (i = 0; i < len; i++) { // Set hash map for the position // of the states which is found j = ((int)(S[i]) - 65); ar[j]++; }} // To find new Closure Statesvoid state(int ar[], int size, char S[]) { int j, k = 0; // Combine multiple states of NFA // to create new states of DFA for (j = 0; j < size; j++) { if (ar[j] != 0) S[k++] = (char)(65 + j); } // mark the end of the state S[k] = '\0';} // To pick the next closure from closure setint closure(int ar[], int size) { int i; // check new closure is present or not for (i = 0; i < size; i++) { if (ar[i] == 1) return i; } return (100);} // Check new DFA states can be// entered in DFA table or notint indexing(struct DFA *dfa) { int i; for (i = 0; i < last_index; i++) { if (dfa[i].count == 0) return 1; } return -1;} /* To Display epsilon closure*/void Display_closure(int states, int closure_ar[], char *closure_table[], char *NFA_TABLE[][symbols + 1], char *DFA_TABLE[][symbols]) { int i; for (i = 0; i < states; i++) { reset(closure_ar, states); closure_ar[i] = 2; // to neglect blank entry if (strcmp(&NFA_TABLE[i][symbols], "-") != 0) { // copy the NFA transition state to buffer strcpy(buffer, &NFA_TABLE[i][symbols]); check(closure_ar, buffer); int z = closure(closure_ar, states); // till closure get completely saturated while (z != 100) { if (strcmp(&NFA_TABLE[z][symbols], "-") != 0) { strcpy(buffer, &NFA_TABLE[z][symbols]); // call the check function check(closure_ar, buffer); } closure_ar[z]++; z = closure(closure_ar, states); } } // print the e closure for every states of NFA printf("\n e-Closure (%c) :\t", (char)(65 + i)); bzero((void *)buffer, MAX_LEN); state(closure_ar, states, buffer); strcpy(&closure_table[i], buffer); printf("%s\n", &closure_table[i]); }} /* To check New States in DFA */int new_states(struct DFA *dfa, char S[]) { int i; // To check the current state is already // being used as a DFA state or not in // DFA transition table for (i = 0; i < last_index; i++) { if (strcmp(&dfa[i].states, S) == 0) return 0; } // push the new strcpy(&dfa[last_index++].states, S); // set the count for new states entered // to zero dfa[last_index - 1].count = 0; return 1;} // Transition function from NFA to DFA// (generally union of closure operation )void trans(char S[], int M, char *clsr_t[], int st, char *NFT[][symbols + 1], char TB[]) { int len = strlen(S); int i, j, k, g; int arr[st]; int sz; reset(arr, st); char temp[MAX_LEN], temp2[MAX_LEN]; char *buff; // Transition function from NFA to DFA for (i = 0; i < len; i++) { j = ((int)(S[i] - 65)); strcpy(temp, &NFT[j][M]); if (strcmp(temp, "-") != 0) { sz = strlen(temp); g = 0; while (g < sz) { k = ((int)(temp[g] - 65)); strcpy(temp2, &clsr_t[k]); check(arr, temp2); g++; } } } bzero((void *)temp, MAX_LEN); state(arr, st, temp); if (temp[0] != '\0') { strcpy(TB, temp); } else strcpy(TB, "-");} /* Display DFA transition state table*/void Display_DFA(int last_index, struct DFA *dfa_states, char *DFA_TABLE[][symbols]) { int i, j; printf("\n\n********************************************************\n\n"); printf("\t\t DFA TRANSITION STATE TABLE \t\t \n\n"); printf("\n STATES OF DFA :\t\t"); for (i = 1; i < last_index; i++) printf("%s, ", &dfa_states[i].states); printf("\n"); printf("\n GIVEN SYMBOLS FOR DFA: \t"); for (i = 0; i < symbols; i++) printf("%d, ", i); printf("\n\n"); printf("STATES\t"); for (i = 0; i < symbols; i++) printf("|%d\t", i); printf("\n"); // display the DFA transition state table printf("--------+-----------------------\n"); for (i = 0; i < zz; i++) { printf("%s\t", &dfa_states[i + 1].states); for (j = 0; j < symbols; j++) { printf("|%s \t", &DFA_TABLE[i][j]); } printf("\n"); }} // Driver Codeint main() { int i, j, states; char T_buf[MAX_LEN]; // creating an array dfa structures struct DFA *dfa_states = malloc(MAX_LEN * (sizeof(dfa))); states = 6, symbols = 2; printf("\n STATES OF NFA :\t\t"); for (i = 0; i < states; i++) printf("%c, ", (char)(65 + i)); printf("\n"); printf("\n GIVEN SYMBOLS FOR NFA: \t"); for (i = 0; i < symbols; i++) printf("%d, ", i); printf("eps"); printf("\n\n"); char *NFA_TABLE[states][symbols + 1]; // Hard coded input for NFA table char *DFA_TABLE[MAX_LEN][symbols]; strcpy(&NFA_TABLE[0][0], "FC"); strcpy(&NFA_TABLE[0][1], "-"); strcpy(&NFA_TABLE[0][2], "BF"); strcpy(&NFA_TABLE[1][0], "-"); strcpy(&NFA_TABLE[1][1], "C"); strcpy(&NFA_TABLE[1][2], "-"); strcpy(&NFA_TABLE[2][0], "-"); strcpy(&NFA_TABLE[2][1], "-"); strcpy(&NFA_TABLE[2][2], "D"); strcpy(&NFA_TABLE[3][0], "E"); strcpy(&NFA_TABLE[3][1], "A"); strcpy(&NFA_TABLE[3][2], "-"); strcpy(&NFA_TABLE[4][0], "A"); strcpy(&NFA_TABLE[4][1], "-"); strcpy(&NFA_TABLE[4][2], "BF"); strcpy(&NFA_TABLE[5][0], "-"); strcpy(&NFA_TABLE[5][1], "-"); strcpy(&NFA_TABLE[5][2], "-"); printf("\n NFA STATE TRANSITION TABLE \n\n\n"); printf("STATES\t"); for (i = 0; i < symbols; i++) printf("|%d\t", i); printf("eps\n"); // Displaying the matrix of NFA transition table printf("--------+------------------------------------\n"); for (i = 0; i < states; i++) { printf("%c\t", (char)(65 + i)); for (j = 0; j <= symbols; j++) { printf("|%s \t", &NFA_TABLE[i][j]); } printf("\n"); } int closure_ar[states]; char *closure_table[states]; Display_closure(states, closure_ar, closure_table, NFA_TABLE, DFA_TABLE); strcpy(&dfa_states[last_index++].states, "-"); dfa_states[last_index - 1].count = 1; bzero((void *)buffer, MAX_LEN); strcpy(buffer, &closure_table[0]); strcpy(&dfa_states[last_index++].states, buffer); int Sm = 1, ind = 1; int start_index = 1; // Filling up the DFA table with transition values // Till new states can be entered in DFA table while (ind != -1) { dfa_states[start_index].count = 1; Sm = 0; for (i = 0; i < symbols; i++) { trans(buffer, i, closure_table, states, NFA_TABLE, T_buf); // storing the new DFA state in buffer strcpy(&DFA_TABLE[zz][i], T_buf); // parameter to control new states Sm = Sm + new_states(dfa_states, T_buf); } ind = indexing(dfa_states); if (ind != -1) strcpy(buffer, &dfa_states[++start_index].states); zz++; } // display the DFA TABLE Display_DFA(last_index, dfa_states, DFA_TABLE); return 0;} Use of NFA with ∈ move : If we want to construct an FA which accepts a language, sometimes it becomes very difficult or seems to be impossible to construct a direct NFA or DFA. But if NFA with ∈ moves is used, then the transitional diagram can be constructed and described easily. Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between DFA and NFA Design 101 sequence detector (Mealy machine) Conversion of Epsilon-NFA to NFA Closure properties of Regular languages Regular expression to ∈-NFA Program to construct a DFA which accept the language L = {anbm | n mod 2=0, m≥1} Removal of ambiguity (Converting an Ambiguous grammar into Unambiguous grammar) Post Correspondence Problem Boyer-Moore Majority Voting Algorithm CYK Algorithm for Context Free Grammar
[ { "code": null, "e": 29834, "s": 29806, "text": "\n20 Feb, 2018" }, { "code": null, "e": 30115, "s": 29834, "text": "Non-determinestic Finite Automata (NFA) : NFA is a finite automaton where for some cases when a single input is given to a single state, the machine goes to more than 1 states, i.e. some of the moves cannot be uniquely determined by the present state and the present input symbol." }, { "code": null, "e": 30166, "s": 30115, "text": "An NFA can be represented as M = { Q, ∑, ∂, q0, F}" }, { "code": null, "e": 30306, "s": 30166, "text": "Q → Finite non-empty set of states.∑ → Finite non-empty set of input symbols.∂ → Transitional Function.q0 → Beginning state.F → Final State" }, { "code": null, "e": 30449, "s": 30306, "text": "NFA with (null) or ∈ move : If any finite automata contains ε (null) move or transaction, then that finite automata is called NFA with ∈ moves" }, { "code": null, "e": 30509, "s": 30449, "text": "Example :Consider the following figure of NFA with ∈ move :" }, { "code": null, "e": 30550, "s": 30509, "text": "Transition state table for the above NFA" }, { "code": null, "e": 30900, "s": 30550, "text": "Epsilon (∈) – closure : Epsilon closure for a given state X is a set of states which can be reached from the states X with only (null) or ε moves including the state X itself. In other words, ε-closure for a state can be obtained by union operation of the ε-closure of the states which can be reached from X with a single ε move in recursive manner." }, { "code": null, "e": 30949, "s": 30900, "text": "For the above example ∈ closure are as follows :" }, { "code": null, "e": 31015, "s": 30949, "text": "∈ closure(A) : {A, B, C}\n∈ closure(B) : {B, C}\n∈ closure(C) : {C}" }, { "code": null, "e": 31298, "s": 31015, "text": " Deterministic Finite Automata (DFA) : DFA is a finite automata where, for all cases, when a single input is given to a single state, the machine goes to a single state, i.e., all the moves of the machine can be uniquely determined by the present state and the present input symbol." }, { "code": null, "e": 31567, "s": 31298, "text": "Step 1 : Take ∈ closure for the beginning state of NFA as beginning state of DFA.Step 2 : Find the states that can be traversed from the present for each input symbol(union of transition value and their closures for each states of NFA present in current state of DFA)." }, { "code": null, "e": 31823, "s": 31567, "text": "Step 3 : If any new state is found take it as current state and repeat step 2.Step 4 : Do repeat Step 2 and Step 3 until no new state present in DFA transition table.Step 5 : Mark the states of DFA which contains final state of NFA as final states of DFA." }, { "code": null, "e": 31881, "s": 31823, "text": "Transition State Table for DFA corresponding to above NFA" }, { "code": null, "e": 31899, "s": 31881, "text": "DFA STATE DIAGRAM" }, { "code": null, "e": 31910, "s": 31899, "text": "Examples :" }, { "code": null, "e": 33976, "s": 31910, "text": "Input : 6\n 2\n FC - BF\n - C -\n - - D\n E A -\n A - BF\n - - -\n\n\nOutput :\n STATES OF NFA : A, B, C, D, E, F,\n\n GIVEN SYMBOLS FOR NFA: 0, 1, eps\n\n\n NFA STATE TRANSITION TABLE \n\n\nSTATES |0 |1 eps\n--------+------------------------------------\nA |FC |- |BF \nB |- |C |- \nC |- |- |D \nD |E |A |- \nE |A |- |BF \nF |- |- |- \n\n e-Closure (A) : ABF\n\n e-Closure (B) : B\n\n e-Closure (C) : CD\n\n e-Closure (D) : D\n\n e-Closure (E) : BEF\n\n e-Closure (F) : F\n\n\n********************************************************\n\n DFA TRANSITION STATE TABLE \n\n\n STATES OF DFA : ABF, CDF, CD, BEF,\n\n GIVEN SYMBOLS FOR DFA: 0, 1,\n\nSTATES |0 |1 \n--------+-----------------------\nABF |CDF |CD \nCDF |BEF |ABF \nCD |BEF |ABF \nBEF |ABF |CD \n\n\n\nInput :\n9\n2\n- - BH\n- - CE\nD - -\n- - G\n- F -\n- - G\n- - BH\nI - -\n- - -\n\n\nOutput :\n\nSTATES OF NFA : A, B, C, D, E, F, G, H, I,\n\n GIVEN SYMBOLS FOR NFA: 0, 1, eps\n\n\n NFA STATE TRANSITION TABLE \n\n\nSTATES |0 |1 eps\n--------+------------------------------------\nA |- |- |BH \nB |- |- |CE \nC |D |- |- \nD |- |- |G \nE |- |F |- \nF |- |- |G \nG |- |- |BH \nH |I |- |- \nI |- |- |- \n\n e-Closure (A) : ABCEH\n\n e-Closure (B) : BCE\n\n e-Closure (C) : C\n\n e-Closure (D) : BCDEGH\n\n e-Closure (E) : E\n\n e-Closure (F) : BCEFGH\n\n e-Closure (G) : BCEGH\n\n e-Closure (H) : H\n\n e-Closure (I) : I\n\n\n********************************************************\n\n DFA TRANSITION STATE TABLE \n\n\n STATES OF DFA : ABCEH, BCDEGHI, BCEFGH,\n\n GIVEN SYMBOLS FOR DFA: 0, 1,\n\nSTATES |0 |1 \n--------+-----------------------\nABCEH |BCDEGHI |BCEFGH \nBCDEGHI |BCDEGHI |BCEFGH \nBCEFGH |BCDEGHI |BCEFGH \n\n" }, { "code": null, "e": 34507, "s": 33976, "text": "Explanation :First line of the input contains the number of states (N) of NFA. Second line of the input says the number of input symbols (S). In example1 number of states of NFA is 6 i.e.( A, B, C, D, E, F) and 2 input symbols i.e. ( 0, 1). Since we are working on NFA with ∈ move, ∈ will be added as an extra input symbol. The next N lines contains the transition values for every state of NFA. The value of ith row, jth column indicates transition value for ith state on jth input symbol. Here in example1 transition(A, 0) : FC." }, { "code": null, "e": 34686, "s": 34507, "text": "Output contains the NFA, ∈ closure for every states of the corresponding NFA and DFA obtained by converting the input NFA. States and input symbols of the DFA are also specified." }, { "code": null, "e": 34734, "s": 34686, "text": "Below is the implementation of above approach :" }, { "code": "// C Program to illustrate how to convert e-nfa to DFA #include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX_LEN 100 char NFA_FILE[MAX_LEN];char buffer[MAX_LEN];int zz = 0; // Structure to store DFA states and their// status ( i.e new entry or already present)struct DFA { char *states; int count;} dfa; int last_index = 0;FILE *fp;int symbols; /* reset the hash map*/void reset(int ar[], int size) { int i; // reset all the values of // the mapping array to zero for (i = 0; i < size; i++) { ar[i] = 0; }} // Check which States are present in the e-closure /* map the states of NFA to a hash set*/void check(int ar[], char S[]) { int i, j; // To parse the individual states of NFA int len = strlen(S); for (i = 0; i < len; i++) { // Set hash map for the position // of the states which is found j = ((int)(S[i]) - 65); ar[j]++; }} // To find new Closure Statesvoid state(int ar[], int size, char S[]) { int j, k = 0; // Combine multiple states of NFA // to create new states of DFA for (j = 0; j < size; j++) { if (ar[j] != 0) S[k++] = (char)(65 + j); } // mark the end of the state S[k] = '\\0';} // To pick the next closure from closure setint closure(int ar[], int size) { int i; // check new closure is present or not for (i = 0; i < size; i++) { if (ar[i] == 1) return i; } return (100);} // Check new DFA states can be// entered in DFA table or notint indexing(struct DFA *dfa) { int i; for (i = 0; i < last_index; i++) { if (dfa[i].count == 0) return 1; } return -1;} /* To Display epsilon closure*/void Display_closure(int states, int closure_ar[], char *closure_table[], char *NFA_TABLE[][symbols + 1], char *DFA_TABLE[][symbols]) { int i; for (i = 0; i < states; i++) { reset(closure_ar, states); closure_ar[i] = 2; // to neglect blank entry if (strcmp(&NFA_TABLE[i][symbols], \"-\") != 0) { // copy the NFA transition state to buffer strcpy(buffer, &NFA_TABLE[i][symbols]); check(closure_ar, buffer); int z = closure(closure_ar, states); // till closure get completely saturated while (z != 100) { if (strcmp(&NFA_TABLE[z][symbols], \"-\") != 0) { strcpy(buffer, &NFA_TABLE[z][symbols]); // call the check function check(closure_ar, buffer); } closure_ar[z]++; z = closure(closure_ar, states); } } // print the e closure for every states of NFA printf(\"\\n e-Closure (%c) :\\t\", (char)(65 + i)); bzero((void *)buffer, MAX_LEN); state(closure_ar, states, buffer); strcpy(&closure_table[i], buffer); printf(\"%s\\n\", &closure_table[i]); }} /* To check New States in DFA */int new_states(struct DFA *dfa, char S[]) { int i; // To check the current state is already // being used as a DFA state or not in // DFA transition table for (i = 0; i < last_index; i++) { if (strcmp(&dfa[i].states, S) == 0) return 0; } // push the new strcpy(&dfa[last_index++].states, S); // set the count for new states entered // to zero dfa[last_index - 1].count = 0; return 1;} // Transition function from NFA to DFA// (generally union of closure operation )void trans(char S[], int M, char *clsr_t[], int st, char *NFT[][symbols + 1], char TB[]) { int len = strlen(S); int i, j, k, g; int arr[st]; int sz; reset(arr, st); char temp[MAX_LEN], temp2[MAX_LEN]; char *buff; // Transition function from NFA to DFA for (i = 0; i < len; i++) { j = ((int)(S[i] - 65)); strcpy(temp, &NFT[j][M]); if (strcmp(temp, \"-\") != 0) { sz = strlen(temp); g = 0; while (g < sz) { k = ((int)(temp[g] - 65)); strcpy(temp2, &clsr_t[k]); check(arr, temp2); g++; } } } bzero((void *)temp, MAX_LEN); state(arr, st, temp); if (temp[0] != '\\0') { strcpy(TB, temp); } else strcpy(TB, \"-\");} /* Display DFA transition state table*/void Display_DFA(int last_index, struct DFA *dfa_states, char *DFA_TABLE[][symbols]) { int i, j; printf(\"\\n\\n********************************************************\\n\\n\"); printf(\"\\t\\t DFA TRANSITION STATE TABLE \\t\\t \\n\\n\"); printf(\"\\n STATES OF DFA :\\t\\t\"); for (i = 1; i < last_index; i++) printf(\"%s, \", &dfa_states[i].states); printf(\"\\n\"); printf(\"\\n GIVEN SYMBOLS FOR DFA: \\t\"); for (i = 0; i < symbols; i++) printf(\"%d, \", i); printf(\"\\n\\n\"); printf(\"STATES\\t\"); for (i = 0; i < symbols; i++) printf(\"|%d\\t\", i); printf(\"\\n\"); // display the DFA transition state table printf(\"--------+-----------------------\\n\"); for (i = 0; i < zz; i++) { printf(\"%s\\t\", &dfa_states[i + 1].states); for (j = 0; j < symbols; j++) { printf(\"|%s \\t\", &DFA_TABLE[i][j]); } printf(\"\\n\"); }} // Driver Codeint main() { int i, j, states; char T_buf[MAX_LEN]; // creating an array dfa structures struct DFA *dfa_states = malloc(MAX_LEN * (sizeof(dfa))); states = 6, symbols = 2; printf(\"\\n STATES OF NFA :\\t\\t\"); for (i = 0; i < states; i++) printf(\"%c, \", (char)(65 + i)); printf(\"\\n\"); printf(\"\\n GIVEN SYMBOLS FOR NFA: \\t\"); for (i = 0; i < symbols; i++) printf(\"%d, \", i); printf(\"eps\"); printf(\"\\n\\n\"); char *NFA_TABLE[states][symbols + 1]; // Hard coded input for NFA table char *DFA_TABLE[MAX_LEN][symbols]; strcpy(&NFA_TABLE[0][0], \"FC\"); strcpy(&NFA_TABLE[0][1], \"-\"); strcpy(&NFA_TABLE[0][2], \"BF\"); strcpy(&NFA_TABLE[1][0], \"-\"); strcpy(&NFA_TABLE[1][1], \"C\"); strcpy(&NFA_TABLE[1][2], \"-\"); strcpy(&NFA_TABLE[2][0], \"-\"); strcpy(&NFA_TABLE[2][1], \"-\"); strcpy(&NFA_TABLE[2][2], \"D\"); strcpy(&NFA_TABLE[3][0], \"E\"); strcpy(&NFA_TABLE[3][1], \"A\"); strcpy(&NFA_TABLE[3][2], \"-\"); strcpy(&NFA_TABLE[4][0], \"A\"); strcpy(&NFA_TABLE[4][1], \"-\"); strcpy(&NFA_TABLE[4][2], \"BF\"); strcpy(&NFA_TABLE[5][0], \"-\"); strcpy(&NFA_TABLE[5][1], \"-\"); strcpy(&NFA_TABLE[5][2], \"-\"); printf(\"\\n NFA STATE TRANSITION TABLE \\n\\n\\n\"); printf(\"STATES\\t\"); for (i = 0; i < symbols; i++) printf(\"|%d\\t\", i); printf(\"eps\\n\"); // Displaying the matrix of NFA transition table printf(\"--------+------------------------------------\\n\"); for (i = 0; i < states; i++) { printf(\"%c\\t\", (char)(65 + i)); for (j = 0; j <= symbols; j++) { printf(\"|%s \\t\", &NFA_TABLE[i][j]); } printf(\"\\n\"); } int closure_ar[states]; char *closure_table[states]; Display_closure(states, closure_ar, closure_table, NFA_TABLE, DFA_TABLE); strcpy(&dfa_states[last_index++].states, \"-\"); dfa_states[last_index - 1].count = 1; bzero((void *)buffer, MAX_LEN); strcpy(buffer, &closure_table[0]); strcpy(&dfa_states[last_index++].states, buffer); int Sm = 1, ind = 1; int start_index = 1; // Filling up the DFA table with transition values // Till new states can be entered in DFA table while (ind != -1) { dfa_states[start_index].count = 1; Sm = 0; for (i = 0; i < symbols; i++) { trans(buffer, i, closure_table, states, NFA_TABLE, T_buf); // storing the new DFA state in buffer strcpy(&DFA_TABLE[zz][i], T_buf); // parameter to control new states Sm = Sm + new_states(dfa_states, T_buf); } ind = indexing(dfa_states); if (ind != -1) strcpy(buffer, &dfa_states[++start_index].states); zz++; } // display the DFA TABLE Display_DFA(last_index, dfa_states, DFA_TABLE); return 0;}", "e": 42213, "s": 34734, "text": null }, { "code": null, "e": 42494, "s": 42213, "text": "Use of NFA with ∈ move : If we want to construct an FA which accepts a language, sometimes it becomes very difficult or seems to be impossible to construct a direct NFA or DFA. But if NFA with ∈ moves is used, then the transitional diagram can be constructed and described easily." }, { "code": null, "e": 42527, "s": 42494, "text": "Theory of Computation & Automata" }, { "code": null, "e": 42625, "s": 42527, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42634, "s": 42625, "text": "Comments" }, { "code": null, "e": 42647, "s": 42634, "text": "Old Comments" }, { "code": null, "e": 42678, "s": 42647, "text": "Difference between DFA and NFA" }, { "code": null, "e": 42723, "s": 42678, "text": "Design 101 sequence detector (Mealy machine)" }, { "code": null, "e": 42756, "s": 42723, "text": "Conversion of Epsilon-NFA to NFA" }, { "code": null, "e": 42796, "s": 42756, "text": "Closure properties of Regular languages" }, { "code": null, "e": 42824, "s": 42796, "text": "Regular expression to ∈-NFA" }, { "code": null, "e": 42905, "s": 42824, "text": "Program to construct a DFA which accept the language L = {anbm | n mod 2=0, m≥1}" }, { "code": null, "e": 42985, "s": 42905, "text": "Removal of ambiguity (Converting an Ambiguous grammar into Unambiguous grammar)" }, { "code": null, "e": 43013, "s": 42985, "text": "Post Correspondence Problem" }, { "code": null, "e": 43051, "s": 43013, "text": "Boyer-Moore Majority Voting Algorithm" } ]
Espresso Testing Framework - View Matchers
Espresso framework provides many view matchers. The purpose of the matcher is to match a view using different attributes of the view like Id, Text, and availability of child view. Each matcher matches a particular attributes of the view and applies to particular type of view. For example, withId matcher matches the Id property of the view and applies to all view, whereas withText matcher matches the Text property of the view and applies to TextView only. In this chapter, let us learn the different matchers provided by espresso testing framework as well as learn the Hamcrest library upon which the espresso matchers are built. Hamcrest library is an important library in the scope of espresso testing framework. Hamcrest is itself a framework for writing matcher objects. Espresso framework extensively uses the Hamcrest library and extend it whenever necessary to provide simple and extendable matchers. Hamcrest provides a simple function assertThat and a collection of matchers to assert any objects. assertThat has three arguments and they are as shown below − String (description of the test, optional) String (description of the test, optional) Object (actual) Object (actual) Matcher (expected) Matcher (expected) Let us write a simple example to test whether a list object has expected value. import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.MatcherAssert.assertThat; @Test public void list_hasValue() { ArrayList<String> list = new ArrayList<String>(); list.add("John"); assertThat("Is list has John?", list, hasItem("John")); } Here, hasItem returns a matcher, which checks whether the actual list has specified value as one of the item. Hamcrest has a lot of built-in matchers and also options to create new matchers. Some of the important built-in matchers useful in espresso testing framework are as follows − Logical based matchers allOf − accept any number of matchers and matches only if all matchers are succeeded. allOf − accept any number of matchers and matches only if all matchers are succeeded. anyOf − accept any number of matchers and matches if any one matcher succeeded. anyOf − accept any number of matchers and matches if any one matcher succeeded. not − accept one matcher and matches only if the matcher failed and vice versa. not − accept one matcher and matches only if the matcher failed and vice versa. equalToIgnoringCase − used to test whether the actual input equals the expected string ignoring case. equalToIgnoringCase − used to test whether the actual input equals the expected string ignoring case. equalToIgnoringWhiteSpace − used to test whether the actual input equals the specified string ignoring case and white spaces. equalToIgnoringWhiteSpace − used to test whether the actual input equals the specified string ignoring case and white spaces. containsString − used to test whether the actual input contains specified string. containsString − used to test whether the actual input contains specified string. endsWith − used to test whether the actual input starts with specified string. endsWith − used to test whether the actual input starts with specified string. startsWith − used to test whether actual the input ends with specified string. startsWith − used to test whether actual the input ends with specified string. closeTo − used to test whether the actual input is close to the expected number. closeTo − used to test whether the actual input is close to the expected number. greaterThan − used to test whether the actual input is greater than the expected number. greaterThan − used to test whether the actual input is greater than the expected number. greaterThanOrEqualTo − used to test whether the actual input is greater than or equal to the expected number. greaterThanOrEqualTo − used to test whether the actual input is greater than or equal to the expected number. lessThan − used to test whether the actual input is less than the expected number. lessThan − used to test whether the actual input is less than the expected number. lessThanOrEqualTo − used to test whether the actual input is less than or equal to the expected number. lessThanOrEqualTo − used to test whether the actual input is less than or equal to the expected number. equalTo − used to test whether the actual input is equals to the expected object equalTo − used to test whether the actual input is equals to the expected object hasToString − used to test whether the actual input has toString method. hasToString − used to test whether the actual input has toString method. instanceOf − used to test whether the actual input is the instance of expected class. instanceOf − used to test whether the actual input is the instance of expected class. isCompatibleType − used to test whether the actual input is compatible with the expected type. isCompatibleType − used to test whether the actual input is compatible with the expected type. notNullValue − used to test whether the actual input is not null. notNullValue − used to test whether the actual input is not null. sameInstance − used to test whether the actual input and expected are of same instance. sameInstance − used to test whether the actual input and expected are of same instance. hasProperty − used to test whether the actual input has the expected property hasProperty − used to test whether the actual input has the expected property Espresso provides the onView() method to match and find the views. It accepts view matchers and returns ViewInteraction object to interact with the matched view. The frequently used list of view matchers are described below − withId() accepts an argument of type int and the argument refers the id of the view. It returns a matcher, which matches the view using the id of the view. The sample code is as follows, onView(withId(R.id.testView)) withText() accepts an argument of type string and the argument refers the value of the view’s text property. It returns a matcher, which matches the view using the text value of the view. It applies to TextView only. The sample code is as follows, onView(withText("Hello World!")) withContentDescription() accepts an argument of type string and the argument refers the value of the view’s content description property. It returns a matcher, which matches the view using the description of the view. The sample code is as follows, onView(withContentDescription("blah")) We can also pass the resource id of the text value instead of the text itself. onView(withContentDescription(R.id.res_id_blah)) hasContentDescription() has no argument. It returns a matcher, which matches the view that has any content description. The sample code is as follows, onView(allOf(withId(R.id.my_view_id), hasContentDescription())) withTagKey() accepts an argument of type string and the argument refers the view’s tag key. It returns a matcher, which matches the view using its tag key. The sample code is as follows, onView(withTagKey("blah")) We can also pass the resource id of the tag name instead of the tag name itself. onView(withTagKey(R.id.res_id_blah)) withTagValue() accepts an argument of type Matcher <Object> and the argument refers the view’s tag value. It returns a matcher, which matches the view using its tag value. The sample code is as follows, onView(withTagValue(is((Object) "blah"))) Here, is is Hamcrest matcher. withClassName() accepts an argument of type Matcher<String> and the argument refers the view’s class name value. It returns a matcher, which matches the view using its class name. The sample code is as follows, onView(withClassName(endsWith("EditText"))) Here, endsWith is Hamcrest matcher and return Matcher<String> withHint() accepts an argument of type Matcher<String> and the argument refers the view’s hint value. It returns a matcher, which matches the view using the hint of the view. The sample code is as follows, onView(withClassName(endsWith("Enter name"))) withInputType() accepts an argument of type int and the argument refers the input type of the view. It returns a matcher, which matches the view using its input type. The sample code is as follows, onView(withInputType(TYPE_CLASS_DATETIME)) Here, TYPE_CLASS_DATETIME refers edit view supporting dates and times. withResourceName() accepts an argument of type Matcher<String> and the argument refers the view’s class name value. It returns a matcher, which matches the view using resource name of the view. The sample code is as follows, onView(withResourceName(endsWith("res_name"))) It accepts string argument as well. The sample code is as follows, onView(withResourceName("my_res_name")) withAlpha() accepts an argument of type float and the argument refers the alpha value of the view. It returns a matcher, which matches the view using the alpha value of the view. The sample code is as follows, onView(withAlpha(0.8)) withEffectiveVisibility() accepts an argument of type ViewMatchers.Visibility and the argument refers the effective visibility of the view. It returns a matcher, which matches the view using the visibility of the view. The sample code is as follows, onView(withEffectiveVisibility(withEffectiveVisibility.INVISIBLE)) withSpinnerText() accepts an argument of type Matcher<String> and the argument refers the Spinner’s current selected view’s value. It returns a matcher, which matches the the spinner based on it’s selected item’s toString value. The sample code is as follows, onView(withSpinnerText(endsWith("USA"))) It accepts string argument or resource id of the string as well. The sample code is as follows, onView(withResourceName("USA")) onView(withResourceName(R.string.res_usa)) withSubString() is similar to withText() except it helps to test substring of the text value of the view. onView(withSubString("Hello")) hasLinks() has no arguments and it returns a matcher, which matches the view having links. It applies to TextView only. The sample code is as follows, onView(allOf(withSubString("Hello"), hasLinks())) Here, allOf is a Hamcrest matcher. allOf returns a matcher, which matches all the passed in matchers and here, it is used to match a view as well as check whether the view has links in its text value. hasTextColor() accepts a single argument of type int and the argument refers the resource id of the color. It returns a matcher, which matches the TextView based on its color. It applies to TextView only. The sample code is as follows, onView(allOf(withSubString("Hello"), hasTextColor(R.color.Red))) hasEllipsizedText() has no argument. It returns a matcher, which matches the TextView that has long text and either ellipsized (first.. ten.. last) or cut off (first...). The sample code is as follows, onView(allOf(withId(R.id.my_text_view_id), hasEllipsizedText())) hasMultilineText() has no argument. It returns a matcher, which matches the TextView that has any multi line text. The sample code is as follows, onView(allOf(withId(R.id.my_test_view_id), hasMultilineText())) hasBackground() accepts a single argument of type int and the argument refers the resource id of the background resource. It returns a matcher, which matches the view based on its background resources. The sample code is as follows, onView(allOf(withId("image"), hasBackground(R.drawable.your_drawable))) hasErrorText() accepts an argument of type Matcher<String> and the argument refers the view’s (EditText) error string value. It returns a matcher, which matches the view using error string of the view. This applies to EditText only. The sample code is as follows, onView(allOf(withId(R.id.editText_name), hasErrorText(is("name is required")))) It accepts string argument as well. The sample code is as follows, onView(allOf(withId(R.id.editText_name), hasErrorText("name is required"))) hasImeAction() accepts an argument of type Matcher<Integer> and the argument refers the view’s (EditText) supported input methods. It returns a matcher, which matches the view using supported input method of the view. This applies to EditText only. The sample code is as follows, onView(allOf(withId(R.id.editText_name), hasImeAction(is(EditorInfo.IME_ACTION_GO)))) Here, EditorInfo.IME_ACTION_GO is on of the input methods options. hasImeAction() accepts integer argument as well. The sample code is as follows, onView(allOf(withId(R.id.editText_name), hasImeAction(EditorInfo.IME_ACTION_GO))) supportsInputMethods() has no argument. It returns a matcher, which matches the view if it supports input methods. The sample code is as follows, onView(allOf(withId(R.id.editText_name), supportsInputMethods())) isRoot() has no argument. It returns a matcher, which matches the root view. The sample code is as follows, onView(allOf(withId(R.id.my_root_id), isRoot())) isDisplayed() has no argument. It returns a matcher, which matches the view that are currently displayed. The sample code is as follows, onView(allOf(withId(R.id.my_view_id), isDisplayed())) isDisplayingAtLeast() accepts a single argument of type int. It returns a matcher, which matches the view that are current displayed at least the specified percentage. The sample code is as follows, onView(allOf(withId(R.id.my_view_id), isDisplayingAtLeast(75))) isCompletelyDisplayed() has no argument. It returns a matcher, which matches the view that are currently displayed completely on the screen. The sample code is as follows, onView(allOf(withId(R.id.my_view_id), isCompletelyDisplayed())) isEnabled() has no argument. It returns a matcher, which matches the view that is enabled. The sample code is as follows, onView(allOf(withId(R.id.my_view_id), isEnabled())) isFocusable() has no argument. It returns a matcher, which matches the view that has focus option. The sample code is as follows, onView(allOf(withId(R.id.my_view_id), isFocusable())) hasFocus() has no argument. It returns a matcher, which matches the view that is currently focused. The sample code is as follows, onView(allOf(withId(R.id.my_view_id), hasFocus())) isClickable() has no argument. It returns a matcher, which matches the view that is click option. The sample code is as follows, onView(allOf(withId(R.id.my_view_id), isClickable())) isSelected() has no argument. It returns a matcher, which matches the view that is currently selected. The sample code is as follows, onView(allOf(withId(R.id.my_view_id), isSelected())) isChecked() has no argument. It returns a matcher, which matches the view that is of type CompoundButton (or subtype of it) and is in checked state. The sample code is as follows, onView(allOf(withId(R.id.my_view_id), isChecked())) isNotChecked() is just opposite to isChecked. The sample code is as *follows, onView(allOf(withId(R.id.my_view_id), isNotChecked())) isJavascriptEnabled() has no argument. It returns a matcher, which matches the WebView that is evaluating JavaScript. The sample code is as follows, onView(allOf(withId(R.id.my_webview_id), isJavascriptEnabled())) withParent() accepts one argument of type Matcher<View>. The argument refers a view. It returns a matcher, which matches the view that specified view is parent view. The sample code is as follows, onView(allOf(withId(R.id.childView), withParent(withId(R.id.parentView)))) hasSibling() accepts one argument of type Matcher>View<. The argument refers a view. It returns a matcher, which matches the view that passed-in view is one of its sibling view. The sample code is as follows, onView(hasSibling(withId(R.id.siblingView))) withChild() accepts one argument of type Matcher<View>. The argument refers a view. It returns a matcher, which matches the view that passed-in view is child view. The sample code is as follows, onView(allOf(withId(R.id.parentView), withChild(withId(R.id.childView)))) hasChildCount() accepts one argument of type int. The argument refers the child count of a view. It returns a matcher, which matches the view that has exactly the same number of child view as specified in the argument. The sample code is as follows, onView(hasChildCount(4)) hasMinimumChildCount() accepts one argument of type int. The argument refers the child count of a view. It returns a matcher, which matches the view that has at least the number of child view as specified in the argument. The sample code is as follows, onView(hasMinimumChildCount(4)) hasDescendant() accepts one argument of type Matcher<View>. The argument refers a view. It returns a matcher, which matches the view that passed-in view is one of the descendant view in the view hierarchy. The sample code is as follows, onView(hasDescendant(withId(R.id.descendantView))) isDescendantOfA() accepts one argument of type Matcher<View>. The argument refers a view. It returns a matcher, which matches the view that passed-in view is one of the ancestor view in the view hierarchy. The sample code is as follows, onView(allOf(withId(R.id.myView), isDescendantOfA(withId(R.id.parentView)))) 17 Lectures 1.5 hours Anuja Jain Print Add Notes Bookmark this page
[ { "code": null, "e": 2435, "s": 1976, "text": "Espresso framework provides many view matchers. The purpose of the matcher is to match a view using different attributes of the view like Id, Text, and availability of child view. Each matcher matches a particular attributes of the view and applies to particular type of view. For example, withId matcher matches the Id property of the view and applies to all view, whereas withText matcher matches the Text property of the view and applies to TextView only." }, { "code": null, "e": 2609, "s": 2435, "text": "In this chapter, let us learn the different matchers provided by espresso testing framework as well as learn the Hamcrest library upon which the espresso matchers are built." }, { "code": null, "e": 2887, "s": 2609, "text": "Hamcrest library is an important library in the scope of espresso testing framework. Hamcrest is itself a framework for writing matcher objects. Espresso framework extensively uses the Hamcrest library and extend it whenever necessary to provide simple and extendable matchers." }, { "code": null, "e": 3047, "s": 2887, "text": "Hamcrest provides a simple function assertThat and a collection of matchers to assert any objects. assertThat has three arguments and they are as shown below −" }, { "code": null, "e": 3090, "s": 3047, "text": "String (description of the test, optional)" }, { "code": null, "e": 3133, "s": 3090, "text": "String (description of the test, optional)" }, { "code": null, "e": 3149, "s": 3133, "text": "Object (actual)" }, { "code": null, "e": 3165, "s": 3149, "text": "Object (actual)" }, { "code": null, "e": 3184, "s": 3165, "text": "Matcher (expected)" }, { "code": null, "e": 3203, "s": 3184, "text": "Matcher (expected)" }, { "code": null, "e": 3283, "s": 3203, "text": "Let us write a simple example to test whether a list object has expected value." }, { "code": null, "e": 3552, "s": 3283, "text": "import static org.hamcrest.Matchers.hasItem;\nimport static org.hamcrest.MatcherAssert.assertThat;\n@Test\npublic void list_hasValue() {\n ArrayList<String> list = new ArrayList<String>();\n list.add(\"John\");\n assertThat(\"Is list has John?\", list, hasItem(\"John\"));\n}" }, { "code": null, "e": 3662, "s": 3552, "text": "Here, hasItem returns a matcher, which checks whether the actual list has specified value as one of the item." }, { "code": null, "e": 3837, "s": 3662, "text": "Hamcrest has a lot of built-in matchers and also options to create new matchers. Some of the important built-in matchers useful in espresso testing framework are as follows −" }, { "code": null, "e": 3860, "s": 3837, "text": "Logical based matchers" }, { "code": null, "e": 3946, "s": 3860, "text": "allOf − accept any number of matchers and matches only if all matchers are succeeded." }, { "code": null, "e": 4032, "s": 3946, "text": "allOf − accept any number of matchers and matches only if all matchers are succeeded." }, { "code": null, "e": 4112, "s": 4032, "text": "anyOf − accept any number of matchers and matches if any one matcher succeeded." }, { "code": null, "e": 4192, "s": 4112, "text": "anyOf − accept any number of matchers and matches if any one matcher succeeded." }, { "code": null, "e": 4272, "s": 4192, "text": "not − accept one matcher and matches only if the matcher failed and vice versa." }, { "code": null, "e": 4352, "s": 4272, "text": "not − accept one matcher and matches only if the matcher failed and vice versa." }, { "code": null, "e": 4454, "s": 4352, "text": "equalToIgnoringCase − used to test whether the actual input equals the expected string ignoring case." }, { "code": null, "e": 4556, "s": 4454, "text": "equalToIgnoringCase − used to test whether the actual input equals the expected string ignoring case." }, { "code": null, "e": 4682, "s": 4556, "text": "equalToIgnoringWhiteSpace − used to test whether the actual input equals the specified string ignoring case and white spaces." }, { "code": null, "e": 4808, "s": 4682, "text": "equalToIgnoringWhiteSpace − used to test whether the actual input equals the specified string ignoring case and white spaces." }, { "code": null, "e": 4890, "s": 4808, "text": "containsString − used to test whether the actual input contains specified string." }, { "code": null, "e": 4972, "s": 4890, "text": "containsString − used to test whether the actual input contains specified string." }, { "code": null, "e": 5051, "s": 4972, "text": "endsWith − used to test whether the actual input starts with specified string." }, { "code": null, "e": 5130, "s": 5051, "text": "endsWith − used to test whether the actual input starts with specified string." }, { "code": null, "e": 5209, "s": 5130, "text": "startsWith − used to test whether actual the input ends with specified string." }, { "code": null, "e": 5288, "s": 5209, "text": "startsWith − used to test whether actual the input ends with specified string." }, { "code": null, "e": 5369, "s": 5288, "text": "closeTo − used to test whether the actual input is close to the expected number." }, { "code": null, "e": 5450, "s": 5369, "text": "closeTo − used to test whether the actual input is close to the expected number." }, { "code": null, "e": 5539, "s": 5450, "text": "greaterThan − used to test whether the actual input is greater than the expected number." }, { "code": null, "e": 5628, "s": 5539, "text": "greaterThan − used to test whether the actual input is greater than the expected number." }, { "code": null, "e": 5738, "s": 5628, "text": "greaterThanOrEqualTo − used to test whether the actual input is greater than or equal to the expected number." }, { "code": null, "e": 5848, "s": 5738, "text": "greaterThanOrEqualTo − used to test whether the actual input is greater than or equal to the expected number." }, { "code": null, "e": 5931, "s": 5848, "text": "lessThan − used to test whether the actual input is less than the expected number." }, { "code": null, "e": 6014, "s": 5931, "text": "lessThan − used to test whether the actual input is less than the expected number." }, { "code": null, "e": 6118, "s": 6014, "text": "lessThanOrEqualTo − used to test whether the actual input is less than or equal to the expected number." }, { "code": null, "e": 6222, "s": 6118, "text": "lessThanOrEqualTo − used to test whether the actual input is less than or equal to the expected number." }, { "code": null, "e": 6303, "s": 6222, "text": "equalTo − used to test whether the actual input is equals to the expected object" }, { "code": null, "e": 6384, "s": 6303, "text": "equalTo − used to test whether the actual input is equals to the expected object" }, { "code": null, "e": 6457, "s": 6384, "text": "hasToString − used to test whether the actual input has toString method." }, { "code": null, "e": 6530, "s": 6457, "text": "hasToString − used to test whether the actual input has toString method." }, { "code": null, "e": 6616, "s": 6530, "text": "instanceOf − used to test whether the actual input is the instance of expected class." }, { "code": null, "e": 6702, "s": 6616, "text": "instanceOf − used to test whether the actual input is the instance of expected class." }, { "code": null, "e": 6797, "s": 6702, "text": "isCompatibleType − used to test whether the actual input is compatible with the expected type." }, { "code": null, "e": 6892, "s": 6797, "text": "isCompatibleType − used to test whether the actual input is compatible with the expected type." }, { "code": null, "e": 6958, "s": 6892, "text": "notNullValue − used to test whether the actual input is not null." }, { "code": null, "e": 7024, "s": 6958, "text": "notNullValue − used to test whether the actual input is not null." }, { "code": null, "e": 7112, "s": 7024, "text": "sameInstance − used to test whether the actual input and expected are of same instance." }, { "code": null, "e": 7200, "s": 7112, "text": "sameInstance − used to test whether the actual input and expected are of same instance." }, { "code": null, "e": 7278, "s": 7200, "text": "hasProperty − used to test whether the actual input has the expected property" }, { "code": null, "e": 7356, "s": 7278, "text": "hasProperty − used to test whether the actual input has the expected property" }, { "code": null, "e": 7582, "s": 7356, "text": "Espresso provides the onView() method to match and find the views. It accepts view matchers and returns ViewInteraction object to interact with the matched view. The frequently used list of view matchers are described below −" }, { "code": null, "e": 7769, "s": 7582, "text": "withId() accepts an argument of type int and the argument refers the id of the view. It returns a matcher, which matches the view using the id of the view. The sample code is as follows," }, { "code": null, "e": 7800, "s": 7769, "text": "onView(withId(R.id.testView))\n" }, { "code": null, "e": 8048, "s": 7800, "text": "withText() accepts an argument of type string and the argument refers the value of the view’s text property. It returns a matcher, which matches the view using the text value of the view. It applies to TextView only. The sample code is as follows," }, { "code": null, "e": 8082, "s": 8048, "text": "onView(withText(\"Hello World!\"))\n" }, { "code": null, "e": 8331, "s": 8082, "text": "withContentDescription() accepts an argument of type string and the argument refers the value of the view’s content description property. It returns a matcher, which matches the view using the description of the view. The sample code is as follows," }, { "code": null, "e": 8371, "s": 8331, "text": "onView(withContentDescription(\"blah\"))\n" }, { "code": null, "e": 8450, "s": 8371, "text": "We can also pass the resource id of the text value instead of the text itself." }, { "code": null, "e": 8500, "s": 8450, "text": "onView(withContentDescription(R.id.res_id_blah))\n" }, { "code": null, "e": 8651, "s": 8500, "text": "hasContentDescription() has no argument. It returns a matcher, which matches the view that has any content description. The sample code is as follows," }, { "code": null, "e": 8716, "s": 8651, "text": "onView(allOf(withId(R.id.my_view_id), hasContentDescription()))\n" }, { "code": null, "e": 8903, "s": 8716, "text": "withTagKey() accepts an argument of type string and the argument refers the view’s tag key. It returns a matcher, which matches the view using its tag key. The sample code is as follows," }, { "code": null, "e": 8931, "s": 8903, "text": "onView(withTagKey(\"blah\"))\n" }, { "code": null, "e": 9012, "s": 8931, "text": "We can also pass the resource id of the tag name instead of the tag name itself." }, { "code": null, "e": 9050, "s": 9012, "text": "onView(withTagKey(R.id.res_id_blah))\n" }, { "code": null, "e": 9253, "s": 9050, "text": "withTagValue() accepts an argument of type Matcher <Object> and the argument refers the view’s tag value. It returns a matcher, which matches the view using its tag value. The sample code is as follows," }, { "code": null, "e": 9296, "s": 9253, "text": "onView(withTagValue(is((Object) \"blah\")))\n" }, { "code": null, "e": 9326, "s": 9296, "text": "Here, is is Hamcrest matcher." }, { "code": null, "e": 9537, "s": 9326, "text": "withClassName() accepts an argument of type Matcher<String> and the argument refers the view’s class name value. It returns a matcher, which matches the view using its class name. The sample code is as follows," }, { "code": null, "e": 9582, "s": 9537, "text": "onView(withClassName(endsWith(\"EditText\")))\n" }, { "code": null, "e": 9644, "s": 9582, "text": "Here, endsWith is Hamcrest matcher and return Matcher<String>" }, { "code": null, "e": 9850, "s": 9644, "text": "withHint() accepts an argument of type Matcher<String> and the argument refers the view’s hint value. It returns a matcher, which matches the view using the hint of the view. The sample code is as follows," }, { "code": null, "e": 9897, "s": 9850, "text": "onView(withClassName(endsWith(\"Enter name\")))\n" }, { "code": null, "e": 10095, "s": 9897, "text": "withInputType() accepts an argument of type int and the argument refers the input type of the view. It returns a matcher, which matches the view using its input type. The sample code is as follows," }, { "code": null, "e": 10139, "s": 10095, "text": "onView(withInputType(TYPE_CLASS_DATETIME))\n" }, { "code": null, "e": 10210, "s": 10139, "text": "Here, TYPE_CLASS_DATETIME refers edit view supporting dates and times." }, { "code": null, "e": 10435, "s": 10210, "text": "withResourceName() accepts an argument of type Matcher<String> and the argument refers the view’s class name value. It returns a matcher, which matches the view using resource name of the view. The sample code is as follows," }, { "code": null, "e": 10483, "s": 10435, "text": "onView(withResourceName(endsWith(\"res_name\")))\n" }, { "code": null, "e": 10550, "s": 10483, "text": "It accepts string argument as well. The sample code is as follows," }, { "code": null, "e": 10591, "s": 10550, "text": "onView(withResourceName(\"my_res_name\"))\n" }, { "code": null, "e": 10801, "s": 10591, "text": "withAlpha() accepts an argument of type float and the argument refers the alpha value of the view. It returns a matcher, which matches the view using the alpha value of the view. The sample code is as follows," }, { "code": null, "e": 10825, "s": 10801, "text": "onView(withAlpha(0.8))\n" }, { "code": null, "e": 11075, "s": 10825, "text": "withEffectiveVisibility() accepts an argument of type ViewMatchers.Visibility and the argument refers the effective visibility of the view. It returns a matcher, which matches the view using the visibility of the view. The sample code is as follows," }, { "code": null, "e": 11143, "s": 11075, "text": "onView(withEffectiveVisibility(withEffectiveVisibility.INVISIBLE))\n" }, { "code": null, "e": 11403, "s": 11143, "text": "withSpinnerText() accepts an argument of type Matcher<String> and the argument refers the Spinner’s current selected view’s value. It returns a matcher, which matches the the spinner based on it’s selected item’s toString value. The sample code is as follows," }, { "code": null, "e": 11445, "s": 11403, "text": "onView(withSpinnerText(endsWith(\"USA\")))\n" }, { "code": null, "e": 11541, "s": 11445, "text": "It accepts string argument or resource id of the string as well. The sample code is as follows," }, { "code": null, "e": 11617, "s": 11541, "text": "onView(withResourceName(\"USA\"))\nonView(withResourceName(R.string.res_usa))\n" }, { "code": null, "e": 11723, "s": 11617, "text": "withSubString() is similar to withText() except it helps to test substring of the text value of the view." }, { "code": null, "e": 11755, "s": 11723, "text": "onView(withSubString(\"Hello\"))\n" }, { "code": null, "e": 11906, "s": 11755, "text": "hasLinks() has no arguments and it returns a matcher, which matches the view having links. It applies to TextView only. The sample code is as follows," }, { "code": null, "e": 11957, "s": 11906, "text": "onView(allOf(withSubString(\"Hello\"), hasLinks()))\n" }, { "code": null, "e": 12158, "s": 11957, "text": "Here, allOf is a Hamcrest matcher. allOf returns a matcher, which matches all the passed in matchers and here, it is used to match a view as well as check whether the view has links in its text value." }, { "code": null, "e": 12394, "s": 12158, "text": "hasTextColor() accepts a single argument of type int and the argument refers the resource id of the color. It returns a matcher, which matches the TextView based on its color. It applies to TextView only. The sample code is as follows," }, { "code": null, "e": 12460, "s": 12394, "text": "onView(allOf(withSubString(\"Hello\"), hasTextColor(R.color.Red)))\n" }, { "code": null, "e": 12662, "s": 12460, "text": "hasEllipsizedText() has no argument. It returns a matcher, which matches the TextView that has long text and either ellipsized (first.. ten.. last) or cut off (first...). The sample code is as follows," }, { "code": null, "e": 12728, "s": 12662, "text": "onView(allOf(withId(R.id.my_text_view_id), hasEllipsizedText()))\n" }, { "code": null, "e": 12874, "s": 12728, "text": "hasMultilineText() has no argument. It returns a matcher, which matches the TextView that has any multi line text. The sample code is as follows," }, { "code": null, "e": 12939, "s": 12874, "text": "onView(allOf(withId(R.id.my_test_view_id), hasMultilineText()))\n" }, { "code": null, "e": 13172, "s": 12939, "text": "hasBackground() accepts a single argument of type int and the argument refers the resource id of the background resource. It returns a matcher, which matches the view based on its background resources. The sample code is as follows," }, { "code": null, "e": 13245, "s": 13172, "text": "onView(allOf(withId(\"image\"), hasBackground(R.drawable.your_drawable)))\n" }, { "code": null, "e": 13509, "s": 13245, "text": "hasErrorText() accepts an argument of type Matcher<String> and the argument refers the view’s (EditText) error string value. It returns a matcher, which matches the view using error string of the view. This applies to EditText only. The sample code is as follows," }, { "code": null, "e": 13590, "s": 13509, "text": "onView(allOf(withId(R.id.editText_name), hasErrorText(is(\"name is required\"))))\n" }, { "code": null, "e": 13657, "s": 13590, "text": "It accepts string argument as well. The sample code is as follows," }, { "code": null, "e": 13734, "s": 13657, "text": "onView(allOf(withId(R.id.editText_name), hasErrorText(\"name is required\")))\n" }, { "code": null, "e": 14014, "s": 13734, "text": "hasImeAction() accepts an argument of type Matcher<Integer> and the argument refers the view’s (EditText) supported input methods. It returns a matcher, which matches the view using supported input method of the view. This applies to EditText only. The sample code is as follows," }, { "code": null, "e": 14101, "s": 14014, "text": "onView(allOf(withId(R.id.editText_name),\nhasImeAction(is(EditorInfo.IME_ACTION_GO))))\n" }, { "code": null, "e": 14248, "s": 14101, "text": "Here, EditorInfo.IME_ACTION_GO is on of the input methods options. hasImeAction() accepts integer argument as well. The sample code is as follows," }, { "code": null, "e": 14331, "s": 14248, "text": "onView(allOf(withId(R.id.editText_name),\nhasImeAction(EditorInfo.IME_ACTION_GO)))\n" }, { "code": null, "e": 14477, "s": 14331, "text": "supportsInputMethods() has no argument. It returns a matcher, which matches the view if it supports input methods. The sample code is as follows," }, { "code": null, "e": 14544, "s": 14477, "text": "onView(allOf(withId(R.id.editText_name), supportsInputMethods()))\n" }, { "code": null, "e": 14652, "s": 14544, "text": "isRoot() has no argument. It returns a matcher, which matches the root view. The sample code is as follows," }, { "code": null, "e": 14702, "s": 14652, "text": "onView(allOf(withId(R.id.my_root_id), isRoot()))\n" }, { "code": null, "e": 14839, "s": 14702, "text": "isDisplayed() has no argument. It returns a matcher, which matches the view that are currently displayed. The sample code is as follows," }, { "code": null, "e": 14894, "s": 14839, "text": "onView(allOf(withId(R.id.my_view_id), isDisplayed()))\n" }, { "code": null, "e": 15093, "s": 14894, "text": "isDisplayingAtLeast() accepts a single argument of type int. It returns a matcher, which matches the view that are current displayed at least the specified percentage. The sample code is as follows," }, { "code": null, "e": 15158, "s": 15093, "text": "onView(allOf(withId(R.id.my_view_id), isDisplayingAtLeast(75)))\n" }, { "code": null, "e": 15330, "s": 15158, "text": "isCompletelyDisplayed() has no argument. It returns a matcher, which matches the view that are currently displayed completely on the screen. The sample code is as follows," }, { "code": null, "e": 15395, "s": 15330, "text": "onView(allOf(withId(R.id.my_view_id), isCompletelyDisplayed()))\n" }, { "code": null, "e": 15517, "s": 15395, "text": "isEnabled() has no argument. It returns a matcher, which matches the view that is enabled. The sample code is as follows," }, { "code": null, "e": 15570, "s": 15517, "text": "onView(allOf(withId(R.id.my_view_id), isEnabled()))\n" }, { "code": null, "e": 15700, "s": 15570, "text": "isFocusable() has no argument. It returns a matcher, which matches the view that has focus option. The sample code is as follows," }, { "code": null, "e": 15755, "s": 15700, "text": "onView(allOf(withId(R.id.my_view_id), isFocusable()))\n" }, { "code": null, "e": 15886, "s": 15755, "text": "hasFocus() has no argument. It returns a matcher, which matches the view that is currently focused. The sample code is as follows," }, { "code": null, "e": 15938, "s": 15886, "text": "onView(allOf(withId(R.id.my_view_id), hasFocus()))\n" }, { "code": null, "e": 16067, "s": 15938, "text": "isClickable() has no argument. It returns a matcher, which matches the view that is click option. The sample code is as follows," }, { "code": null, "e": 16122, "s": 16067, "text": "onView(allOf(withId(R.id.my_view_id), isClickable()))\n" }, { "code": null, "e": 16256, "s": 16122, "text": "isSelected() has no argument. It returns a matcher, which matches the view that is currently selected. The sample code is as follows," }, { "code": null, "e": 16310, "s": 16256, "text": "onView(allOf(withId(R.id.my_view_id), isSelected()))\n" }, { "code": null, "e": 16490, "s": 16310, "text": "isChecked() has no argument. It returns a matcher, which matches the view that is of type CompoundButton (or subtype of it) and is in checked state. The sample code is as follows," }, { "code": null, "e": 16543, "s": 16490, "text": "onView(allOf(withId(R.id.my_view_id), isChecked()))\n" }, { "code": null, "e": 16621, "s": 16543, "text": "isNotChecked() is just opposite to isChecked. The sample code is as *follows," }, { "code": null, "e": 16677, "s": 16621, "text": "onView(allOf(withId(R.id.my_view_id), isNotChecked()))\n" }, { "code": null, "e": 16826, "s": 16677, "text": "isJavascriptEnabled() has no argument. It returns a matcher, which matches the WebView that is evaluating JavaScript. The sample code is as follows," }, { "code": null, "e": 16892, "s": 16826, "text": "onView(allOf(withId(R.id.my_webview_id), isJavascriptEnabled()))\n" }, { "code": null, "e": 17089, "s": 16892, "text": "withParent() accepts one argument of type Matcher<View>. The argument refers a view. It returns a matcher, which matches the view that specified view is parent view. The sample code is as follows," }, { "code": null, "e": 17165, "s": 17089, "text": "onView(allOf(withId(R.id.childView), withParent(withId(R.id.parentView))))\n" }, { "code": null, "e": 17374, "s": 17165, "text": "hasSibling() accepts one argument of type Matcher>View<. The argument refers a view. It returns a matcher, which matches the view that passed-in view is one of its sibling view. The sample code is as follows," }, { "code": null, "e": 17420, "s": 17374, "text": "onView(hasSibling(withId(R.id.siblingView)))\n" }, { "code": null, "e": 17615, "s": 17420, "text": "withChild() accepts one argument of type Matcher<View>. The argument refers a view. It returns a matcher, which matches the view that passed-in view is child view. The sample code is as follows," }, { "code": null, "e": 17690, "s": 17615, "text": "onView(allOf(withId(R.id.parentView), withChild(withId(R.id.childView))))\n" }, { "code": null, "e": 17940, "s": 17690, "text": "hasChildCount() accepts one argument of type int. The argument refers the child count of a view. It returns a matcher, which matches the view that has exactly the same number of child view as specified in the argument. The sample code is as follows," }, { "code": null, "e": 17966, "s": 17940, "text": "onView(hasChildCount(4))\n" }, { "code": null, "e": 18219, "s": 17966, "text": "hasMinimumChildCount() accepts one argument of type int. The argument refers the child count of a view. It returns a matcher, which matches the view that has at least the number of child view as specified in the argument. The sample code is as follows," }, { "code": null, "e": 18252, "s": 18219, "text": "onView(hasMinimumChildCount(4))\n" }, { "code": null, "e": 18489, "s": 18252, "text": "hasDescendant() accepts one argument of type Matcher<View>. The argument refers a view. It returns a matcher, which matches the view that passed-in view is one of the descendant view in the view hierarchy. The sample code is as follows," }, { "code": null, "e": 18541, "s": 18489, "text": "onView(hasDescendant(withId(R.id.descendantView)))\n" }, { "code": null, "e": 18778, "s": 18541, "text": "isDescendantOfA() accepts one argument of type Matcher<View>. The argument refers a view. It returns a matcher, which matches the view that passed-in view is one of the ancestor view in the view hierarchy. The sample code is as follows," }, { "code": null, "e": 18856, "s": 18778, "text": "onView(allOf(withId(R.id.myView), isDescendantOfA(withId(R.id.parentView))))\n" }, { "code": null, "e": 18891, "s": 18856, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 18903, "s": 18891, "text": " Anuja Jain" }, { "code": null, "e": 18910, "s": 18903, "text": " Print" }, { "code": null, "e": 18921, "s": 18910, "text": " Add Notes" } ]
Ngx-Bootstrap - Sortable
ngx-bootstrap sortable component provides a configurable sortable component, with drag drop support. bs-sortable bs-sortable fieldName − string, field name if input array consists of objects. fieldName − string, field name if input array consists of objects. itemActiveClass − string, class name for active item. itemActiveClass − string, class name for active item. itemActiveStyle − { [key: string]: string; }, style object for active item. itemActiveStyle − { [key: string]: string; }, style object for active item. itemClass − string, class name for item itemClass − string, class name for item itemStyle − string, class name for item itemStyle − string, class name for item itemTemplate − TemplateRef<any>, used to specify a custom item template. Template variables: item and index; itemTemplate − TemplateRef<any>, used to specify a custom item template. Template variables: item and index; placeholderClass − string, class name for placeholder placeholderClass − string, class name for placeholder placeholderItem − string, placeholder item which will be shown if collection is empty placeholderItem − string, placeholder item which will be shown if collection is empty placeholderStyle − string, style object for placeholder placeholderStyle − string, style object for placeholder wrapperClass − string, class name for items wrapper wrapperClass − string, class name for items wrapper wrapperStyle − { [key: string]: string; }, style object for items wrapper wrapperStyle − { [key: string]: string; }, style object for items wrapper onChange − fired on array change (reordering, insert, remove), same as ngModelChange. Returns new items collection as a payload. onChange − fired on array change (reordering, insert, remove), same as ngModelChange. Returns new items collection as a payload. As we're going to use a sortable, We've to update app.module.ts used in ngx-bootstrap Rating chapter to use SortableModule and DraggableItemService. Update app.module.ts to use the SortableModule and DraggableItemService. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { CollapseModule } from 'ngx-bootstrap/collapse'; import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker'; import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown'; import { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination'; import { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover'; import { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar'; import { RatingModule, RatingConfig } from 'ngx-bootstrap/rating'; import { SortableModule, DraggableItemService } from 'ngx-bootstrap/sortable'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule, CollapseModule, BsDatepickerModule.forRoot(), BsDropdownModule, ModalModule, PaginationModule, PopoverModule, ProgressbarModule, RatingModule, SortableModule ], providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig, BsModalService, PaginationConfig, ProgressbarConfig, RatingConfig, DraggableItemService], bootstrap: [AppComponent] }) export class AppModule { } Update styles.css to use styles for sortable component. Styles.css .sortableItem { padding: 6px 12px; margin-bottom: 4px; font-size: 14px; line-height: 1.4em; text-align: center; cursor: grab; border: 1px solid transparent; border-radius: 4px; border-color: #adadad; } .sortableItemActive { background-color: #e6e6e6; box-shadow: inset 0 3px 5px rgba(0,0,0,.125); } .sortableWrapper { min-height: 150px; } Update test.component.html to use the sortable component. test.component.html <bs-sortable [(ngModel)]="items" fieldName="name" itemClass="sortableItem" itemActiveClass="sortableItemActive" wrapperClass="sortableWrapper"> </bs-sortable> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { items = [ { id: 1, name: 'Apple' }, { id: 2, name: 'Orange' }, { id: 3, name: 'Mango' } ]; constructor() {} ngOnInit(): void { } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200. Print Add Notes Bookmark this page
[ { "code": null, "e": 2201, "s": 2100, "text": "ngx-bootstrap sortable component provides a configurable sortable component, with drag drop support." }, { "code": null, "e": 2213, "s": 2201, "text": "bs-sortable" }, { "code": null, "e": 2225, "s": 2213, "text": "bs-sortable" }, { "code": null, "e": 2292, "s": 2225, "text": "fieldName − string, field name if input array consists of objects." }, { "code": null, "e": 2359, "s": 2292, "text": "fieldName − string, field name if input array consists of objects." }, { "code": null, "e": 2413, "s": 2359, "text": "itemActiveClass − string, class name for active item." }, { "code": null, "e": 2467, "s": 2413, "text": "itemActiveClass − string, class name for active item." }, { "code": null, "e": 2543, "s": 2467, "text": "itemActiveStyle − { [key: string]: string; }, style object for active item." }, { "code": null, "e": 2619, "s": 2543, "text": "itemActiveStyle − { [key: string]: string; }, style object for active item." }, { "code": null, "e": 2659, "s": 2619, "text": "itemClass − string, class name for item" }, { "code": null, "e": 2699, "s": 2659, "text": "itemClass − string, class name for item" }, { "code": null, "e": 2739, "s": 2699, "text": "itemStyle − string, class name for item" }, { "code": null, "e": 2779, "s": 2739, "text": "itemStyle − string, class name for item" }, { "code": null, "e": 2888, "s": 2779, "text": "itemTemplate − TemplateRef<any>, used to specify a custom item template. Template variables: item and index;" }, { "code": null, "e": 2997, "s": 2888, "text": "itemTemplate − TemplateRef<any>, used to specify a custom item template. Template variables: item and index;" }, { "code": null, "e": 3051, "s": 2997, "text": "placeholderClass − string, class name for placeholder" }, { "code": null, "e": 3105, "s": 3051, "text": "placeholderClass − string, class name for placeholder" }, { "code": null, "e": 3191, "s": 3105, "text": "placeholderItem − string, placeholder item which will be shown if collection is empty" }, { "code": null, "e": 3277, "s": 3191, "text": "placeholderItem − string, placeholder item which will be shown if collection is empty" }, { "code": null, "e": 3333, "s": 3277, "text": "placeholderStyle − string, style object for placeholder" }, { "code": null, "e": 3389, "s": 3333, "text": "placeholderStyle − string, style object for placeholder" }, { "code": null, "e": 3441, "s": 3389, "text": "wrapperClass − string, class name for items wrapper" }, { "code": null, "e": 3493, "s": 3441, "text": "wrapperClass − string, class name for items wrapper" }, { "code": null, "e": 3567, "s": 3493, "text": "wrapperStyle − { [key: string]: string; }, style object for items wrapper" }, { "code": null, "e": 3641, "s": 3567, "text": "wrapperStyle − { [key: string]: string; }, style object for items wrapper" }, { "code": null, "e": 3770, "s": 3641, "text": "onChange − fired on array change (reordering, insert, remove), same as ngModelChange. Returns new items collection as a payload." }, { "code": null, "e": 3899, "s": 3770, "text": "onChange − fired on array change (reordering, insert, remove), same as ngModelChange. Returns new items collection as a payload." }, { "code": null, "e": 4048, "s": 3899, "text": "As we're going to use a sortable, We've to update app.module.ts used in ngx-bootstrap Rating chapter to use SortableModule and DraggableItemService." }, { "code": null, "e": 4121, "s": 4048, "text": "Update app.module.ts to use the SortableModule and DraggableItemService." }, { "code": null, "e": 4135, "s": 4121, "text": "app.module.ts" }, { "code": null, "e": 6015, "s": 4135, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\nimport { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination';\nimport { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover';\nimport { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar';\nimport { RatingModule, RatingConfig } from 'ngx-bootstrap/rating';\nimport { SortableModule, DraggableItemService } from 'ngx-bootstrap/sortable';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule,\n ModalModule,\n PaginationModule,\n PopoverModule,\n ProgressbarModule,\n RatingModule,\n SortableModule\n ],\n providers: [AlertConfig, \n BsDatepickerConfig, \n BsDropdownConfig,\n BsModalService,\n PaginationConfig,\n ProgressbarConfig,\n RatingConfig,\n DraggableItemService],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 6071, "s": 6015, "text": "Update styles.css to use styles for sortable component." }, { "code": null, "e": 6082, "s": 6071, "text": "Styles.css" }, { "code": null, "e": 6459, "s": 6082, "text": ".sortableItem {\n padding: 6px 12px;\n margin-bottom: 4px;\n font-size: 14px;\n line-height: 1.4em;\n text-align: center;\n cursor: grab;\n border: 1px solid transparent;\n border-radius: 4px;\n border-color: #adadad;\n}\n\n.sortableItemActive {\n background-color: #e6e6e6;\n box-shadow: inset 0 3px 5px rgba(0,0,0,.125);\n}\n\n.sortableWrapper {\n min-height: 150px;\n}" }, { "code": null, "e": 6517, "s": 6459, "text": "Update test.component.html to use the sortable component." }, { "code": null, "e": 6537, "s": 6517, "text": "test.component.html" }, { "code": null, "e": 6711, "s": 6537, "text": "<bs-sortable\n [(ngModel)]=\"items\"\n fieldName=\"name\"\n itemClass=\"sortableItem\"\n itemActiveClass=\"sortableItemActive\"\n wrapperClass=\"sortableWrapper\">\n</bs-sortable>" }, { "code": null, "e": 6777, "s": 6711, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 6795, "s": 6777, "text": "test.component.ts" }, { "code": null, "e": 7252, "s": 6795, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n items = [\n {\n id: 1,\n name: 'Apple'\n },\n {\n id: 2,\n name: 'Orange'\n },\n {\n id: 3,\n name: 'Mango'\n }\n ];\n constructor() {}\n ngOnInit(): void {\n } \n}" }, { "code": null, "e": 7307, "s": 7252, "text": "Run the following command to start the angular server." }, { "code": null, "e": 7317, "s": 7307, "text": "ng serve\n" }, { "code": null, "e": 7376, "s": 7317, "text": "Once server is up and running. Open http://localhost:4200." }, { "code": null, "e": 7383, "s": 7376, "text": " Print" }, { "code": null, "e": 7394, "s": 7383, "text": " Add Notes" } ]
How to create a responsive navigation bar with dropdown in CSS?
Following is the code to create a responsive navigation bar with dropdown − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> *,*::after,*::before{ box-sizing: border-box; } .menu-btn { font-size: 18px; font-weight: bold; display: inline-block; text-align: center; background-color: #040008; color: white; padding: 20px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; border: none; width: 100%; } .dropdown-menu { position: relative; display: inline-block; } .menu-content { display: none; position: absolute; width: 100%; background-color: #017575; min-width: 160px; z-index: 1; } nav{ background-color: #017575; width: 100%; } .links,.links-hidden{ display: inline-block; color: rgb(255, 255, 255); text-decoration: none; font-size: 18px; font-weight: bold; padding: 20px; } .links-hidden:hover,.links:hover { background-color: rgb(8, 107, 46); } .dropdown-menu:hover .menu-content { display: block; } .dropdown-menu:hover .menu-btn { background-color: #3e8e41; } .hamburger { color: white; font-weight: bolder; display: none; } @media screen and (max-width: 880px) { nav a:not(:first-child) { display: none; } nav a.hamburger { float: right; display: block; padding: 12px; } .dropdown-menu{ display: none; } nav.openNav a.hamburger { position: relative; } nav.openNav a { float: none; display: block; text-align: center; } } nav.openNav div.dropdown-menu{ display: block; width: 100%; } </style> </head> <body> <nav> <a class="links" href="#">HOME</a> <a class="links" href="#">EMPLOYEES</a> <a class="links" href="#">CAREER</a> <a class="links" href="#">Our History</a> <a class="links" href="#">Fund Us</a> <a class="links" href="#">More Info</a> <div class="dropdown-menu"> <button class="menu-btn">Open <</button> <div class="menu-content"> <a class="links-hidden" href="#">Contact Us</a> <a class="links-hidden" href="#">Visit Us</a> <a class="links-hidden" href="#">About Us</a> </div> </div> <a class="hamburger">☰</a> </nav> <script> var x = document.getElementsByTagName("nav")[0]; function toggleNav() { if (x.className === "") { x.className = " openNav"; } else { x.className = ""; } } document.querySelector(".hamburger").addEventListener("click", toggleNav); </script> </body> </html> The above code will produce the following output − On resizing the window to 880px or less − On opening the hamburger menu and then the dropdown −
[ { "code": null, "e": 1138, "s": 1062, "text": "Following is the code to create a responsive navigation bar with dropdown −" }, { "code": null, "e": 1149, "s": 1138, "text": " Live Demo" }, { "code": null, "e": 3561, "s": 1149, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\n*,*::after,*::before{\n box-sizing: border-box;\n}\n.menu-btn {\n font-size: 18px;\n font-weight: bold;\n display: inline-block;\n text-align: center;\n background-color: #040008;\n color: white;\n padding: 20px;\n font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n border: none;\n width: 100%;\n}\n.dropdown-menu {\n position: relative;\n display: inline-block;\n}\n.menu-content {\n display: none;\n position: absolute;\n width: 100%;\n background-color: #017575;\n min-width: 160px;\n z-index: 1;\n}\nnav{\n background-color: #017575;\n width: 100%;\n}\n.links,.links-hidden{\n display: inline-block;\n color: rgb(255, 255, 255);\n text-decoration: none;\n font-size: 18px;\n font-weight: bold;\n padding: 20px;\n}\n.links-hidden:hover,.links:hover {\n background-color: rgb(8, 107, 46);\n}\n.dropdown-menu:hover .menu-content {\n display: block;\n}\n.dropdown-menu:hover .menu-btn {\n background-color: #3e8e41;\n}\n.hamburger {\n color: white;\n font-weight: bolder;\n display: none;\n}\n@media screen and (max-width: 880px) {\n nav a:not(:first-child) {\n display: none;\n }\n nav a.hamburger {\n float: right;\n display: block;\n padding: 12px;\n }\n .dropdown-menu{\n display: none;\n }\n nav.openNav a.hamburger {\n position: relative;\n }\n nav.openNav a {\n float: none;\n display: block;\n text-align: center;\n }\n}\nnav.openNav div.dropdown-menu{\n display: block;\n width: 100%;\n}\n</style>\n</head>\n<body>\n<nav>\n<a class=\"links\" href=\"#\">HOME</a>\n<a class=\"links\" href=\"#\">EMPLOYEES</a>\n<a class=\"links\" href=\"#\">CAREER</a>\n<a class=\"links\" href=\"#\">Our History</a>\n<a class=\"links\" href=\"#\">Fund Us</a>\n<a class=\"links\" href=\"#\">More Info</a>\n<div class=\"dropdown-menu\">\n<button class=\"menu-btn\">Open <</button>\n<div class=\"menu-content\">\n<a class=\"links-hidden\" href=\"#\">Contact Us</a>\n<a class=\"links-hidden\" href=\"#\">Visit Us</a>\n<a class=\"links-hidden\" href=\"#\">About Us</a>\n</div>\n</div>\n<a class=\"hamburger\">☰</a>\n</nav>\n<script>\nvar x = document.getElementsByTagName(\"nav\")[0];\nfunction toggleNav() {\n if (x.className === \"\") {\n x.className = \" openNav\";\n } else {\n x.className = \"\";\n }\n}\ndocument.querySelector(\".hamburger\").addEventListener(\"click\", toggleNav);\n</script>\n</body>\n</html>" }, { "code": null, "e": 3612, "s": 3561, "text": "The above code will produce the following output −" }, { "code": null, "e": 3654, "s": 3612, "text": "On resizing the window to 880px or less −" }, { "code": null, "e": 3708, "s": 3654, "text": "On opening the hamburger menu and then the dropdown −" } ]
Item-Based Collaborative Filtering in Python | by Yohan Jeong | Towards Data Science
Item-based collaborative filtering is the recommendation system to use the similarity between items using the ratings by users. In this article, I explain its basic concept and practice how to make the item-based collaborative filtering using Python. The fundamental assumption for this method is that a user gives similar ratings to similar movies. Consider the following table for movie ratings. In this example, the rating for Movie_1 by User_1 is empty. Let’s predict this rating using the item-based collaborative filtering. Step 1: Find the most similar (the nearest) movies to the movie for which you want to predict the rating. There are multiple ways to find the nearest movies. Here, I use the cosine similarity. In using the cosine similarity, replace the missing value for 0. Look at the graph below. The x-axis represents ratings by User_0 and the y-axis ratings by User_1. Then, we can find points for each movie in the space. For example, Movie_3 corresponds to the point (5,2) in the space. The cosine similarity uses cos(θ) to measure the distance between two vectors. As θ increases, cos(θ) decreases (cos(θ) = 1 when θ = 0 and cos(θ) = 0 when θ = 90). Therefore, as the value of θ is smaller, the two vectors are considered closer (the similarity gets greater). Since θ1 is the smallest and θ3 is the largest, Movie_3 is the closest to Movie_1, and Movie_2 is the farthest. What is noteworthy here is that the similarities between movies are determined by ALL USERS. For example, the similarity between Movie_1 and Movie_3 is calculated using the ratings by both of User_0 and User_1. Step 2: Calculate the weighted average of the ratings for the most similar movies by the user. A user gives similar ratings to similar movies. Therefore, when we predict a rating for a movie by a user, it is reasonable to use the average of ratings for the similar movies by the user. Set the number of the nearest neighbors as 2. Then we use Movie_3 and Movie_0 to predict the rating for Movie_0 by User_1. The rating for Movie_3 by User_1 is 2, and the rating for Movie_0 by User_1 is 3. If Movie_3 and Movie_0 are similar to Movie_1 at the same distance, we can estimate the rating for Movie_1 by User_1 as 2.5. However, if Movie_3 is considered closer to Movie_1, the weight for Movie_3 should be greater than that for Movie_0. Therefore, the predicted rating for Movie_1 will be closer to the rating for Movie_3 as the picture below indicates. Using the cosine similarity as the weight, the predicted rating is 2.374. For better understanding, the dataset with 10 movies and 10 users is used here. (the numbers are randomly selected.) df 10 movies and 10 users 0 represents missing values. The percentage of users rating movies is 50% (only 50 ratings are given). In real movie datasets, this percentage becomes less than 10%. I assume that a user did not watch a movie if the user did not rate the movie. The NearestNeighbors() in the sklearn.neighbors library can be used to calculate the distance between movies using the cosine similarity and find the nearest neighbors for each movie. from sklearn.neighbors import NearestNeighborsknn = NearestNeighbors(metric='cosine', algorithm='brute')knn.fit(df.values)distances, indices = knn.kneighbors(df.values, n_neighbors=3) The number of the nearest neighbors (n_neighbors)is set to be 3. Since this includes the movie itself, generally it finds two nearest movies except the movie itself. indices[Out] array([[0, 7, 5], [1, 3, 7], [2, 1, 6], .... [9, 0, 7]]) indices shows the indices of the nearest neighbors for each movie. Each row corresponds to the row in the df. The first element in a row is the most similar (nearest) movie. Generally, it is the movie itself. The second element is the second nearest, and the third is the third nearest. For example, in the first row [0,7,5], the nearest movie to movie_0 is itself, the second nearest movie is movie_7, and the third is movie_5. distances[Out] array([[0.00000000e+00, 3.19586183e-01, 4.03404722e-01], [4.44089210e-16, 3.68421053e-01, 3.95436458e-01], [0.00000000e+00, 5.20766162e-01, 5.24329288e-01], ....[1.11022302e-16, 4.22649731e-01, 4.81455027e-01]]) distances shows the distance between movies. A smaller number means the movie is closer. Each number in this array corresponds to the number in the indices array. Predicting a rating for a movie by a user is equivalent to calculating the weighted average of ratings for the similar movies by the user. For practice, predict the rating for movie_0 by user_7. First, find the nearest neighbors for movie_0 using NearestNeighbors(). # get the index for 'movie_0'index_for_movie = df.index.tolist().index('movie_0')# find the indices for the similar moviessim_movies = indices[index_for_movie].tolist()# distances between 'movie_0' and the similar moviesmovie_distances = distances[index_for_movie].tolist()# the position of 'movie_0' in the list sim_moviesid_movie = sim_movies.index(index_for_movie)# remove 'movie_0' from the list sim_moviessim_movies.remove(index_for_movie)# remove 'movie_0' from the list movie_distancesmovie_distances.pop(id_movie)print('The Nearest Movies to movie_0:', sim_movies)print('The Distance from movie_0:', movie_distances) The most similar movies to movie_0 are movie_7 and movie_5, and the distances from movie_0 are 0.3196 and 0.4034, respectively. The formula to calculate the predicted rating is as follows: R(m, u) = {∑ j S(m, j)R(j, u)}/ ∑ j S(m, j) R(m, u): the rating for movie m by user u S(m, j): the similarity between movie m and movie j j ∈ J where J is the set of the similar movies to movie m This formula simply implies that the predicted rating for movie m by user u is the weighted average of ratings for the similar movies by user u. The weight for each rating, (S(m, k)/∑ j S(m, j)), becomes greater when movie m and movie k are closer. The denominator of this term makes the sum of all the weights equal 1. Let’s predict the rating for movie_0 by user_7, R(0,7): R(0,7)=[S(0,5)∗R(5,7)+S(0,7)∗R(7,7)]/[S(0,5)+S(0,7)] Since the distances between movie_0 and movie_5 and between movie_0 and movie_7 are 0.4034 and 0.3196, the similarities are S(0,5) = (1-0.4034) S(0,7) = (1-0.3196). Because R(5,7) = 2 and R(7,7) = 3, the predicted R(0,7) is 2.5328. The code below predicts the ratings for all the movie which user_4 has not watched. (n_neighbors = 3) The copy of the original dataset, df1, updates all the predicted ratings for user_4. The following code is the function to show the recommended movies for a selected user using the updated dataset. For example, let’s get 5 recommended movies for user_4. recommend_movies('user_4', 5) The output shows the list of the movies the user already watched and the list of the recommended movies. movie_2 has the highest predicted rating for user_4. The goal of this project is to build a recommender which recommends movies for a selected user. If we enter a user name into the recommender, the recommender is supposed to return the list of recommended movies which have the highest predicted ratings. Combining the codes above, we can build the movie recommender for any selected user. Let's recommend movies for user_4 with n_neighbors = 3 and the number of recommended movies = 4. movie_recommender('user_4', 3, 4) In this article, I briefly explained the basic concept of the item-based collaborative filtering and showed how to build the recommendation engine using this method. The additional code and movie dataset for this practice can be found here.
[ { "code": null, "e": 423, "s": 172, "text": "Item-based collaborative filtering is the recommendation system to use the similarity between items using the ratings by users. In this article, I explain its basic concept and practice how to make the item-based collaborative filtering using Python." }, { "code": null, "e": 570, "s": 423, "text": "The fundamental assumption for this method is that a user gives similar ratings to similar movies. Consider the following table for movie ratings." }, { "code": null, "e": 702, "s": 570, "text": "In this example, the rating for Movie_1 by User_1 is empty. Let’s predict this rating using the item-based collaborative filtering." }, { "code": null, "e": 808, "s": 702, "text": "Step 1: Find the most similar (the nearest) movies to the movie for which you want to predict the rating." }, { "code": null, "e": 1179, "s": 808, "text": "There are multiple ways to find the nearest movies. Here, I use the cosine similarity. In using the cosine similarity, replace the missing value for 0. Look at the graph below. The x-axis represents ratings by User_0 and the y-axis ratings by User_1. Then, we can find points for each movie in the space. For example, Movie_3 corresponds to the point (5,2) in the space." }, { "code": null, "e": 1565, "s": 1179, "text": "The cosine similarity uses cos(θ) to measure the distance between two vectors. As θ increases, cos(θ) decreases (cos(θ) = 1 when θ = 0 and cos(θ) = 0 when θ = 90). Therefore, as the value of θ is smaller, the two vectors are considered closer (the similarity gets greater). Since θ1 is the smallest and θ3 is the largest, Movie_3 is the closest to Movie_1, and Movie_2 is the farthest." }, { "code": null, "e": 1776, "s": 1565, "text": "What is noteworthy here is that the similarities between movies are determined by ALL USERS. For example, the similarity between Movie_1 and Movie_3 is calculated using the ratings by both of User_0 and User_1." }, { "code": null, "e": 1871, "s": 1776, "text": "Step 2: Calculate the weighted average of the ratings for the most similar movies by the user." }, { "code": null, "e": 2184, "s": 1871, "text": "A user gives similar ratings to similar movies. Therefore, when we predict a rating for a movie by a user, it is reasonable to use the average of ratings for the similar movies by the user. Set the number of the nearest neighbors as 2. Then we use Movie_3 and Movie_0 to predict the rating for Movie_0 by User_1." }, { "code": null, "e": 2699, "s": 2184, "text": "The rating for Movie_3 by User_1 is 2, and the rating for Movie_0 by User_1 is 3. If Movie_3 and Movie_0 are similar to Movie_1 at the same distance, we can estimate the rating for Movie_1 by User_1 as 2.5. However, if Movie_3 is considered closer to Movie_1, the weight for Movie_3 should be greater than that for Movie_0. Therefore, the predicted rating for Movie_1 will be closer to the rating for Movie_3 as the picture below indicates. Using the cosine similarity as the weight, the predicted rating is 2.374." }, { "code": null, "e": 2816, "s": 2699, "text": "For better understanding, the dataset with 10 movies and 10 users is used here. (the numbers are randomly selected.)" }, { "code": null, "e": 2819, "s": 2816, "text": "df" }, { "code": null, "e": 2842, "s": 2819, "text": "10 movies and 10 users" }, { "code": null, "e": 2871, "s": 2842, "text": "0 represents missing values." }, { "code": null, "e": 3008, "s": 2871, "text": "The percentage of users rating movies is 50% (only 50 ratings are given). In real movie datasets, this percentage becomes less than 10%." }, { "code": null, "e": 3087, "s": 3008, "text": "I assume that a user did not watch a movie if the user did not rate the movie." }, { "code": null, "e": 3271, "s": 3087, "text": "The NearestNeighbors() in the sklearn.neighbors library can be used to calculate the distance between movies using the cosine similarity and find the nearest neighbors for each movie." }, { "code": null, "e": 3455, "s": 3271, "text": "from sklearn.neighbors import NearestNeighborsknn = NearestNeighbors(metric='cosine', algorithm='brute')knn.fit(df.values)distances, indices = knn.kneighbors(df.values, n_neighbors=3)" }, { "code": null, "e": 3621, "s": 3455, "text": "The number of the nearest neighbors (n_neighbors)is set to be 3. Since this includes the movie itself, generally it finds two nearest movies except the movie itself." }, { "code": null, "e": 3740, "s": 3621, "text": "indices[Out] array([[0, 7, 5], [1, 3, 7], [2, 1, 6], .... [9, 0, 7]])" }, { "code": null, "e": 4169, "s": 3740, "text": "indices shows the indices of the nearest neighbors for each movie. Each row corresponds to the row in the df. The first element in a row is the most similar (nearest) movie. Generally, it is the movie itself. The second element is the second nearest, and the third is the third nearest. For example, in the first row [0,7,5], the nearest movie to movie_0 is itself, the second nearest movie is movie_7, and the third is movie_5." }, { "code": null, "e": 4410, "s": 4169, "text": "distances[Out] array([[0.00000000e+00, 3.19586183e-01, 4.03404722e-01], [4.44089210e-16, 3.68421053e-01, 3.95436458e-01], [0.00000000e+00, 5.20766162e-01, 5.24329288e-01], ....[1.11022302e-16, 4.22649731e-01, 4.81455027e-01]])" }, { "code": null, "e": 4573, "s": 4410, "text": "distances shows the distance between movies. A smaller number means the movie is closer. Each number in this array corresponds to the number in the indices array." }, { "code": null, "e": 4712, "s": 4573, "text": "Predicting a rating for a movie by a user is equivalent to calculating the weighted average of ratings for the similar movies by the user." }, { "code": null, "e": 4840, "s": 4712, "text": "For practice, predict the rating for movie_0 by user_7. First, find the nearest neighbors for movie_0 using NearestNeighbors()." }, { "code": null, "e": 5465, "s": 4840, "text": "# get the index for 'movie_0'index_for_movie = df.index.tolist().index('movie_0')# find the indices for the similar moviessim_movies = indices[index_for_movie].tolist()# distances between 'movie_0' and the similar moviesmovie_distances = distances[index_for_movie].tolist()# the position of 'movie_0' in the list sim_moviesid_movie = sim_movies.index(index_for_movie)# remove 'movie_0' from the list sim_moviessim_movies.remove(index_for_movie)# remove 'movie_0' from the list movie_distancesmovie_distances.pop(id_movie)print('The Nearest Movies to movie_0:', sim_movies)print('The Distance from movie_0:', movie_distances)" }, { "code": null, "e": 5593, "s": 5465, "text": "The most similar movies to movie_0 are movie_7 and movie_5, and the distances from movie_0 are 0.3196 and 0.4034, respectively." }, { "code": null, "e": 5654, "s": 5593, "text": "The formula to calculate the predicted rating is as follows:" }, { "code": null, "e": 5698, "s": 5654, "text": "R(m, u) = {∑ j S(m, j)R(j, u)}/ ∑ j S(m, j)" }, { "code": null, "e": 5740, "s": 5698, "text": "R(m, u): the rating for movie m by user u" }, { "code": null, "e": 5792, "s": 5740, "text": "S(m, j): the similarity between movie m and movie j" }, { "code": null, "e": 5850, "s": 5792, "text": "j ∈ J where J is the set of the similar movies to movie m" }, { "code": null, "e": 6170, "s": 5850, "text": "This formula simply implies that the predicted rating for movie m by user u is the weighted average of ratings for the similar movies by user u. The weight for each rating, (S(m, k)/∑ j S(m, j)), becomes greater when movie m and movie k are closer. The denominator of this term makes the sum of all the weights equal 1." }, { "code": null, "e": 6226, "s": 6170, "text": "Let’s predict the rating for movie_0 by user_7, R(0,7):" }, { "code": null, "e": 6279, "s": 6226, "text": "R(0,7)=[S(0,5)∗R(5,7)+S(0,7)∗R(7,7)]/[S(0,5)+S(0,7)]" }, { "code": null, "e": 6403, "s": 6279, "text": "Since the distances between movie_0 and movie_5 and between movie_0 and movie_7 are 0.4034 and 0.3196, the similarities are" }, { "code": null, "e": 6423, "s": 6403, "text": "S(0,5) = (1-0.4034)" }, { "code": null, "e": 6444, "s": 6423, "text": "S(0,7) = (1-0.3196)." }, { "code": null, "e": 6511, "s": 6444, "text": "Because R(5,7) = 2 and R(7,7) = 3, the predicted R(0,7) is 2.5328." }, { "code": null, "e": 6613, "s": 6511, "text": "The code below predicts the ratings for all the movie which user_4 has not watched. (n_neighbors = 3)" }, { "code": null, "e": 6811, "s": 6613, "text": "The copy of the original dataset, df1, updates all the predicted ratings for user_4. The following code is the function to show the recommended movies for a selected user using the updated dataset." }, { "code": null, "e": 6867, "s": 6811, "text": "For example, let’s get 5 recommended movies for user_4." }, { "code": null, "e": 6897, "s": 6867, "text": "recommend_movies('user_4', 5)" }, { "code": null, "e": 7055, "s": 6897, "text": "The output shows the list of the movies the user already watched and the list of the recommended movies. movie_2 has the highest predicted rating for user_4." }, { "code": null, "e": 7393, "s": 7055, "text": "The goal of this project is to build a recommender which recommends movies for a selected user. If we enter a user name into the recommender, the recommender is supposed to return the list of recommended movies which have the highest predicted ratings. Combining the codes above, we can build the movie recommender for any selected user." }, { "code": null, "e": 7490, "s": 7393, "text": "Let's recommend movies for user_4 with n_neighbors = 3 and the number of recommended movies = 4." }, { "code": null, "e": 7524, "s": 7490, "text": "movie_recommender('user_4', 3, 4)" }, { "code": null, "e": 7690, "s": 7524, "text": "In this article, I briefly explained the basic concept of the item-based collaborative filtering and showed how to build the recommendation engine using this method." } ]
PHP | base64_encode() Function - GeeksforGeeks
14 Aug, 2018 The base64_encode() function is an inbuilt function in PHP which is used to Encodes data with MIME base64. MIME (Multipurpose Internet Mail Extensions) base64 is used to encode the string in base64. The base64_encoded data takes 33% more space then original data. Syntax: string base64_encode( $data ) Parameters: This function accepts single parameter $data which is mandatory. It is used to specify the string encoding. Return value: This function returns the encoded string in base64 on success or returns False in case of failure. Below programs illustrate the base64_encode() function in PHP: Program 1: <?php // Program to illustrate base64_encode()// function$str = 'GeeksforGeeks'; echo base64_encode($str);?> R2Vla3Nmb3JHZWVrcw== Program 2: <?php // Program to illustrate base64_encode()// function$str = 'GFG, A computer Science Portal For Geeks';echo base64_encode($str). "\n"; $str = '';echo base64_encode($str). "\n"; $str = 1;echo base64_encode($str). "\n"; $str = '@#$';echo base64_encode($str). "\n";?> R0ZHLCBBIGNvbXB1dGVyIFNjaWVuY2UgUG9ydGFsIEZvciBHZWVrcw== MQ== QCMk Reference: http://php.net/manual/en/function.base64-encode.php PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? Comparing two dates in PHP How to receive JSON POST with PHP ? PHP | Converting string to Date and DateTime Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25164, "s": 25136, "text": "\n14 Aug, 2018" }, { "code": null, "e": 25428, "s": 25164, "text": "The base64_encode() function is an inbuilt function in PHP which is used to Encodes data with MIME base64. MIME (Multipurpose Internet Mail Extensions) base64 is used to encode the string in base64. The base64_encoded data takes 33% more space then original data." }, { "code": null, "e": 25436, "s": 25428, "text": "Syntax:" }, { "code": null, "e": 25466, "s": 25436, "text": "string base64_encode( $data )" }, { "code": null, "e": 25586, "s": 25466, "text": "Parameters: This function accepts single parameter $data which is mandatory. It is used to specify the string encoding." }, { "code": null, "e": 25699, "s": 25586, "text": "Return value: This function returns the encoded string in base64 on success or returns False in case of failure." }, { "code": null, "e": 25762, "s": 25699, "text": "Below programs illustrate the base64_encode() function in PHP:" }, { "code": null, "e": 25773, "s": 25762, "text": "Program 1:" }, { "code": "<?php // Program to illustrate base64_encode()// function$str = 'GeeksforGeeks'; echo base64_encode($str);?>", "e": 25884, "s": 25773, "text": null }, { "code": null, "e": 25906, "s": 25884, "text": "R2Vla3Nmb3JHZWVrcw==\n" }, { "code": null, "e": 25917, "s": 25906, "text": "Program 2:" }, { "code": "<?php // Program to illustrate base64_encode()// function$str = 'GFG, A computer Science Portal For Geeks';echo base64_encode($str). \"\\n\"; $str = '';echo base64_encode($str). \"\\n\"; $str = 1;echo base64_encode($str). \"\\n\"; $str = '@#$';echo base64_encode($str). \"\\n\";?>", "e": 26190, "s": 25917, "text": null }, { "code": null, "e": 26259, "s": 26190, "text": "R0ZHLCBBIGNvbXB1dGVyIFNjaWVuY2UgUG9ydGFsIEZvciBHZWVrcw==\n\nMQ==\nQCMk\n" }, { "code": null, "e": 26322, "s": 26259, "text": "Reference: http://php.net/manual/en/function.base64-encode.php" }, { "code": null, "e": 26335, "s": 26322, "text": "PHP-function" }, { "code": null, "e": 26339, "s": 26335, "text": "PHP" }, { "code": null, "e": 26356, "s": 26339, "text": "Web Technologies" }, { "code": null, "e": 26360, "s": 26356, "text": "PHP" }, { "code": null, "e": 26458, "s": 26360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26508, "s": 26458, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26548, "s": 26508, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 26575, "s": 26548, "text": "Comparing two dates in PHP" }, { "code": null, "e": 26611, "s": 26575, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 26656, "s": 26611, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 26698, "s": 26656, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26731, "s": 26698, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26774, "s": 26731, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26836, "s": 26774, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Big Data Analytics - K-Means Clustering
k-means clustering aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean, serving as a prototype of the cluster. This results in a partitioning of the data space into Voronoi cells. Given a set of observations (x1, x2, ..., xn), where each observation is a d-dimensional real vector, k-means clustering aims to partition the n observations into k groups G = {G1, G2, ..., Gk} so as to minimize the within-cluster sum of squares (WCSS) defined as follows − argmin∑i=1k∑x∈Si∥x−μi∥2 The later formula shows the objective function that is minimized in order to find the optimal prototypes in k-means clustering. The intuition of the formula is that we would like to find groups that are different with each other and each member of each group should be similar with the other members of each cluster. The following example demonstrates how to run the k-means clustering algorithm in R. library(ggplot2) # Prepare Data data = mtcars # We need to scale the data to have zero mean and unit variance data <- scale(data) # Determine number of clusters wss <- (nrow(data)-1)*sum(apply(data,2,var)) for (i in 2:dim(data)[2]) { wss[i] <- sum(kmeans(data, centers = i)$withinss) } # Plot the clusters plot(1:dim(data)[2], wss, type = "b", xlab = "Number of Clusters", ylab = "Within groups sum of squares") In order to find a good value for K, we can plot the within groups sum of squares for different values of K. This metric normally decreases as more groups are added, we would like to find a point where the decrease in the within groups sum of squares starts decreasing slowly. In the plot, this value is best represented by K = 6. Now that the value of K has been defined, it is needed to run the algorithm with that value. # K-Means Cluster Analysis fit <- kmeans(data, 5) # 5 cluster solution # get cluster means aggregate(data,by = list(fit$cluster),FUN = mean) # append cluster assignment data <- data.frame(data, fit$cluster) 65 Lectures 6 hours Arnab Chakraborty 18 Lectures 1.5 hours Pranjal Srivastava, Harshit Srivastava 23 Lectures 2 hours John Shea 18 Lectures 1.5 hours Pranjal Srivastava 46 Lectures 3.5 hours Pranjal Srivastava 37 Lectures 3.5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2802, "s": 2554, "text": "k-means clustering aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean, serving as a prototype of the cluster. This results in a partitioning of the data space into Voronoi cells." }, { "code": null, "e": 3077, "s": 2802, "text": "Given a set of observations (x1, x2, ..., xn), where each observation is a d-dimensional real vector, k-means clustering aims to partition the n observations into k groups G = {G1, G2, ..., Gk} so as to minimize the within-cluster sum of squares (WCSS) defined as follows −" }, { "code": null, "e": 3101, "s": 3077, "text": "argmin∑i=1k∑x∈Si∥x−μi∥2" }, { "code": null, "e": 3418, "s": 3101, "text": "The later formula shows the objective function that is minimized in order to find the optimal prototypes in k-means clustering. The intuition of the formula is that we would like to find groups that are different with each other and each member of each group should be similar with the other members of each cluster." }, { "code": null, "e": 3503, "s": 3418, "text": "The following example demonstrates how to run the k-means clustering algorithm in R." }, { "code": null, "e": 3938, "s": 3503, "text": "library(ggplot2)\n# Prepare Data \ndata = mtcars \n\n# We need to scale the data to have zero mean and unit variance \ndata <- scale(data) \n\n# Determine number of clusters \nwss <- (nrow(data)-1)*sum(apply(data,2,var)) \nfor (i in 2:dim(data)[2]) { \n wss[i] <- sum(kmeans(data, centers = i)$withinss) \n} \n\n# Plot the clusters \nplot(1:dim(data)[2], wss, type = \"b\", xlab = \"Number of Clusters\", \n ylab = \"Within groups sum of squares\")" }, { "code": null, "e": 4269, "s": 3938, "text": "In order to find a good value for K, we can plot the within groups sum of squares for different values of K. This metric normally decreases as more groups are added, we would like to find a point where the decrease in the within groups sum of squares starts decreasing slowly. In the plot, this value is best represented by K = 6." }, { "code": null, "e": 4362, "s": 4269, "text": "Now that the value of K has been defined, it is needed to run the algorithm with that value." }, { "code": null, "e": 4578, "s": 4362, "text": "# K-Means Cluster Analysis\nfit <- kmeans(data, 5) # 5 cluster solution \n\n# get cluster means \naggregate(data,by = list(fit$cluster),FUN = mean) \n\n# append cluster assignment \ndata <- data.frame(data, fit$cluster) \n" }, { "code": null, "e": 4611, "s": 4578, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 4630, "s": 4611, "text": " Arnab Chakraborty" }, { "code": null, "e": 4665, "s": 4630, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4705, "s": 4665, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 4738, "s": 4705, "text": "\n 23 Lectures \n 2 hours \n" }, { "code": null, "e": 4749, "s": 4738, "text": " John Shea" }, { "code": null, "e": 4784, "s": 4749, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4804, "s": 4784, "text": " Pranjal Srivastava" }, { "code": null, "e": 4839, "s": 4804, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4859, "s": 4839, "text": " Pranjal Srivastava" }, { "code": null, "e": 4894, "s": 4859, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4934, "s": 4894, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 4941, "s": 4934, "text": " Print" }, { "code": null, "e": 4952, "s": 4941, "text": " Add Notes" } ]
Differences between CSS and PHP - GeeksforGeeks
15 Sep, 2020 CSS: CSS stands for Cascading Style Sheet, it is a style sheet language used to shape the HTML elements that will be displayed in the browsers as a web-page. By using CSS, the website which has been created by using HTML will look attractive. Basically CSS gives the outer cover on any HTML elements. If you consider HTML as a skeleton of the web-page then the CSS will be the skin of the skeleton. The Internet media type (MIME type) of CSS is text/CSS. Example: This example describes the use of simple CSS. CSS has been used with HTML inside the style tag. HTML <!DOCTYPE ><html> <head> <style> h1 { color: white; background-color: red; } p { color: blue; } </style> </head> <body> <h1>Geeksforgeeks</h1> <p>A computer science portal for geeks</p> </body></html> Output: PHP: PHP stands for Hypertext Preprocessor. PHP is a server-side, scripting language (a script-based program) and is used to develop Web applications. It can be embedded in HTML, and it’s appropriate for the creation of dynamic web pages and database applications. It’s viewed as a benevolent language with capacities to effectively interface with MySQL, Oracle, and different databases. The primary objective of PHP is to allow web developers to create dynamically generated pages rapidly. Example: PHP <?php // Here echo command is// used to display contentecho "Welcome to GFG!"; ?> Output: Welcome to GFG! Differences between CSS and PHP : CSS-Misc PHP-Misc CSS PHP PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to Create Time-Table schedule using HTML ? How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? PHP in_array() Function How to convert array to string in PHP ? How to pop an alert message box using PHP ?
[ { "code": null, "e": 25608, "s": 25580, "text": "\n15 Sep, 2020" }, { "code": null, "e": 26063, "s": 25608, "text": "CSS: CSS stands for Cascading Style Sheet, it is a style sheet language used to shape the HTML elements that will be displayed in the browsers as a web-page. By using CSS, the website which has been created by using HTML will look attractive. Basically CSS gives the outer cover on any HTML elements. If you consider HTML as a skeleton of the web-page then the CSS will be the skin of the skeleton. The Internet media type (MIME type) of CSS is text/CSS." }, { "code": null, "e": 26168, "s": 26063, "text": "Example: This example describes the use of simple CSS. CSS has been used with HTML inside the style tag." }, { "code": null, "e": 26173, "s": 26168, "text": "HTML" }, { "code": "<!DOCTYPE ><html> <head> <style> h1 { color: white; background-color: red; } p { color: blue; } </style> </head> <body> <h1>Geeksforgeeks</h1> <p>A computer science portal for geeks</p> </body></html>", "e": 26507, "s": 26173, "text": null }, { "code": null, "e": 26515, "s": 26507, "text": "Output:" }, { "code": null, "e": 27006, "s": 26515, "text": "PHP: PHP stands for Hypertext Preprocessor. PHP is a server-side, scripting language (a script-based program) and is used to develop Web applications. It can be embedded in HTML, and it’s appropriate for the creation of dynamic web pages and database applications. It’s viewed as a benevolent language with capacities to effectively interface with MySQL, Oracle, and different databases. The primary objective of PHP is to allow web developers to create dynamically generated pages rapidly." }, { "code": null, "e": 27015, "s": 27006, "text": "Example:" }, { "code": null, "e": 27019, "s": 27015, "text": "PHP" }, { "code": "<?php // Here echo command is// used to display contentecho \"Welcome to GFG!\"; ?> ", "e": 27104, "s": 27019, "text": null }, { "code": null, "e": 27112, "s": 27104, "text": "Output:" }, { "code": null, "e": 27129, "s": 27112, "text": "Welcome to GFG!\n" }, { "code": null, "e": 27163, "s": 27129, "text": "Differences between CSS and PHP :" }, { "code": null, "e": 27172, "s": 27163, "text": "CSS-Misc" }, { "code": null, "e": 27181, "s": 27172, "text": "PHP-Misc" }, { "code": null, "e": 27185, "s": 27181, "text": "CSS" }, { "code": null, "e": 27189, "s": 27185, "text": "PHP" }, { "code": null, "e": 27193, "s": 27189, "text": "PHP" }, { "code": null, "e": 27291, "s": 27193, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27328, "s": 27291, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27357, "s": 27328, "text": "Form validation using jQuery" }, { "code": null, "e": 27396, "s": 27357, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 27438, "s": 27396, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 27485, "s": 27438, "text": "How to Create Time-Table schedule using HTML ?" }, { "code": null, "e": 27530, "s": 27485, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 27580, "s": 27530, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27604, "s": 27580, "text": "PHP in_array() Function" }, { "code": null, "e": 27644, "s": 27604, "text": "How to convert array to string in PHP ?" } ]
JSP - Http Status Codes
In this chapter, we will discuss the Http Status Codes in JSP. The format of the HTTP request and the HTTP response messages are similar and will have the following structure − An initial status line + CRLF (Carriage Return + Line Feed ie. New Line) An initial status line + CRLF (Carriage Return + Line Feed ie. New Line) Zero or more header lines + CRLF Zero or more header lines + CRLF A blank line ie. a CRLF A blank line ie. a CRLF An optional message body like file, query data or query output. An optional message body like file, query data or query output. For example, a server response header looks like the following − HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: ... (Blank Line) <!doctype ...> <html> <head>...</head> <body> ... </body> </html> The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the example), and a very short message corresponding to the status code (OK in the example). Following table lists out the HTTP status codes and associated messages that might be returned from the Web Server − Following methods can be used to set the HTTP Status Code in your servlet program. These methods are available with the HttpServletResponse object. public void setStatus ( int statusCode ) This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter. public void sendRedirect(String url) This method generates a 302 response along with a Location header giving the URL of the new document. public void sendError(int code, String message) This method sends a status code (usually 404) along with a short message that is automatically formatted inside an HTML document and sent to the client. Following example shows how a 407 error code is sent to the client browser. After this, the browser would show you "Need authentication!!!" message. <html> <head> <title>Setting HTTP Status Code</title> </head> <body> <% // Set error code and reason. response.sendError(407, "Need authentication!!!" ); %> </body> </html> You will receive the following output − HTTP Status 407 - Need authentication!!! type Status report message Need authentication!!! description The client must first authenticate itself with the proxy (Need authentication!!!). Apache Tomcat/5.5.29 type Status report message Need authentication!!! description The client must first authenticate itself with the proxy (Need authentication!!!). To become more comfortable with HTTP status codes, try to set different status codes and their description. 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2416, "s": 2239, "text": "In this chapter, we will discuss the Http Status Codes in JSP. The format of the HTTP request and the HTTP response messages are similar and will have the following structure −" }, { "code": null, "e": 2489, "s": 2416, "text": "An initial status line + CRLF (Carriage Return + Line Feed ie. New Line)" }, { "code": null, "e": 2562, "s": 2489, "text": "An initial status line + CRLF (Carriage Return + Line Feed ie. New Line)" }, { "code": null, "e": 2595, "s": 2562, "text": "Zero or more header lines + CRLF" }, { "code": null, "e": 2628, "s": 2595, "text": "Zero or more header lines + CRLF" }, { "code": null, "e": 2652, "s": 2628, "text": "A blank line ie. a CRLF" }, { "code": null, "e": 2676, "s": 2652, "text": "A blank line ie. a CRLF" }, { "code": null, "e": 2740, "s": 2676, "text": "An optional message body like file, query data or query output." }, { "code": null, "e": 2804, "s": 2740, "text": "An optional message body like file, query data or query output." }, { "code": null, "e": 2869, "s": 2804, "text": "For example, a server response header looks like the following −" }, { "code": null, "e": 3041, "s": 2869, "text": "HTTP/1.1 200 OK\nContent-Type: text/html\nHeader2: ...\n...\nHeaderN: ...\n (Blank Line)\n<!doctype ...>\n\n<html>\n <head>...</head>\n \n <body>\n ...\n </body>\n</html>" }, { "code": null, "e": 3228, "s": 3041, "text": "The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the example), and a very short message corresponding to the status code (OK in the example)." }, { "code": null, "e": 3345, "s": 3228, "text": "Following table lists out the HTTP status codes and associated messages that might be returned from the Web Server −" }, { "code": null, "e": 3493, "s": 3345, "text": "Following methods can be used to set the HTTP Status Code in your servlet program. These methods are available with the HttpServletResponse object." }, { "code": null, "e": 3534, "s": 3493, "text": "public void setStatus ( int statusCode )" }, { "code": null, "e": 3802, "s": 3534, "text": "This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter." }, { "code": null, "e": 3839, "s": 3802, "text": "public void sendRedirect(String url)" }, { "code": null, "e": 3941, "s": 3839, "text": "This method generates a 302 response along with a Location header giving the URL of the new document." }, { "code": null, "e": 3989, "s": 3941, "text": "public void sendError(int code, String message)" }, { "code": null, "e": 4142, "s": 3989, "text": "This method sends a status code (usually 404) along with a short message that is automatically formatted inside an HTML document and sent to the client." }, { "code": null, "e": 4291, "s": 4142, "text": "Following example shows how a 407 error code is sent to the client browser. After this, the browser would show you \"Need authentication!!!\" message." }, { "code": null, "e": 4516, "s": 4291, "text": "<html>\n <head>\n <title>Setting HTTP Status Code</title>\n </head>\n \n <body>\n <%\n // Set error code and reason.\n response.sendError(407, \"Need authentication!!!\" );\n %>\n </body>\n</html>" }, { "code": null, "e": 4556, "s": 4516, "text": "You will receive the following output −" }, { "code": null, "e": 4764, "s": 4556, "text": "HTTP Status 407 - Need authentication!!!\ntype Status report\nmessage Need authentication!!!\ndescription The client must first authenticate itself with the proxy (Need authentication!!!).\nApache Tomcat/5.5.29\n" }, { "code": null, "e": 4783, "s": 4764, "text": "type Status report" }, { "code": null, "e": 4814, "s": 4783, "text": "message Need authentication!!!" }, { "code": null, "e": 4909, "s": 4814, "text": "description The client must first authenticate itself with the proxy (Need authentication!!!)." }, { "code": null, "e": 5017, "s": 4909, "text": "To become more comfortable with HTTP status codes, try to set different status codes and their description." }, { "code": null, "e": 5052, "s": 5017, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 5067, "s": 5052, "text": " Chaand Sheikh" }, { "code": null, "e": 5102, "s": 5067, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 5117, "s": 5102, "text": " Chaand Sheikh" }, { "code": null, "e": 5152, "s": 5117, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5166, "s": 5152, "text": " Karthikeya T" }, { "code": null, "e": 5201, "s": 5166, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5217, "s": 5201, "text": " TELCOMA Global" }, { "code": null, "e": 5250, "s": 5217, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 5266, "s": 5250, "text": " TELCOMA Global" }, { "code": null, "e": 5300, "s": 5266, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 5308, "s": 5300, "text": " Uplatz" }, { "code": null, "e": 5315, "s": 5308, "text": " Print" }, { "code": null, "e": 5326, "s": 5315, "text": " Add Notes" } ]
Tree and Distance | Practice | GeeksforGeeks
Given a tree with N nodes rooted at 1, the task is to find the maximum distance of node X from any other node Note: All the nodes are numbered from 1 to N. Input: 1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. 2. The first line of each test case contains two space-separated single integers N and X. 3. Next N-1 lines contain two space-separated integers u and v, represents an edge in between them Output: For each test case, print the answer Constraints: 1. 1 <= T <= 5 2. 1 <= X <= N <= 105 Example: Input: 2 4 2 1 2 3 4 4 1 5 3 1 2 2 3 3 4 4 5 Output: 3 2 0 chaitanyasai3213 months ago #include <bits/stdc++.h>using namespace std; int main() {int t;cin>>t;while(t--){ int n,x; cin>>n>>x; vector<int> adj[n+1]; for(int i=0;i<n-1;i++) { int u,v; cin>>u>>v; adj[u].push_back(v); adj[v].push_back(u); } queue<pair<int,int> >q; q.push({x,0}); int ma=0,vis[n+1]={0}; while(!q.empty()) { auto get=q.front(); int child=get.first; int cou=get.second; q.pop(); vis[child]=1; ma=max(ma,cou); for(auto it:adj[child]) { if(!vis[it]) { q.push({it,cou+1}); } } } cout<<ma<<"\n"; }} 0 neznajko6 months ago Yeeh! 0.2/2.2 //////////////////////////////////////////////////////// #include <iostream> #include <vector> #include <algorithm> // max using namespace std; //////////////////////////////////////////////////////// class solutn { private: int d = -1; // distance int m = 0; // max distance const vector<vector<int>>& g; // adjacency list void xp( int v, int u); // explore v <- u public: solutn( const vector<vector<int>>& g): g( g) {} int maxdist( int x); }; void solutn::xp( int v, int u) { // explore v comming from u d++; // previsit if( g[ v].size() == 1 and u > 0) { m = max( m, d); // update m if v is leaf node } else { for( int w: g[ v]) { if( w != u) xp( w, v); } } d--; // postvisit } int solutn::maxdist( int x) { xp( x, 0); return m; } //////////////////////////////////////////////////////// int main() { int tc; std::cin >> tc; while( tc--) { int n, x; std::cin >> n >> x; vector<vector<int>> g( n + 1); for( int j = 0; j < n - 1; ++j) { int u, v; std::cin >> u >> v; g[ u].push_back( v); g[ v].push_back( u); } solutn s( g); cout << s.maxdist( x) << endl; } } //////////////////////////////////////////////////////// // log: //////////////////////////////////////////////////////// 0 imranwahid6 months ago Easy C++ solution using DFS https://ide.geeksforgeeks.org/EfZctZjVNj #include<bits/stdc++.h> using namespace std; // function for dfs traversal void dfs(unordered_map<int,vector<int>>&m,int curr,vector<bool>&vis,int dis,int &ans) { vis[curr]=true; // take the maximum of the current distance and the ans encountered so far ans=max(ans,dis); for(auto it:m[curr]) { if(!vis[it]) { dfs(m,it,vis,dis+1,ans); } } } int maxDistance(unordered_map<int,vector<int>>&m,int n,int x) { vector<bool>vis(n+1,false); int ans=0; dfs(m,x,vis,0,ans); return ans; } int main() { int t; cin>>t; while(t--) { int n,x; unordered_map<int,vector<int>>m; cin>>n>>x; for(int i=0;i<n-1;i++) { int u,v; cin>>u>>v; m[u].push_back(v); m[v].push_back(u); } cout<<maxDistance(m,n,x)<<endl; } return 0; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 384, "s": 226, "text": "Given a tree with N nodes rooted at 1, the task is to find the maximum distance of node X from any other node\n\nNote: All the nodes are numbered from 1 to N. " }, { "code": null, "e": 717, "s": 384, "text": "Input: \n1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.\n2. The first line of each test case contains two space-separated single integers N and X.\n3. Next N-1 lines contain two space-separated integers u and v, represents an edge in between them" }, { "code": null, "e": 763, "s": 717, "text": "\nOutput: For each test case, print the answer" }, { "code": null, "e": 870, "s": 763, "text": "\nConstraints:\n1. 1 <= T <= 5\n2. 1 <= X <= N <= 105\n\n\nExample:\nInput:\n2\n4 2\n1 2\n3 4\n4 1\n5 3\n1 2\n2 3\n3 4\n4 5" }, { "code": null, "e": 882, "s": 870, "text": "Output:\n3\n2" }, { "code": null, "e": 884, "s": 882, "text": "0" }, { "code": null, "e": 912, "s": 884, "text": "chaitanyasai3213 months ago" }, { "code": null, "e": 957, "s": 912, "text": "#include <bits/stdc++.h>using namespace std;" }, { "code": null, "e": 1574, "s": 957, "text": "int main() {int t;cin>>t;while(t--){ int n,x; cin>>n>>x; vector<int> adj[n+1]; for(int i=0;i<n-1;i++) { int u,v; cin>>u>>v; adj[u].push_back(v); adj[v].push_back(u); } queue<pair<int,int> >q; q.push({x,0}); int ma=0,vis[n+1]={0}; while(!q.empty()) { auto get=q.front(); int child=get.first; int cou=get.second; q.pop(); vis[child]=1; ma=max(ma,cou); for(auto it:adj[child]) { if(!vis[it]) { q.push({it,cou+1}); } } } cout<<ma<<\"\\n\"; }}" }, { "code": null, "e": 1576, "s": 1574, "text": "0" }, { "code": null, "e": 1597, "s": 1576, "text": "neznajko6 months ago" }, { "code": null, "e": 1611, "s": 1597, "text": "Yeeh! 0.2/2.2" }, { "code": null, "e": 3004, "s": 1611, "text": "////////////////////////////////////////////////////////\n#include <iostream>\n#include <vector>\n#include <algorithm> // max\nusing namespace std;\n////////////////////////////////////////////////////////\nclass solutn {\nprivate:\n int d = -1; // distance\n int m = 0; // max distance\n const vector<vector<int>>& g; // adjacency list\n void xp( int v, int u); // explore v <- u\npublic:\n solutn( const vector<vector<int>>& g): g( g) {}\n int maxdist( int x);\n};\nvoid solutn::xp( int v, int u)\n{ // explore v comming from u\n d++; // previsit\n if( g[ v].size() == 1 and u > 0) {\n m = max( m, d); // update m if v is leaf node\n } else {\n for( int w: g[ v]) {\n if( w != u) xp( w, v);\n }\n }\n d--; // postvisit\n}\nint solutn::maxdist( int x)\n{\n xp( x, 0);\n return m;\n}\n////////////////////////////////////////////////////////\nint main()\n{\n int tc;\n std::cin >> tc;\n while( tc--) {\n int n, x;\n std::cin >> n >> x;\n vector<vector<int>> g( n + 1);\n for( int j = 0; j < n - 1; ++j) {\n int u, v;\n std::cin >> u >> v;\n g[ u].push_back( v);\n g[ v].push_back( u);\n }\n solutn s( g);\n cout << s.maxdist( x) << endl;\n }\n}\n////////////////////////////////////////////////////////\n// log:\n////////////////////////////////////////////////////////" }, { "code": null, "e": 3006, "s": 3004, "text": "0" }, { "code": null, "e": 3029, "s": 3006, "text": "imranwahid6 months ago" }, { "code": null, "e": 3057, "s": 3029, "text": "Easy C++ solution using DFS" }, { "code": null, "e": 3098, "s": 3057, "text": "https://ide.geeksforgeeks.org/EfZctZjVNj" }, { "code": null, "e": 3954, "s": 3098, "text": "#include<bits/stdc++.h>\nusing namespace std;\n// function for dfs traversal\nvoid dfs(unordered_map<int,vector<int>>&m,int curr,vector<bool>&vis,int dis,int &ans)\n{\n vis[curr]=true;\n // take the maximum of the current distance and the ans encountered so far\n ans=max(ans,dis);\n for(auto it:m[curr])\n {\n if(!vis[it])\n {\n dfs(m,it,vis,dis+1,ans);\n }\n }\n}\nint maxDistance(unordered_map<int,vector<int>>&m,int n,int x)\n{\n vector<bool>vis(n+1,false);\n int ans=0;\n dfs(m,x,vis,0,ans);\n return ans;\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t int n,x;\n\t unordered_map<int,vector<int>>m;\n\t cin>>n>>x;\n\t for(int i=0;i<n-1;i++)\n\t {\n\t int u,v;\n\t cin>>u>>v;\n\t m[u].push_back(v);\n\t m[v].push_back(u);\n\t }\n\t cout<<maxDistance(m,n,x)<<endl;\n\t}\n\treturn 0;\n}" }, { "code": null, "e": 4100, "s": 3954, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 4136, "s": 4100, "text": " Login to access your submissions. " }, { "code": null, "e": 4146, "s": 4136, "text": "\nProblem\n" }, { "code": null, "e": 4156, "s": 4146, "text": "\nContest\n" }, { "code": null, "e": 4219, "s": 4156, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4367, "s": 4219, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4575, "s": 4367, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 4681, "s": 4575, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Kali Linux - Information Gathering Tools
In this chapter, we will discuss the information gathering tools of Kali Linux. NMAP and ZenMAP are useful tools for the scanning phase of Ethical Hacking in Kali Linux. NMAP and ZenMAP are practically the same tool, however NMAP uses command line while ZenMAP has a GUI. NMAP is a free utility tool for network discovery and security auditing. Many systems and network administrators also find it useful for tasks such as network inventory, managing service upgrade schedules, and monitoring host or service uptime. NMAP uses raw IP packets in novel ways to determine which hosts are available on the network, what services (application name and version) those hosts are offering, which operating systems (and OS versions) they are running, what type of packet filters/firewalls are in use, etc. Now, let’s go step by step and learn how to use NMAP and ZenMAP. Step 1 − To open, go to Applications → 01-Information Gathering → nmap or zenmap. Step 2 − The next step is to detect the OS type/version of the target host. Based on the help indicated by NMAP, the parameter of OS type/version detection is variable “-O”. For more information, use this link: https://nmap.org/book/man-os-detection.html The command that we will use is − nmap -O 192.168.1.101 The following screenshot shows where you need to type the above command to see the Nmap output − Step 3 − Next, open the TCP and UDP ports. To scan all the TCP ports based on NMAP, use the following command − nmap -p 1-65535 -T4 192.168.1.101 Where the parameter “–p” indicates all the TCP ports that have to be scanned. In this case, we are scanning all the ports and “-T4” is the speed of scanning at which NMAP has to run. Following are the results. In green are all the TCP open ports and in red are all the closed ports. However, NMAP does not show as the list is too long. Stealth scan or SYN is also known as half-open scan, as it doesn’t complete the TCP three-way handshake. A hacker sends a SYN packet to the target; if a SYN/ACK frame is received back, then it’s assumed the target would complete the connect and the port is listening. If an RST is received back from the target, then it is assumed the port isn’t active or is closed. Now to see the SYN scan in practice, use the parameter –sS in NMAP. Following is the full command − nmap -sS -T4 192.168.1.101 The following screenshot shows how to use this command − Searchsploit is a tool that helps Kali Linux users to directly search with the command line from Exploit database archive. To open it, go to Applications → 08-Exploitation Tools → searchsploit, as shown in the following screenshot. After opening the terminal, type "searchsploit exploit index name". In this section, we will learn how to use some DNS tools that Kali has incorporated. Basically, these tools help in zone transfers or domain IP resolving issues. The first tool is dnsenum.pl which is a PERL script that helps to get MX, A, and other records connect to a domain. Click the terminal on the left panel. Type “dnsenum domain name” and all the records will be shown. In this case, it shows A records. The second tool is DNSMAP which helps to find the phone numbers, contacts, and other subdomain connected to this domain, that we are searching. Following is an example. Click the terminal as in the upper section , then write “dnsmap domain name” The third tool is dnstracer, which determines where a given Domain Name Server (DNS) gets its information from for a given hostname. Click the terminal as in the upper section, then type “dnstracer domain name”. LBD (Load Balancing Detector) tools are very interesting as they detect if a given domain uses DNS and/or HTTP load balancing. It is important because if you have two servers, one or the other may not be updated and you can try to exploit it. Following are the steps to use it − First, click the terminal on the left panel. Then, type “lbd domainname”. If it produces a result as “FOUND”, it means that the server has a load balance. In this case, the result is “NOT FOUND”. Hping3 is widely used by ethical hackers. It is nearly similar to ping tools but is more advanced, as it can bypass the firewall filter and use TCP, UDP, ICMP and RAW-IP protocols. It has a traceroute mode and the ability to send files between a covered channel. Click the terminal on the left panel. Type “hping3 –h” which will show how to use this command. The other command is “hping3 domain or IP -parameter” 84 Lectures 6.5 hours Mohamad Mahjoub 8 Lectures 1 hours Corey Charles 21 Lectures 4 hours Atul Tiwari 55 Lectures 3 hours Musab Zayadneh 29 Lectures 2 hours Musab Zayadneh 32 Lectures 4 hours Adnaan Arbaaz Ahmed Print Add Notes Bookmark this page
[ { "code": null, "e": 2109, "s": 2029, "text": "In this chapter, we will discuss the information gathering tools of Kali Linux." }, { "code": null, "e": 2301, "s": 2109, "text": "NMAP and ZenMAP are useful tools for the scanning phase of Ethical Hacking in Kali Linux. NMAP and ZenMAP are practically the same tool, however NMAP uses command line while ZenMAP has a GUI." }, { "code": null, "e": 2546, "s": 2301, "text": "NMAP is a free utility tool for network discovery and security auditing. Many systems and network administrators also find it useful for tasks such as network inventory, managing service upgrade schedules, and monitoring host or service uptime." }, { "code": null, "e": 2826, "s": 2546, "text": "NMAP uses raw IP packets in novel ways to determine which hosts are available on the network, what services (application name and version) those hosts are offering, which operating systems (and OS versions) they are running, what type of packet filters/firewalls are in use, etc." }, { "code": null, "e": 2891, "s": 2826, "text": "Now, let’s go step by step and learn how to use NMAP and ZenMAP." }, { "code": null, "e": 2973, "s": 2891, "text": "Step 1 − To open, go to Applications → 01-Information Gathering → nmap or zenmap." }, { "code": null, "e": 3228, "s": 2973, "text": "Step 2 − The next step is to detect the OS type/version of the target host. Based on the help indicated by NMAP, the parameter of OS type/version detection is variable “-O”. For more information, use this link: https://nmap.org/book/man-os-detection.html" }, { "code": null, "e": 3262, "s": 3228, "text": "The command that we will use is −" }, { "code": null, "e": 3285, "s": 3262, "text": "nmap -O 192.168.1.101\n" }, { "code": null, "e": 3382, "s": 3285, "text": "The following screenshot shows where you need to type the above command to see the Nmap output −" }, { "code": null, "e": 3494, "s": 3382, "text": "Step 3 − Next, open the TCP and UDP ports. To scan all the TCP ports based on NMAP, use the following command −" }, { "code": null, "e": 3531, "s": 3494, "text": "nmap -p 1-65535 -T4 192.168.1.101 \n" }, { "code": null, "e": 3714, "s": 3531, "text": "Where the parameter “–p” indicates all the TCP ports that have to be scanned. In this case, we are scanning all the ports and “-T4” is the speed of scanning at which NMAP has to run." }, { "code": null, "e": 3867, "s": 3714, "text": "Following are the results. In green are all the TCP open ports and in red are all the closed ports. However, NMAP does not show as the list is too long." }, { "code": null, "e": 4234, "s": 3867, "text": "Stealth scan or SYN is also known as half-open scan, as it doesn’t complete the TCP three-way handshake. A hacker sends a SYN packet to the target; if a SYN/ACK frame is received back, then it’s assumed the target would complete the connect and the port is listening. If an RST is received back from the target, then it is assumed the port isn’t active or is closed." }, { "code": null, "e": 4334, "s": 4234, "text": "Now to see the SYN scan in practice, use the parameter –sS in NMAP. Following is the full command −" }, { "code": null, "e": 4363, "s": 4334, "text": "nmap -sS -T4 192.168.1.101 \n" }, { "code": null, "e": 4420, "s": 4363, "text": "The following screenshot shows how to use this command −" }, { "code": null, "e": 4543, "s": 4420, "text": "Searchsploit is a tool that helps Kali Linux users to directly search with the command line from Exploit database archive." }, { "code": null, "e": 4652, "s": 4543, "text": "To open it, go to Applications → 08-Exploitation Tools → searchsploit, as shown in the following screenshot." }, { "code": null, "e": 4720, "s": 4652, "text": "After opening the terminal, type \"searchsploit exploit index name\"." }, { "code": null, "e": 4882, "s": 4720, "text": "In this section, we will learn how to use some DNS tools that Kali has incorporated. Basically, these tools help in zone transfers or domain IP resolving issues." }, { "code": null, "e": 4998, "s": 4882, "text": "The first tool is dnsenum.pl which is a PERL script that helps to get MX, A, and other records connect to a domain." }, { "code": null, "e": 5036, "s": 4998, "text": "Click the terminal on the left panel." }, { "code": null, "e": 5132, "s": 5036, "text": "Type “dnsenum domain name” and all the records will be shown. In this case, it shows A records." }, { "code": null, "e": 5301, "s": 5132, "text": "The second tool is DNSMAP which helps to find the phone numbers, contacts, and other subdomain connected to this domain, that we are searching. Following is an example." }, { "code": null, "e": 5378, "s": 5301, "text": "Click the terminal as in the upper section , then write “dnsmap domain name”" }, { "code": null, "e": 5511, "s": 5378, "text": "The third tool is dnstracer, which determines where a given Domain Name Server (DNS) gets its information from for a given hostname." }, { "code": null, "e": 5590, "s": 5511, "text": "Click the terminal as in the upper section, then type “dnstracer domain name”." }, { "code": null, "e": 5869, "s": 5590, "text": "LBD (Load Balancing Detector) tools are very interesting as they detect if a given domain uses DNS and/or HTTP load balancing. It is important because if you have two servers, one or the other may not be updated and you can try to exploit it. Following are the steps to use it −" }, { "code": null, "e": 5914, "s": 5869, "text": "First, click the terminal on the left panel." }, { "code": null, "e": 6065, "s": 5914, "text": "Then, type “lbd domainname”. If it produces a result as “FOUND”, it means that the server has a load balance. In this case, the result is “NOT FOUND”." }, { "code": null, "e": 6328, "s": 6065, "text": "Hping3 is widely used by ethical hackers. It is nearly similar to ping tools but is more advanced, as it can bypass the firewall filter and use TCP, UDP, ICMP and RAW-IP protocols. It has a traceroute mode and the ability to send files between a covered channel." }, { "code": null, "e": 6366, "s": 6328, "text": "Click the terminal on the left panel." }, { "code": null, "e": 6424, "s": 6366, "text": "Type “hping3 –h” which will show how to use this command." }, { "code": null, "e": 6478, "s": 6424, "text": "The other command is “hping3 domain or IP -parameter”" }, { "code": null, "e": 6513, "s": 6478, "text": "\n 84 Lectures \n 6.5 hours \n" }, { "code": null, "e": 6530, "s": 6513, "text": " Mohamad Mahjoub" }, { "code": null, "e": 6562, "s": 6530, "text": "\n 8 Lectures \n 1 hours \n" }, { "code": null, "e": 6577, "s": 6562, "text": " Corey Charles" }, { "code": null, "e": 6610, "s": 6577, "text": "\n 21 Lectures \n 4 hours \n" }, { "code": null, "e": 6623, "s": 6610, "text": " Atul Tiwari" }, { "code": null, "e": 6656, "s": 6623, "text": "\n 55 Lectures \n 3 hours \n" }, { "code": null, "e": 6672, "s": 6656, "text": " Musab Zayadneh" }, { "code": null, "e": 6705, "s": 6672, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 6721, "s": 6705, "text": " Musab Zayadneh" }, { "code": null, "e": 6754, "s": 6721, "text": "\n 32 Lectures \n 4 hours \n" }, { "code": null, "e": 6775, "s": 6754, "text": " Adnaan Arbaaz Ahmed" }, { "code": null, "e": 6782, "s": 6775, "text": " Print" }, { "code": null, "e": 6793, "s": 6782, "text": " Add Notes" } ]
Order strings by length of characters IN mYsql?
You can order by length of characters with the help of CHAR_LENGTH() function from MySQL. The function returns the number of characters i.e. 4 for the following string − AMIT To order strings by length of characters, the following is the syntax − select *from yourTableName order by CHAR_LENGTH(yourColumnName); To understand the above concept, let us first create a table. The following is the query to create a table − mysql> create table OrderByCharacterLength −> ( −> BookName varchar(200) −> ); Query OK, 0 rows affected (1.97 sec) Insert some records in the table with the help of insert command. The query is as follows − mysql> insert into OrderByCharacterLength values('Let us C'); Query OK, 1 row affected (0.31 sec) mysql> insert into OrderByCharacterLength values('Introduction to C'); Query OK, 1 row affected (0.20 sec) mysql> insert into OrderByCharacterLength values('Data Structure And Algorithm in Java '); Query OK, 1 row affected (0.13 sec) mysql> insert into OrderByCharacterLength values('C in Depth'); Query OK, 1 row affected (0.17 sec) mysql> insert into OrderByCharacterLength values('Java Projects'); Query OK, 1 row affected (0.23 sec) Let us display all records in a sequence as inserted in the table above. The query is as follows − mysql> select *from OrderByCharacterLength; The following is the output − +---------------------------------------+ | BookName | +---------------------------------------+ | Let us C | | Introduction to C | | Data Structure And Algorithm in Java | | C in Depth | | Java Projects | +---------------------------------------+ 5 rows in set (0.00 sec) Here is the query that display all records arranged according to the length of characters. If a column value has minimum length then it gets higher priority and will get displayed first. The query is as follows − mysql> select *from OrderByCharacterLength order by CHAR_LENGTH(BookName); The following is the output − +---------------------------------------+ | BookName | +---------------------------------------+ | Let us C | | C in Depth | | Java Projects | | Introduction to C | | Data Structure And Algorithm in Java | +---------------------------------------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1232, "s": 1062, "text": "You can order by length of characters with the help of CHAR_LENGTH() function from MySQL. The function returns the number of characters i.e. 4 for the following string −" }, { "code": null, "e": 1237, "s": 1232, "text": "AMIT" }, { "code": null, "e": 1309, "s": 1237, "text": "To order strings by length of characters, the following is the syntax −" }, { "code": null, "e": 1374, "s": 1309, "text": "select *from yourTableName order by CHAR_LENGTH(yourColumnName);" }, { "code": null, "e": 1483, "s": 1374, "text": "To understand the above concept, let us first create a table. The following is the query to create a table −" }, { "code": null, "e": 1608, "s": 1483, "text": "mysql> create table OrderByCharacterLength\n −> (\n −> BookName varchar(200)\n −> );\nQuery OK, 0 rows affected (1.97 sec)" }, { "code": null, "e": 1700, "s": 1608, "text": "Insert some records in the table with the help of insert command. The query is as follows −" }, { "code": null, "e": 2239, "s": 1700, "text": "mysql> insert into OrderByCharacterLength values('Let us C');\nQuery OK, 1 row affected (0.31 sec)\n\nmysql> insert into OrderByCharacterLength values('Introduction to C');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into OrderByCharacterLength values('Data Structure And Algorithm in Java ');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into OrderByCharacterLength values('C in Depth');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into OrderByCharacterLength values('Java Projects');\nQuery OK, 1 row affected (0.23 sec)" }, { "code": null, "e": 2338, "s": 2239, "text": "Let us display all records in a sequence as inserted in the table above. The query is as follows −" }, { "code": null, "e": 2382, "s": 2338, "text": "mysql> select *from OrderByCharacterLength;" }, { "code": null, "e": 2412, "s": 2382, "text": "The following is the output −" }, { "code": null, "e": 2815, "s": 2412, "text": "+---------------------------------------+\n| BookName |\n+---------------------------------------+\n| Let us C |\n| Introduction to C |\n| Data Structure And Algorithm in Java |\n| C in Depth |\n| Java Projects |\n+---------------------------------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 3002, "s": 2815, "text": "Here is the query that display all records arranged according to the length of characters. If a column value has minimum length then it gets higher priority and will get displayed first." }, { "code": null, "e": 3028, "s": 3002, "text": "The query is as follows −" }, { "code": null, "e": 3103, "s": 3028, "text": "mysql> select *from OrderByCharacterLength order by CHAR_LENGTH(BookName);" }, { "code": null, "e": 3133, "s": 3103, "text": "The following is the output −" }, { "code": null, "e": 3536, "s": 3133, "text": "+---------------------------------------+\n| BookName |\n+---------------------------------------+\n| Let us C |\n| C in Depth |\n| Java Projects |\n| Introduction to C |\n| Data Structure And Algorithm in Java |\n+---------------------------------------+\n5 rows in set (0.00 sec)" } ]
Getting started with planned contrasts in R | Towards Data Science
It’s a situation many of us face: You just ran an ANOVA, and your results are significant... but what next? We basically know that something is going on, but what exactly? Which treatments are making the difference? This is where planned contrasts come in. They sound more complicated than they are, and they are a flexible statistical tool that makes this ANOVA post-hoc test extremely powerful. Just a quick note before I get going: In this tutorial, I will just talk about orthogonal contrast ... you do not need to know what this means, just in case you heard the term, and we're looking for this. For this tutorial, we will be using the salaries dataset. It contains data on the salaries of different professors. Load it using the following command. df=Salaries We will need the “car” package for the next step, so install the package using the below command if you haven’t done so already. If you aren’t sure whether you’ve already installed the package, just run this command. install.packages("car") Now, the ANOVA we want to do is to see whether the professors' rank has any impact on their salary. We also want to take all other intuitively important variables into account ... technically making this an ANCOVA. We run the below commands to get the output. library(car)aov1 = aov(salary ~ sex + rank + yrs.since.phd + yrs.service + discipline, df)Anova(aov1 ,type="III") This yields the following result. So we can see that rank does influence the salary of the professors. But how exactly? Planned contrasts can help us find out more about this. However, planned contrasts require that you really understand your independent variable of interest. Let’s look at the independent variable of interest first. What does “rank” contain. For this, run the following command to see the levels of “rank.” levels(df$rank) This yields the following output. In the US ... and this is an American dataset ... there is a huge difference between being an assistant professor and being an associate professor. Associate professors are part of faculty and are most often tenured. Assistant professors aren’t part of faculty and most often not tenured. A question planned contrasts can help us answer is, “Is being an Associate Professor important for a professor’s salary, or is it important to be part of the faculty?” ... do you see what we are doing here? We are using implicit information in the data to group our levels in new ways and reveal more information about the effect's true underlying drivers. Basically, we are saying ... “We know that there are three levels, but how can we group these levels to reveal more information?” — we are contrasting groups of data. You would normally run two planned contrasts in a situation like this: First, you would want to see if being part of faculty makes a difference. Second, you would want to see if differences within faculty make a difference. Below is a graphical representation of what we are trying to achieve. We communicate this to R with the help of orthogonal contrasts, which use a specific notation. The notation consists of four rules: We use zero (0) for groups excluded from a contrast. We use negative values (<0) for the baseline group. We use positive values (>0) for the treatment group. The sum of the treatments' values in every contrast needs to be zero (0). This doesn't sound very easy but is very simple once you see how this plays out for the example. The contrasts in the schematic would be communicated to R in the following way: Contrast 1: In the first contrast, we group AssocProf and Prof into the treatment condition. Therefore, they both are assigned a positive value. To keep things simple, we choose a low value (1). As AssistProf is now the baseline, needs to be negative, and contrast 1 in total needs to add up to zero (0), we are required to assign it a -2. Contrast 2: In the second contrast, we only want to see whether differences among tenured positions impact the salary. Therefore, we exclude AsstProf by assigning it a 0. We choose to make Prof the treatment condition and AssocProf the baseline condition ... we could also switch the two of them, but changes in direction are dangerous as we might forget about them when we later interpret the results. To keep things simple, we keep the direction as it is (treatment is the more senior condition). Also, to keep things simple, we again choose low values and assign the treatment condition Prof a 1. Therefore, the baseline condition AssocProf has to be a -1, as the contrast in total needs to add up to 0. This is exactly how we communicate the assigned contrasts to R. contrast1 = c(-2,1,1)contrast2 = c(0,-1,1) And then, we tell R to assign these contrasts to the variable rank in the dataset df. contrasts(df$rank) = cbind(contrast1, contrast2) To check if the contrasts were assigned correctly, we can repeat the contrast() command to see how they are now saved in R. contrasts(df$rank) As we can see, they have been implemented correctly. So now we can proceed with our analysis. We analyze our contrasts by rerunning the same ANOVA command that we ran before. However, because now R has more information on the structure of the variable rank in the form of contrasts, the output will be different. aov1 = aov(salary ~ sex + rank + yrs.since.phd + yrs.service + discipline, df) And this time, we do not want to access the information in the form of an ANOVA output but in the form of regression output. Therefore, we ask for the output using the summary.lm command. summary.lm(aov1) As one can see, R now produces output, in which the levels of the variable rank are replaced with the two contrasts. Both contrasts are significant, meaning that becoming tenured affects professors’ salaries and so does moving up among tenured positions. We would report this finding in the following way: An ANOVA revealed that there was a significant effect of professors’ ranks on their salaries (F(2, 390) = 68.41, p < .001) while controlling for their sex, the number of years since they completed their PhD, the number of years of service, and the academic discipline they work in. Further investigation of the impact of professors’ ranks on their salaries using planned contrasts revealed that being faculty (associate or full professor) was associated with a significant increase in salary compared to being an assistant professor, t(390) = 7.64, p < .001 (two-tailed), and that once being faculty, being a full professor instead of an associated professor was associated with a further increase, t(390) = 9.08, p < .001 (two-tailed).
[ { "code": null, "e": 387, "s": 171, "text": "It’s a situation many of us face: You just ran an ANOVA, and your results are significant... but what next? We basically know that something is going on, but what exactly? Which treatments are making the difference?" }, { "code": null, "e": 568, "s": 387, "text": "This is where planned contrasts come in. They sound more complicated than they are, and they are a flexible statistical tool that makes this ANOVA post-hoc test extremely powerful." }, { "code": null, "e": 773, "s": 568, "text": "Just a quick note before I get going: In this tutorial, I will just talk about orthogonal contrast ... you do not need to know what this means, just in case you heard the term, and we're looking for this." }, { "code": null, "e": 926, "s": 773, "text": "For this tutorial, we will be using the salaries dataset. It contains data on the salaries of different professors. Load it using the following command." }, { "code": null, "e": 938, "s": 926, "text": "df=Salaries" }, { "code": null, "e": 1155, "s": 938, "text": "We will need the “car” package for the next step, so install the package using the below command if you haven’t done so already. If you aren’t sure whether you’ve already installed the package, just run this command." }, { "code": null, "e": 1179, "s": 1155, "text": "install.packages(\"car\")" }, { "code": null, "e": 1439, "s": 1179, "text": "Now, the ANOVA we want to do is to see whether the professors' rank has any impact on their salary. We also want to take all other intuitively important variables into account ... technically making this an ANCOVA. We run the below commands to get the output." }, { "code": null, "e": 1553, "s": 1439, "text": "library(car)aov1 = aov(salary ~ sex + rank + yrs.since.phd + yrs.service + discipline, df)Anova(aov1 ,type=\"III\")" }, { "code": null, "e": 1587, "s": 1553, "text": "This yields the following result." }, { "code": null, "e": 1830, "s": 1587, "text": "So we can see that rank does influence the salary of the professors. But how exactly? Planned contrasts can help us find out more about this. However, planned contrasts require that you really understand your independent variable of interest." }, { "code": null, "e": 1979, "s": 1830, "text": "Let’s look at the independent variable of interest first. What does “rank” contain. For this, run the following command to see the levels of “rank.”" }, { "code": null, "e": 1995, "s": 1979, "text": "levels(df$rank)" }, { "code": null, "e": 2029, "s": 1995, "text": "This yields the following output." }, { "code": null, "e": 2842, "s": 2029, "text": "In the US ... and this is an American dataset ... there is a huge difference between being an assistant professor and being an associate professor. Associate professors are part of faculty and are most often tenured. Assistant professors aren’t part of faculty and most often not tenured. A question planned contrasts can help us answer is, “Is being an Associate Professor important for a professor’s salary, or is it important to be part of the faculty?” ... do you see what we are doing here? We are using implicit information in the data to group our levels in new ways and reveal more information about the effect's true underlying drivers. Basically, we are saying ... “We know that there are three levels, but how can we group these levels to reveal more information?” — we are contrasting groups of data." }, { "code": null, "e": 3136, "s": 2842, "text": "You would normally run two planned contrasts in a situation like this: First, you would want to see if being part of faculty makes a difference. Second, you would want to see if differences within faculty make a difference. Below is a graphical representation of what we are trying to achieve." }, { "code": null, "e": 3268, "s": 3136, "text": "We communicate this to R with the help of orthogonal contrasts, which use a specific notation. The notation consists of four rules:" }, { "code": null, "e": 3321, "s": 3268, "text": "We use zero (0) for groups excluded from a contrast." }, { "code": null, "e": 3373, "s": 3321, "text": "We use negative values (<0) for the baseline group." }, { "code": null, "e": 3426, "s": 3373, "text": "We use positive values (>0) for the treatment group." }, { "code": null, "e": 3500, "s": 3426, "text": "The sum of the treatments' values in every contrast needs to be zero (0)." }, { "code": null, "e": 3677, "s": 3500, "text": "This doesn't sound very easy but is very simple once you see how this plays out for the example. The contrasts in the schematic would be communicated to R in the following way:" }, { "code": null, "e": 4017, "s": 3677, "text": "Contrast 1: In the first contrast, we group AssocProf and Prof into the treatment condition. Therefore, they both are assigned a positive value. To keep things simple, we choose a low value (1). As AssistProf is now the baseline, needs to be negative, and contrast 1 in total needs to add up to zero (0), we are required to assign it a -2." }, { "code": null, "e": 4724, "s": 4017, "text": "Contrast 2: In the second contrast, we only want to see whether differences among tenured positions impact the salary. Therefore, we exclude AsstProf by assigning it a 0. We choose to make Prof the treatment condition and AssocProf the baseline condition ... we could also switch the two of them, but changes in direction are dangerous as we might forget about them when we later interpret the results. To keep things simple, we keep the direction as it is (treatment is the more senior condition). Also, to keep things simple, we again choose low values and assign the treatment condition Prof a 1. Therefore, the baseline condition AssocProf has to be a -1, as the contrast in total needs to add up to 0." }, { "code": null, "e": 4788, "s": 4724, "text": "This is exactly how we communicate the assigned contrasts to R." }, { "code": null, "e": 4831, "s": 4788, "text": "contrast1 = c(-2,1,1)contrast2 = c(0,-1,1)" }, { "code": null, "e": 4917, "s": 4831, "text": "And then, we tell R to assign these contrasts to the variable rank in the dataset df." }, { "code": null, "e": 4966, "s": 4917, "text": "contrasts(df$rank) = cbind(contrast1, contrast2)" }, { "code": null, "e": 5090, "s": 4966, "text": "To check if the contrasts were assigned correctly, we can repeat the contrast() command to see how they are now saved in R." }, { "code": null, "e": 5109, "s": 5090, "text": "contrasts(df$rank)" }, { "code": null, "e": 5203, "s": 5109, "text": "As we can see, they have been implemented correctly. So now we can proceed with our analysis." }, { "code": null, "e": 5422, "s": 5203, "text": "We analyze our contrasts by rerunning the same ANOVA command that we ran before. However, because now R has more information on the structure of the variable rank in the form of contrasts, the output will be different." }, { "code": null, "e": 5501, "s": 5422, "text": "aov1 = aov(salary ~ sex + rank + yrs.since.phd + yrs.service + discipline, df)" }, { "code": null, "e": 5689, "s": 5501, "text": "And this time, we do not want to access the information in the form of an ANOVA output but in the form of regression output. Therefore, we ask for the output using the summary.lm command." }, { "code": null, "e": 5706, "s": 5689, "text": "summary.lm(aov1)" }, { "code": null, "e": 5961, "s": 5706, "text": "As one can see, R now produces output, in which the levels of the variable rank are replaced with the two contrasts. Both contrasts are significant, meaning that becoming tenured affects professors’ salaries and so does moving up among tenured positions." }, { "code": null, "e": 6012, "s": 5961, "text": "We would report this finding in the following way:" } ]
C++ Ostream Library - put
It is used to inserts character c into the stream.this function accesses the output sequence by first constructing a sentry object. Then (if good), it inserts c into its associated stream buffer object as if calling its member function sputc, and finally destroys the sentry object before returning. Following is the declaration for std::ostream::put. ostream& put (char c); c − Character to write. It returns the ostream object (*this). Basic guarantee − if an exception is thrown, the object is in a valid state. Modifies the stream object. Concurrent access to the same stream object may cause data races, except for the standard stream objects (cout, cerr, clog) when these are synchronized with stdio. In below example explains about std::ostream::put. #include <iostream> #include <fstream> int main () { std::ofstream outfile ("test.txt"); char ch; std::cout << "Type some text (type a dot to finish):\n"; do { ch = std::cin.get(); outfile.put(ch); } while (ch!='.'); return 0; } Let us compile and run the above program, this will produce the following result − Type some text (type a dot to finish): tutorialspoint. Print Add Notes Bookmark this page
[ { "code": null, "e": 2903, "s": 2603, "text": "It is used to inserts character c into the stream.this function accesses the output sequence by first constructing a sentry object. Then (if good), it inserts c into its associated stream buffer object as if calling its member function sputc, and finally destroys the sentry object before returning." }, { "code": null, "e": 2955, "s": 2903, "text": "Following is the declaration for std::ostream::put." }, { "code": null, "e": 2978, "s": 2955, "text": "ostream& put (char c);" }, { "code": null, "e": 3002, "s": 2978, "text": "c − Character to write." }, { "code": null, "e": 3041, "s": 3002, "text": "It returns the ostream object (*this)." }, { "code": null, "e": 3118, "s": 3041, "text": "Basic guarantee − if an exception is thrown, the object is in a valid state." }, { "code": null, "e": 3310, "s": 3118, "text": "Modifies the stream object. Concurrent access to the same stream object may cause data races, except for the standard stream objects (cout, cerr, clog) when these are synchronized with stdio." }, { "code": null, "e": 3361, "s": 3310, "text": "In below example explains about std::ostream::put." }, { "code": null, "e": 3623, "s": 3361, "text": "#include <iostream>\n#include <fstream>\n\nint main () {\n std::ofstream outfile (\"test.txt\");\n char ch;\n\n std::cout << \"Type some text (type a dot to finish):\\n\";\n do {\n ch = std::cin.get();\n outfile.put(ch);\n } while (ch!='.');\n\n return 0;\n}" }, { "code": null, "e": 3706, "s": 3623, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3762, "s": 3706, "text": "Type some text (type a dot to finish):\ntutorialspoint.\n" }, { "code": null, "e": 3769, "s": 3762, "text": " Print" }, { "code": null, "e": 3780, "s": 3769, "text": " Add Notes" } ]
Multidimensional array in Java
Following is a simple example of a multi-dimensional array. Live Demo public class Tester { public static void main(String[] args) { int[][] multidimensionalArray = { {1,2},{2,3}, {3,4} }; for(int i = 0 ; i < 3 ; i++){ //row for(int j = 0 ; j < 2; j++){ System.out.print(multidimensionalArray[i][j] + " "); } System.out.println(); } } } 1 2 2 3 3 4
[ { "code": null, "e": 1123, "s": 1062, "text": "Following is a simple example of a multi-dimensional array. " }, { "code": null, "e": 1133, "s": 1123, "text": "Live Demo" }, { "code": null, "e": 1478, "s": 1133, "text": "public class Tester {\n public static void main(String[] args) {\n int[][] multidimensionalArray = { {1,2},{2,3}, {3,4} };\n \n for(int i = 0 ; i < 3 ; i++){\n //row\n for(int j = 0 ; j < 2; j++){\n System.out.print(multidimensionalArray[i][j] + \" \");\n }\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 1490, "s": 1478, "text": "1 2\n2 3\n3 4" } ]
How can we run Matplotlib in Tkinter?
Python Matplotlib library is helpful in many applications for visualizing the given data and information in terms of graphs and plots. It is possible to run matplotlib in a Tkinter application. Generally, importing any Python library explicitly in an application gives access to all its functions and modules in the library. To create a GUI application that uses matplotlib and its functions, we have to import the library using the command from matplotlib.pyplot as plt. However, we also use Tkagg in the backend that uses the Tkinter user interface interactively. In this example, we have imported Tkagg and matplotlib to visualize the given data points by plotting them inside a canvas widget. # Import required libraries from tkinter import * from tkinter import ttk import matplotlib from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg # Create an instance of tkinter frame win= Tk() # Set the window size win.geometry("700x350") # Use TkAgg matplotlib.use("TkAgg") # Create a figure of specific size figure = Figure(figsize=(3, 3), dpi=100) # Define the points for plotting the figure plot = figure.add_subplot(1, 1, 1) plot.plot(0.5, 0.3, color="blue", marker="o", linestyle="") # Define Data points for x and y axis x = [0.2,0.5,0.8,1.0 ] y = [ 1.0, 1.2, 1.3,1.4] plot.plot(x, y, color="red", marker="x", linestyle="") # Add a canvas widget to associate the figure with canvas canvas = FigureCanvasTkAgg(figure, win) canvas.get_tk_widget().grid(row=0, column=0) win.mainloop() When we run the above code, a plot will appear in the window with some data points on the X and Y axis.
[ { "code": null, "e": 1387, "s": 1062, "text": "Python Matplotlib library is helpful in many applications for visualizing the given data and information in terms of graphs and plots. It is possible to run matplotlib in a Tkinter application. Generally, importing any Python library explicitly in an application gives access to all its functions and modules in the library." }, { "code": null, "e": 1628, "s": 1387, "text": "To create a GUI application that uses matplotlib and its functions, we have to import the library using the command from matplotlib.pyplot as plt. However, we also use Tkagg in the backend that uses the Tkinter user interface interactively." }, { "code": null, "e": 1759, "s": 1628, "text": "In this example, we have imported Tkagg and matplotlib to visualize the given data points by plotting them inside a canvas widget." }, { "code": null, "e": 2604, "s": 1759, "text": "# Import required libraries\nfrom tkinter import *\nfrom tkinter import ttk\nimport matplotlib\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n\n# Create an instance of tkinter frame\nwin= Tk()\n\n# Set the window size\nwin.geometry(\"700x350\")\n\n# Use TkAgg\nmatplotlib.use(\"TkAgg\")\n\n# Create a figure of specific size\nfigure = Figure(figsize=(3, 3), dpi=100)\n\n# Define the points for plotting the figure\nplot = figure.add_subplot(1, 1, 1)\nplot.plot(0.5, 0.3, color=\"blue\", marker=\"o\", linestyle=\"\")\n\n# Define Data points for x and y axis\nx = [0.2,0.5,0.8,1.0 ]\ny = [ 1.0, 1.2, 1.3,1.4]\nplot.plot(x, y, color=\"red\", marker=\"x\", linestyle=\"\")\n\n# Add a canvas widget to associate the figure with canvas\ncanvas = FigureCanvasTkAgg(figure, win)\ncanvas.get_tk_widget().grid(row=0, column=0)\n\nwin.mainloop()" }, { "code": null, "e": 2708, "s": 2604, "text": "When we run the above code, a plot will appear in the window with some data points on the X and Y axis." } ]
Add multiple number input fields with JOptionPane and display the sum in Console with Java
At first, set multiple number input fields − JTextField text1 = new JTextField(10); JTextField text2 = new JTextField(10); JTextField text3 = new JTextField(10); JTextField text4 = new JTextField(10); JTextField text5 = new JTextField(10); JTextField text6 = new JTextField(10); JTextField text7 = new JTextField(10); JTextField text8 = new JTextField(10); panel.add(text1); panel.add(text2); panel.add(text3); panel.add(text4); panel.add(text5); panel.add(text6); panel.add(text7); panel.add(text8); Now, let us add the values of the multiple number input fields created above − System.out.println(Integer.parseInt(text1.getText()) + Integer.parseInt(text2.getText()) + Integer.parseInt(text3.getText())+ Integer.parseInt(text4.getText())+ Integer.parseInt(text5.getText())+ Integer.parseInt(text6.getText())+ Integer.parseInt(text7.getText())+ Integer.parseInt(text8.getText())); Above, we have displayed the sum in the Console. The following is an example to sum multiple number input fields with JOptionPane − package my; import java.awt.GridLayout; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class SwingDemo { public static void main(String[] args) { JPanel panel = new JPanel(new GridLayout(5, 3)); JTextField text1 = new JTextField(10); JTextField text2 = new JTextField(10); JTextField text3 = new JTextField(10); JTextField text4 = new JTextField(10); JTextField text5 = new JTextField(10); JTextField text6 = new JTextField(10); JTextField text7 = new JTextField(10); JTextField text8 = new JTextField(10); panel.add(text1); panel.add(text2); panel.add(text3); panel.add(text4); panel.add(text5); panel.add(text6); panel.add(text7); panel.add(text8); JOptionPane.showMessageDialog(null, panel); System.out.println(Integer.parseInt(text1.getText()) + Integer.parseInt(text2.getText()) + Integer.parseInt(text3.getText())+ Integer.parseInt(text4.getText())+ Integer.parseInt(text5.getText())+ Integer.parseInt(text6.getText())+ Integer.parseInt(text7.getText())+ Integer.parseInt(text8.getText())); } } Now, enter the numbers in the TextField and click OK − On pressing OK above, the result would be visible in the Console that is sum of all the numbers added above −
[ { "code": null, "e": 1107, "s": 1062, "text": "At first, set multiple number input fields −" }, { "code": null, "e": 1563, "s": 1107, "text": "JTextField text1 = new JTextField(10);\nJTextField text2 = new JTextField(10);\nJTextField text3 = new JTextField(10);\nJTextField text4 = new JTextField(10);\nJTextField text5 = new JTextField(10);\nJTextField text6 = new JTextField(10);\nJTextField text7 = new JTextField(10);\nJTextField text8 = new JTextField(10);\npanel.add(text1);\npanel.add(text2);\npanel.add(text3);\npanel.add(text4);\npanel.add(text5);\npanel.add(text6);\npanel.add(text7);\npanel.add(text8);" }, { "code": null, "e": 1642, "s": 1563, "text": "Now, let us add the values of the multiple number input fields created above −" }, { "code": null, "e": 1953, "s": 1642, "text": "System.out.println(Integer.parseInt(text1.getText()) + Integer.parseInt(text2.getText()) +\n Integer.parseInt(text3.getText())+ Integer.parseInt(text4.getText())+\n Integer.parseInt(text5.getText())+ Integer.parseInt(text6.getText())+\n Integer.parseInt(text7.getText())+ Integer.parseInt(text8.getText()));" }, { "code": null, "e": 2002, "s": 1953, "text": "Above, we have displayed the sum in the Console." }, { "code": null, "e": 2085, "s": 2002, "text": "The following is an example to sum multiple number input fields with JOptionPane −" }, { "code": null, "e": 3283, "s": 2085, "text": "package my;\nimport java.awt.GridLayout;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\npublic class SwingDemo {\n public static void main(String[] args) {\n JPanel panel = new JPanel(new GridLayout(5, 3));\n JTextField text1 = new JTextField(10);\n JTextField text2 = new JTextField(10);\n JTextField text3 = new JTextField(10);\n JTextField text4 = new JTextField(10);\n JTextField text5 = new JTextField(10);\n JTextField text6 = new JTextField(10);\n JTextField text7 = new JTextField(10);\n JTextField text8 = new JTextField(10);\n panel.add(text1);\n panel.add(text2);\n panel.add(text3);\n panel.add(text4);\n panel.add(text5);\n panel.add(text6);\n panel.add(text7);\n panel.add(text8);\n JOptionPane.showMessageDialog(null, panel);\n System.out.println(Integer.parseInt(text1.getText()) + Integer.parseInt(text2.getText()) +\n Integer.parseInt(text3.getText())+ Integer.parseInt(text4.getText())+\n Integer.parseInt(text5.getText())+ Integer.parseInt(text6.getText())+\n Integer.parseInt(text7.getText())+ Integer.parseInt(text8.getText()));\n }\n}" }, { "code": null, "e": 3338, "s": 3283, "text": "Now, enter the numbers in the TextField and click OK −" }, { "code": null, "e": 3448, "s": 3338, "text": "On pressing OK above, the result would be visible in the Console that is sum of all the numbers added above −" } ]
8085 program to divide two 16 bit numbers - GeeksforGeeks
26 Jul, 2021 Problem – Write an assembly language program in 8085 microprocessor to divide two 16 bit numbers. Assumption – Starting address of program: 2000 Input memory location: 2050, 2051, 2052, 2053 Output memory location: 2054, 2055, 2056, 2057. Example – INPUT: (2050H) = 04H (2051H) = 00H (2052H) = 02H (2053H) = 00H OUTPUT: (2054H) = 02H (2055H) = 00H (2056H) = FEH (2057H) = FFH RESULT: Hence we have divided two 16 bit numbers. Algorithm – Initialise register BC as 0000H for Quotient. Load the divisor in HL pair and save it in DE register pair. Load the dividend in HL pair. Subtract the content of accumulator with E register. Move the content A to C and H to A. Subtract with borrow the content of A with D. Move the value of accumulator to H. If CY=1, goto step 10, otherwise next step. Increment register B and jump to step 4. ADD both contents of DE and HL. Store the remainder in memory. Move the content of C to L & B to H. Store the quotient in memory. Initialise register BC as 0000H for Quotient. Load the divisor in HL pair and save it in DE register pair. Load the dividend in HL pair. Subtract the content of accumulator with E register. Move the content A to C and H to A. Subtract with borrow the content of A with D. Move the value of accumulator to H. If CY=1, goto step 10, otherwise next step. Increment register B and jump to step 4. ADD both contents of DE and HL. Store the remainder in memory. Move the content of C to L & B to H. Store the quotient in memory. Program – Explanation – LXI B, 0000H: initialise BC register as 0000H. LHLD 2052H: load the HL pair with address 2052. XCHG: exchange the content of HL pair with DE pair register. LHLD 2050: load the HL pair with address 2050. MOV A, L: move the content of register L into register A. SUB E: subtract the contents of register E with contents of accumulator. MOV L, A: move the content of register A into register L. MOV A, H: move the content of register H into register A. SBB D: subtract the contents of register D with contents of accumulator with carry. MOV H, A: move the content of register A into register H. JC 2017: jump to address 2017 if there is carry. INX B: increment BC register by one. JMP 200B: jump to address 200B. DAD D: add the contents of DE and HL pair. SHLD 2056: stores the content of HL pair into memory address 2056 and 2057. MOV L, C: move the content of register C into register L. MOV H, B: move the content of register B into register H. SHLD 2054: stores the content of HL pair into memory address 2054 and 2055. HLT: terminates the execution of program. LXI B, 0000H: initialise BC register as 0000H. LHLD 2052H: load the HL pair with address 2052. XCHG: exchange the content of HL pair with DE pair register. LHLD 2050: load the HL pair with address 2050. MOV A, L: move the content of register L into register A. SUB E: subtract the contents of register E with contents of accumulator. MOV L, A: move the content of register A into register L. MOV A, H: move the content of register H into register A. SBB D: subtract the contents of register D with contents of accumulator with carry. MOV H, A: move the content of register A into register H. JC 2017: jump to address 2017 if there is carry. INX B: increment BC register by one. JMP 200B: jump to address 200B. DAD D: add the contents of DE and HL pair. SHLD 2056: stores the content of HL pair into memory address 2056 and 2057. MOV L, C: move the content of register C into register L. MOV H, B: move the content of register B into register H. SHLD 2054: stores the content of HL pair into memory address 2054 and 2055. HLT: terminates the execution of program. ShaktirajDaudra unmesh_mandal gabaa406 microprocessor system-programming Computer Organization & Architecture microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Architecture of 8085 microprocessor Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) Direct Access Media (DMA) Controller in Computer Architecture Pin diagram of 8086 microprocessor Difference between SRAM and DRAM Computer Organization | Different Instruction Cycles Shift Micro-Operations in Computer Architecture I2C Communication Protocol Difference between RISC and CISC processor | Set 2 General purpose registers in 8086 microprocessor
[ { "code": null, "e": 24780, "s": 24752, "text": "\n26 Jul, 2021" }, { "code": null, "e": 24879, "s": 24780, "text": "Problem – Write an assembly language program in 8085 microprocessor to divide two 16 bit numbers. " }, { "code": null, "e": 24894, "s": 24879, "text": "Assumption – " }, { "code": null, "e": 24930, "s": 24894, "text": "Starting address of program: 2000 " }, { "code": null, "e": 24978, "s": 24930, "text": "Input memory location: 2050, 2051, 2052, 2053 " }, { "code": null, "e": 25028, "s": 24978, "text": "Output memory location: 2054, 2055, 2056, 2057. " }, { "code": null, "e": 25040, "s": 25028, "text": "Example – " }, { "code": null, "e": 25230, "s": 25040, "text": "INPUT:\n (2050H) = 04H\n (2051H) = 00H \n (2052H) = 02H \n (2053H) = 00H\nOUTPUT:\n (2054H) = 02H\n (2055H) = 00H\n (2056H) = FEH\n (2057H) = FFH " }, { "code": null, "e": 25281, "s": 25230, "text": "RESULT: Hence we have divided two 16 bit numbers. " }, { "code": null, "e": 25295, "s": 25281, "text": "Algorithm – " }, { "code": null, "e": 25832, "s": 25295, "text": "Initialise register BC as 0000H for Quotient. Load the divisor in HL pair and save it in DE register pair. Load the dividend in HL pair. Subtract the content of accumulator with E register. Move the content A to C and H to A. Subtract with borrow the content of A with D. Move the value of accumulator to H. If CY=1, goto step 10, otherwise next step. Increment register B and jump to step 4. ADD both contents of DE and HL. Store the remainder in memory. Move the content of C to L & B to H. Store the quotient in memory. " }, { "code": null, "e": 25880, "s": 25832, "text": "Initialise register BC as 0000H for Quotient. " }, { "code": null, "e": 25943, "s": 25880, "text": "Load the divisor in HL pair and save it in DE register pair. " }, { "code": null, "e": 25975, "s": 25943, "text": "Load the dividend in HL pair. " }, { "code": null, "e": 26030, "s": 25975, "text": "Subtract the content of accumulator with E register. " }, { "code": null, "e": 26068, "s": 26030, "text": "Move the content A to C and H to A. " }, { "code": null, "e": 26116, "s": 26068, "text": "Subtract with borrow the content of A with D. " }, { "code": null, "e": 26154, "s": 26116, "text": "Move the value of accumulator to H. " }, { "code": null, "e": 26200, "s": 26154, "text": "If CY=1, goto step 10, otherwise next step. " }, { "code": null, "e": 26243, "s": 26200, "text": "Increment register B and jump to step 4. " }, { "code": null, "e": 26277, "s": 26243, "text": "ADD both contents of DE and HL. " }, { "code": null, "e": 26310, "s": 26277, "text": "Store the remainder in memory. " }, { "code": null, "e": 26349, "s": 26310, "text": "Move the content of C to L & B to H. " }, { "code": null, "e": 26381, "s": 26349, "text": "Store the quotient in memory. " }, { "code": null, "e": 26393, "s": 26381, "text": "Program – " }, { "code": null, "e": 26409, "s": 26393, "text": "Explanation – " }, { "code": null, "e": 27492, "s": 26409, "text": "LXI B, 0000H: initialise BC register as 0000H. LHLD 2052H: load the HL pair with address 2052. XCHG: exchange the content of HL pair with DE pair register. LHLD 2050: load the HL pair with address 2050. MOV A, L: move the content of register L into register A. SUB E: subtract the contents of register E with contents of accumulator. MOV L, A: move the content of register A into register L. MOV A, H: move the content of register H into register A. SBB D: subtract the contents of register D with contents of accumulator with carry. MOV H, A: move the content of register A into register H. JC 2017: jump to address 2017 if there is carry. INX B: increment BC register by one. JMP 200B: jump to address 200B. DAD D: add the contents of DE and HL pair. SHLD 2056: stores the content of HL pair into memory address 2056 and 2057. MOV L, C: move the content of register C into register L. MOV H, B: move the content of register B into register H. SHLD 2054: stores the content of HL pair into memory address 2054 and 2055. HLT: terminates the execution of program. " }, { "code": null, "e": 27541, "s": 27492, "text": "LXI B, 0000H: initialise BC register as 0000H. " }, { "code": null, "e": 27591, "s": 27541, "text": "LHLD 2052H: load the HL pair with address 2052. " }, { "code": null, "e": 27654, "s": 27591, "text": "XCHG: exchange the content of HL pair with DE pair register. " }, { "code": null, "e": 27703, "s": 27654, "text": "LHLD 2050: load the HL pair with address 2050. " }, { "code": null, "e": 27763, "s": 27703, "text": "MOV A, L: move the content of register L into register A. " }, { "code": null, "e": 27838, "s": 27763, "text": "SUB E: subtract the contents of register E with contents of accumulator. " }, { "code": null, "e": 27898, "s": 27838, "text": "MOV L, A: move the content of register A into register L. " }, { "code": null, "e": 27958, "s": 27898, "text": "MOV A, H: move the content of register H into register A. " }, { "code": null, "e": 28044, "s": 27958, "text": "SBB D: subtract the contents of register D with contents of accumulator with carry. " }, { "code": null, "e": 28104, "s": 28044, "text": "MOV H, A: move the content of register A into register H. " }, { "code": null, "e": 28155, "s": 28104, "text": "JC 2017: jump to address 2017 if there is carry. " }, { "code": null, "e": 28194, "s": 28155, "text": "INX B: increment BC register by one. " }, { "code": null, "e": 28228, "s": 28194, "text": "JMP 200B: jump to address 200B. " }, { "code": null, "e": 28273, "s": 28228, "text": "DAD D: add the contents of DE and HL pair. " }, { "code": null, "e": 28351, "s": 28273, "text": "SHLD 2056: stores the content of HL pair into memory address 2056 and 2057. " }, { "code": null, "e": 28411, "s": 28351, "text": "MOV L, C: move the content of register C into register L. " }, { "code": null, "e": 28471, "s": 28411, "text": "MOV H, B: move the content of register B into register H. " }, { "code": null, "e": 28549, "s": 28471, "text": "SHLD 2054: stores the content of HL pair into memory address 2054 and 2055. " }, { "code": null, "e": 28593, "s": 28549, "text": "HLT: terminates the execution of program. " }, { "code": null, "e": 28611, "s": 28595, "text": "ShaktirajDaudra" }, { "code": null, "e": 28625, "s": 28611, "text": "unmesh_mandal" }, { "code": null, "e": 28634, "s": 28625, "text": "gabaa406" }, { "code": null, "e": 28649, "s": 28634, "text": "microprocessor" }, { "code": null, "e": 28668, "s": 28649, "text": "system-programming" }, { "code": null, "e": 28705, "s": 28668, "text": "Computer Organization & Architecture" }, { "code": null, "e": 28720, "s": 28705, "text": "microprocessor" }, { "code": null, "e": 28818, "s": 28720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28854, "s": 28818, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 28945, "s": 28854, "text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)" }, { "code": null, "e": 29007, "s": 28945, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 29042, "s": 29007, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 29075, "s": 29042, "text": "Difference between SRAM and DRAM" }, { "code": null, "e": 29128, "s": 29075, "text": "Computer Organization | Different Instruction Cycles" }, { "code": null, "e": 29176, "s": 29128, "text": "Shift Micro-Operations in Computer Architecture" }, { "code": null, "e": 29203, "s": 29176, "text": "I2C Communication Protocol" }, { "code": null, "e": 29254, "s": 29203, "text": "Difference between RISC and CISC processor | Set 2" } ]
Manage Your Entire R Code Base With TODOr | by Bryan Jenks | Towards Data Science
Never forget to fix your FIXME's or do your TODO's ever again! TODOr Is an incredibly helpful R Package and RStudio Add in that makes the management of all of your developer comments incredibly easy. “I need to remember to fix this bug...” mean[1] # FIXME: This doesn't work#> Error in mean[1] : object of type 'closure' is not subsettable Then you move on and continue your work intending to come back to this issue later. A codebase could be littered with these types of comments. These Reminders that R Package developers create with every intention of correcting, can often be forgotten or misplaced within a sprawling codebase. TODOr eases the burden of technical debt when it comes to resolving all of these reminders for the health of your codebase. TODOr will find all of these reminders in an entire file, project, or package. Even multiple types of files are supported and you will be given an itemized list of what type of reminder, the details of the reminder, the file its located in, the line it’s on, and clicking an item in this list will take you exactly to the line of code you needed to fix! What do you need to do to witness this power? Just this: todor::todor() By default, TODOr will return all of the comments with the correct markers (i.e. “TODO”, “FIXME”, etc.) in an entire R Project (when you have a .Rproj file in the directory) not just the current file. “ALL the comments? But i don't care about ALL the comments, only my TODO’s...” What is returned is not literally every comment, TODOr looks for comments beginning with marker words. The defaults are: FIXME TODO CHANGED IDEA HACK NOTE REVIEW BUG QUESTION COMBAK TEMP TODOr can look at more than just a project, you can also have it search a single file: todor::todor_file("my_file.Rmd") Or even an entire R package: todor::todor_package() By default, TODOr will look for all of the aforementioned comment markers. You will get a list of all of them returned to you but what if you have a very large codebase? Like ggplot2 big? You may want to only look at a few specific types of comments we can do this by passing a vector to the function: todor::todor(c("TODO", "FIXME")) This will only show the comments that are TODO’s and FIXME’s. So in this way we can filter our searches down to which types of comments we want returned and from specific files. What if you don't like the default markers? What if you wanted this functionality for your team but you wanted to tag comments with your team members' names? We can actually define a custom list of TODOr search patterns so that we can define new keywords for the function to find throughout our codebase. To do this we need to use the options function: options(todor_patterns = c("FIXME", "TODO", "BRYAN")) Now whenever I place my name next to a comment, it will be picked up by TODOr as a valid marker comment to be returned*. *It is important to note that these search patterns are case sensitive: # BRYAN please fix this bug <---- would be picked up# bryan please fix this bug <---- This would be ignored There are several other file types that TODOr can find markers in and return in a list format. To make it so these other file types will be searched we can configure some of these options with the options() function. todor_rmd — When set to TRUE it searches also through Rmd(Rmarkdown) files (default TRUE). The Rmarkdown marker comments returned will be both code chunk and markdown space comments that use HTML syntax: todor_rnw — When set to TRUE it searches also through Rnw(Sweave) files (default FALSE). Sweave is the combination of LaTeX with executable R code chunks, the comments that will be returned are both the code chunk and LaTeX comments: todor_rhtml — When set to TRUE it searches also through RHTML files (default FALSE). Just like RMarkdown documents both the HTML style and R style comments will be picked up as long as the correct marker is used. todor_exlude_packrat —When set to FALSE, all files in the “packrat” directory are excluded (default TRUE). If you have ever used packrat to take a snapshot of your package or project dependencies for reproducibility, then you probably don't want TODOr to pick up all the developer comments for all of those dependency packages. I ran this once and you definitely want to change this to FALSE as the default is TRUE and you may get a list like this. What if you actually wanted to ignore R files? This option only ignore R script files not RMarkdown. todor_exclude_r — When TRUE, it ignores R files (default FALSE) I hope you found this article helpful and decide to use TODOr in your workflow. I have used this package in production with my work in the public sector government and found it to be incredibly helpful to pepper in comments to myself and then easily follow up on them later. If you prefer a video format of this package review and want to grab all the files i use in my R Package reviews you can get them here: For all of my R Package reviews I also keep all code and sample documents available in a single repo if you would like any of the code/documents I used in the making of this review: github.com If you enjoy R Package reviews you can check out my previous review on the Patchwork package: medium.com [1] D. Krzemiński, TODOr — RStudio add-in for finding TODO, FIXME, CHANGED etc. comments in your code. (2017), GitHub.com
[ { "code": null, "e": 110, "s": 47, "text": "Never forget to fix your FIXME's or do your TODO's ever again!" }, { "code": null, "e": 247, "s": 110, "text": "TODOr Is an incredibly helpful R Package and RStudio Add in that makes the management of all of your developer comments incredibly easy." }, { "code": null, "e": 287, "s": 247, "text": "“I need to remember to fix this bug...”" }, { "code": null, "e": 387, "s": 287, "text": "mean[1] # FIXME: This doesn't work#> Error in mean[1] : object of type 'closure' is not subsettable" }, { "code": null, "e": 680, "s": 387, "text": "Then you move on and continue your work intending to come back to this issue later. A codebase could be littered with these types of comments. These Reminders that R Package developers create with every intention of correcting, can often be forgotten or misplaced within a sprawling codebase." }, { "code": null, "e": 804, "s": 680, "text": "TODOr eases the burden of technical debt when it comes to resolving all of these reminders for the health of your codebase." }, { "code": null, "e": 1158, "s": 804, "text": "TODOr will find all of these reminders in an entire file, project, or package. Even multiple types of files are supported and you will be given an itemized list of what type of reminder, the details of the reminder, the file its located in, the line it’s on, and clicking an item in this list will take you exactly to the line of code you needed to fix!" }, { "code": null, "e": 1215, "s": 1158, "text": "What do you need to do to witness this power? Just this:" }, { "code": null, "e": 1230, "s": 1215, "text": "todor::todor()" }, { "code": null, "e": 1431, "s": 1230, "text": "By default, TODOr will return all of the comments with the correct markers (i.e. “TODO”, “FIXME”, etc.) in an entire R Project (when you have a .Rproj file in the directory) not just the current file." }, { "code": null, "e": 1510, "s": 1431, "text": "“ALL the comments? But i don't care about ALL the comments, only my TODO’s...”" }, { "code": null, "e": 1631, "s": 1510, "text": "What is returned is not literally every comment, TODOr looks for comments beginning with marker words. The defaults are:" }, { "code": null, "e": 1637, "s": 1631, "text": "FIXME" }, { "code": null, "e": 1642, "s": 1637, "text": "TODO" }, { "code": null, "e": 1650, "s": 1642, "text": "CHANGED" }, { "code": null, "e": 1655, "s": 1650, "text": "IDEA" }, { "code": null, "e": 1660, "s": 1655, "text": "HACK" }, { "code": null, "e": 1665, "s": 1660, "text": "NOTE" }, { "code": null, "e": 1672, "s": 1665, "text": "REVIEW" }, { "code": null, "e": 1676, "s": 1672, "text": "BUG" }, { "code": null, "e": 1685, "s": 1676, "text": "QUESTION" }, { "code": null, "e": 1692, "s": 1685, "text": "COMBAK" }, { "code": null, "e": 1697, "s": 1692, "text": "TEMP" }, { "code": null, "e": 1784, "s": 1697, "text": "TODOr can look at more than just a project, you can also have it search a single file:" }, { "code": null, "e": 1817, "s": 1784, "text": "todor::todor_file(\"my_file.Rmd\")" }, { "code": null, "e": 1846, "s": 1817, "text": "Or even an entire R package:" }, { "code": null, "e": 1869, "s": 1846, "text": "todor::todor_package()" }, { "code": null, "e": 2057, "s": 1869, "text": "By default, TODOr will look for all of the aforementioned comment markers. You will get a list of all of them returned to you but what if you have a very large codebase? Like ggplot2 big?" }, { "code": null, "e": 2171, "s": 2057, "text": "You may want to only look at a few specific types of comments we can do this by passing a vector to the function:" }, { "code": null, "e": 2204, "s": 2171, "text": "todor::todor(c(\"TODO\", \"FIXME\"))" }, { "code": null, "e": 2266, "s": 2204, "text": "This will only show the comments that are TODO’s and FIXME’s." }, { "code": null, "e": 2382, "s": 2266, "text": "So in this way we can filter our searches down to which types of comments we want returned and from specific files." }, { "code": null, "e": 2426, "s": 2382, "text": "What if you don't like the default markers?" }, { "code": null, "e": 2540, "s": 2426, "text": "What if you wanted this functionality for your team but you wanted to tag comments with your team members' names?" }, { "code": null, "e": 2735, "s": 2540, "text": "We can actually define a custom list of TODOr search patterns so that we can define new keywords for the function to find throughout our codebase. To do this we need to use the options function:" }, { "code": null, "e": 2789, "s": 2735, "text": "options(todor_patterns = c(\"FIXME\", \"TODO\", \"BRYAN\"))" }, { "code": null, "e": 2910, "s": 2789, "text": "Now whenever I place my name next to a comment, it will be picked up by TODOr as a valid marker comment to be returned*." }, { "code": null, "e": 2982, "s": 2910, "text": "*It is important to note that these search patterns are case sensitive:" }, { "code": null, "e": 3090, "s": 2982, "text": "# BRYAN please fix this bug <---- would be picked up# bryan please fix this bug <---- This would be ignored" }, { "code": null, "e": 3307, "s": 3090, "text": "There are several other file types that TODOr can find markers in and return in a list format. To make it so these other file types will be searched we can configure some of these options with the options() function." }, { "code": null, "e": 3398, "s": 3307, "text": "todor_rmd — When set to TRUE it searches also through Rmd(Rmarkdown) files (default TRUE)." }, { "code": null, "e": 3511, "s": 3398, "text": "The Rmarkdown marker comments returned will be both code chunk and markdown space comments that use HTML syntax:" }, { "code": null, "e": 3600, "s": 3511, "text": "todor_rnw — When set to TRUE it searches also through Rnw(Sweave) files (default FALSE)." }, { "code": null, "e": 3745, "s": 3600, "text": "Sweave is the combination of LaTeX with executable R code chunks, the comments that will be returned are both the code chunk and LaTeX comments:" }, { "code": null, "e": 3830, "s": 3745, "text": "todor_rhtml — When set to TRUE it searches also through RHTML files (default FALSE)." }, { "code": null, "e": 3958, "s": 3830, "text": "Just like RMarkdown documents both the HTML style and R style comments will be picked up as long as the correct marker is used." }, { "code": null, "e": 4065, "s": 3958, "text": "todor_exlude_packrat —When set to FALSE, all files in the “packrat” directory are excluded (default TRUE)." }, { "code": null, "e": 4286, "s": 4065, "text": "If you have ever used packrat to take a snapshot of your package or project dependencies for reproducibility, then you probably don't want TODOr to pick up all the developer comments for all of those dependency packages." }, { "code": null, "e": 4407, "s": 4286, "text": "I ran this once and you definitely want to change this to FALSE as the default is TRUE and you may get a list like this." }, { "code": null, "e": 4508, "s": 4407, "text": "What if you actually wanted to ignore R files? This option only ignore R script files not RMarkdown." }, { "code": null, "e": 4572, "s": 4508, "text": "todor_exclude_r — When TRUE, it ignores R files (default FALSE)" }, { "code": null, "e": 4847, "s": 4572, "text": "I hope you found this article helpful and decide to use TODOr in your workflow. I have used this package in production with my work in the public sector government and found it to be incredibly helpful to pepper in comments to myself and then easily follow up on them later." }, { "code": null, "e": 4983, "s": 4847, "text": "If you prefer a video format of this package review and want to grab all the files i use in my R Package reviews you can get them here:" }, { "code": null, "e": 5165, "s": 4983, "text": "For all of my R Package reviews I also keep all code and sample documents available in a single repo if you would like any of the code/documents I used in the making of this review:" }, { "code": null, "e": 5176, "s": 5165, "text": "github.com" }, { "code": null, "e": 5270, "s": 5176, "text": "If you enjoy R Package reviews you can check out my previous review on the Patchwork package:" }, { "code": null, "e": 5281, "s": 5270, "text": "medium.com" } ]
Channel in Golang - GeeksforGeeks
20 Nov, 2019 In Go language, a channel is a medium through which a goroutine communicates with another goroutine and this communication is lock-free. Or in other words, a channel is a technique which allows to let one goroutine to send data to another goroutine. By default channel is bidirectional, means the goroutines can send or receive data through the same channel as shown in the below image: In Go language, a channel is created using chan keyword and it can only transfer data of the same type, different types of data are not allowed to transport from the same channel. Syntax: var Channel_name chan Type You can also create a channel using make() function using a shorthand declaration. Syntax: channel_name:= make(chan Type) Example: // Go program to illustrate// how to create a channelpackage main import "fmt" func main() { // Creating a channel // Using var keyword var mychannel chan int fmt.Println("Value of the channel: ", mychannel) fmt.Printf("Type of the channel: %T ", mychannel) // Creating a channel using make() function mychannel1 := make(chan int) fmt.Println("\nValue of the channel1: ", mychannel1) fmt.Printf("Type of the channel1: %T ", mychannel1)} Output: Value of the channel: Type of the channel: chan int Value of the channel1: 0x432080 Type of the channel1: chan int In Go language, channel work with two principal operations one is sending and another one is receiving, both the operations collectively known as communication. And the direction of <- operator indicates whether the data is received or send. In the channel, the send and receive operation block until another side is not ready by default. It allows goroutine to synchronize with each other without explicit locks or condition variables. Send operation: The send operation is used to send data from one goroutine to another goroutine with the help of a channel. Values like int, float64, and bool can safe and easy to send through a channel because they are copied so there is no risk of accidental concurrent access of the same value. Similarly, strings are also safe to transfer because they are immutable. But for sending pointers or reference like a slice, map, etc. through a channel are not safe because the value of pointers or reference may change by sending goroutine or by the receiving goroutine at the same time and the result is unpredicted. So, when you use pointers or references in the channel you must make sure that they can only access by the one goroutine at a time.Mychannel <- elementThe above statement indicates that the data(element) send to the channel(Mychannel) with the help of a <- operator.Receive operation: The receive operation is used to receive the data sent by the send operator.element := <-MychannelThe above statement indicates that the element receives data from the channel(Mychannel). If the result of the received statement is not going to use is also a valid statement. You can also write a receive statement as:<-Mychannel Send operation: The send operation is used to send data from one goroutine to another goroutine with the help of a channel. Values like int, float64, and bool can safe and easy to send through a channel because they are copied so there is no risk of accidental concurrent access of the same value. Similarly, strings are also safe to transfer because they are immutable. But for sending pointers or reference like a slice, map, etc. through a channel are not safe because the value of pointers or reference may change by sending goroutine or by the receiving goroutine at the same time and the result is unpredicted. So, when you use pointers or references in the channel you must make sure that they can only access by the one goroutine at a time.Mychannel <- elementThe above statement indicates that the data(element) send to the channel(Mychannel) with the help of a <- operator. Mychannel <- element The above statement indicates that the data(element) send to the channel(Mychannel) with the help of a <- operator. Receive operation: The receive operation is used to receive the data sent by the send operator.element := <-MychannelThe above statement indicates that the element receives data from the channel(Mychannel). If the result of the received statement is not going to use is also a valid statement. You can also write a receive statement as:<-Mychannel element := <-Mychannel The above statement indicates that the element receives data from the channel(Mychannel). If the result of the received statement is not going to use is also a valid statement. You can also write a receive statement as: <-Mychannel Example: // Go program to illustrate send// and receive operationpackage main import "fmt" func myfunc(ch chan int) { fmt.Println(234 + <-ch)}func main() { fmt.Println("start Main method") // Creating a channel ch := make(chan int) go myfunc(ch) ch <- 23 fmt.Println("End Main method")} Output: start Main method 257 End Main method You can also close a channel with the help of close() function. This is an in-built function and sets a flag which indicates that no more value will send to this channel. Syntax: close() You can also close the channel using for range loop. Here, the receiver goroutine can check the channel is open or close with the help of the given syntax: ele, ok:= <- Mychannel Here, if the value of ok is true which means the channel is open so, read operations can be performed. And if the value of is false which means the channel is closed so, read operations are not going to perform. Example: // Go program to illustrate how// to close a channel using for// range loop and close functionpackage main import "fmt" // Functionfunc myfun(mychnl chan string) { for v := 0; v < 4; v++ { mychnl <- "GeeksforGeeks" } close(mychnl)} // Main functionfunc main() { // Creating a channel c := make(chan string) // calling Goroutine go myfun(c) // When the value of ok is // set to true means the // channel is open and it // can send or receive data // When the value of ok is set to // false means the channel is closed for { res, ok := <-c if ok == false { fmt.Println("Channel Close ", ok) break } fmt.Println("Channel Open ", res, ok) }} Output: Channel Open GeeksforGeeks true Channel Open GeeksforGeeks true Channel Open GeeksforGeeks true Channel Open GeeksforGeeks true Channel Close false Blocking Send and Receive: In the channel when the data sent to a channel the control is blocked in that send statement until other goroutine reads from that channel. Similarly, when a channel receives data from the goroutine the read statement block until another goroutine statement. Zero Value Channel: The zero value of the channel is nil. For loop in Channel: A for loop can iterate over the sequential values sent on the channel until it closed.Syntax:for item := range Chnl { // statements.. } Example:// Go program to illustrate how to// use for loop in the channel package main import "fmt" // Main functionfunc main() { // Creating a channel // Using make() function mychnl := make(chan string) // Anonymous goroutine go func() { mychnl <- "GFG" mychnl <- "gfg" mychnl <- "Geeks" mychnl <- "GeeksforGeeks" close(mychnl) }() // Using for loop for res := range mychnl { fmt.Println(res) }}Output:GFG gfg Geeks GeeksforGeeks Syntax: for item := range Chnl { // statements.. } Example: // Go program to illustrate how to// use for loop in the channel package main import "fmt" // Main functionfunc main() { // Creating a channel // Using make() function mychnl := make(chan string) // Anonymous goroutine go func() { mychnl <- "GFG" mychnl <- "gfg" mychnl <- "Geeks" mychnl <- "GeeksforGeeks" close(mychnl) }() // Using for loop for res := range mychnl { fmt.Println(res) }} Output: GFG gfg Geeks GeeksforGeeks Length of the Channel: In channel, you can find the length of the channel using len() function. Here, the length indicates the number of value queued in the channel buffer.Example:// Go program to illustrate how to// find the length of the channel package main import "fmt"a// Main functionfunc main() { // Creating a channel // Using make() function mychnl := make(chan string, 4) mychnl <- "GFG" mychnl <- "gfg" mychnl <- "Geeks" mychnl <- "GeeksforGeeks" // Finding the length of the channel // Using len() function fmt.Println("Length of the channel is: ", len(mychnl))}Output:Length of the channel is: 4 Example: // Go program to illustrate how to// find the length of the channel package main import "fmt"a// Main functionfunc main() { // Creating a channel // Using make() function mychnl := make(chan string, 4) mychnl <- "GFG" mychnl <- "gfg" mychnl <- "Geeks" mychnl <- "GeeksforGeeks" // Finding the length of the channel // Using len() function fmt.Println("Length of the channel is: ", len(mychnl))} Output: Length of the channel is: 4 Capacity of the Channel: In channel, you can find the capacity of the channel using cap() function. Here, the capacity indicates the size of the buffer.Example:// Go program to illustrate how to// find the capacity of the channel package main import "fmt" // Main functionfunc main() { // Creating a channel // Using make() function mychnl := make(chan string, 5) mychnl <- "GFG" mychnl <- "gfg" mychnl <- "Geeks" mychnl <- "GeeksforGeeks" // Finding the capacity of the channel // Using cap() function fmt.Println("Capacity of the channel is: ", cap(mychnl))}Output:Capacity of the channel is: 5 Example: // Go program to illustrate how to// find the capacity of the channel package main import "fmt" // Main functionfunc main() { // Creating a channel // Using make() function mychnl := make(chan string, 5) mychnl <- "GFG" mychnl <- "gfg" mychnl <- "Geeks" mychnl <- "GeeksforGeeks" // Finding the capacity of the channel // Using cap() function fmt.Println("Capacity of the channel is: ", cap(mychnl))} Output: Capacity of the channel is: 5 Select and case statement in Channel: In go language, select statement is just like a switch statement without any input parameter. This select statement is used in the channel to perform a single operation out of multiple operations provided by the case block. Golang Golang-Concurrency Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to concatenate two strings in Golang time.Sleep() Function in Golang With Examples Time Formatting in Golang strings.Contains Function in Golang with Examples strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples Golang Maps How to convert a string in lower case in Golang? How to compare times in Golang? Inheritance in GoLang
[ { "code": null, "e": 24932, "s": 24904, "text": "\n20 Nov, 2019" }, { "code": null, "e": 25319, "s": 24932, "text": "In Go language, a channel is a medium through which a goroutine communicates with another goroutine and this communication is lock-free. Or in other words, a channel is a technique which allows to let one goroutine to send data to another goroutine. By default channel is bidirectional, means the goroutines can send or receive data through the same channel as shown in the below image:" }, { "code": null, "e": 25499, "s": 25319, "text": "In Go language, a channel is created using chan keyword and it can only transfer data of the same type, different types of data are not allowed to transport from the same channel." }, { "code": null, "e": 25507, "s": 25499, "text": "Syntax:" }, { "code": null, "e": 25534, "s": 25507, "text": "var Channel_name chan Type" }, { "code": null, "e": 25617, "s": 25534, "text": "You can also create a channel using make() function using a shorthand declaration." }, { "code": null, "e": 25625, "s": 25617, "text": "Syntax:" }, { "code": null, "e": 25656, "s": 25625, "text": "channel_name:= make(chan Type)" }, { "code": null, "e": 25665, "s": 25656, "text": "Example:" }, { "code": "// Go program to illustrate// how to create a channelpackage main import \"fmt\" func main() { // Creating a channel // Using var keyword var mychannel chan int fmt.Println(\"Value of the channel: \", mychannel) fmt.Printf(\"Type of the channel: %T \", mychannel) // Creating a channel using make() function mychannel1 := make(chan int) fmt.Println(\"\\nValue of the channel1: \", mychannel1) fmt.Printf(\"Type of the channel1: %T \", mychannel1)}", "e": 26135, "s": 25665, "text": null }, { "code": null, "e": 26143, "s": 26135, "text": "Output:" }, { "code": null, "e": 26264, "s": 26143, "text": "Value of the channel: \nType of the channel: chan int \nValue of the channel1: 0x432080\nType of the channel1: chan int \n" }, { "code": null, "e": 26701, "s": 26264, "text": "In Go language, channel work with two principal operations one is sending and another one is receiving, both the operations collectively known as communication. And the direction of <- operator indicates whether the data is received or send. In the channel, the send and receive operation block until another side is not ready by default. It allows goroutine to synchronize with each other without explicit locks or condition variables." }, { "code": null, "e": 27932, "s": 26701, "text": "Send operation: The send operation is used to send data from one goroutine to another goroutine with the help of a channel. Values like int, float64, and bool can safe and easy to send through a channel because they are copied so there is no risk of accidental concurrent access of the same value. Similarly, strings are also safe to transfer because they are immutable. But for sending pointers or reference like a slice, map, etc. through a channel are not safe because the value of pointers or reference may change by sending goroutine or by the receiving goroutine at the same time and the result is unpredicted. So, when you use pointers or references in the channel you must make sure that they can only access by the one goroutine at a time.Mychannel <- elementThe above statement indicates that the data(element) send to the channel(Mychannel) with the help of a <- operator.Receive operation: The receive operation is used to receive the data sent by the send operator.element := <-MychannelThe above statement indicates that the element receives data from the channel(Mychannel). If the result of the received statement is not going to use is also a valid statement. You can also write a receive statement as:<-Mychannel" }, { "code": null, "e": 28816, "s": 27932, "text": "Send operation: The send operation is used to send data from one goroutine to another goroutine with the help of a channel. Values like int, float64, and bool can safe and easy to send through a channel because they are copied so there is no risk of accidental concurrent access of the same value. Similarly, strings are also safe to transfer because they are immutable. But for sending pointers or reference like a slice, map, etc. through a channel are not safe because the value of pointers or reference may change by sending goroutine or by the receiving goroutine at the same time and the result is unpredicted. So, when you use pointers or references in the channel you must make sure that they can only access by the one goroutine at a time.Mychannel <- elementThe above statement indicates that the data(element) send to the channel(Mychannel) with the help of a <- operator." }, { "code": null, "e": 28837, "s": 28816, "text": "Mychannel <- element" }, { "code": null, "e": 28953, "s": 28837, "text": "The above statement indicates that the data(element) send to the channel(Mychannel) with the help of a <- operator." }, { "code": null, "e": 29301, "s": 28953, "text": "Receive operation: The receive operation is used to receive the data sent by the send operator.element := <-MychannelThe above statement indicates that the element receives data from the channel(Mychannel). If the result of the received statement is not going to use is also a valid statement. You can also write a receive statement as:<-Mychannel" }, { "code": null, "e": 29324, "s": 29301, "text": "element := <-Mychannel" }, { "code": null, "e": 29544, "s": 29324, "text": "The above statement indicates that the element receives data from the channel(Mychannel). If the result of the received statement is not going to use is also a valid statement. You can also write a receive statement as:" }, { "code": null, "e": 29556, "s": 29544, "text": "<-Mychannel" }, { "code": null, "e": 29565, "s": 29556, "text": "Example:" }, { "code": "// Go program to illustrate send// and receive operationpackage main import \"fmt\" func myfunc(ch chan int) { fmt.Println(234 + <-ch)}func main() { fmt.Println(\"start Main method\") // Creating a channel ch := make(chan int) go myfunc(ch) ch <- 23 fmt.Println(\"End Main method\")}", "e": 29870, "s": 29565, "text": null }, { "code": null, "e": 29878, "s": 29870, "text": "Output:" }, { "code": null, "e": 29917, "s": 29878, "text": "start Main method\n257\nEnd Main method\n" }, { "code": null, "e": 30088, "s": 29917, "text": "You can also close a channel with the help of close() function. This is an in-built function and sets a flag which indicates that no more value will send to this channel." }, { "code": null, "e": 30096, "s": 30088, "text": "Syntax:" }, { "code": null, "e": 30104, "s": 30096, "text": "close()" }, { "code": null, "e": 30260, "s": 30104, "text": "You can also close the channel using for range loop. Here, the receiver goroutine can check the channel is open or close with the help of the given syntax:" }, { "code": null, "e": 30283, "s": 30260, "text": "ele, ok:= <- Mychannel" }, { "code": null, "e": 30495, "s": 30283, "text": "Here, if the value of ok is true which means the channel is open so, read operations can be performed. And if the value of is false which means the channel is closed so, read operations are not going to perform." }, { "code": null, "e": 30504, "s": 30495, "text": "Example:" }, { "code": "// Go program to illustrate how// to close a channel using for// range loop and close functionpackage main import \"fmt\" // Functionfunc myfun(mychnl chan string) { for v := 0; v < 4; v++ { mychnl <- \"GeeksforGeeks\" } close(mychnl)} // Main functionfunc main() { // Creating a channel c := make(chan string) // calling Goroutine go myfun(c) // When the value of ok is // set to true means the // channel is open and it // can send or receive data // When the value of ok is set to // false means the channel is closed for { res, ok := <-c if ok == false { fmt.Println(\"Channel Close \", ok) break } fmt.Println(\"Channel Open \", res, ok) }}", "e": 31255, "s": 30504, "text": null }, { "code": null, "e": 31263, "s": 31255, "text": "Output:" }, { "code": null, "e": 31417, "s": 31263, "text": "Channel Open GeeksforGeeks true\nChannel Open GeeksforGeeks true\nChannel Open GeeksforGeeks true\nChannel Open GeeksforGeeks true\nChannel Close false\n" }, { "code": null, "e": 31703, "s": 31417, "text": "Blocking Send and Receive: In the channel when the data sent to a channel the control is blocked in that send statement until other goroutine reads from that channel. Similarly, when a channel receives data from the goroutine the read statement block until another goroutine statement." }, { "code": null, "e": 31761, "s": 31703, "text": "Zero Value Channel: The zero value of the channel is nil." }, { "code": null, "e": 32435, "s": 31761, "text": "For loop in Channel: A for loop can iterate over the sequential values sent on the channel until it closed.Syntax:for item := range Chnl { \n // statements..\n}\nExample:// Go program to illustrate how to// use for loop in the channel package main import \"fmt\" // Main functionfunc main() { // Creating a channel // Using make() function mychnl := make(chan string) // Anonymous goroutine go func() { mychnl <- \"GFG\" mychnl <- \"gfg\" mychnl <- \"Geeks\" mychnl <- \"GeeksforGeeks\" close(mychnl) }() // Using for loop for res := range mychnl { fmt.Println(res) }}Output:GFG\ngfg\nGeeks\nGeeksforGeeks\n\n" }, { "code": null, "e": 32443, "s": 32435, "text": "Syntax:" }, { "code": null, "e": 32493, "s": 32443, "text": "for item := range Chnl { \n // statements..\n}\n" }, { "code": null, "e": 32502, "s": 32493, "text": "Example:" }, { "code": "// Go program to illustrate how to// use for loop in the channel package main import \"fmt\" // Main functionfunc main() { // Creating a channel // Using make() function mychnl := make(chan string) // Anonymous goroutine go func() { mychnl <- \"GFG\" mychnl <- \"gfg\" mychnl <- \"Geeks\" mychnl <- \"GeeksforGeeks\" close(mychnl) }() // Using for loop for res := range mychnl { fmt.Println(res) }}", "e": 32969, "s": 32502, "text": null }, { "code": null, "e": 32977, "s": 32969, "text": "Output:" }, { "code": null, "e": 33007, "s": 32977, "text": "GFG\ngfg\nGeeks\nGeeksforGeeks\n\n" }, { "code": null, "e": 33653, "s": 33007, "text": "Length of the Channel: In channel, you can find the length of the channel using len() function. Here, the length indicates the number of value queued in the channel buffer.Example:// Go program to illustrate how to// find the length of the channel package main import \"fmt\"a// Main functionfunc main() { // Creating a channel // Using make() function mychnl := make(chan string, 4) mychnl <- \"GFG\" mychnl <- \"gfg\" mychnl <- \"Geeks\" mychnl <- \"GeeksforGeeks\" // Finding the length of the channel // Using len() function fmt.Println(\"Length of the channel is: \", len(mychnl))}Output:Length of the channel is: 4" }, { "code": null, "e": 33662, "s": 33653, "text": "Example:" }, { "code": "// Go program to illustrate how to// find the length of the channel package main import \"fmt\"a// Main functionfunc main() { // Creating a channel // Using make() function mychnl := make(chan string, 4) mychnl <- \"GFG\" mychnl <- \"gfg\" mychnl <- \"Geeks\" mychnl <- \"GeeksforGeeks\" // Finding the length of the channel // Using len() function fmt.Println(\"Length of the channel is: \", len(mychnl))}", "e": 34093, "s": 33662, "text": null }, { "code": null, "e": 34101, "s": 34093, "text": "Output:" }, { "code": null, "e": 34130, "s": 34101, "text": "Length of the channel is: 4" }, { "code": null, "e": 34765, "s": 34130, "text": "Capacity of the Channel: In channel, you can find the capacity of the channel using cap() function. Here, the capacity indicates the size of the buffer.Example:// Go program to illustrate how to// find the capacity of the channel package main import \"fmt\" // Main functionfunc main() { // Creating a channel // Using make() function mychnl := make(chan string, 5) mychnl <- \"GFG\" mychnl <- \"gfg\" mychnl <- \"Geeks\" mychnl <- \"GeeksforGeeks\" // Finding the capacity of the channel // Using cap() function fmt.Println(\"Capacity of the channel is: \", cap(mychnl))}Output:Capacity of the channel is: 5" }, { "code": null, "e": 34774, "s": 34765, "text": "Example:" }, { "code": "// Go program to illustrate how to// find the capacity of the channel package main import \"fmt\" // Main functionfunc main() { // Creating a channel // Using make() function mychnl := make(chan string, 5) mychnl <- \"GFG\" mychnl <- \"gfg\" mychnl <- \"Geeks\" mychnl <- \"GeeksforGeeks\" // Finding the capacity of the channel // Using cap() function fmt.Println(\"Capacity of the channel is: \", cap(mychnl))}", "e": 35212, "s": 34774, "text": null }, { "code": null, "e": 35220, "s": 35212, "text": "Output:" }, { "code": null, "e": 35251, "s": 35220, "text": "Capacity of the channel is: 5" }, { "code": null, "e": 35513, "s": 35251, "text": "Select and case statement in Channel: In go language, select statement is just like a switch statement without any input parameter. This select statement is used in the channel to perform a single operation out of multiple operations provided by the case block." }, { "code": null, "e": 35520, "s": 35513, "text": "Golang" }, { "code": null, "e": 35539, "s": 35520, "text": "Golang-Concurrency" }, { "code": null, "e": 35551, "s": 35539, "text": "Go Language" }, { "code": null, "e": 35649, "s": 35551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35701, "s": 35649, "text": "Different ways to concatenate two strings in Golang" }, { "code": null, "e": 35747, "s": 35701, "text": "time.Sleep() Function in Golang With Examples" }, { "code": null, "e": 35773, "s": 35747, "text": "Time Formatting in Golang" }, { "code": null, "e": 35823, "s": 35773, "text": "strings.Contains Function in Golang with Examples" }, { "code": null, "e": 35874, "s": 35823, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 35921, "s": 35874, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 35933, "s": 35921, "text": "Golang Maps" }, { "code": null, "e": 35982, "s": 35933, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 36014, "s": 35982, "text": "How to compare times in Golang?" } ]
A Short Introduction to ggvis in R | Towards Data Science
The Grammar of Graphics, the product of Leland Wilkinson’s multi-decade long work and research in the graphics domain, provides the philosophical basis for R graphing libraries such as ggplot2, ggvis and Julia graphing libraries such as Gadfly. Although, there are other libraries which can provide you really amazing graphics but what distinguishes these packages is that they are based on the research done by Wilkinson which essentially tries to look at graphics as a language and breaks it down into separate components just like any other language breaks down its components into subject, verb, object etc. Wilkinson wrote a statistical package known for its comprehensive graphics in the early 1970s which he later sold to SPSS in mid-1990s. While working at SPSS, he wrote his groundbreaking research that was mentioned a while back. His research has had a major impact on the philosophy of graphics in computer sciences. The most famous plotting package in R ggplot2, maintained by Winston Chang and Hadley Wickham, derives its underlying philosophy from The Grammar of Graphics. Another such package is ggvis. We’ll talk about the latter. ggplot2 in itself is an amazing package. ggvis takes nothing away from that, rather it is just an extension of the former with the ability to build HTML graphs. Because ggvis graphs are HTML, they can be used in a shiny web application, R markdown reports and with JavaScript too. We’ll figure out what some of it means in a while. The documentation for ggvis can be found here along with a really good tutorial on datacamp. For additional information, you can visit RStudio’s blog on ggvis along with a crisp summary of The Grammar of Graphics. The prime motive of this post is to explore and understand the grammar and syntax of ggvis. $ religiongdp <- read.table("/Users/kovid.rathee/Downloads/ReligionGDP.csv", header=TRUE, sep=",")$ religiongdp %>% ggvis (~GDP, ~Religiosity) %>% layer_points() The first thing that we’d learn about is the pipe operator %>% taken from the magrittr package. This works just like a shell pipe operator works. religiongdp %>% compute_smooth(GDP ~ Religiosity) %>% ggvis (~pred_, ~resp_) %>% layer_lines(stroke := "darkblue", strokeWidth := 3, strokeDash := 5) religiongdp %>% compute_smooth(GDP ~ Religiosity) %>% ggvis (~pred_, ~resp_) %>% layer_points(fill := "darkblue", size = 0.5) Plotting the original data with a line that kind of fits. We can consider it to be a regression line. The features in the dataset are not enough to do a proper classification so as to guess what a country’s or a state’s GDP should be. Apart from religiosity, there are a lot more important things like population, the form of government so on and so forth. But even from this graph, we can loosely establish that there’s a negative correlation between GDP and Religiosity — although, there are two main exceptions of that, Kuwait and the United States of America. We can call them the outliers. Please notice the settings button on the upper right corner of the rendition. When you click on that button, it provides you with an option to download a svg file or a png file. ggvis also distinguishes itself from ggplot2 for having interactive features like input sliders. Interactivity is one of the major achievements of ggvis. It works in the same way how it would work in a Tableau or Qlikview environment, however, when writing your own code using these libraries, you’ll have much more control and a much clearer understanding of how these graphs are rendered. Here’s an example: religiongdp %>% ggvis (~GDP, ~Religiosity) %>% layer_points(fill := "darkblue", size := input_slider (5,15,value=1)) %>% layer_smooths(stroke:="orange", span = input_slider (5,15,value=1)) iris %>% ggvis(~Sepal.Length,~Sepal.Width,fill=~Species) %>% layer_smooths(span = 2, stroke := “darkred”, strokeDash := 6) %>% layer_smooths(span = 1, stroke := “darkblue”) %>% layer_smooths(span = 0.5, stroke := “orange”) iris %>% ggvis(~Sepal.Length,~Sepal.Width,fill=~Species) %>% layer_points() %>% add_axis ("x",title="Sepal Length",properties=axis_props(axis=list(stroke="darkblue"),grid=list(stroke="brown",strokeDash=3),ticks=list(stroke="orange",strokeWidth=2),labels=list(angle=45, align="left", fontSize=12))) iris %>% ggvis (~Sepal.Length,~Sepal.Width) %>% mutate(Sepal.Length = Sepal.Length * 1.5) %>% layer_points(fill=~Species,size=~Petal.Width) %>% add_axis(“x”,title=”Sepal Length”,orient=”top”) %>% add_axis(“y”,title=”Sepal Width”,orient=”right”) %>% add_legend(c(“size”,”fill”),title=”Petal Width”)) iris %>% ggvis(x=~Sepal.Length,y=~Petal.Length,fill=~Species) %>% layer_points(opacity=~Sepal.Width) %>% layer_model_predictions(model="lm",stroke:="green",opacity=3) iris %>% ggvis(x=~Sepal.Length,y=~Petal.Length,fill=~Species) %>% layer_points(opacity=~Sepal.Width) %>% layer_model_predictions(model="loess",stroke:="green",opacity=3) ggvis is a great package which provides an upgrade to ggplot2 with a lot of new age features like — interactive plots and the ability to create HTML plots enabling embedding of these plots in Shiny applications and more. Wilkinson’s work has greatly affected the discourse in the language of plotting — which is done on a daily basis while doing data analysis, business intelligence, machine learning and more.
[ { "code": null, "e": 784, "s": 172, "text": "The Grammar of Graphics, the product of Leland Wilkinson’s multi-decade long work and research in the graphics domain, provides the philosophical basis for R graphing libraries such as ggplot2, ggvis and Julia graphing libraries such as Gadfly. Although, there are other libraries which can provide you really amazing graphics but what distinguishes these packages is that they are based on the research done by Wilkinson which essentially tries to look at graphics as a language and breaks it down into separate components just like any other language breaks down its components into subject, verb, object etc." }, { "code": null, "e": 1320, "s": 784, "text": "Wilkinson wrote a statistical package known for its comprehensive graphics in the early 1970s which he later sold to SPSS in mid-1990s. While working at SPSS, he wrote his groundbreaking research that was mentioned a while back. His research has had a major impact on the philosophy of graphics in computer sciences. The most famous plotting package in R ggplot2, maintained by Winston Chang and Hadley Wickham, derives its underlying philosophy from The Grammar of Graphics. Another such package is ggvis. We’ll talk about the latter." }, { "code": null, "e": 1652, "s": 1320, "text": "ggplot2 in itself is an amazing package. ggvis takes nothing away from that, rather it is just an extension of the former with the ability to build HTML graphs. Because ggvis graphs are HTML, they can be used in a shiny web application, R markdown reports and with JavaScript too. We’ll figure out what some of it means in a while." }, { "code": null, "e": 1958, "s": 1652, "text": "The documentation for ggvis can be found here along with a really good tutorial on datacamp. For additional information, you can visit RStudio’s blog on ggvis along with a crisp summary of The Grammar of Graphics. The prime motive of this post is to explore and understand the grammar and syntax of ggvis." }, { "code": null, "e": 2120, "s": 1958, "text": "$ religiongdp <- read.table(\"/Users/kovid.rathee/Downloads/ReligionGDP.csv\", header=TRUE, sep=\",\")$ religiongdp %>% ggvis (~GDP, ~Religiosity) %>% layer_points()" }, { "code": null, "e": 2266, "s": 2120, "text": "The first thing that we’d learn about is the pipe operator %>% taken from the magrittr package. This works just like a shell pipe operator works." }, { "code": null, "e": 2416, "s": 2266, "text": "religiongdp %>% compute_smooth(GDP ~ Religiosity) %>% ggvis (~pred_, ~resp_) %>% layer_lines(stroke := \"darkblue\", strokeWidth := 3, strokeDash := 5)" }, { "code": null, "e": 2542, "s": 2416, "text": "religiongdp %>% compute_smooth(GDP ~ Religiosity) %>% ggvis (~pred_, ~resp_) %>% layer_points(fill := \"darkblue\", size = 0.5)" }, { "code": null, "e": 3137, "s": 2542, "text": "Plotting the original data with a line that kind of fits. We can consider it to be a regression line. The features in the dataset are not enough to do a proper classification so as to guess what a country’s or a state’s GDP should be. Apart from religiosity, there are a lot more important things like population, the form of government so on and so forth. But even from this graph, we can loosely establish that there’s a negative correlation between GDP and Religiosity — although, there are two main exceptions of that, Kuwait and the United States of America. We can call them the outliers." }, { "code": null, "e": 3315, "s": 3137, "text": "Please notice the settings button on the upper right corner of the rendition. When you click on that button, it provides you with an option to download a svg file or a png file." }, { "code": null, "e": 3725, "s": 3315, "text": "ggvis also distinguishes itself from ggplot2 for having interactive features like input sliders. Interactivity is one of the major achievements of ggvis. It works in the same way how it would work in a Tableau or Qlikview environment, however, when writing your own code using these libraries, you’ll have much more control and a much clearer understanding of how these graphs are rendered. Here’s an example:" }, { "code": null, "e": 3914, "s": 3725, "text": "religiongdp %>% ggvis (~GDP, ~Religiosity) %>% layer_points(fill := \"darkblue\", size := input_slider (5,15,value=1)) %>% layer_smooths(stroke:=\"orange\", span = input_slider (5,15,value=1))" }, { "code": null, "e": 4137, "s": 3914, "text": "iris %>% ggvis(~Sepal.Length,~Sepal.Width,fill=~Species) %>% layer_smooths(span = 2, stroke := “darkred”, strokeDash := 6) %>% layer_smooths(span = 1, stroke := “darkblue”) %>% layer_smooths(span = 0.5, stroke := “orange”)" }, { "code": null, "e": 4435, "s": 4137, "text": "iris %>% ggvis(~Sepal.Length,~Sepal.Width,fill=~Species) %>% layer_points() %>% add_axis (\"x\",title=\"Sepal Length\",properties=axis_props(axis=list(stroke=\"darkblue\"),grid=list(stroke=\"brown\",strokeDash=3),ticks=list(stroke=\"orange\",strokeWidth=2),labels=list(angle=45, align=\"left\", fontSize=12)))" }, { "code": null, "e": 4734, "s": 4435, "text": "iris %>% ggvis (~Sepal.Length,~Sepal.Width) %>% mutate(Sepal.Length = Sepal.Length * 1.5) %>% layer_points(fill=~Species,size=~Petal.Width) %>% add_axis(“x”,title=”Sepal Length”,orient=”top”) %>% add_axis(“y”,title=”Sepal Width”,orient=”right”) %>% add_legend(c(“size”,”fill”),title=”Petal Width”))" }, { "code": null, "e": 4901, "s": 4734, "text": "iris %>% ggvis(x=~Sepal.Length,y=~Petal.Length,fill=~Species) %>% layer_points(opacity=~Sepal.Width) %>% layer_model_predictions(model=\"lm\",stroke:=\"green\",opacity=3)" }, { "code": null, "e": 5071, "s": 4901, "text": "iris %>% ggvis(x=~Sepal.Length,y=~Petal.Length,fill=~Species) %>% layer_points(opacity=~Sepal.Width) %>% layer_model_predictions(model=\"loess\",stroke:=\"green\",opacity=3)" } ]
7 Best Python Packages Kagglers Are Using Without Telling You | Towards Data Science
Kaggle is a hot spot for what is trending in data science and machine learning. Due to its competitiveness, the top players are constantly looking for new tools, technologies, and frameworks that give them an edge over others. If a new package or an algorithm delivers actionable value, there is a good chance it receives immediate adoption and becomes popular. This post is about 7 of such trendies packages that are direct replacements for many tools and technologies that are either outdated or need urgent upgrades. Above is a 100k row dataset with 75 features projected to 2D using a package called UMAP. Each dot represents a single sample in a classification problem and is color-encoded based on their class. Massive datasets like these can make you miserable during EDA, mainly because of the computation and time expenses they come with. So, it is important that each plot you create is spot-on and reveals something significant about the data. I think that’s one of the reasons why UMAP (Uniform Manifold Approximation and Projection) is so well-received on Kaggle. It is efficient, low-code, and lets you take a real “look” at the data from a high-dimensional perspective: When I look at plots like these, they remind me of why I got into data science in the first place — data is beautiful! https://umap-learn.readthedocs.io/en/latest/ https://github.com/lmcinnes/umap UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction UMAP offers an easy, Sklearn-compatible API. After importing the UMAP module, call its fit on the feature and target arrays (X, y) to project them to 2D by default: The most important parameters of UMAP estimator are n_neighbors and min_dist (minimum distance). Think of n_neighbors as a handle that controls the zoom level of the projection. min_dist is the minimum distance between each projected point. If you wish to project to a higher dimension, you can tweak n_components just like in Sklearn's PCA. As dataset sizes are getting bigger, people are paying more attention to out-of-memory, multi-threaded data preprocessing tools to escape the performance limitations of Pandas. One of the most promising tools in this regard is datatable, inspired by R's data.table package. It is developed by H2O.ai to support parallel-computing and out-of-memory operations on big data (up to 100 GB), as required by today's machine learning applications. While datatable does not have as large a suite of manipulation functions as pandas, it is found to heavily outperform it on most common operations. In an experiment done on a 100M row dataset, datatable manages to read the data into memory in just over a minute, 9 times faster than pandas. https://github.com/h2oai/datatable https://datatable.readthedocs.io/en/latest/?badge=latest The main data structure in datatable is Frame (as in DataFrame). >>> type(frame)datatable.Frame A simple GroupBy operation: Lazypredict is one of the best one-liner packages I have ever seen. Using the library, you can train almost all Sklearn models plus XGBoost and LightGBM in a single line of code. It only has two estimators — one for regression and one for classification. Fitting either one on a dataset with a given target will evaluate more than 30 base models and generate a report with their rankings on several popular metrics. An insight like this will free you from the manual task of selecting a base model, a time much better spent on tasks like feature engineering. https://lazypredict.readthedocs.io/en/latest/index.html https://github.com/shankarpandala/lazypredict One of the more recent libraries I have added to my skill-stack is Kagglers’ favorite — Optuna. Optuna is a next-generation automatic hyperparameter tuning framework designed to work on virtually any model and neural network available in today’s ML and Deep learning packages. It offers several advantages over similar tools like GridSearch, TPOT, HyperOPT, etc.: Platform-agnostic: has APIs to work with any framework, including XGBoost, LightGBM, CatBoost, Sklearn, Keras, TensorFlow, PyTorch, etc. A large suite of optimization algorithms with early stopping and pruning features baked in Easy parallelization with little or no changes to the code Built-in support to visually explore tuning history and the importance of each hyperparameter. My most favorite feature is its ability to pause/resume/save search histories. Optuna keeps track of all previous rounds of tuning, and you can resume the search for however long you want until you get the performance you want. Besides, you can make Optuna RAM-independent for massive datasets and searching by storing results in a local or a remote database by adding an extra parameter. https://github.com/optuna/optuna https://optuna.readthedocs.io/en/stable/ Optuna: A Next-generation Hyperparameter Optimization Framework For the sake of simplicity, we are trying to optimize the function (x — 1)2 + (y + 3)2. As you can see, the tuned values for x and y are pretty close to the optimal (1, -3). Hyperparameter tuning for real estimators is a bit more involved, so why don’t you check out my detailed guide: towardsdatascience.com Explainable AI (XAI) is one of the strongest trends in the ML and AI sphere. Companies and businesses are starting to be fussy over the adoption of AI solutions due to their “black box” nature. Hey, no one can blame them. If data scientists themselves are coming up with tools to understand the models they created, the worries and suspicions of business owners are entirely justified. One of those tools that often come up in grandmasters’ notebooks on Kaggle is SHAP. SHAP (Shapley Additive exPlanations) is an approach to explain how a model works using concepts from game theory. At its score, SHAP uses something called Shapley values to explain: Which features in the model are the most important The model’s decisions behind any single prediction. For example, asking which features led to this particular output. The most notable aspects of SHAP are its unified theme and unique plots that break down the mechanics of any model and neural network. Here is an example plot that shows the feature importances in terms of Shapley values for a single prediction: Trust me, SHAP has way cooler plots. It is such a powerful tool that the Kaggle platform has an entire free course built around it. https://shap.readthedocs.io/en/latest/index.html https://github.com/slundberg/shap A Unified Approach to Interpreting Model Predictions From local explanations to a global understanding with explainable AI for trees Explainable machine-learning predictions for the prevention of hypoxemia during surgery Here is a short snippet to create a bee swarm plot of all predictions from the classic Diabetes dataset: If you thought GPUs are deep learning-exclusive, you are horribly mistaken. The cuDF library, created by the open-source platform RAPIDs, enables you to run tabular manipulation operations on one or more GPUs. Unlike datatable, cuDF has a very similar API to Pandas, thus offering a less steep learning curve. As it is standard with GPUs, the library is super fast, giving it an edge over datatable when combined with its Pandas-like API. The only hassle when using cuDF is its installation — it requires: CUDA Toolkit 11.0+ NVIDIA driver 450.80.02+ Pascal architecture or better (Compute Capability >=6.0) If you want to try out the library without installation limitations, Kaggle kernels are a great option. Here is a notebook to get you started. https://docs.rapids.ai/api/cudf/stable/ https://github.com/rapidsai/cudf Here is a snippet from the documentation that shows a simple GroupBy operation on the tips dataset: Normally, I am against any library or tool that takes a programmer away from writing actual code. But, since auto-EDA libraries are all the rage now on Kaggle, I had to include this section for completeness. Initially, this section was supposed to be only about AutoViz, which uses XGBoost under the hood to display the most important information of the dataset (that’s why I chose it). Later, I decided to include a few others as well. Here is a list of the best auto EDA libraries I have found: DataPrep — the most comprehensive auto EDA [GitHub, Documentation] AutoViz — the fastest auto EDA [GitHub] PandasProfiling — the earliest and one of the best auto EDA tools [GitHub, Documentation] Lux — the most user-friendly and luxurious EDA [GitHub, Documentation] If you want to see how each package performs EDA, check out this great notebook on Kaggle. The available tools and packages to execute data science tasks are endless. Everyone has the right to be overwhelmed by this. But I sincerely hope the tools outlined in this post helped narrow down your focus to what is trending and delivering results in the hands of members of the largest ML community.
[ { "code": null, "e": 251, "s": 171, "text": "Kaggle is a hot spot for what is trending in data science and machine learning." }, { "code": null, "e": 533, "s": 251, "text": "Due to its competitiveness, the top players are constantly looking for new tools, technologies, and frameworks that give them an edge over others. If a new package or an algorithm delivers actionable value, there is a good chance it receives immediate adoption and becomes popular." }, { "code": null, "e": 691, "s": 533, "text": "This post is about 7 of such trendies packages that are direct replacements for many tools and technologies that are either outdated or need urgent upgrades." }, { "code": null, "e": 888, "s": 691, "text": "Above is a 100k row dataset with 75 features projected to 2D using a package called UMAP. Each dot represents a single sample in a classification problem and is color-encoded based on their class." }, { "code": null, "e": 1126, "s": 888, "text": "Massive datasets like these can make you miserable during EDA, mainly because of the computation and time expenses they come with. So, it is important that each plot you create is spot-on and reveals something significant about the data." }, { "code": null, "e": 1356, "s": 1126, "text": "I think that’s one of the reasons why UMAP (Uniform Manifold Approximation and Projection) is so well-received on Kaggle. It is efficient, low-code, and lets you take a real “look” at the data from a high-dimensional perspective:" }, { "code": null, "e": 1475, "s": 1356, "text": "When I look at plots like these, they remind me of why I got into data science in the first place — data is beautiful!" }, { "code": null, "e": 1520, "s": 1475, "text": "https://umap-learn.readthedocs.io/en/latest/" }, { "code": null, "e": 1553, "s": 1520, "text": "https://github.com/lmcinnes/umap" }, { "code": null, "e": 1629, "s": 1553, "text": "UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction" }, { "code": null, "e": 1794, "s": 1629, "text": "UMAP offers an easy, Sklearn-compatible API. After importing the UMAP module, call its fit on the feature and target arrays (X, y) to project them to 2D by default:" }, { "code": null, "e": 2035, "s": 1794, "text": "The most important parameters of UMAP estimator are n_neighbors and min_dist (minimum distance). Think of n_neighbors as a handle that controls the zoom level of the projection. min_dist is the minimum distance between each projected point." }, { "code": null, "e": 2136, "s": 2035, "text": "If you wish to project to a higher dimension, you can tweak n_components just like in Sklearn's PCA." }, { "code": null, "e": 2313, "s": 2136, "text": "As dataset sizes are getting bigger, people are paying more attention to out-of-memory, multi-threaded data preprocessing tools to escape the performance limitations of Pandas." }, { "code": null, "e": 2577, "s": 2313, "text": "One of the most promising tools in this regard is datatable, inspired by R's data.table package. It is developed by H2O.ai to support parallel-computing and out-of-memory operations on big data (up to 100 GB), as required by today's machine learning applications." }, { "code": null, "e": 2868, "s": 2577, "text": "While datatable does not have as large a suite of manipulation functions as pandas, it is found to heavily outperform it on most common operations. In an experiment done on a 100M row dataset, datatable manages to read the data into memory in just over a minute, 9 times faster than pandas." }, { "code": null, "e": 2903, "s": 2868, "text": "https://github.com/h2oai/datatable" }, { "code": null, "e": 2960, "s": 2903, "text": "https://datatable.readthedocs.io/en/latest/?badge=latest" }, { "code": null, "e": 3025, "s": 2960, "text": "The main data structure in datatable is Frame (as in DataFrame)." }, { "code": null, "e": 3056, "s": 3025, "text": ">>> type(frame)datatable.Frame" }, { "code": null, "e": 3084, "s": 3056, "text": "A simple GroupBy operation:" }, { "code": null, "e": 3152, "s": 3084, "text": "Lazypredict is one of the best one-liner packages I have ever seen." }, { "code": null, "e": 3500, "s": 3152, "text": "Using the library, you can train almost all Sklearn models plus XGBoost and LightGBM in a single line of code. It only has two estimators — one for regression and one for classification. Fitting either one on a dataset with a given target will evaluate more than 30 base models and generate a report with their rankings on several popular metrics." }, { "code": null, "e": 3643, "s": 3500, "text": "An insight like this will free you from the manual task of selecting a base model, a time much better spent on tasks like feature engineering." }, { "code": null, "e": 3699, "s": 3643, "text": "https://lazypredict.readthedocs.io/en/latest/index.html" }, { "code": null, "e": 3745, "s": 3699, "text": "https://github.com/shankarpandala/lazypredict" }, { "code": null, "e": 3841, "s": 3745, "text": "One of the more recent libraries I have added to my skill-stack is Kagglers’ favorite — Optuna." }, { "code": null, "e": 4022, "s": 3841, "text": "Optuna is a next-generation automatic hyperparameter tuning framework designed to work on virtually any model and neural network available in today’s ML and Deep learning packages." }, { "code": null, "e": 4109, "s": 4022, "text": "It offers several advantages over similar tools like GridSearch, TPOT, HyperOPT, etc.:" }, { "code": null, "e": 4246, "s": 4109, "text": "Platform-agnostic: has APIs to work with any framework, including XGBoost, LightGBM, CatBoost, Sklearn, Keras, TensorFlow, PyTorch, etc." }, { "code": null, "e": 4337, "s": 4246, "text": "A large suite of optimization algorithms with early stopping and pruning features baked in" }, { "code": null, "e": 4396, "s": 4337, "text": "Easy parallelization with little or no changes to the code" }, { "code": null, "e": 4491, "s": 4396, "text": "Built-in support to visually explore tuning history and the importance of each hyperparameter." }, { "code": null, "e": 4719, "s": 4491, "text": "My most favorite feature is its ability to pause/resume/save search histories. Optuna keeps track of all previous rounds of tuning, and you can resume the search for however long you want until you get the performance you want." }, { "code": null, "e": 4880, "s": 4719, "text": "Besides, you can make Optuna RAM-independent for massive datasets and searching by storing results in a local or a remote database by adding an extra parameter." }, { "code": null, "e": 4913, "s": 4880, "text": "https://github.com/optuna/optuna" }, { "code": null, "e": 4954, "s": 4913, "text": "https://optuna.readthedocs.io/en/stable/" }, { "code": null, "e": 5018, "s": 4954, "text": "Optuna: A Next-generation Hyperparameter Optimization Framework" }, { "code": null, "e": 5192, "s": 5018, "text": "For the sake of simplicity, we are trying to optimize the function (x — 1)2 + (y + 3)2. As you can see, the tuned values for x and y are pretty close to the optimal (1, -3)." }, { "code": null, "e": 5304, "s": 5192, "text": "Hyperparameter tuning for real estimators is a bit more involved, so why don’t you check out my detailed guide:" }, { "code": null, "e": 5327, "s": 5304, "text": "towardsdatascience.com" }, { "code": null, "e": 5521, "s": 5327, "text": "Explainable AI (XAI) is one of the strongest trends in the ML and AI sphere. Companies and businesses are starting to be fussy over the adoption of AI solutions due to their “black box” nature." }, { "code": null, "e": 5713, "s": 5521, "text": "Hey, no one can blame them. If data scientists themselves are coming up with tools to understand the models they created, the worries and suspicions of business owners are entirely justified." }, { "code": null, "e": 5797, "s": 5713, "text": "One of those tools that often come up in grandmasters’ notebooks on Kaggle is SHAP." }, { "code": null, "e": 5979, "s": 5797, "text": "SHAP (Shapley Additive exPlanations) is an approach to explain how a model works using concepts from game theory. At its score, SHAP uses something called Shapley values to explain:" }, { "code": null, "e": 6030, "s": 5979, "text": "Which features in the model are the most important" }, { "code": null, "e": 6148, "s": 6030, "text": "The model’s decisions behind any single prediction. For example, asking which features led to this particular output." }, { "code": null, "e": 6394, "s": 6148, "text": "The most notable aspects of SHAP are its unified theme and unique plots that break down the mechanics of any model and neural network. Here is an example plot that shows the feature importances in terms of Shapley values for a single prediction:" }, { "code": null, "e": 6526, "s": 6394, "text": "Trust me, SHAP has way cooler plots. It is such a powerful tool that the Kaggle platform has an entire free course built around it." }, { "code": null, "e": 6575, "s": 6526, "text": "https://shap.readthedocs.io/en/latest/index.html" }, { "code": null, "e": 6609, "s": 6575, "text": "https://github.com/slundberg/shap" }, { "code": null, "e": 6662, "s": 6609, "text": "A Unified Approach to Interpreting Model Predictions" }, { "code": null, "e": 6742, "s": 6662, "text": "From local explanations to a global understanding with explainable AI for trees" }, { "code": null, "e": 6830, "s": 6742, "text": "Explainable machine-learning predictions for the prevention of hypoxemia during surgery" }, { "code": null, "e": 6935, "s": 6830, "text": "Here is a short snippet to create a bee swarm plot of all predictions from the classic Diabetes dataset:" }, { "code": null, "e": 7011, "s": 6935, "text": "If you thought GPUs are deep learning-exclusive, you are horribly mistaken." }, { "code": null, "e": 7145, "s": 7011, "text": "The cuDF library, created by the open-source platform RAPIDs, enables you to run tabular manipulation operations on one or more GPUs." }, { "code": null, "e": 7374, "s": 7145, "text": "Unlike datatable, cuDF has a very similar API to Pandas, thus offering a less steep learning curve. As it is standard with GPUs, the library is super fast, giving it an edge over datatable when combined with its Pandas-like API." }, { "code": null, "e": 7441, "s": 7374, "text": "The only hassle when using cuDF is its installation — it requires:" }, { "code": null, "e": 7460, "s": 7441, "text": "CUDA Toolkit 11.0+" }, { "code": null, "e": 7485, "s": 7460, "text": "NVIDIA driver 450.80.02+" }, { "code": null, "e": 7542, "s": 7485, "text": "Pascal architecture or better (Compute Capability >=6.0)" }, { "code": null, "e": 7685, "s": 7542, "text": "If you want to try out the library without installation limitations, Kaggle kernels are a great option. Here is a notebook to get you started." }, { "code": null, "e": 7725, "s": 7685, "text": "https://docs.rapids.ai/api/cudf/stable/" }, { "code": null, "e": 7758, "s": 7725, "text": "https://github.com/rapidsai/cudf" }, { "code": null, "e": 7858, "s": 7758, "text": "Here is a snippet from the documentation that shows a simple GroupBy operation on the tips dataset:" }, { "code": null, "e": 8066, "s": 7858, "text": "Normally, I am against any library or tool that takes a programmer away from writing actual code. But, since auto-EDA libraries are all the rage now on Kaggle, I had to include this section for completeness." }, { "code": null, "e": 8295, "s": 8066, "text": "Initially, this section was supposed to be only about AutoViz, which uses XGBoost under the hood to display the most important information of the dataset (that’s why I chose it). Later, I decided to include a few others as well." }, { "code": null, "e": 8355, "s": 8295, "text": "Here is a list of the best auto EDA libraries I have found:" }, { "code": null, "e": 8422, "s": 8355, "text": "DataPrep — the most comprehensive auto EDA [GitHub, Documentation]" }, { "code": null, "e": 8462, "s": 8422, "text": "AutoViz — the fastest auto EDA [GitHub]" }, { "code": null, "e": 8552, "s": 8462, "text": "PandasProfiling — the earliest and one of the best auto EDA tools [GitHub, Documentation]" }, { "code": null, "e": 8623, "s": 8552, "text": "Lux — the most user-friendly and luxurious EDA [GitHub, Documentation]" }, { "code": null, "e": 8714, "s": 8623, "text": "If you want to see how each package performs EDA, check out this great notebook on Kaggle." }, { "code": null, "e": 8840, "s": 8714, "text": "The available tools and packages to execute data science tasks are endless. Everyone has the right to be overwhelmed by this." } ]
Remove default list-style in Bootstrap
To remove the list styles in Bootstrap, use the .list-unstyled class. You can try to run the following code to implement the .list-unstyled class − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <h2>Technologies</h2> <ul class = "list-inline"> <li><a href = "#">Home</a></li> <li><a href = "#">PHP</a></li> <li><a href = "#">Java</a></li> <li><a href = "#">jQuery</a></li> <li><a href = "#">JavaScript</a></li> <li><a href = "#">Ruby</a></li> </ul> </div> <div class = "container"> <h2>Technologies (Unstyled)</h2> <ul class = "list-unstyled"> <li><a href = "#">Home</a></li> <li><a href = "#">PHP</a></li> <li><a href = "#">Java</a></li> <li><a href = "#">jQuery</a></li> <li><a href = "#">JavaScript</a></li> <li><a href = "#">Ruby</a></li> </ul> </div> </body> </html>
[ { "code": null, "e": 1132, "s": 1062, "text": "To remove the list styles in Bootstrap, use the .list-unstyled class." }, { "code": null, "e": 1210, "s": 1132, "text": "You can try to run the following code to implement the .list-unstyled class −" }, { "code": null, "e": 1220, "s": 1210, "text": "Live Demo" }, { "code": null, "e": 2333, "s": 1220, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h2>Technologies</h2>\n <ul class = \"list-inline\">\n <li><a href = \"#\">Home</a></li>\n <li><a href = \"#\">PHP</a></li>\n <li><a href = \"#\">Java</a></li>\n <li><a href = \"#\">jQuery</a></li>\n <li><a href = \"#\">JavaScript</a></li>\n <li><a href = \"#\">Ruby</a></li>\n </ul>\n </div>\n <div class = \"container\">\n <h2>Technologies (Unstyled)</h2>\n <ul class = \"list-unstyled\">\n <li><a href = \"#\">Home</a></li>\n <li><a href = \"#\">PHP</a></li>\n <li><a href = \"#\">Java</a></li>\n <li><a href = \"#\">jQuery</a></li>\n <li><a href = \"#\">JavaScript</a></li>\n <li><a href = \"#\">Ruby</a></li>\n </ul>\n </div>\n </body>\n</html>" } ]
How to clear a Tkinter ListBox?
To create a list of items with a scrollable widget, Tkinter provides the Listbox widget. With the Listbox widget, we can create a list that contains items called List items. Depending upon the configuration, the user can select one or multiple items from the list. If we want to clear the items in the Listbox widget, we can use the delete(0, END) method. Besides deleting all the items in the Listbox, we can delete a single item as well by selecting an item from the Listbox, i.e., by using currselection() method to select an item and delete it using the delete() function. # Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame or window win=Tk() # Set the size of the window win.geometry("700x250") # Create a Listbox widget lb=Listbox(win, width=100, height=5, font=('TkMenuFont, 20')) lb.pack() # Once the list item is deleted, we can insert a new item in the listbox def delete(): lb.delete(0,END) Label(win, text="Nothing Found Here!", font=('TkheadingFont, 20')).pack() # Add items in the Listbox lb.insert("end","item1","item2","item3","item4","item5") # Add a Button to Edit and Delete the Listbox Item ttk.Button(win, text="Delete", command=delete).pack() win.mainloop() If we run the above code, it will display a list of items in the list box and a button to clear the Listbox. Now, click the "Delete" button to clear the Listbox widget.
[ { "code": null, "e": 1327, "s": 1062, "text": "To create a list of items with a scrollable widget, Tkinter provides the Listbox widget. With the Listbox widget, we can create a list that contains items called List items. Depending upon the configuration, the user can select one or multiple items from the list." }, { "code": null, "e": 1639, "s": 1327, "text": "If we want to clear the items in the Listbox widget, we can use the delete(0, END) method. Besides deleting all the items in the Listbox, we can delete a single item as well by selecting an item from the Listbox, i.e., by using currselection() method to select an item and delete it using the delete() function." }, { "code": null, "e": 2326, "s": 1639, "text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the window\nwin.geometry(\"700x250\")\n\n# Create a Listbox widget\nlb=Listbox(win, width=100, height=5, font=('TkMenuFont, 20'))\nlb.pack()\n\n# Once the list item is deleted, we can insert a new item in the listbox\ndef delete():\n lb.delete(0,END)\n Label(win, text=\"Nothing Found Here!\",\n font=('TkheadingFont, 20')).pack()\n\n# Add items in the Listbox\nlb.insert(\"end\",\"item1\",\"item2\",\"item3\",\"item4\",\"item5\")\n\n# Add a Button to Edit and Delete the Listbox Item\nttk.Button(win, text=\"Delete\", command=delete).pack()\n\nwin.mainloop()" }, { "code": null, "e": 2435, "s": 2326, "text": "If we run the above code, it will display a list of items in the list box and a button to clear the Listbox." }, { "code": null, "e": 2495, "s": 2435, "text": "Now, click the \"Delete\" button to clear the Listbox widget." } ]