title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
GATE | Gate IT 2005 | Question 76 - GeeksforGeeks
28 Jun, 2021 A company has a class C network address of 204.204.204.0. It wishes to have three subnets, one with 100 hosts and two with 50 hosts each. Which one of the following options represents a feasible set of subnet address/subnet mask pairs? (A) 204.204.204.128/255.255.255.192204.204.204.0/255.255.255.128204.204.204.64/255.255.255.128(B) 204.204.204.0/255.255.255.192204.204.204.192/255.255.255.128204.204.204.64/255.255.255.128(C) 204.204.204.128/255.255.255.128204.204.204.192/255.255.255.192204.204.204.224/255.255.255.192(D) 204.204.204.128/255.255.255.128204.204.204.64/255.255.255.192204.204.204.0/255.255.255.192Answer: (D)Explanation: Background Reading: IP address is used to uniquely identify a host. ->Address range Class A 1.0.0.1 to 126.255.255.254 Class B 128.1.0.1 to 191.255.255.254 Class C 192.0.1.1 to 223.255.254.254 Class D 224.0.0.0 to 239.255.255.255 (127.0.0.0 to 127.255.255.255 – used for loopback functionality : which will point back to the computer’s own tcp/ip network configuration.) (1)x.x.x.0 and x.x.x.255 addresses are used for directed broadcast address and network ID. So,these two addresses are not used by hosts. (2)Network ID is computed by performing logical & on IP address with subnet mask. -> IPV4 addresses are 32 bit and they are used as follows for: Identifying Networks(bit no.) Identifying Hosts(bit no.) Class A 1-8 9-32 Class B 1-16 17-32 Class C 1-24 25-32 Now, let’s come back to the question: Here, company has class C address of 204.204.204.0(11001100.11001100.11001100.00000000), 1-24 bits are identifying the network. So, network has IP addresses from 204.204.204.0 to 204.204.204.255. ->Subnetting is a practice in which we can divide the network in two or more parts. For this we will have to borrow few bits from the hosts part. -> In subnet mask, all network + subnetwork bits are 1 and host bits are 0. Option (A) 204.204.204.128/255.255.255.192 204.204.204.0/255.255.255.128 204.204.204.64/255.255.255.128 1) 11001100.11001100.11001100.10000000/11111111.11111111.11111111.11000000 Network bits-26 (as 26 bits are 1 in the subnet mask) so sub-network id = 204.204.204.128 (refer(2)) 6 bits ‘0’ in subnet mask,i.e. 64(i.e. 2^6) -2 = 62 hosts (refer (1) ) 2) 11001100.11001100.11001100.00000000/11111111.11111111.11111111.10000000 Network bits-25 (as 25 bits are 1 in the subnet mask) so sub-network id = 204.204.204.0 (refer(2)) 7 bits ‘0’ in subnet mask,i.e. 128(i.e.2^7) -2 =126 hosts (refer (1) ) 3) 11001100.11001100.11001100.01000000/11111111.11111111.11111111.10000000 Network bits-25 (as 25 bits are 1 in the subnet mask) so sub-network id = 204.204.204.0 ( refer(2)) 7 bits ‘0’ in subnet mask,i.e. 128(i.e.2^7) -2 = 126 hosts (refer (1) ) Though the networks are divided into subnets containing 62,126,126 hosts which satisfy our minimum criteria of 50,50,100. But, two subnets have same network ID thus,they are not different.Thus,this division is only of two subnets but we need 3 ,so A option is incorrect. Option (B) 204.204.204.0/255.255.255.192 204.204.204.192/255.255.255.128 204.204.204.64/255.255.255.128 1) 11001100.11001100.11001100.00000000/11111111.11111111.11111111.11000000 Network bits-26 (as 26 bits are 1 in the subnet mask) so sub-network id = 204.204.204.0 (refer(2)) 6 bits ‘0’ in subnet mask,i.e. 64(i.e. 2^6)-2=62 hosts (refer (1)) 2) 11001100.11001100.11001100.11000000/11111111.11111111.11111111.10000000 Network bits-25 (as 25 bits are 1 in the subnet mask) so sub-network id = 204.204.204.128 (refer(2)) 7 bits ‘0’ in subnet mask,i.e. 128(i.e.2^7)-2=126 hosts (refer (1)) 3) 11001100.11001100.11001100.01000000/11111111.11111111.11111111.10000000 Network bits-25 (as 25 bits are 1 in the subnet mask) so sub-network id = 204.204.204.0 (refer(2)) 7 bits ‘0’ in subnet mask,i.e. 128(i.e.2^7)-2=126 hosts (refer (1)) Though the networks are divided into subnets containing 62,126,126 hosts which satisfy our minimum criteria of 50,50,100. But, two subnets have same network ID thus,they are not different.Thus,this division is only of two subnets. Option (C) 204.204.204.128/255.255.255.128 204.204.204.192/255.255.255.192 204.204.204.224/255.255.255.192 1) 11001100.11001100.11001100.10000000/11111111.11111111.11111111.10000000 Network bits-25 (as 25 bits are 1 in the subnet mask) so sub-network id == 204.204.204.128 (refer(2)) 7 bits ‘0’ in subnet mask,i.e. 128(i.e. 2^7) -2 =126 hosts (refer 1) 2) 11001100.11001100.11001100.11000000/11111111.11111111.11111111.11000000 Network bits-26 (as 25 bits are 1 in the subnet mask) so sub-network id == 204.204.204.192 (refer(2)) 6 bits ‘0’ in subnet mask,i.e. 64(i.e.2^6)-2=62 hosts(refer 1) 3) 11001100.11001100.11001100.11110000/11111111.11111111.11111111.11000000 Network bits-26 (as 26 bits are 1 in the subnet mask) so sub-network id == 204.204.204.192 (refer (2)) 6 bits ‘0’ in subnet mask,i.e. 64(i.e.2^6) -2=62 hosts (refer 1) Though the networks are divided into subnets containing 62,62,126 hosts which satisfy our minimum criteria of 50,50,100. But, two subnets have same network ID thus,they are not different.Thus,this division is only of two subnets. Option (D) 204.204.204.128/255.255.255.128 204.204.204.64/255.255.255.192 204.204.204.0/255.255.255.192 1) 11001100.11001100.11001100.10000000/11111111.11111111.11111111.10000000 –> Network bits-25 (as 25 bits are 1 in the subnet mask) so sub-network id == 204.204.204.128 (refer(2)) 7 bits ‘0’ in subnet mask,i.e. 128(i.e. 2^7)-2=126 hosts (refer(1)) 2) 11001100.11001100.11001100.01000000/11111111.11111111.11111111.11000000 –> Network bits-26 (as 25 bits are 1 in the subnet mask) so sub-network id == 204.204.204.64 (refer(2)) 6 bits ‘0’ in subnet mask,i.e. 64(i.e.2^6)-2=62 hosts (refer(1)) 3) 11001100.11001100.11001100.00000000/11111111.11111111.11111111.11000000 –> Network bits-26 (as 26 bits are 1 in the subnet mask) so sub-network id == 204.204.204.0 (refer(2)) 6 bits ‘0’ in subnet mask,i.e. 64(i.e.2^6)-2=62 host bits (refer(1)) This satisfies the minimum criteria of 50,50 and 100 hosts and all subnet IDs are different .Thus,option D is correct. This explanation is provided by Shashank Shanker.Quiz of this Question Gate IT 2005 GATE-Gate IT 2005 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25711, "s": 25683, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25947, "s": 25711, "text": "A company has a class C network address of 204.204.204.0. It wishes to have three subnets, one with 100 hosts and two with 50 hosts each. Which one of the following options represents a feasible set of subnet address/subnet mask pairs?" }, { "code": null, "e": 26372, "s": 25947, "text": " (A) 204.204.204.128/255.255.255.192204.204.204.0/255.255.255.128204.204.204.64/255.255.255.128(B) 204.204.204.0/255.255.255.192204.204.204.192/255.255.255.128204.204.204.64/255.255.255.128(C) 204.204.204.128/255.255.255.128204.204.204.192/255.255.255.192204.204.204.224/255.255.255.192(D) 204.204.204.128/255.255.255.128204.204.204.64/255.255.255.192204.204.204.0/255.255.255.192Answer: (D)Explanation: Background Reading:" }, { "code": null, "e": 26420, "s": 26372, "text": "IP address is used to uniquely identify a host." }, { "code": null, "e": 26599, "s": 26420, "text": "->Address range\n Class A 1.0.0.1 to 126.255.255.254\n Class B 128.1.0.1 to 191.255.255.254\n Class C 192.0.1.1 to 223.255.254.254\n Class D 224.0.0.0 to 239.255.255.255\n" }, { "code": null, "e": 26740, "s": 26599, "text": "(127.0.0.0 to 127.255.255.255 – used for loopback functionality : which will point back to the computer’s own tcp/ip network configuration.)" }, { "code": null, "e": 26877, "s": 26740, "text": "(1)x.x.x.0 and x.x.x.255 addresses are used for directed broadcast address and network ID. So,these two addresses are not used by hosts." }, { "code": null, "e": 27022, "s": 26877, "text": "(2)Network ID is computed by performing logical & on IP address with subnet mask. -> IPV4 addresses are 32 bit and they are used as follows for:" }, { "code": null, "e": 27265, "s": 27022, "text": " Identifying Networks(bit no.) Identifying Hosts(bit no.)\n Class A 1-8 9-32 \n Class B 1-16 17-32\n Class C 1-24 25-32\n" }, { "code": null, "e": 27303, "s": 27265, "text": "Now, let’s come back to the question:" }, { "code": null, "e": 27499, "s": 27303, "text": "Here, company has class C address of 204.204.204.0(11001100.11001100.11001100.00000000), 1-24 bits are identifying the network. So, network has IP addresses from 204.204.204.0 to 204.204.204.255." }, { "code": null, "e": 27645, "s": 27499, "text": "->Subnetting is a practice in which we can divide the network in two or more parts. For this we will have to borrow few bits from the hosts part." }, { "code": null, "e": 27721, "s": 27645, "text": "-> In subnet mask, all network + subnetwork bits are 1 and host bits are 0." }, { "code": null, "e": 27827, "s": 27721, "text": "Option (A) \n204.204.204.128/255.255.255.192\n204.204.204.0/255.255.255.128\n204.204.204.64/255.255.255.128\n" }, { "code": null, "e": 28074, "s": 27827, "text": "1) 11001100.11001100.11001100.10000000/11111111.11111111.11111111.11000000 Network bits-26 (as 26 bits are 1 in the subnet mask) so sub-network id = 204.204.204.128 (refer(2)) 6 bits ‘0’ in subnet mask,i.e. 64(i.e. 2^6) -2 = 62 hosts (refer (1) )" }, { "code": null, "e": 28319, "s": 28074, "text": "2) 11001100.11001100.11001100.00000000/11111111.11111111.11111111.10000000 Network bits-25 (as 25 bits are 1 in the subnet mask) so sub-network id = 204.204.204.0 (refer(2)) 7 bits ‘0’ in subnet mask,i.e. 128(i.e.2^7) -2 =126 hosts (refer (1) )" }, { "code": null, "e": 28566, "s": 28319, "text": "3) 11001100.11001100.11001100.01000000/11111111.11111111.11111111.10000000 Network bits-25 (as 25 bits are 1 in the subnet mask) so sub-network id = 204.204.204.0 ( refer(2)) 7 bits ‘0’ in subnet mask,i.e. 128(i.e.2^7) -2 = 126 hosts (refer (1) )" }, { "code": null, "e": 28837, "s": 28566, "text": "Though the networks are divided into subnets containing 62,126,126 hosts which satisfy our minimum criteria of 50,50,100. But, two subnets have same network ID thus,they are not different.Thus,this division is only of two subnets but we need 3 ,so A option is incorrect." }, { "code": null, "e": 28943, "s": 28837, "text": "Option (B) \n204.204.204.0/255.255.255.192\n204.204.204.192/255.255.255.128\n204.204.204.64/255.255.255.128\n" }, { "code": null, "e": 29184, "s": 28943, "text": "1) 11001100.11001100.11001100.00000000/11111111.11111111.11111111.11000000 Network bits-26 (as 26 bits are 1 in the subnet mask) so sub-network id = 204.204.204.0 (refer(2)) 6 bits ‘0’ in subnet mask,i.e. 64(i.e. 2^6)-2=62 hosts (refer (1))" }, { "code": null, "e": 29428, "s": 29184, "text": "2) 11001100.11001100.11001100.11000000/11111111.11111111.11111111.10000000 Network bits-25 (as 25 bits are 1 in the subnet mask) so sub-network id = 204.204.204.128 (refer(2)) 7 bits ‘0’ in subnet mask,i.e. 128(i.e.2^7)-2=126 hosts (refer (1))" }, { "code": null, "e": 29670, "s": 29428, "text": "3) 11001100.11001100.11001100.01000000/11111111.11111111.11111111.10000000 Network bits-25 (as 25 bits are 1 in the subnet mask) so sub-network id = 204.204.204.0 (refer(2)) 7 bits ‘0’ in subnet mask,i.e. 128(i.e.2^7)-2=126 hosts (refer (1))" }, { "code": null, "e": 29901, "s": 29670, "text": "Though the networks are divided into subnets containing 62,126,126 hosts which satisfy our minimum criteria of 50,50,100. But, two subnets have same network ID thus,they are not different.Thus,this division is only of two subnets." }, { "code": null, "e": 30010, "s": 29901, "text": "Option (C) \n204.204.204.128/255.255.255.128\n204.204.204.192/255.255.255.192\n204.204.204.224/255.255.255.192\n" }, { "code": null, "e": 30256, "s": 30010, "text": "1) 11001100.11001100.11001100.10000000/11111111.11111111.11111111.10000000 Network bits-25 (as 25 bits are 1 in the subnet mask) so sub-network id == 204.204.204.128 (refer(2)) 7 bits ‘0’ in subnet mask,i.e. 128(i.e. 2^7) -2 =126 hosts (refer 1)" }, { "code": null, "e": 30496, "s": 30256, "text": "2) 11001100.11001100.11001100.11000000/11111111.11111111.11111111.11000000 Network bits-26 (as 25 bits are 1 in the subnet mask) so sub-network id == 204.204.204.192 (refer(2)) 6 bits ‘0’ in subnet mask,i.e. 64(i.e.2^6)-2=62 hosts(refer 1)" }, { "code": null, "e": 30739, "s": 30496, "text": "3) 11001100.11001100.11001100.11110000/11111111.11111111.11111111.11000000 Network bits-26 (as 26 bits are 1 in the subnet mask) so sub-network id == 204.204.204.192 (refer (2)) 6 bits ‘0’ in subnet mask,i.e. 64(i.e.2^6) -2=62 hosts (refer 1)" }, { "code": null, "e": 30969, "s": 30739, "text": "Though the networks are divided into subnets containing 62,62,126 hosts which satisfy our minimum criteria of 50,50,100. But, two subnets have same network ID thus,they are not different.Thus,this division is only of two subnets." }, { "code": null, "e": 31075, "s": 30969, "text": "Option (D) \n204.204.204.128/255.255.255.128\n204.204.204.64/255.255.255.192\n204.204.204.0/255.255.255.192\n" }, { "code": null, "e": 31323, "s": 31075, "text": "1) 11001100.11001100.11001100.10000000/11111111.11111111.11111111.10000000 –> Network bits-25 (as 25 bits are 1 in the subnet mask) so sub-network id == 204.204.204.128 (refer(2)) 7 bits ‘0’ in subnet mask,i.e. 128(i.e. 2^7)-2=126 hosts (refer(1))" }, { "code": null, "e": 31567, "s": 31323, "text": "2) 11001100.11001100.11001100.01000000/11111111.11111111.11111111.11000000 –> Network bits-26 (as 25 bits are 1 in the subnet mask) so sub-network id == 204.204.204.64 (refer(2)) 6 bits ‘0’ in subnet mask,i.e. 64(i.e.2^6)-2=62 hosts (refer(1))" }, { "code": null, "e": 31933, "s": 31567, "text": "3) 11001100.11001100.11001100.00000000/11111111.11111111.11111111.11000000 –> Network bits-26 (as 26 bits are 1 in the subnet mask) so sub-network id == 204.204.204.0 (refer(2)) 6 bits ‘0’ in subnet mask,i.e. 64(i.e.2^6)-2=62 host bits (refer(1)) This satisfies the minimum criteria of 50,50 and 100 hosts and all subnet IDs are different .Thus,option D is correct." }, { "code": null, "e": 32004, "s": 31933, "text": "This explanation is provided by Shashank Shanker.Quiz of this Question" }, { "code": null, "e": 32017, "s": 32004, "text": "Gate IT 2005" }, { "code": null, "e": 32035, "s": 32017, "text": "GATE-Gate IT 2005" }, { "code": null, "e": 32040, "s": 32035, "text": "GATE" }, { "code": null, "e": 32138, "s": 32040, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32172, "s": 32138, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 32206, "s": 32172, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 32240, "s": 32206, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 32273, "s": 32240, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 32309, "s": 32273, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 32345, "s": 32309, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 32379, "s": 32345, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 32413, "s": 32379, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 32447, "s": 32413, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Python | Finding 'n' Character Words in a Text File - GeeksforGeeks
26 Mar, 2020 This article aims to find words with a certain number of character. In the code mentioned below, a python program is given to find the words contain three characters in the text file. Examples: Input : Hello, how are you ? Output :howareyou Code: Python program to find the words contain three characters in the text file count = 1chrw = "" # text filefile = open('textfile.txt', 'r')while 1: sp = file.read(1) if count<= 3: chrw = chrw + sp if count>3: if sp ==" ": count = 0 if len(chrw)>0: print(chrw) chrw ="" elif sp !=" ": chrw ="" count = count + 1 if not sp: break file.close() Output: how are you Python file-handling-programs python-file-handling Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n26 Mar, 2020" }, { "code": null, "e": 25721, "s": 25537, "text": "This article aims to find words with a certain number of character. In the code mentioned below, a python program is given to find the words contain three characters in the text file." }, { "code": null, "e": 25731, "s": 25721, "text": "Examples:" }, { "code": null, "e": 25760, "s": 25731, "text": "Input : Hello, how are you ?" }, { "code": null, "e": 25778, "s": 25760, "text": "Output :howareyou" }, { "code": null, "e": 25859, "s": 25778, "text": "Code: Python program to find the words contain three characters in the text file" }, { "code": "count = 1chrw = \"\" # text filefile = open('textfile.txt', 'r')while 1: sp = file.read(1) if count<= 3: chrw = chrw + sp if count>3: if sp ==\" \": count = 0 if len(chrw)>0: print(chrw) chrw =\"\" elif sp !=\" \": chrw =\"\" count = count + 1 if not sp: break file.close() ", "e": 26238, "s": 25859, "text": null }, { "code": null, "e": 26246, "s": 26238, "text": "Output:" }, { "code": null, "e": 26261, "s": 26246, "text": "how \nare \nyou\n" }, { "code": null, "e": 26291, "s": 26261, "text": "Python file-handling-programs" }, { "code": null, "e": 26312, "s": 26291, "text": "python-file-handling" }, { "code": null, "e": 26319, "s": 26312, "text": "Python" }, { "code": null, "e": 26335, "s": 26319, "text": "Python Programs" }, { "code": null, "e": 26433, "s": 26335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26465, "s": 26433, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26507, "s": 26465, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26549, "s": 26507, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26576, "s": 26549, "text": "Python Classes and Objects" }, { "code": null, "e": 26632, "s": 26576, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26654, "s": 26632, "text": "Defaultdict in Python" }, { "code": null, "e": 26693, "s": 26654, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26739, "s": 26693, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26777, "s": 26739, "text": "Python | Convert a list to dictionary" } ]
Difference between Boxing and Unboxing in C# - GeeksforGeeks
17 Apr, 2019 Boxing and unboxing is an important concept in C#. C# Type System contains three data types: Value Types (int, char, etc), Reference Types (object) and Pointer Types. Basically, it converts a Value Type to a Reference Type, and vice versa. Boxing and Unboxing enables a unified view of the type system in which a value of any type can be treated as an object. // C# program to illustrate Boxingusing System; public class GFG { static public void Main() { int val = 2019; // Boxing object o = val; // Change the value of val val = 2000; Console.WriteLine("Value type of val is {0}", val); Console.WriteLine("Object type of val is {0}", o); }} Output: Value type of val is 2000 Object type of val is 2019 // C# program to illustrate Unboxingusing System; public class GFG { static public void Main() { int val = 2019; // Boxing object o = val; // Unboxing int x = (int)o; Console.WriteLine("Value of o is {0}", o); Console.WriteLine("Value of x is {0}", x); }} Output: Value of o is 2019 Value of x is 2019 CSharp-Basics C# Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Differences between IPv4 and IPv6
[ { "code": null, "e": 25070, "s": 25042, "text": "\n17 Apr, 2019" }, { "code": null, "e": 25430, "s": 25070, "text": "Boxing and unboxing is an important concept in C#. C# Type System contains three data types: Value Types (int, char, etc), Reference Types (object) and Pointer Types. Basically, it converts a Value Type to a Reference Type, and vice versa. Boxing and Unboxing enables a unified view of the type system in which a value of any type can be treated as an object." }, { "code": "// C# program to illustrate Boxingusing System; public class GFG { static public void Main() { int val = 2019; // Boxing object o = val; // Change the value of val val = 2000; Console.WriteLine(\"Value type of val is {0}\", val); Console.WriteLine(\"Object type of val is {0}\", o); }}", "e": 25777, "s": 25430, "text": null }, { "code": null, "e": 25785, "s": 25777, "text": "Output:" }, { "code": null, "e": 25839, "s": 25785, "text": "Value type of val is 2000\nObject type of val is 2019\n" }, { "code": "// C# program to illustrate Unboxingusing System; public class GFG { static public void Main() { int val = 2019; // Boxing object o = val; // Unboxing int x = (int)o; Console.WriteLine(\"Value of o is {0}\", o); Console.WriteLine(\"Value of x is {0}\", x); }}", "e": 26160, "s": 25839, "text": null }, { "code": null, "e": 26168, "s": 26160, "text": "Output:" }, { "code": null, "e": 26207, "s": 26168, "text": "Value of o is 2019\nValue of x is 2019\n" }, { "code": null, "e": 26221, "s": 26207, "text": "CSharp-Basics" }, { "code": null, "e": 26224, "s": 26221, "text": "C#" }, { "code": null, "e": 26243, "s": 26224, "text": "Difference Between" }, { "code": null, "e": 26341, "s": 26243, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26369, "s": 26341, "text": "C# Dictionary with examples" }, { "code": null, "e": 26384, "s": 26369, "text": "C# | Delegates" }, { "code": null, "e": 26407, "s": 26384, "text": "C# | Method Overriding" }, { "code": null, "e": 26429, "s": 26407, "text": "C# | Abstract Classes" }, { "code": null, "e": 26475, "s": 26429, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 26506, "s": 26475, "text": "Difference between BFS and DFS" }, { "code": null, "e": 26546, "s": 26506, "text": "Class method vs Static method in Python" }, { "code": null, "e": 26578, "s": 26546, "text": "Differences between TCP and UDP" }, { "code": null, "e": 26639, "s": 26578, "text": "Difference between var, let and const keywords in JavaScript" } ]
Sort an array where a subarray of a sorted array is in reverse order - GeeksforGeeks
15 Nov, 2021 Given an array of N numbers where a subarray is sorted in descending order and rest of the numbers in the array are in ascending order. The task is to sort an array where a subarray of a sorted array is in reversed order. Examples: Input: 2 5 65 55 50 70 90 Output: 2 5 50 55 65 70 90 The subarray from 2nd index to 4th index is in reverse order. So the subarray is reversed, and the sorted array is printed. Input: 1 7 6 5 4 3 2 8 Output: 1 2 3 4 5 6 7 8 A naive approach will be to sort the array and print the array. Time Complexity of this approach will be O(N log n).An efficient approach will be to find and store the starting index and ending index of the reversed subarray. Since the subarray is in descending order and the rest of the elements are in ascending order, only reversing the subarray will sort the complete array. Reverse the subarray using two pointer approach. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to sort an array where// a subarray of a sorted array// is in reversed order#include <bits/stdc++.h>using namespace std; // Function to print the sorted array// by reversing the subarrayvoid printSorted(int a[], int n){ int front = -1, back = -1; // find the starting index of the // reversed subarray for (int i = 1; i < n; i++) { if (a[i] < a[i - 1]) { front = i - 1; break; } } // find the ending index of the // reversed subarray for (int i = n - 2; i >= 0; i--) { if (a[i] > a[i + 1]) { back = i + 1; break; } } // if no reversed subarray is present if (front == -1 and back == -1) { for (int i = 0; i < n; i++) cout << a[i] << " "; return; } // swap the reversed subarray while (front <= back) { // swaps the front and back element // using c++ STL swap(a[front], a[back]); // move the pointers one step // ahead and one step back front++; back--; } for (int i = 0; i < n; i++) cout << a[i] << " ";} // Driver Codeint main(){ int a[] = { 1, 7, 6, 5, 4, 3, 2, 8 }; int n = sizeof(a) / sizeof(a[0]); printSorted(a, n); return 0;} // Java program to sort an array where// a subarray of a sorted array// is in reversed orderimport java.io.*; class GFG{ // Function to print the sorted array// by reversing the subarraystatic void printSorted(int a[], int n){ int front = -1, back = -1; // find the starting index of the // reversed subarray for (int i = 1; i < n; i++) { if (a[i] < a[i - 1]) { front = i - 1; break; } } // find the ending index of the // reversed subarray for (int i = n - 2; i >= 0; i--) { if (a[i] > a[i + 1]) { back = i + 1; break; } } // if no reversed subarray is present if (front == -1 && back == -1) { for (int i = 0; i < n; i++) System.out.println(a[i] + " "); return; } // swap the reversed subarray while (front <= back) { // swaps the front and back element // using c++ STL int temp = a[front]; a[front] = a[back]; a[back] = temp; // move the pointers one step // ahead and one step back front++; back--; } for (int i = 0; i < n; i++) System.out.print(a[i] + " ");} // Driver Codepublic static void main (String[] args){ int a[] = { 1, 7, 6, 5, 4, 3, 2, 8 }; int n = a.length; printSorted(a, n);;}} // This code is contributed by anuj_67.. # Python 3 program to sort an array where# a subarray of a sorted array is in# reversed order # Function to print the sorted array# by reversing the subarraydef printSorted(a, n): front = -1 back = -1 # find the starting index of the # reversed subarray for i in range(1, n, 1): if (a[i] < a[i - 1]): front = i - 1 break # find the ending index of the # reversed subarray i = n - 2 while(i >= 0): if (a[i] > a[i + 1]): back = i + 1 break i -= 1 # if no reversed subarray is present if (front == -1 and back == -1): for i in range(0, n, 1): print(a[i], end = " ") return # swap the reversed subarray while (front <= back): # swaps the front and back element # using c++ STL temp = a[front] a[front] = a[back] a[back] = temp # move the pointers one step # ahead and one step back front += 1 back -= 1 for i in range(0, n, 1): print(a[i], end = " ") # Driver Codeif __name__ == '__main__': a = [1, 7, 6, 5, 4, 3, 2, 8] n = len(a) printSorted(a, n) # This code is contributed by# Sahil_Shelangia // C# program to sort an array where// a subarray of a sorted array// is in reversed orderusing System; class GFG{ // Function to print the sorted array// by reversing the subarraystatic void printSorted(int []a, int n){ int front = -1, back = -1; // find the starting index of the // reversed subarray for (int i = 1; i < n; i++) { if (a[i] < a[i - 1]) { front = i - 1; break; } } // find the ending index of the // reversed subarray for (int i = n - 2; i >= 0; i--) { if (a[i] > a[i + 1]) { back = i + 1; break; } } // if no reversed subarray is present if (front == -1 && back == -1) { for (int i = 0; i < n; i++) { Console.Write(a[i] + " "); } return; } // swap the reversed subarray while (front <= back) { // swaps the front and back element // using c++ STL swap(a, front, back); // move the pointers one step // ahead and one step back front++; back--; } for (int i = 0; i < n; i++) { Console.Write(a[i] + " "); }} static void swap(int[] a, int front, int back){ int c = a[front]; a[front] = a[back]; a[back] = c;} // Driver Codepublic static void Main(){ int []a = {1, 7, 6, 5, 4, 3, 2, 8}; int n = a.Length; printSorted(a, n);}} // This code contributed by 29AjayKumar <?php// PHP program to sort an array where// a subarray of a sorted array// is in reversed order // Function to print the sorted array// by reversing the subarrayfunction printSorted($a, $n){ $front = -1; $back = -1; // find the starting index of the // reversed subarray for ($i = 1; $i < $n; $i++) { if ($a[$i] < $a[$i - 1]) { $front = $i - 1; break; } } // find the ending index of the // reversed subarray for ($i = $n - 2; $i >= 0; $i--) { if ($a[$i] > $a[$i + 1]) { $back = $i + 1; break; } } // if no reversed subarray is present if ($front == -1 && $back == -1) { for ($i = 0; $i < $n; $i++) echo $a[$i] . " "; return; } // swap the reversed subarray while ($front <= $back) { // swaps the front and back element // using c++ STL $temp = $a[$front]; $a[$front] = $a[$back]; $a[$back] = $temp; // move the pointers one step // ahead and one step back $front++; $back--; } for ($i = 0; $i < $n; $i++) echo $a[$i] . " ";} // Driver Code$a = array(1, 7, 6, 5, 4, 3, 2, 8);$n = sizeof($a);printSorted($a, $n); // This code is contributed// by Akanksha Rai <script> // JavaScript program to sort an array where// a subarray of a sorted array// is in reversed order // Function to print the sorted array // by reversing the subarray function printSorted(a , n) { var front = -1, back = -1; // find the starting index of the // reversed subarray for (i = 1; i < n; i++) { if (a[i] < a[i - 1]) { front = i - 1; break; } } // find the ending index of the // reversed subarray for (i = n - 2; i >= 0; i--) { if (a[i] > a[i + 1]) { back = i + 1; break; } } // if no reversed subarray is present if (front == -1 && back == -1) { for (i = 0; i < n; i++) document.write(a[i] + " "); return; } // swap the reversed subarray while (front <= back) { // swaps the front and back element // using c++ STL var temp = a[front]; a[front] = a[back]; a[back] = temp; // move the pointers one step // ahead and one step back front++; back--; } for (i = 0; i < n; i++) document.write(a[i] + " "); } // Driver Code var a = [ 1, 7, 6, 5, 4, 3, 2, 8 ]; var n = a.length; printSorted(a, n); // This code is contributed by todaysgaurav </script> 1 2 3 4 5 6 7 8 Time Complexity: O(n) vt_m 29AjayKumar Akanksha_Rai sahilshelangia todaysgaurav akshaysingh98088 ankita_saini Reverse Sorting Quiz subarray two-pointer-algorithm Arrays two-pointer-algorithm Arrays Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Find subarray with given sum | Set 1 (Nonnegative Numbers) Remove duplicates from sorted array Move all negative numbers to beginning and positive to end with constant extra space Building Heap from Array
[ { "code": null, "e": 26066, "s": 26038, "text": "\n15 Nov, 2021" }, { "code": null, "e": 26289, "s": 26066, "text": "Given an array of N numbers where a subarray is sorted in descending order and rest of the numbers in the array are in ascending order. The task is to sort an array where a subarray of a sorted array is in reversed order. " }, { "code": null, "e": 26300, "s": 26289, "text": "Examples: " }, { "code": null, "e": 26478, "s": 26300, "text": "Input: 2 5 65 55 50 70 90 Output: 2 5 50 55 65 70 90 The subarray from 2nd index to 4th index is in reverse order. So the subarray is reversed, and the sorted array is printed. " }, { "code": null, "e": 26525, "s": 26478, "text": "Input: 1 7 6 5 4 3 2 8 Output: 1 2 3 4 5 6 7 8" }, { "code": null, "e": 26954, "s": 26525, "text": "A naive approach will be to sort the array and print the array. Time Complexity of this approach will be O(N log n).An efficient approach will be to find and store the starting index and ending index of the reversed subarray. Since the subarray is in descending order and the rest of the elements are in ascending order, only reversing the subarray will sort the complete array. Reverse the subarray using two pointer approach. " }, { "code": null, "e": 27007, "s": 26954, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27011, "s": 27007, "text": "C++" }, { "code": null, "e": 27016, "s": 27011, "text": "Java" }, { "code": null, "e": 27024, "s": 27016, "text": "Python3" }, { "code": null, "e": 27027, "s": 27024, "text": "C#" }, { "code": null, "e": 27031, "s": 27027, "text": "PHP" }, { "code": null, "e": 27042, "s": 27031, "text": "Javascript" }, { "code": "// C++ program to sort an array where// a subarray of a sorted array// is in reversed order#include <bits/stdc++.h>using namespace std; // Function to print the sorted array// by reversing the subarrayvoid printSorted(int a[], int n){ int front = -1, back = -1; // find the starting index of the // reversed subarray for (int i = 1; i < n; i++) { if (a[i] < a[i - 1]) { front = i - 1; break; } } // find the ending index of the // reversed subarray for (int i = n - 2; i >= 0; i--) { if (a[i] > a[i + 1]) { back = i + 1; break; } } // if no reversed subarray is present if (front == -1 and back == -1) { for (int i = 0; i < n; i++) cout << a[i] << \" \"; return; } // swap the reversed subarray while (front <= back) { // swaps the front and back element // using c++ STL swap(a[front], a[back]); // move the pointers one step // ahead and one step back front++; back--; } for (int i = 0; i < n; i++) cout << a[i] << \" \";} // Driver Codeint main(){ int a[] = { 1, 7, 6, 5, 4, 3, 2, 8 }; int n = sizeof(a) / sizeof(a[0]); printSorted(a, n); return 0;}", "e": 28310, "s": 27042, "text": null }, { "code": "// Java program to sort an array where// a subarray of a sorted array// is in reversed orderimport java.io.*; class GFG{ // Function to print the sorted array// by reversing the subarraystatic void printSorted(int a[], int n){ int front = -1, back = -1; // find the starting index of the // reversed subarray for (int i = 1; i < n; i++) { if (a[i] < a[i - 1]) { front = i - 1; break; } } // find the ending index of the // reversed subarray for (int i = n - 2; i >= 0; i--) { if (a[i] > a[i + 1]) { back = i + 1; break; } } // if no reversed subarray is present if (front == -1 && back == -1) { for (int i = 0; i < n; i++) System.out.println(a[i] + \" \"); return; } // swap the reversed subarray while (front <= back) { // swaps the front and back element // using c++ STL int temp = a[front]; a[front] = a[back]; a[back] = temp; // move the pointers one step // ahead and one step back front++; back--; } for (int i = 0; i < n; i++) System.out.print(a[i] + \" \");} // Driver Codepublic static void main (String[] args){ int a[] = { 1, 7, 6, 5, 4, 3, 2, 8 }; int n = a.length; printSorted(a, n);;}} // This code is contributed by anuj_67..", "e": 29704, "s": 28310, "text": null }, { "code": "# Python 3 program to sort an array where# a subarray of a sorted array is in# reversed order # Function to print the sorted array# by reversing the subarraydef printSorted(a, n): front = -1 back = -1 # find the starting index of the # reversed subarray for i in range(1, n, 1): if (a[i] < a[i - 1]): front = i - 1 break # find the ending index of the # reversed subarray i = n - 2 while(i >= 0): if (a[i] > a[i + 1]): back = i + 1 break i -= 1 # if no reversed subarray is present if (front == -1 and back == -1): for i in range(0, n, 1): print(a[i], end = \" \") return # swap the reversed subarray while (front <= back): # swaps the front and back element # using c++ STL temp = a[front] a[front] = a[back] a[back] = temp # move the pointers one step # ahead and one step back front += 1 back -= 1 for i in range(0, n, 1): print(a[i], end = \" \") # Driver Codeif __name__ == '__main__': a = [1, 7, 6, 5, 4, 3, 2, 8] n = len(a) printSorted(a, n) # This code is contributed by# Sahil_Shelangia", "e": 30931, "s": 29704, "text": null }, { "code": "// C# program to sort an array where// a subarray of a sorted array// is in reversed orderusing System; class GFG{ // Function to print the sorted array// by reversing the subarraystatic void printSorted(int []a, int n){ int front = -1, back = -1; // find the starting index of the // reversed subarray for (int i = 1; i < n; i++) { if (a[i] < a[i - 1]) { front = i - 1; break; } } // find the ending index of the // reversed subarray for (int i = n - 2; i >= 0; i--) { if (a[i] > a[i + 1]) { back = i + 1; break; } } // if no reversed subarray is present if (front == -1 && back == -1) { for (int i = 0; i < n; i++) { Console.Write(a[i] + \" \"); } return; } // swap the reversed subarray while (front <= back) { // swaps the front and back element // using c++ STL swap(a, front, back); // move the pointers one step // ahead and one step back front++; back--; } for (int i = 0; i < n; i++) { Console.Write(a[i] + \" \"); }} static void swap(int[] a, int front, int back){ int c = a[front]; a[front] = a[back]; a[back] = c;} // Driver Codepublic static void Main(){ int []a = {1, 7, 6, 5, 4, 3, 2, 8}; int n = a.Length; printSorted(a, n);}} // This code contributed by 29AjayKumar", "e": 32406, "s": 30931, "text": null }, { "code": "<?php// PHP program to sort an array where// a subarray of a sorted array// is in reversed order // Function to print the sorted array// by reversing the subarrayfunction printSorted($a, $n){ $front = -1; $back = -1; // find the starting index of the // reversed subarray for ($i = 1; $i < $n; $i++) { if ($a[$i] < $a[$i - 1]) { $front = $i - 1; break; } } // find the ending index of the // reversed subarray for ($i = $n - 2; $i >= 0; $i--) { if ($a[$i] > $a[$i + 1]) { $back = $i + 1; break; } } // if no reversed subarray is present if ($front == -1 && $back == -1) { for ($i = 0; $i < $n; $i++) echo $a[$i] . \" \"; return; } // swap the reversed subarray while ($front <= $back) { // swaps the front and back element // using c++ STL $temp = $a[$front]; $a[$front] = $a[$back]; $a[$back] = $temp; // move the pointers one step // ahead and one step back $front++; $back--; } for ($i = 0; $i < $n; $i++) echo $a[$i] . \" \";} // Driver Code$a = array(1, 7, 6, 5, 4, 3, 2, 8);$n = sizeof($a);printSorted($a, $n); // This code is contributed// by Akanksha Rai", "e": 33712, "s": 32406, "text": null }, { "code": "<script> // JavaScript program to sort an array where// a subarray of a sorted array// is in reversed order // Function to print the sorted array // by reversing the subarray function printSorted(a , n) { var front = -1, back = -1; // find the starting index of the // reversed subarray for (i = 1; i < n; i++) { if (a[i] < a[i - 1]) { front = i - 1; break; } } // find the ending index of the // reversed subarray for (i = n - 2; i >= 0; i--) { if (a[i] > a[i + 1]) { back = i + 1; break; } } // if no reversed subarray is present if (front == -1 && back == -1) { for (i = 0; i < n; i++) document.write(a[i] + \" \"); return; } // swap the reversed subarray while (front <= back) { // swaps the front and back element // using c++ STL var temp = a[front]; a[front] = a[back]; a[back] = temp; // move the pointers one step // ahead and one step back front++; back--; } for (i = 0; i < n; i++) document.write(a[i] + \" \"); } // Driver Code var a = [ 1, 7, 6, 5, 4, 3, 2, 8 ]; var n = a.length; printSorted(a, n); // This code is contributed by todaysgaurav </script>", "e": 35187, "s": 33712, "text": null }, { "code": null, "e": 35203, "s": 35187, "text": "1 2 3 4 5 6 7 8" }, { "code": null, "e": 35228, "s": 35205, "text": "Time Complexity: O(n) " }, { "code": null, "e": 35233, "s": 35228, "text": "vt_m" }, { "code": null, "e": 35245, "s": 35233, "text": "29AjayKumar" }, { "code": null, "e": 35258, "s": 35245, "text": "Akanksha_Rai" }, { "code": null, "e": 35273, "s": 35258, "text": "sahilshelangia" }, { "code": null, "e": 35286, "s": 35273, "text": "todaysgaurav" }, { "code": null, "e": 35303, "s": 35286, "text": "akshaysingh98088" }, { "code": null, "e": 35316, "s": 35303, "text": "ankita_saini" }, { "code": null, "e": 35324, "s": 35316, "text": "Reverse" }, { "code": null, "e": 35337, "s": 35324, "text": "Sorting Quiz" }, { "code": null, "e": 35346, "s": 35337, "text": "subarray" }, { "code": null, "e": 35368, "s": 35346, "text": "two-pointer-algorithm" }, { "code": null, "e": 35375, "s": 35368, "text": "Arrays" }, { "code": null, "e": 35397, "s": 35375, "text": "two-pointer-algorithm" }, { "code": null, "e": 35404, "s": 35397, "text": "Arrays" }, { "code": null, "e": 35412, "s": 35404, "text": "Reverse" }, { "code": null, "e": 35510, "s": 35412, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35537, "s": 35510, "text": "Count pairs with given sum" }, { "code": null, "e": 35568, "s": 35537, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 35593, "s": 35568, "text": "Window Sliding Technique" }, { "code": null, "e": 35631, "s": 35593, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35652, "s": 35631, "text": "Next Greater Element" }, { "code": null, "e": 35710, "s": 35652, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 35769, "s": 35710, "text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)" }, { "code": null, "e": 35805, "s": 35769, "text": "Remove duplicates from sorted array" }, { "code": null, "e": 35890, "s": 35805, "text": "Move all negative numbers to beginning and positive to end with constant extra space" } ]
Semantic-UI | Input Field - GeeksforGeeks
20 May, 2020 Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. Semantic-UI classes can be applied to the Input field to modify and design them as needed. Example 1: Simple Input Field HTML <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div class="ui container"> <h2>Simple Text Input Field</h2> <div class="ui input"> <input type="text" placeholder="Enter Name"> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> </body></html> Output: Example 2: Input Field showing data Loading HTML <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div class="ui container"> <h2>Text Field with Loading Icon</h2> <div class="ui icon input loading"> <input type="text" placeholder="Enter School"> <i class="search icon"></i> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> </body></html> Output: And you can add class ‘ui left icon input loading’ to show that loading icon in the left. Example 3: Action Input Field HTML <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div class="ui container"> <h2>Text Field With Button</h2> <div class="ui action input"> <input type="text" placeholder="Search"> <button class="ui button">Search</button> </div> </div> <br> <div class="ui container"> <h2>Text field with dropdown list and Button</h2> <div class="ui action input"> <input type="text" placeholder="Search..."> <select class="ui compact selection dropdown"> <option value="web">Web</option> <option selected="" value="images">Images</option> <option value="videos">Videos</option> </select> <div class="ui button">Search</div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> </body></html> Output: Example 4: Labelled Input File HTML <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div class="ui container"> <h2>Labelled in front.</h2> <div class="ui labeled input"> <div class="ui label"> https:// </div> <input type="text" placeholder="geeksforgeeks.com"> </div> </div> <br> <div class="ui container"> <h2>Labelled in the end.</h2> <div class="ui right labeled input"> <input type="text" placeholder="Find domain"> <div class="ui dropdown label"> <div class="text">.com</div> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> </body></html> Output: Semantic-UI CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26033, "s": 26005, "text": "\n20 May, 2020" }, { "code": null, "e": 26379, "s": 26033, "text": "Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. Semantic-UI classes can be applied to the Input field to modify and design them as needed." }, { "code": null, "e": 26409, "s": 26379, "text": "Example 1: Simple Input Field" }, { "code": null, "e": 26414, "s": 26409, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div class=\"ui container\"> <h2>Simple Text Input Field</h2> <div class=\"ui input\"> <input type=\"text\" placeholder=\"Enter Name\"> </div> </div> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> </body></html>", "e": 26962, "s": 26414, "text": null }, { "code": null, "e": 26972, "s": 26962, "text": "Output: " }, { "code": null, "e": 27016, "s": 26972, "text": "Example 2: Input Field showing data Loading" }, { "code": null, "e": 27021, "s": 27016, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div class=\"ui container\"> <h2>Text Field with Loading Icon</h2> <div class=\"ui icon input loading\"> <input type=\"text\" placeholder=\"Enter School\"> <i class=\"search icon\"></i> </div> </div> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> </body></html>", "e": 27632, "s": 27021, "text": null }, { "code": null, "e": 27642, "s": 27632, "text": "Output: " }, { "code": null, "e": 27732, "s": 27642, "text": "And you can add class ‘ui left icon input loading’ to show that loading icon in the left." }, { "code": null, "e": 27762, "s": 27732, "text": "Example 3: Action Input Field" }, { "code": null, "e": 27767, "s": 27762, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div class=\"ui container\"> <h2>Text Field With Button</h2> <div class=\"ui action input\"> <input type=\"text\" placeholder=\"Search\"> <button class=\"ui button\">Search</button> </div> </div> <br> <div class=\"ui container\"> <h2>Text field with dropdown list and Button</h2> <div class=\"ui action input\"> <input type=\"text\" placeholder=\"Search...\"> <select class=\"ui compact selection dropdown\"> <option value=\"web\">Web</option> <option selected=\"\" value=\"images\">Images</option> <option value=\"videos\">Videos</option> </select> <div class=\"ui button\">Search</div> </div> </div> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> </body></html>", "e": 28925, "s": 27767, "text": null }, { "code": null, "e": 28934, "s": 28925, "text": "Output: " }, { "code": null, "e": 28965, "s": 28934, "text": "Example 4: Labelled Input File" }, { "code": null, "e": 28970, "s": 28965, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div class=\"ui container\"> <h2>Labelled in front.</h2> <div class=\"ui labeled input\"> <div class=\"ui label\"> https:// </div> <input type=\"text\" placeholder=\"geeksforgeeks.com\"> </div> </div> <br> <div class=\"ui container\"> <h2>Labelled in the end.</h2> <div class=\"ui right labeled input\"> <input type=\"text\" placeholder=\"Find domain\"> <div class=\"ui dropdown label\"> <div class=\"text\">.com</div> </div> </div> </div> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> </body></html>", "e": 29982, "s": 28970, "text": null }, { "code": null, "e": 29991, "s": 29982, "text": "Output: " }, { "code": null, "e": 30003, "s": 29991, "text": "Semantic-UI" }, { "code": null, "e": 30007, "s": 30003, "text": "CSS" }, { "code": null, "e": 30024, "s": 30007, "text": "Web Technologies" }, { "code": null, "e": 30122, "s": 30024, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30177, "s": 30122, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 30214, "s": 30177, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 30278, "s": 30214, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 30315, "s": 30278, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30376, "s": 30315, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 30416, "s": 30376, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30449, "s": 30416, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30494, "s": 30449, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30537, "s": 30494, "text": "How to fetch data from an API in ReactJS ?" } ]
LocalTime toString() method in Java with Examples - GeeksforGeeks
06 Dec, 2018 The toString() method of LocalTime class is used to represents this time as a String, such as 20:15:34.111. Following ISO-8601 formats are used for representation: HH:mm HH:mm:ss HH:mm:ss.SSS HH:mm:ss.SSSSSS HH:mm:ss.SSSSSSSSS This method is derived from the Object Class and behaves in a similar way. Syntax: public String toString() Parameters: This method accepts no parameter. Return value: This method returns a String representation of this LocalTime. Below programs illustrate the toString() method: Program 1: // Java program to demonstrate// LocalTime.toString() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime object LocalTime time = LocalTime.parse("19:34:50.63"); // print LocalTime System.out.println("LocalTime : " + time.toString()); }} LocalTime : 19:34:50.630 Program 2: // Java program to demonstrate// LocalTime.toString() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime object LocalTime time = LocalTime.parse("01:00:01"); // print LocalTime System.out.println("Old LocalTime: " + time.toString()); // add 600 Minutes using plusMinutes() LocalTime value = time.plusMinutes(600); // print result System.out.println("New LocalTime: " + value.toString()); }} Old LocalTime: 01:00:01 New LocalTime: 11:00:01 References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#toString() Java-Functions Java-LocalTime Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 25505, "s": 25477, "text": "\n06 Dec, 2018" }, { "code": null, "e": 25613, "s": 25505, "text": "The toString() method of LocalTime class is used to represents this time as a String, such as 20:15:34.111." }, { "code": null, "e": 25669, "s": 25613, "text": "Following ISO-8601 formats are used for representation:" }, { "code": null, "e": 25675, "s": 25669, "text": "HH:mm" }, { "code": null, "e": 25684, "s": 25675, "text": "HH:mm:ss" }, { "code": null, "e": 25697, "s": 25684, "text": "HH:mm:ss.SSS" }, { "code": null, "e": 25713, "s": 25697, "text": "HH:mm:ss.SSSSSS" }, { "code": null, "e": 25732, "s": 25713, "text": "HH:mm:ss.SSSSSSSSS" }, { "code": null, "e": 25807, "s": 25732, "text": "This method is derived from the Object Class and behaves in a similar way." }, { "code": null, "e": 25815, "s": 25807, "text": "Syntax:" }, { "code": null, "e": 25841, "s": 25815, "text": "public String toString()\n" }, { "code": null, "e": 25887, "s": 25841, "text": "Parameters: This method accepts no parameter." }, { "code": null, "e": 25964, "s": 25887, "text": "Return value: This method returns a String representation of this LocalTime." }, { "code": null, "e": 26013, "s": 25964, "text": "Below programs illustrate the toString() method:" }, { "code": null, "e": 26024, "s": 26013, "text": "Program 1:" }, { "code": "// Java program to demonstrate// LocalTime.toString() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime object LocalTime time = LocalTime.parse(\"19:34:50.63\"); // print LocalTime System.out.println(\"LocalTime : \" + time.toString()); }}", "e": 26399, "s": 26024, "text": null }, { "code": null, "e": 26425, "s": 26399, "text": "LocalTime : 19:34:50.630\n" }, { "code": null, "e": 26436, "s": 26425, "text": "Program 2:" }, { "code": "// Java program to demonstrate// LocalTime.toString() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime object LocalTime time = LocalTime.parse(\"01:00:01\"); // print LocalTime System.out.println(\"Old LocalTime: \" + time.toString()); // add 600 Minutes using plusMinutes() LocalTime value = time.plusMinutes(600); // print result System.out.println(\"New LocalTime: \" + value.toString()); }}", "e": 27023, "s": 26436, "text": null }, { "code": null, "e": 27072, "s": 27023, "text": "Old LocalTime: 01:00:01\nNew LocalTime: 11:00:01\n" }, { "code": null, "e": 27163, "s": 27072, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#toString()" }, { "code": null, "e": 27178, "s": 27163, "text": "Java-Functions" }, { "code": null, "e": 27193, "s": 27178, "text": "Java-LocalTime" }, { "code": null, "e": 27211, "s": 27193, "text": "Java-time package" }, { "code": null, "e": 27216, "s": 27211, "text": "Java" }, { "code": null, "e": 27221, "s": 27216, "text": "Java" }, { "code": null, "e": 27319, "s": 27221, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27349, "s": 27319, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27368, "s": 27349, "text": "Interfaces in Java" }, { "code": null, "e": 27383, "s": 27368, "text": "Stream In Java" }, { "code": null, "e": 27414, "s": 27383, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27432, "s": 27414, "text": "ArrayList in Java" }, { "code": null, "e": 27464, "s": 27432, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27484, "s": 27464, "text": "Stack Class in Java" }, { "code": null, "e": 27516, "s": 27484, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27540, "s": 27516, "text": "Singleton Class in Java" } ]
varchar, varchar(max) and nvarchar in MS SQL Server - GeeksforGeeks
03 Sep, 2020 We know that a database can different datatypes. Consider an organization having various databases like Employees, Departments, Finance. The employee database has a table that stores the details of each employee and employee is uniquely identified using the employee ID. In most of the cases, an employee ID has a combination of digits and letters. How can the database store the values? It uses a special datatype named varchar or Variable Character datatype. It uses numbers and letters. varchar :Variable Character or varchar for short is a datatype that stores non-Unicode data.The syntax for varchar is:Syntax :varchar (n) n – is the number of bytes. The maximum storage capacity is upto 8000 bytes.varchar(max) :It stores character string data of maximum storage size 231-1 bytes.Syntax :varchar(max) nvarchar :This stores variable length unicode data.Syntax for nvarchar is:Syntax :nvarchar n – is the number of bytes and can store upto 4000 bytes. If the length for the datatype isn’t specified, it takes the default value of 1. These datatypes can be used while creating a table. varchar :Variable Character or varchar for short is a datatype that stores non-Unicode data.The syntax for varchar is:Syntax :varchar (n) n – is the number of bytes. The maximum storage capacity is upto 8000 bytes. varchar (n) n – is the number of bytes. The maximum storage capacity is upto 8000 bytes. varchar(max) :It stores character string data of maximum storage size 231-1 bytes.Syntax :varchar(max) Syntax : varchar(max) nvarchar :This stores variable length unicode data.Syntax for nvarchar is:Syntax :nvarchar n – is the number of bytes and can store upto 4000 bytes. If the length for the datatype isn’t specified, it takes the default value of 1. These datatypes can be used while creating a table. nvarchar n – is the number of bytes and can store upto 4000 bytes. If the length for the datatype isn’t specified, it takes the default value of 1. These datatypes can be used while creating a table. An overview of these datatypes : *n is the number of bytes *max is the maximum storage value. *n is the number of bytes. DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? Difference between DDL and DML in DBMS SQL | Views Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE SQL - ORDER BY SQL | Subquery
[ { "code": null, "e": 25161, "s": 25133, "text": "\n03 Sep, 2020" }, { "code": null, "e": 25432, "s": 25161, "text": "We know that a database can different datatypes. Consider an organization having various databases like Employees, Departments, Finance. The employee database has a table that stores the details of each employee and employee is uniquely identified using the employee ID." }, { "code": null, "e": 25651, "s": 25432, "text": "In most of the cases, an employee ID has a combination of digits and letters. How can the database store the values? It uses a special datatype named varchar or Variable Character datatype. It uses numbers and letters." }, { "code": null, "e": 26250, "s": 25651, "text": "varchar :Variable Character or varchar for short is a datatype that stores non-Unicode data.The syntax for varchar is:Syntax :varchar (n)\nn – is the number of bytes. The maximum storage capacity is upto 8000 bytes.varchar(max) :It stores character string data of maximum storage size 231-1 bytes.Syntax :varchar(max)\nnvarchar :This stores variable length unicode data.Syntax for nvarchar is:Syntax :nvarchar\nn – is the number of bytes and can store upto 4000 bytes. If the length for the datatype isn’t specified, it takes the default value of 1. These datatypes can be used while creating a table." }, { "code": null, "e": 26465, "s": 26250, "text": "varchar :Variable Character or varchar for short is a datatype that stores non-Unicode data.The syntax for varchar is:Syntax :varchar (n)\nn – is the number of bytes. The maximum storage capacity is upto 8000 bytes." }, { "code": null, "e": 26478, "s": 26465, "text": "varchar (n)\n" }, { "code": null, "e": 26555, "s": 26478, "text": "n – is the number of bytes. The maximum storage capacity is upto 8000 bytes." }, { "code": null, "e": 26659, "s": 26555, "text": "varchar(max) :It stores character string data of maximum storage size 231-1 bytes.Syntax :varchar(max)\n" }, { "code": null, "e": 26668, "s": 26659, "text": "Syntax :" }, { "code": null, "e": 26682, "s": 26668, "text": "varchar(max)\n" }, { "code": null, "e": 26964, "s": 26682, "text": "nvarchar :This stores variable length unicode data.Syntax for nvarchar is:Syntax :nvarchar\nn – is the number of bytes and can store upto 4000 bytes. If the length for the datatype isn’t specified, it takes the default value of 1. These datatypes can be used while creating a table." }, { "code": null, "e": 26974, "s": 26964, "text": "nvarchar\n" }, { "code": null, "e": 27165, "s": 26974, "text": "n – is the number of bytes and can store upto 4000 bytes. If the length for the datatype isn’t specified, it takes the default value of 1. These datatypes can be used while creating a table." }, { "code": null, "e": 27198, "s": 27165, "text": "An overview of these datatypes :" }, { "code": null, "e": 27224, "s": 27198, "text": "*n is the number of bytes" }, { "code": null, "e": 27259, "s": 27224, "text": "*max is the maximum storage value." }, { "code": null, "e": 27286, "s": 27259, "text": "*n is the number of bytes." }, { "code": null, "e": 27295, "s": 27286, "text": "DBMS-SQL" }, { "code": null, "e": 27306, "s": 27295, "text": "SQL-Server" }, { "code": null, "e": 27310, "s": 27306, "text": "SQL" }, { "code": null, "e": 27314, "s": 27310, "text": "SQL" }, { "code": null, "e": 27412, "s": 27314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27436, "s": 27412, "text": "SQL Interview Questions" }, { "code": null, "e": 27447, "s": 27436, "text": "CTE in SQL" }, { "code": null, "e": 27513, "s": 27447, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27552, "s": 27513, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 27564, "s": 27552, "text": "SQL | Views" }, { "code": null, "e": 27609, "s": 27564, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 27641, "s": 27609, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 27680, "s": 27641, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 27695, "s": 27680, "text": "SQL - ORDER BY" } ]
Find the number of ways to divide number into four parts such that a = c and b = d - GeeksforGeeks
09 Nov, 2021 Given a number N. Find the number of ways to divide a number into four parts(a, b, c, d) such that a = c and b = d and a not equal to b. Examples: Input : N = 6 Output : 1 Explanation : four parts are {1, 2, 1, 2}Input : N = 20 Output : 4 Explanation : possible ways are {1, 1, 9, 9}, {2, 2, 8, 8}, {3, 3, 7, 7} and {4, 4, 6, 6}. Approach : If the given N is odd the answer is 0, because the sum of four parts will not be even number.If n is divisible by 4 then answer will be n/4 -1(here a equals to b can be possible so subtract that possibility) otherwise n/4.Below is the implementation of the above approach : C++ Java Python3 C# PHP Javascript // C++ implementation for above approach#include <bits/stdc++.h>using namespace std; // Function to find the number of ways to divide// N into four parts such that a = c and b = dint possibleways(int n){ if (n % 2 == 1) return 0; else if (n % 4 == 0) return n / 4 - 1; else return n / 4;} // Driver codeint main(){ int n = 20; cout << possibleways(n); return 0;} // Java implementation for above approachclass GFG{ // Function to find the number of ways to divide// N into four parts such that a = c and b = dstatic int possibleways(int n){ if (n % 2 == 1) return 0; else if (n % 4 == 0) return n / 4 - 1; else return n / 4;} // Driver codepublic static void main(String[] args){ int n = 20; System.out.println(possibleways(n));}} // This code contributed by Rajput-Ji # Python3 implementation for above approach # Function to find the number of ways# to divide N into four parts# such that a = c and b = ddef possibleways(n): if (n % 2 == 1): return 0; elif (n % 4 == 0): return n // 4 - 1; else: return n // 4; # Driver coden = 20;print(possibleways(n)); # This code is contributed by mits // C# implementation for above approachclass GFG{ // Function to find the number of ways to divide// N into four parts such that a = c and b = dstatic int possibleways(int n){ if (n % 2 == 1) return 0; else if (n % 4 == 0) return n / 4 - 1; else return n / 4;} // Driver codestatic void Main(){ int n = 20; System.Console.WriteLine(possibleways(n));}} // This code is contributed by mits <?php// PHP implementation for above approach // Function to find the number of ways to divide// N into four parts such that a = c and b = dfunction possibleways($n){ if ($n % 2 == 1) return 0; else if ($n % 4 == 0) return $n / 4 - 1; else return $n / 4;} // Driver code$n = 20;echo possibleways($n); // This code is contributed by ajit?> <script>// java script implementation for above approach // Function to find the number of ways to divide// N into four parts such that a = c and b = dfunction possibleways(n){ if (n % 2 == 1) return 0; else if (n % 4 == 0) return n / 4 - 1; else return n / 4;} // Driver codelet n = 20;document.write( possibleways(n)); // This code is contributed by Gottumukkala Bobby</script> Time Complexity: O(1) Auxiliary Space: O(1) Mithun Kumar Rajput-Ji jit_t gottumukkalabobby ruhelaa48 rohitkumarsinghcna Competitive Programming Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multistage Graph (Shortest Path) Breadth First Traversal ( BFS ) on a 2D array Shortest path in a directed graph by Dijkstra’s algorithm 5 Best Books for Competitive Programming 5 Best Languages for Competitive Programming Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26333, "s": 26305, "text": "\n09 Nov, 2021" }, { "code": null, "e": 26481, "s": 26333, "text": "Given a number N. Find the number of ways to divide a number into four parts(a, b, c, d) such that a = c and b = d and a not equal to b. Examples: " }, { "code": null, "e": 26664, "s": 26481, "text": "Input : N = 6 Output : 1 Explanation : four parts are {1, 2, 1, 2}Input : N = 20 Output : 4 Explanation : possible ways are {1, 1, 9, 9}, {2, 2, 8, 8}, {3, 3, 7, 7} and {4, 4, 6, 6}." }, { "code": null, "e": 26951, "s": 26664, "text": "Approach : If the given N is odd the answer is 0, because the sum of four parts will not be even number.If n is divisible by 4 then answer will be n/4 -1(here a equals to b can be possible so subtract that possibility) otherwise n/4.Below is the implementation of the above approach : " }, { "code": null, "e": 26955, "s": 26951, "text": "C++" }, { "code": null, "e": 26960, "s": 26955, "text": "Java" }, { "code": null, "e": 26968, "s": 26960, "text": "Python3" }, { "code": null, "e": 26971, "s": 26968, "text": "C#" }, { "code": null, "e": 26975, "s": 26971, "text": "PHP" }, { "code": null, "e": 26986, "s": 26975, "text": "Javascript" }, { "code": "// C++ implementation for above approach#include <bits/stdc++.h>using namespace std; // Function to find the number of ways to divide// N into four parts such that a = c and b = dint possibleways(int n){ if (n % 2 == 1) return 0; else if (n % 4 == 0) return n / 4 - 1; else return n / 4;} // Driver codeint main(){ int n = 20; cout << possibleways(n); return 0;}", "e": 27388, "s": 26986, "text": null }, { "code": "// Java implementation for above approachclass GFG{ // Function to find the number of ways to divide// N into four parts such that a = c and b = dstatic int possibleways(int n){ if (n % 2 == 1) return 0; else if (n % 4 == 0) return n / 4 - 1; else return n / 4;} // Driver codepublic static void main(String[] args){ int n = 20; System.out.println(possibleways(n));}} // This code contributed by Rajput-Ji", "e": 27834, "s": 27388, "text": null }, { "code": "# Python3 implementation for above approach # Function to find the number of ways# to divide N into four parts# such that a = c and b = ddef possibleways(n): if (n % 2 == 1): return 0; elif (n % 4 == 0): return n // 4 - 1; else: return n // 4; # Driver coden = 20;print(possibleways(n)); # This code is contributed by mits", "e": 28188, "s": 27834, "text": null }, { "code": "// C# implementation for above approachclass GFG{ // Function to find the number of ways to divide// N into four parts such that a = c and b = dstatic int possibleways(int n){ if (n % 2 == 1) return 0; else if (n % 4 == 0) return n / 4 - 1; else return n / 4;} // Driver codestatic void Main(){ int n = 20; System.Console.WriteLine(possibleways(n));}} // This code is contributed by mits", "e": 28616, "s": 28188, "text": null }, { "code": "<?php// PHP implementation for above approach // Function to find the number of ways to divide// N into four parts such that a = c and b = dfunction possibleways($n){ if ($n % 2 == 1) return 0; else if ($n % 4 == 0) return $n / 4 - 1; else return $n / 4;} // Driver code$n = 20;echo possibleways($n); // This code is contributed by ajit?>", "e": 28985, "s": 28616, "text": null }, { "code": "<script>// java script implementation for above approach // Function to find the number of ways to divide// N into four parts such that a = c and b = dfunction possibleways(n){ if (n % 2 == 1) return 0; else if (n % 4 == 0) return n / 4 - 1; else return n / 4;} // Driver codelet n = 20;document.write( possibleways(n)); // This code is contributed by Gottumukkala Bobby</script>", "e": 29396, "s": 28985, "text": null }, { "code": null, "e": 29418, "s": 29396, "text": "Time Complexity: O(1)" }, { "code": null, "e": 29440, "s": 29418, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 29453, "s": 29440, "text": "Mithun Kumar" }, { "code": null, "e": 29463, "s": 29453, "text": "Rajput-Ji" }, { "code": null, "e": 29469, "s": 29463, "text": "jit_t" }, { "code": null, "e": 29487, "s": 29469, "text": "gottumukkalabobby" }, { "code": null, "e": 29497, "s": 29487, "text": "ruhelaa48" }, { "code": null, "e": 29516, "s": 29497, "text": "rohitkumarsinghcna" }, { "code": null, "e": 29540, "s": 29516, "text": "Competitive Programming" }, { "code": null, "e": 29553, "s": 29540, "text": "Mathematical" }, { "code": null, "e": 29572, "s": 29553, "text": "School Programming" }, { "code": null, "e": 29585, "s": 29572, "text": "Mathematical" }, { "code": null, "e": 29683, "s": 29585, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29716, "s": 29683, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 29762, "s": 29716, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 29820, "s": 29762, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 29861, "s": 29820, "text": "5 Best Books for Competitive Programming" }, { "code": null, "e": 29906, "s": 29861, "text": "5 Best Languages for Competitive Programming" }, { "code": null, "e": 29936, "s": 29906, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29996, "s": 29936, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 30011, "s": 29996, "text": "C++ Data Types" }, { "code": null, "e": 30054, "s": 30011, "text": "Set in C++ Standard Template Library (STL)" } ]
GATE | GATE CS 2010 | Question 28 - GeeksforGeeks
15 Nov, 2018 The degree sequence of a simple graph is the sequence of the degrees of the nodes in the graph in decreasing order. Which of the following sequences can not be the degree sequence of any graph? (I) 7, 6, 5, 4, 4, 3, 2, 1 (II) 6, 6, 6, 6, 3, 3, 2, 2 (III) 7, 6, 6, 4, 4, 3, 2, 2 (IV) 8, 7, 7, 6, 4, 2, 1, 1 (A) I and II(B) III and IV(C) IV only(D) II and IVAnswer: (D)Explanation: A generic algorithm or method to solve this question is 1: procedure isV alidDegreeSequence(L) 2: for n in list L do 3: if L doesn’t have n elements next to the current one then return false 4: decrement next n elements of the list by 1 5: arrange it back as a degree sequence, i.e. in descending order 6: if any element of the list becomes negative then return false 7: return true Rationale behind this method comes from the properties of simple graph. Enumerating the f alse returns, 1) if L doesn’t have enough elements after the current one or 2) if any element of the list becomes negative, then it means that there aren’t enough nodes to accommodate edges in a simple graph fashion, which will lead to violation of either of the two conditions of the simple graph (no self-loops and no multiple-edges between two nodes), if not others. See https://www.geeksforgeeks.org/data-structures-and-algorithms-set-25/ This solution is contributed by Vineet Purswani. Another one: A degree sequence d1,d2,d2. . . dn of non negative integer is graphical if it is a degree sequence of a graph. We now introduce a powerful tool to determine whether a particular sequence is graphical due to Havel and Hakimi Havel–Hakimi Theorem : → According to this theorem, Let D be sequence the d1,d2,d2. . . dn with d1 ≥ d2 ≥ d2 ≥ . . . dn for n≥ 2 and di ≥ 0. → Then D0 be the sequence obtained by: → Discarding d1, and→ Subtracting 1 from each of the next d1 entries of D.→ That is Degree sequence D0 would be : d2-1, d2-1, d3-1 . . . , dd1+1 -1 . . . , dn→ Then, D is graphical if and only if D0 is graphical. Now, we apply this theorem to given sequences: option I) 7,6,5,4,4,3,2,1 → 5,4,3,3,2,1,0 → 3,2,2,1,0,0 → 1,1,0,0,0 → 0,0,0,0 so its graphical. Option II) 6,6,6,6,3,3,2,2 → 5,5,5,2,2,1,2 ( arrange in ascending order) → 5,5,5,2,2,2,1 → 4,4,1,1,1,0 → 3,0,0,0,0 → 2,-1,-1,-1,0 but d (degree of a vertex) is non negative so its not a graphical. Option III) 7,6,6,4,4,3,2,2 → 5,5,3,3,2,1,1 → 4,2,2,1,1,0 → 1,1,0,0,0 → 0,0,0,0 so its graphical. Option IV) 8,7,7,6,4,2,1,1 , here degree of a vertex is 8 and total number of vertices are 8 , so it’s impossible, hence it’s not graphical. Hence only option I) and III) are graphic sequence and answer is option-D This solution is contributed by Nirmal Bharadwaj.Quiz of this Question GATE-CS-2010 GATE-GATE CS 2010 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25771, "s": 25743, "text": "\n15 Nov, 2018" }, { "code": null, "e": 25965, "s": 25771, "text": "The degree sequence of a simple graph is the sequence of the degrees of the nodes in the graph in decreasing order. Which of the following sequences can not be the degree sequence of any graph?" }, { "code": null, "e": 26078, "s": 25965, "text": "(I) 7, 6, 5, 4, 4, 3, 2, 1\n(II) 6, 6, 6, 6, 3, 3, 2, 2\n(III) 7, 6, 6, 4, 4, 3, 2, 2\n(IV) 8, 7, 7, 6, 4, 2, 1, 1 " }, { "code": null, "e": 26208, "s": 26078, "text": "(A) I and II(B) III and IV(C) IV only(D) II and IVAnswer: (D)Explanation: A generic algorithm or method to solve this question is" }, { "code": null, "e": 26247, "s": 26208, "text": "1: procedure isV alidDegreeSequence(L)" }, { "code": null, "e": 26269, "s": 26247, "text": "2: for n in list L do" }, { "code": null, "e": 26343, "s": 26269, "text": "3: if L doesn’t have n elements next to the current one then return false" }, { "code": null, "e": 26389, "s": 26343, "text": "4: decrement next n elements of the list by 1" }, { "code": null, "e": 26455, "s": 26389, "text": "5: arrange it back as a degree sequence, i.e. in descending order" }, { "code": null, "e": 26520, "s": 26455, "text": "6: if any element of the list becomes negative then return false" }, { "code": null, "e": 26535, "s": 26520, "text": "7: return true" }, { "code": null, "e": 26995, "s": 26535, "text": "Rationale behind this method comes from the properties of simple graph. Enumerating the f alse returns, 1) if L doesn’t have enough elements after the current one or 2) if any element of the list becomes negative, then it means that there aren’t enough nodes to accommodate edges in a simple graph fashion, which will lead to violation of either of the two conditions of the simple graph (no self-loops and no multiple-edges between two nodes), if not others." }, { "code": null, "e": 27068, "s": 26995, "text": "See https://www.geeksforgeeks.org/data-structures-and-algorithms-set-25/" }, { "code": null, "e": 27117, "s": 27068, "text": "This solution is contributed by Vineet Purswani." }, { "code": null, "e": 27130, "s": 27117, "text": "Another one:" }, { "code": null, "e": 27354, "s": 27130, "text": "A degree sequence d1,d2,d2. . . dn of non negative integer is graphical if it is a degree sequence of a graph. We now introduce a powerful tool to determine whether a particular sequence is graphical due to Havel and Hakimi" }, { "code": null, "e": 27377, "s": 27354, "text": "Havel–Hakimi Theorem :" }, { "code": null, "e": 27495, "s": 27377, "text": "→ According to this theorem, Let D be sequence the d1,d2,d2. . . dn with d1 ≥ d2 ≥ d2 ≥ . . . dn for n≥ 2 and di ≥ 0." }, { "code": null, "e": 27534, "s": 27495, "text": "→ Then D0 be the sequence obtained by:" }, { "code": null, "e": 27747, "s": 27534, "text": "→ Discarding d1, and→ Subtracting 1 from each of the next d1 entries of D.→ That is Degree sequence D0 would be : d2-1, d2-1, d3-1 . . . , dd1+1 -1 . . . , dn→ Then, D is graphical if and only if D0 is graphical." }, { "code": null, "e": 27794, "s": 27747, "text": "Now, we apply this theorem to given sequences:" }, { "code": null, "e": 27890, "s": 27794, "text": "option I) 7,6,5,4,4,3,2,1 → 5,4,3,3,2,1,0 → 3,2,2,1,0,0 → 1,1,0,0,0 → 0,0,0,0 so its graphical." }, { "code": null, "e": 28087, "s": 27890, "text": "Option II) 6,6,6,6,3,3,2,2 → 5,5,5,2,2,1,2 ( arrange in ascending order) → 5,5,5,2,2,2,1 → 4,4,1,1,1,0 → 3,0,0,0,0 → 2,-1,-1,-1,0 but d (degree of a vertex) is non negative so its not a graphical." }, { "code": null, "e": 28185, "s": 28087, "text": "Option III) 7,6,6,4,4,3,2,2 → 5,5,3,3,2,1,1 → 4,2,2,1,1,0 → 1,1,0,0,0 → 0,0,0,0 so its graphical." }, { "code": null, "e": 28326, "s": 28185, "text": "Option IV) 8,7,7,6,4,2,1,1 , here degree of a vertex is 8 and total number of vertices are 8 , so it’s impossible, hence it’s not graphical." }, { "code": null, "e": 28400, "s": 28326, "text": "Hence only option I) and III) are graphic sequence and answer is option-D" }, { "code": null, "e": 28471, "s": 28400, "text": "This solution is contributed by Nirmal Bharadwaj.Quiz of this Question" }, { "code": null, "e": 28484, "s": 28471, "text": "GATE-CS-2010" }, { "code": null, "e": 28502, "s": 28484, "text": "GATE-GATE CS 2010" }, { "code": null, "e": 28507, "s": 28502, "text": "GATE" }, { "code": null, "e": 28605, "s": 28507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28639, "s": 28605, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 28673, "s": 28639, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 28707, "s": 28673, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 28740, "s": 28707, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 28776, "s": 28740, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 28810, "s": 28776, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 28846, "s": 28810, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 28880, "s": 28846, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 28914, "s": 28880, "text": "GATE | GATE-CS-2009 | Question 38" } ]
jQuery | delay() with Examples - GeeksforGeeks
13 Feb, 2019 The delay() is an inbuilt method in jQuery which is used to set a timer to delay the execution of the next item in the queue.Syntax: $(selector).delay(para1, para2); Parameter: It accepts two parameters which are specified below- para1: It specifies the speed of the delay. para2: It is optional and specifies the name of the queue. Return Value: It returns the selected element with the specified speed. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script> <!-- jquery code to demonstrate delay method --> $(document).ready(function() { $("button").click(function() { $("#d1").delay("slow").fadeIn(); $("#d2").delay("fast").fadeIn(); $("#d3").delay(1000).fadeIn(); $("#d4").delay(4000).fadeIn(); }); }); </script></head> <body> <!-- click on this button --> <button>Click Me!</button> <br> <br> <div id="d1" style="width:50px;height:50px;display: none;background-color:lightgreen;"></div> <br> <div id="d2" style="width:50px;height:50px;display: none;background-color:green;"></div> <br> <div id="d3" style="width:50px;height:50px;display: none;background-color:orange;"></div> <br> <div id="d4" style="width:50px;height:50px;display: none;background-color:yellow;"></div> <br></body> </html> Output:Before clicking the “Click Me” button-After clicking the “Click Me” button- Code #2:In the below code, It has been shown that how to delay an animation using this method. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { <!-- jQuery code to show the working of delay method --> $("#btn1").click(function() { $("div").animate({ height: "150px" }); $("div").animate({ width: "150px" }); $("div").delay(1200).animate({ width: "300px", padding: "30px" }); }); }); </script> <style> #d { display: block; width: 200px; height: 100px; background-color: green; font-size: 30px; padding: 10px; } </style></head> <body> <div id="d">GeeksforGeeks !</div><!--click on this button to show the effect of delay method --> <p> <button id="btn1">Click Me!</button> </p></body> </html> Output:Before clicking the “Click Me” button-After clicking the “Click Me” button- jQuery-Effects JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? 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 change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 41968, "s": 41940, "text": "\n13 Feb, 2019" }, { "code": null, "e": 42101, "s": 41968, "text": "The delay() is an inbuilt method in jQuery which is used to set a timer to delay the execution of the next item in the queue.Syntax:" }, { "code": null, "e": 42135, "s": 42101, "text": "$(selector).delay(para1, para2);\n" }, { "code": null, "e": 42199, "s": 42135, "text": "Parameter: It accepts two parameters which are specified below-" }, { "code": null, "e": 42243, "s": 42199, "text": "para1: It specifies the speed of the delay." }, { "code": null, "e": 42302, "s": 42243, "text": "para2: It is optional and specifies the name of the queue." }, { "code": null, "e": 42374, "s": 42302, "text": "Return Value: It returns the selected element with the specified speed." }, { "code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script> <!-- jquery code to demonstrate delay method --> $(document).ready(function() { $(\"button\").click(function() { $(\"#d1\").delay(\"slow\").fadeIn(); $(\"#d2\").delay(\"fast\").fadeIn(); $(\"#d3\").delay(1000).fadeIn(); $(\"#d4\").delay(4000).fadeIn(); }); }); </script></head> <body> <!-- click on this button --> <button>Click Me!</button> <br> <br> <div id=\"d1\" style=\"width:50px;height:50px;display: none;background-color:lightgreen;\"></div> <br> <div id=\"d2\" style=\"width:50px;height:50px;display: none;background-color:green;\"></div> <br> <div id=\"d3\" style=\"width:50px;height:50px;display: none;background-color:orange;\"></div> <br> <div id=\"d4\" style=\"width:50px;height:50px;display: none;background-color:yellow;\"></div> <br></body> </html>", "e": 43453, "s": 42374, "text": null }, { "code": null, "e": 43536, "s": 43453, "text": "Output:Before clicking the “Click Me” button-After clicking the “Click Me” button-" }, { "code": null, "e": 43631, "s": 43536, "text": "Code #2:In the below code, It has been shown that how to delay an animation using this method." }, { "code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script> $(document).ready(function() { <!-- jQuery code to show the working of delay method --> $(\"#btn1\").click(function() { $(\"div\").animate({ height: \"150px\" }); $(\"div\").animate({ width: \"150px\" }); $(\"div\").delay(1200).animate({ width: \"300px\", padding: \"30px\" }); }); }); </script> <style> #d { display: block; width: 200px; height: 100px; background-color: green; font-size: 30px; padding: 10px; } </style></head> <body> <div id=\"d\">GeeksforGeeks !</div><!--click on this button to show the effect of delay method --> <p> <button id=\"btn1\">Click Me!</button> </p></body> </html>", "e": 44660, "s": 43631, "text": null }, { "code": null, "e": 44743, "s": 44660, "text": "Output:Before clicking the “Click Me” button-After clicking the “Click Me” button-" }, { "code": null, "e": 44758, "s": 44743, "text": "jQuery-Effects" }, { "code": null, "e": 44769, "s": 44758, "text": "JavaScript" }, { "code": null, "e": 44776, "s": 44769, "text": "JQuery" }, { "code": null, "e": 44874, "s": 44776, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44914, "s": 44874, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 44959, "s": 44914, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 45020, "s": 44959, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 45092, "s": 45020, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 45161, "s": 45092, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 45207, "s": 45161, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 45236, "s": 45207, "text": "Form validation using jQuery" }, { "code": null, "e": 45299, "s": 45236, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 45376, "s": 45299, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
Find the first and last M digits from K-th power of N - GeeksforGeeks
26 May, 2021 Given a two integers N and K, the task is to find the first M and last M digits of the number NK .Examples: Input: N = 2345, K = 3, M = 3 Output: 128 625 Explanation: 2345 3 = 12895213625 Therefore, the first M(= 3) digits are 128 and the last three digits are 625.Input: N = 12, K = 12, M = 4 Output: 8916 8256 Explanation: 12 12 = 8916100448256 Naive Approach: The simplest approach to solve the problem is to calculate the value of NK and iterate to first M digits and find the last M digits by NK mod 10M. Time Complexity: O(K) Auxiliary Space: O(1)Efficient Approach: The above approach can be optimized by the following observation: Let us consider a number x which can be written as 10y Where y is a decimal number. Let x = NKNK = 10 y Taking log10 on both sides of the above expression, we get: K * log10(N) = log10(10 y) => K * log10(N) = y * (log1010) => y = K * log10(N)Now y will be a decimal number of form abc—.xyz— Therefore, NK = 10abc—.xyz— => NK = 10abc— + 0.xyz— => NK = 10abc— * 100.xyz— In the above equation, 10abc— only moves the decimal point forward. By calculating 100.xyz—, the first M digits can be figured out by moving the decimal point forward. Follow the steps below to solve the problem: Find the first M digits of NK by calculating (NK)mod(10M). Calculate K * log10(N). Calculate 10K * log10(N). Find the first M digits by calculating 10K * log10(N) * 10M – 1 . Print the first and last M digits obtained. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement// the above approach#include <bits/stdc++.h>#define ll long long intusing namespace std; // Function to find a^b modulo Mll modPower(ll a, ll b, ll M){ ll res = 1; while (b) { if (b & 1) res = res * a % M; a = a * a % M; b >>= 1; } return res;} // Function to find the first and last// M digits from N^Kvoid findFirstAndLastM(ll N, ll K, ll M){ // Calculate Last M digits ll lastM = modPower(N, K, (1LL) * pow(10, M)); // Calculate First M digits ll firstM; double y = (double)K * log10(N * 1.0); // Extract the number after decimal y = y - (ll)y; // Find 10 ^ y double temp = pow(10.0, y); // Move the Decimal Point M - 1 digits forward firstM = temp * (1LL) * pow(10, M - 1); // Print the result cout << firstM << " " << lastM << endl;} // Driver Codeint main(){ ll N = 12, K = 12, M = 4; findFirstAndLastM(N, K, M); return 0;} // Java program to implement// the above approachclass GFG{ // Function to find a^b modulo Mstatic long modPower(long a, long b, long M){ long res = 1; while (b > 0) { if (b % 2 == 1) res = res * a % M; a = a * a % M; b >>= 1; } return res;} // Function to find the first and last// M digits from N^Kstatic void findFirstAndLastM(long N, long K, long M){ // Calculate Last M digits long lastM = modPower(N, K, (1L) * (long)Math.pow(10, M)); // Calculate First M digits long firstM; double y = (double)K * Math.log10(N * 1.0); // Extract the number after decimal y = y - (long)y; // Find 10 ^ y double temp = Math.pow(10.0, y); // Move the Decimal Point M - 1 digits forward firstM = (long)(temp * (1L) * Math.pow(10, (M - 1))); // Print the result System.out.print(firstM + " " + lastM + "\n");} // Driver Codepublic static void main(String[] args){ long N = 12, K = 12, M = 4; findFirstAndLastM(N, K, M);}} // This code is contributed by Rajput-Ji # Python3 program to implement# the above approachfrom math import * # Function to find a^b modulo Mdef modPower(a, b, M): res = 1 while (b): if (b & 1): res = res * a % M a = a * a % M b >>= 1 return res # Function to find the first and# last M digits from N^Kdef findFirstAndLastM(N, K, M): # Calculate Last M digits lastM = modPower(N, K, int(pow(10, M))) # Calculate First M digits firstM = 0 y = K * log10(N * 1.0) # Extract the number after decimal y = y - int(y) # Find 10 ^ y temp = pow(10.0, y) # Move the Decimal Point M - 1 # digits forward firstM = int(temp * pow(10, M - 1)) # Print the result print(firstM, lastM) # Driver CodeN = 12K = 12M = 4 findFirstAndLastM(N, K, M) # This code is contributed by himanshu77 // C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find a^b modulo Mstatic long modPower(long a, long b, long M){ long res = 1; while (b > 0) { if (b % 2 == 1) res = res * a % M; a = a * a % M; b >>= 1; } return res;} // Function to find the first and last// M digits from N^Kstatic void findFirstAndLastM(long N, long K, long M){ // Calculate Last M digits long lastM = modPower(N, K, (1L) * (long)Math.Pow(10, M)); // Calculate First M digits long firstM; double y = (double)K * Math.Log10(N * 1.0); // Extract the number after decimal y = y - (long)y; // Find 10 ^ y double temp = Math.Pow(10.0, y); // Move the Decimal Point M - 1 digits forward firstM = (long)(temp * (1L) * Math.Pow(10, (M - 1))); // Print the result Console.Write(firstM + " " + lastM + "\n");} // Driver Codepublic static void Main(String[] args){ long N = 12, K = 12, M = 4; findFirstAndLastM(N, K, M);}} // This code is contributed by gauravrajput1 <script> // JavaScript Program to implement// the above approach // Function to find a^b modulo Mfunction modPower(a, b, M){ var res = 1; while (b) { if (b & 1) res = res * a % M; a = a * a % M; b >>= 1; } return res;} // Function to find the first and last// M digits from N^Kfunction findFirstAndLastM(N, K, M){ // Calculate Last M digits var lastM = modPower(N, K, Math.pow(10, M)); // Calculate First M digits var firstM; var y = K * Math.log10(N * 1.0); // Extract the number after decimal y = y - parseInt(y); // Find 10 ^ y var temp = Math.pow(10.0, y); // Move the Decimal Point M - 1 digits forward firstM = temp * Math.pow(10, M - 1); // Print the result document.write( parseInt(firstM) + " " + parseInt(lastM) );} // Driver Codevar N = 12, K = 12, M = 4;findFirstAndLastM(N, K, M); </script> 8916 8256 Time Complexity: O(log K) Auxiliary Space: O(1) Rajput-Ji GauravRajput1 himanshu77 itsok maths-power Modular Arithmetic number-digits Mathematical Mathematical Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Check if a number is Palindrome Generate all permutation of a set in Python Program to multiply two matrices Segment Tree | Set 1 (Sum of given range) How to check if a given point lies inside or outside a polygon? Merge two sorted arrays with O(1) extra space Count ways to reach the n'th stair
[ { "code": null, "e": 25961, "s": 25933, "text": "\n26 May, 2021" }, { "code": null, "e": 26071, "s": 25961, "text": "Given a two integers N and K, the task is to find the first M and last M digits of the number NK .Examples: " }, { "code": null, "e": 26312, "s": 26071, "text": "Input: N = 2345, K = 3, M = 3 Output: 128 625 Explanation: 2345 3 = 12895213625 Therefore, the first M(= 3) digits are 128 and the last three digits are 625.Input: N = 12, K = 12, M = 4 Output: 8916 8256 Explanation: 12 12 = 8916100448256 " }, { "code": null, "e": 26606, "s": 26312, "text": "Naive Approach: The simplest approach to solve the problem is to calculate the value of NK and iterate to first M digits and find the last M digits by NK mod 10M. Time Complexity: O(K) Auxiliary Space: O(1)Efficient Approach: The above approach can be optimized by the following observation: " }, { "code": null, "e": 27145, "s": 26606, "text": "Let us consider a number x which can be written as 10y Where y is a decimal number. Let x = NKNK = 10 y Taking log10 on both sides of the above expression, we get: K * log10(N) = log10(10 y) => K * log10(N) = y * (log1010) => y = K * log10(N)Now y will be a decimal number of form abc—.xyz— Therefore, NK = 10abc—.xyz— => NK = 10abc— + 0.xyz— => NK = 10abc— * 100.xyz— In the above equation, 10abc— only moves the decimal point forward. By calculating 100.xyz—, the first M digits can be figured out by moving the decimal point forward. " }, { "code": null, "e": 27192, "s": 27145, "text": "Follow the steps below to solve the problem: " }, { "code": null, "e": 27251, "s": 27192, "text": "Find the first M digits of NK by calculating (NK)mod(10M)." }, { "code": null, "e": 27275, "s": 27251, "text": "Calculate K * log10(N)." }, { "code": null, "e": 27301, "s": 27275, "text": "Calculate 10K * log10(N)." }, { "code": null, "e": 27367, "s": 27301, "text": "Find the first M digits by calculating 10K * log10(N) * 10M – 1 ." }, { "code": null, "e": 27411, "s": 27367, "text": "Print the first and last M digits obtained." }, { "code": null, "e": 27463, "s": 27411, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27467, "s": 27463, "text": "C++" }, { "code": null, "e": 27472, "s": 27467, "text": "Java" }, { "code": null, "e": 27480, "s": 27472, "text": "Python3" }, { "code": null, "e": 27483, "s": 27480, "text": "C#" }, { "code": null, "e": 27494, "s": 27483, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>#define ll long long intusing namespace std; // Function to find a^b modulo Mll modPower(ll a, ll b, ll M){ ll res = 1; while (b) { if (b & 1) res = res * a % M; a = a * a % M; b >>= 1; } return res;} // Function to find the first and last// M digits from N^Kvoid findFirstAndLastM(ll N, ll K, ll M){ // Calculate Last M digits ll lastM = modPower(N, K, (1LL) * pow(10, M)); // Calculate First M digits ll firstM; double y = (double)K * log10(N * 1.0); // Extract the number after decimal y = y - (ll)y; // Find 10 ^ y double temp = pow(10.0, y); // Move the Decimal Point M - 1 digits forward firstM = temp * (1LL) * pow(10, M - 1); // Print the result cout << firstM << \" \" << lastM << endl;} // Driver Codeint main(){ ll N = 12, K = 12, M = 4; findFirstAndLastM(N, K, M); return 0;}", "e": 28458, "s": 27494, "text": null }, { "code": "// Java program to implement// the above approachclass GFG{ // Function to find a^b modulo Mstatic long modPower(long a, long b, long M){ long res = 1; while (b > 0) { if (b % 2 == 1) res = res * a % M; a = a * a % M; b >>= 1; } return res;} // Function to find the first and last// M digits from N^Kstatic void findFirstAndLastM(long N, long K, long M){ // Calculate Last M digits long lastM = modPower(N, K, (1L) * (long)Math.pow(10, M)); // Calculate First M digits long firstM; double y = (double)K * Math.log10(N * 1.0); // Extract the number after decimal y = y - (long)y; // Find 10 ^ y double temp = Math.pow(10.0, y); // Move the Decimal Point M - 1 digits forward firstM = (long)(temp * (1L) * Math.pow(10, (M - 1))); // Print the result System.out.print(firstM + \" \" + lastM + \"\\n\");} // Driver Codepublic static void main(String[] args){ long N = 12, K = 12, M = 4; findFirstAndLastM(N, K, M);}} // This code is contributed by Rajput-Ji", "e": 29602, "s": 28458, "text": null }, { "code": "# Python3 program to implement# the above approachfrom math import * # Function to find a^b modulo Mdef modPower(a, b, M): res = 1 while (b): if (b & 1): res = res * a % M a = a * a % M b >>= 1 return res # Function to find the first and# last M digits from N^Kdef findFirstAndLastM(N, K, M): # Calculate Last M digits lastM = modPower(N, K, int(pow(10, M))) # Calculate First M digits firstM = 0 y = K * log10(N * 1.0) # Extract the number after decimal y = y - int(y) # Find 10 ^ y temp = pow(10.0, y) # Move the Decimal Point M - 1 # digits forward firstM = int(temp * pow(10, M - 1)) # Print the result print(firstM, lastM) # Driver CodeN = 12K = 12M = 4 findFirstAndLastM(N, K, M) # This code is contributed by himanshu77", "e": 30434, "s": 29602, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find a^b modulo Mstatic long modPower(long a, long b, long M){ long res = 1; while (b > 0) { if (b % 2 == 1) res = res * a % M; a = a * a % M; b >>= 1; } return res;} // Function to find the first and last// M digits from N^Kstatic void findFirstAndLastM(long N, long K, long M){ // Calculate Last M digits long lastM = modPower(N, K, (1L) * (long)Math.Pow(10, M)); // Calculate First M digits long firstM; double y = (double)K * Math.Log10(N * 1.0); // Extract the number after decimal y = y - (long)y; // Find 10 ^ y double temp = Math.Pow(10.0, y); // Move the Decimal Point M - 1 digits forward firstM = (long)(temp * (1L) * Math.Pow(10, (M - 1))); // Print the result Console.Write(firstM + \" \" + lastM + \"\\n\");} // Driver Codepublic static void Main(String[] args){ long N = 12, K = 12, M = 4; findFirstAndLastM(N, K, M);}} // This code is contributed by gauravrajput1", "e": 31605, "s": 30434, "text": null }, { "code": "<script> // JavaScript Program to implement// the above approach // Function to find a^b modulo Mfunction modPower(a, b, M){ var res = 1; while (b) { if (b & 1) res = res * a % M; a = a * a % M; b >>= 1; } return res;} // Function to find the first and last// M digits from N^Kfunction findFirstAndLastM(N, K, M){ // Calculate Last M digits var lastM = modPower(N, K, Math.pow(10, M)); // Calculate First M digits var firstM; var y = K * Math.log10(N * 1.0); // Extract the number after decimal y = y - parseInt(y); // Find 10 ^ y var temp = Math.pow(10.0, y); // Move the Decimal Point M - 1 digits forward firstM = temp * Math.pow(10, M - 1); // Print the result document.write( parseInt(firstM) + \" \" + parseInt(lastM) );} // Driver Codevar N = 12, K = 12, M = 4;findFirstAndLastM(N, K, M); </script>", "e": 32510, "s": 31605, "text": null }, { "code": null, "e": 32520, "s": 32510, "text": "8916 8256" }, { "code": null, "e": 32571, "s": 32522, "text": "Time Complexity: O(log K) Auxiliary Space: O(1) " }, { "code": null, "e": 32581, "s": 32571, "text": "Rajput-Ji" }, { "code": null, "e": 32595, "s": 32581, "text": "GauravRajput1" }, { "code": null, "e": 32606, "s": 32595, "text": "himanshu77" }, { "code": null, "e": 32612, "s": 32606, "text": "itsok" }, { "code": null, "e": 32624, "s": 32612, "text": "maths-power" }, { "code": null, "e": 32643, "s": 32624, "text": "Modular Arithmetic" }, { "code": null, "e": 32657, "s": 32643, "text": "number-digits" }, { "code": null, "e": 32670, "s": 32657, "text": "Mathematical" }, { "code": null, "e": 32683, "s": 32670, "text": "Mathematical" }, { "code": null, "e": 32702, "s": 32683, "text": "Modular Arithmetic" }, { "code": null, "e": 32800, "s": 32702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32844, "s": 32800, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 32875, "s": 32844, "text": "Modular multiplicative inverse" }, { "code": null, "e": 32900, "s": 32875, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 32932, "s": 32900, "text": "Check if a number is Palindrome" }, { "code": null, "e": 32976, "s": 32932, "text": "Generate all permutation of a set in Python" }, { "code": null, "e": 33009, "s": 32976, "text": "Program to multiply two matrices" }, { "code": null, "e": 33051, "s": 33009, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 33115, "s": 33051, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 33161, "s": 33115, "text": "Merge two sorted arrays with O(1) extra space" } ]
AngularJS | ng-focus Directive - GeeksforGeeks
31 Aug, 2021 The ng-focus Directive in AngluarJS is used to apply custom behavior when an element is focused. It can be used to show/hide some element or it can popup alert when element is being focused. It is supported by <a>, <input>, <select> and <textarea> elements. Syntax: <element ng-focus="expression"> Contents... </element> Where expressions tells what to do when input get focused. Example 1: This example uses ng-focus Directive to display text area field. html <!DOCTYPE html><html> <head> <title>ng-focus Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-focus Directive</h2> <a href="" ng-focus="isCheck=true"> Click to proceed. </a> <br><br> <div class="row" ng-show="isCheck"> Enter Name: <input type="text" ng-focus="isCheck=true" placeholder="geeksforgeeks" /> </div></body> </html> Output: Before clicking the link: After clicking the link: Example 2: This example uses ng-focus Directive to display focus on input text field. html <!DOCTYPE html><html> <head> <title>ng-focus Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="app" style="text-align:center;"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-focus Directive</h2> <div ng-controller="geek"> Input: <input type="text" ng-focus="focused = true" ng-blur="focused = false" /> <pre ng-show="focused">Input is focused.</pre> </div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { }]); </script></body> </html> Output: Before click on text area: After click on text area: Supported Browser: Google Chrome Microsoft Edge Firefox Opera Safari ysachin2314 AngularJS-Directives AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Auth Guards in Angular 9/10/11 Angular PrimeNG Calendar Component What is AOT and JIT Compiler in Angular ? How to bundle an Angular app for production? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26160, "s": 26132, "text": "\n31 Aug, 2021" }, { "code": null, "e": 26418, "s": 26160, "text": "The ng-focus Directive in AngluarJS is used to apply custom behavior when an element is focused. It can be used to show/hide some element or it can popup alert when element is being focused. It is supported by <a>, <input>, <select> and <textarea> elements." }, { "code": null, "e": 26428, "s": 26418, "text": "Syntax: " }, { "code": null, "e": 26483, "s": 26428, "text": "<element ng-focus=\"expression\"> Contents... </element>" }, { "code": null, "e": 26542, "s": 26483, "text": "Where expressions tells what to do when input get focused." }, { "code": null, "e": 26620, "s": 26542, "text": "Example 1: This example uses ng-focus Directive to display text area field. " }, { "code": null, "e": 26625, "s": 26620, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>ng-focus Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"\" style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-focus Directive</h2> <a href=\"\" ng-focus=\"isCheck=true\"> Click to proceed. </a> <br><br> <div class=\"row\" ng-show=\"isCheck\"> Enter Name: <input type=\"text\" ng-focus=\"isCheck=true\" placeholder=\"geeksforgeeks\" /> </div></body> </html>", "e": 27212, "s": 26625, "text": null }, { "code": null, "e": 27248, "s": 27212, "text": "Output: Before clicking the link: " }, { "code": null, "e": 27275, "s": 27248, "text": "After clicking the link: " }, { "code": null, "e": 27363, "s": 27275, "text": "Example 2: This example uses ng-focus Directive to display focus on input text field. " }, { "code": null, "e": 27368, "s": 27363, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>ng-focus Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"app\" style=\"text-align:center;\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-focus Directive</h2> <div ng-controller=\"geek\"> Input: <input type=\"text\" ng-focus=\"focused = true\" ng-blur=\"focused = false\" /> <pre ng-show=\"focused\">Input is focused.</pre> </div> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function ($scope) { }]); </script></body> </html>", "e": 28053, "s": 27368, "text": null }, { "code": null, "e": 28090, "s": 28053, "text": "Output: Before click on text area: " }, { "code": null, "e": 28118, "s": 28090, "text": "After click on text area: " }, { "code": null, "e": 28137, "s": 28118, "text": "Supported Browser:" }, { "code": null, "e": 28151, "s": 28137, "text": "Google Chrome" }, { "code": null, "e": 28166, "s": 28151, "text": "Microsoft Edge" }, { "code": null, "e": 28174, "s": 28166, "text": "Firefox" }, { "code": null, "e": 28180, "s": 28174, "text": "Opera" }, { "code": null, "e": 28188, "s": 28180, "text": "Safari " }, { "code": null, "e": 28200, "s": 28188, "text": "ysachin2314" }, { "code": null, "e": 28221, "s": 28200, "text": "AngularJS-Directives" }, { "code": null, "e": 28231, "s": 28221, "text": "AngularJS" }, { "code": null, "e": 28248, "s": 28231, "text": "Web Technologies" }, { "code": null, "e": 28346, "s": 28248, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28381, "s": 28346, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 28412, "s": 28381, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 28447, "s": 28412, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 28489, "s": 28447, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 28534, "s": 28489, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 28574, "s": 28534, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28607, "s": 28574, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28652, "s": 28607, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28695, "s": 28652, "text": "How to fetch data from an API in ReactJS ?" } ]
Java.io.FilePermission Class in Java - GeeksforGeeks
01 Feb, 2017 java.io.FilePermission class is used to represent access to a file or a directory. These accesses are in the form of a path name and a set of actions associated to the path name(specifies which file to be open along with the the extension and the path). For Example, in FilePermission(“GEEKS.txt”, “read”) “GEEKS.txt” is the path and “read” is action being performed. These actions are as follows : read : read permission to the file write : write permission to the file delete : delete permission to the file by calling File.delete readlink : read link permission execute : executed the permission Declaration : public final class FilePermission extends Permission implements Serializable Constructors : FilePermission(String p, String a) : Creates a new file permission object with "a" action. Methods of FilePermission Class : equals(Object FP_obj) : java.io.FilePermission.equals(Object FP_obj) tells whether the two (i.e. checks the FP_obj pathname and filename with this object) FilePermission objects are equal or not.Syntax :public boolean equals(Object FP_obj) Parameters : FP_obj : the FilePermission object to be verified with this object Returns : true : if both the objects are equal else, false. Exception : ---------- Implementation :// Java Program illustrating equals() method import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { boolean bool = false; // Creating new FilePermissions("Path", "action") FilePermission FP_obj1 = new FilePermission("GEEKS", "read"); FilePermission FP_obj2 = new FilePermission("ABC", "write"); FilePermission FP_obj3 = new FilePermission("GEEKS", "read"); // Use of equals method bool = FP_obj2.equals(FP_obj1); System.out.println("Whether FP_obj1 equals FP_obj2 : " + bool); bool = FP_obj2.equals(FP_obj3); System.out.println("Whether FP_obj2 equals FP_obj2 : " + bool); bool = FP_obj1.equals(FP_obj3); System.out.println("Whether FP_obj3 equals FP_obj1 : " + bool); }}Output :Whether FP_obj1 equals FP_obj2 : false Whether FP_obj2 equals FP_obj2 : false Whether FP_obj3 equals FP_obj1 : true public boolean equals(Object FP_obj) Parameters : FP_obj : the FilePermission object to be verified with this object Returns : true : if both the objects are equal else, false. Exception : ---------- Implementation : // Java Program illustrating equals() method import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { boolean bool = false; // Creating new FilePermissions("Path", "action") FilePermission FP_obj1 = new FilePermission("GEEKS", "read"); FilePermission FP_obj2 = new FilePermission("ABC", "write"); FilePermission FP_obj3 = new FilePermission("GEEKS", "read"); // Use of equals method bool = FP_obj2.equals(FP_obj1); System.out.println("Whether FP_obj1 equals FP_obj2 : " + bool); bool = FP_obj2.equals(FP_obj3); System.out.println("Whether FP_obj2 equals FP_obj2 : " + bool); bool = FP_obj1.equals(FP_obj3); System.out.println("Whether FP_obj3 equals FP_obj1 : " + bool); }} Output : Whether FP_obj1 equals FP_obj2 : false Whether FP_obj2 equals FP_obj2 : false Whether FP_obj3 equals FP_obj1 : true getActions() : java.io.FilePermission.getActions() tells the action of this FilePermission Object. If in case there are two actions along with the object : delete and read, then the method will return “read, delete”.In such cases this method returns “canonical string” : read, write, execute, delete, readlinkSyntax :public String getActions() Parameters : ---------- Returns : canonical string : representing the actions associated with the object. Exception : ---------- Implementation :// Java Program illustrating getActions() methodimport java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1 = new FilePermission("GEEKS", "read, delete, write"); FilePermission FP_obj2 = new FilePermission("ABC", "write, read, execute"); FilePermission FP_obj3 = new FilePermission("GEEKS", "delete, readlink, read"); // Use of getActions() method String str = FP_obj1.getActions(); System.out.println("Actions with FP_obj1 : " + str); str = FP_obj2.getActions(); System.out.println("Actions with FP_obj2 : " + str); str = FP_obj3.getActions(); System.out.println("Actions with FP_obj3 : " + str); }}Output :Actions with FP_obj1 : read,write,delete Actions with FP_obj2 : read,write,execute Actions with FP_obj3 : read,delete,readlink public String getActions() Parameters : ---------- Returns : canonical string : representing the actions associated with the object. Exception : ---------- Implementation : // Java Program illustrating getActions() methodimport java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1 = new FilePermission("GEEKS", "read, delete, write"); FilePermission FP_obj2 = new FilePermission("ABC", "write, read, execute"); FilePermission FP_obj3 = new FilePermission("GEEKS", "delete, readlink, read"); // Use of getActions() method String str = FP_obj1.getActions(); System.out.println("Actions with FP_obj1 : " + str); str = FP_obj2.getActions(); System.out.println("Actions with FP_obj2 : " + str); str = FP_obj3.getActions(); System.out.println("Actions with FP_obj3 : " + str); }} Output : Actions with FP_obj1 : read,write,delete Actions with FP_obj2 : read,write,execute Actions with FP_obj3 : read,delete,readlink hashCode() : java.io.FilePermission.hashCode() returns hash code for the argumented FilePermission ObjectSyntax :public int hashCode() Parameters : -------- Returns : hash code value for the argumented object Exception : ---------- Implementation :// Java Program illustrating hashCode() method import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1=new FilePermission("GEEKS", "read, delete, write"); // Use of hashCode() method int i = FP_obj1.hashCode(); System.out.println("hashCode value for FP_obj1 : " + i); }}Output :hashCode value for FP_obj1 : 0 public int hashCode() Parameters : -------- Returns : hash code value for the argumented object Exception : ---------- Implementation : // Java Program illustrating hashCode() method import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1=new FilePermission("GEEKS", "read, delete, write"); // Use of hashCode() method int i = FP_obj1.hashCode(); System.out.println("hashCode value for FP_obj1 : " + i); }} Output : hashCode value for FP_obj1 : 0 implies(Permission arg) :java.io.FilePermission.implies(Permission arg) tells whether this FilePermision has the argumented Permission or not.Syntax :public boolean implies(Permission arg) Parameters : arg : Permission to be checked Returns : true if the FilePermission object has the argumented Permission else, false Exception : ---------- Implementation :// Java Program illustrating implies() method import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1 = new FilePermission("GEEKS", "read"); FilePermission FP_obj2 = new FilePermission("ABC", "write"); FilePermission FP_obj3 = new FilePermission("GEEKS", "delete"); // Use of implies() method boolean check = FP_obj1.implies(FP_obj2); System.out.println("Using implies() for FP_obj1 : " + check); // Checked here with the same FilePermission object check = FP_obj2.implies(FP_obj2); System.out.println("Using implies() for FP_obj2 : " + check); }}Output :Using implies() for FP_obj1 : false Using implies() for FP_obj2 : true public boolean implies(Permission arg) Parameters : arg : Permission to be checked Returns : true if the FilePermission object has the argumented Permission else, false Exception : ---------- Implementation : // Java Program illustrating implies() method import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1 = new FilePermission("GEEKS", "read"); FilePermission FP_obj2 = new FilePermission("ABC", "write"); FilePermission FP_obj3 = new FilePermission("GEEKS", "delete"); // Use of implies() method boolean check = FP_obj1.implies(FP_obj2); System.out.println("Using implies() for FP_obj1 : " + check); // Checked here with the same FilePermission object check = FP_obj2.implies(FP_obj2); System.out.println("Using implies() for FP_obj2 : " + check); }} Output : Using implies() for FP_obj1 : false Using implies() for FP_obj2 : true newPermissionCollection() :java.io.FilePermission.newPermissionCollection() creates PermissionCollection object having the FilePermission objects.Syntax :public PermissionCollection newPermissionCollection() Parameters : arg : Permission to be checked Returns : new PermissionCollection object having the FilePermission objects. Exception : ---------- Implementation :// Java Program illustrating newPermissionCollection() method import java.io.*;import java.security.PermissionCollection;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1 = new FilePermission("GEEKS.txt", "read"); // Creating new PermissionCollection // Use of newPermissionCollection() PermissionCollection FP = FP_obj1.newPermissionCollection(); // Collecting the Permissions of FP_obj1 for FP FP.add(FP_obj1); boolean check = FP.implies(new FilePermission("GEEKS.txt", "read")); System.out.println("Is newPermissionCollection() working : " + check); }}Output :Is newPermissionCollection() working : true public PermissionCollection newPermissionCollection() Parameters : arg : Permission to be checked Returns : new PermissionCollection object having the FilePermission objects. Exception : ---------- Implementation : // Java Program illustrating newPermissionCollection() method import java.io.*;import java.security.PermissionCollection;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1 = new FilePermission("GEEKS.txt", "read"); // Creating new PermissionCollection // Use of newPermissionCollection() PermissionCollection FP = FP_obj1.newPermissionCollection(); // Collecting the Permissions of FP_obj1 for FP FP.add(FP_obj1); boolean check = FP.implies(new FilePermission("GEEKS.txt", "read")); System.out.println("Is newPermissionCollection() working : " + check); }} Output : Is newPermissionCollection() working : true This article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-I/O Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25249, "s": 25221, "text": "\n01 Feb, 2017" }, { "code": null, "e": 25503, "s": 25249, "text": "java.io.FilePermission class is used to represent access to a file or a directory. These accesses are in the form of a path name and a set of actions associated to the path name(specifies which file to be open along with the the extension and the path)." }, { "code": null, "e": 25617, "s": 25503, "text": "For Example, in FilePermission(“GEEKS.txt”, “read”) “GEEKS.txt” is the path and “read” is action being performed." }, { "code": null, "e": 25648, "s": 25617, "text": "These actions are as follows :" }, { "code": null, "e": 25683, "s": 25648, "text": "read : read permission to the file" }, { "code": null, "e": 25720, "s": 25683, "text": "write : write permission to the file" }, { "code": null, "e": 25782, "s": 25720, "text": "delete : delete permission to the file by calling File.delete" }, { "code": null, "e": 25814, "s": 25782, "text": "readlink : read link permission" }, { "code": null, "e": 25848, "s": 25814, "text": "execute : executed the permission" }, { "code": null, "e": 25862, "s": 25848, "text": "Declaration :" }, { "code": null, "e": 25948, "s": 25862, "text": "public final class FilePermission\n extends Permission\n implements Serializable" }, { "code": null, "e": 25963, "s": 25948, "text": "Constructors :" }, { "code": null, "e": 26054, "s": 25963, "text": "FilePermission(String p, String a) : Creates a new file permission object with \"a\" action." }, { "code": null, "e": 26088, "s": 26054, "text": "Methods of FilePermission Class :" }, { "code": null, "e": 27456, "s": 26088, "text": "equals(Object FP_obj) : java.io.FilePermission.equals(Object FP_obj) tells whether the two (i.e. checks the FP_obj pathname and filename with this object) FilePermission objects are equal or not.Syntax :public boolean equals(Object FP_obj)\nParameters : \nFP_obj : the FilePermission object to be verified with this object\nReturns :\ntrue : if both the objects are equal else, false.\nException : \n----------\nImplementation :// Java Program illustrating equals() method import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { boolean bool = false; // Creating new FilePermissions(\"Path\", \"action\") FilePermission FP_obj1 = new FilePermission(\"GEEKS\", \"read\"); FilePermission FP_obj2 = new FilePermission(\"ABC\", \"write\"); FilePermission FP_obj3 = new FilePermission(\"GEEKS\", \"read\"); // Use of equals method bool = FP_obj2.equals(FP_obj1); System.out.println(\"Whether FP_obj1 equals FP_obj2 : \" + bool); bool = FP_obj2.equals(FP_obj3); System.out.println(\"Whether FP_obj2 equals FP_obj2 : \" + bool); bool = FP_obj1.equals(FP_obj3); System.out.println(\"Whether FP_obj3 equals FP_obj1 : \" + bool); }}Output :Whether FP_obj1 equals FP_obj2 : false\nWhether FP_obj2 equals FP_obj2 : false\nWhether FP_obj3 equals FP_obj1 : true" }, { "code": null, "e": 27659, "s": 27456, "text": "public boolean equals(Object FP_obj)\nParameters : \nFP_obj : the FilePermission object to be verified with this object\nReturns :\ntrue : if both the objects are equal else, false.\nException : \n----------\n" }, { "code": null, "e": 27676, "s": 27659, "text": "Implementation :" }, { "code": "// Java Program illustrating equals() method import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { boolean bool = false; // Creating new FilePermissions(\"Path\", \"action\") FilePermission FP_obj1 = new FilePermission(\"GEEKS\", \"read\"); FilePermission FP_obj2 = new FilePermission(\"ABC\", \"write\"); FilePermission FP_obj3 = new FilePermission(\"GEEKS\", \"read\"); // Use of equals method bool = FP_obj2.equals(FP_obj1); System.out.println(\"Whether FP_obj1 equals FP_obj2 : \" + bool); bool = FP_obj2.equals(FP_obj3); System.out.println(\"Whether FP_obj2 equals FP_obj2 : \" + bool); bool = FP_obj1.equals(FP_obj3); System.out.println(\"Whether FP_obj3 equals FP_obj1 : \" + bool); }}", "e": 28500, "s": 27676, "text": null }, { "code": null, "e": 28509, "s": 28500, "text": "Output :" }, { "code": null, "e": 28625, "s": 28509, "text": "Whether FP_obj1 equals FP_obj2 : false\nWhether FP_obj2 equals FP_obj2 : false\nWhether FP_obj3 equals FP_obj1 : true" }, { "code": null, "e": 30041, "s": 28625, "text": "getActions() : java.io.FilePermission.getActions() tells the action of this FilePermission Object. If in case there are two actions along with the object : delete and read, then the method will return “read, delete”.In such cases this method returns “canonical string” : read, write, execute, delete, readlinkSyntax :public String getActions()\nParameters : \n----------\nReturns :\ncanonical string : representing the actions associated with the object.\nException : \n----------\nImplementation :// Java Program illustrating getActions() methodimport java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1 = new FilePermission(\"GEEKS\", \"read, delete, write\"); FilePermission FP_obj2 = new FilePermission(\"ABC\", \"write, read, execute\"); FilePermission FP_obj3 = new FilePermission(\"GEEKS\", \"delete, readlink, read\"); // Use of getActions() method String str = FP_obj1.getActions(); System.out.println(\"Actions with FP_obj1 : \" + str); str = FP_obj2.getActions(); System.out.println(\"Actions with FP_obj2 : \" + str); str = FP_obj3.getActions(); System.out.println(\"Actions with FP_obj3 : \" + str); }}Output :Actions with FP_obj1 : read,write,delete\nActions with FP_obj2 : read,write,execute\nActions with FP_obj3 : read,delete,readlink" }, { "code": null, "e": 30200, "s": 30041, "text": "public String getActions()\nParameters : \n----------\nReturns :\ncanonical string : representing the actions associated with the object.\nException : \n----------\n" }, { "code": null, "e": 30217, "s": 30200, "text": "Implementation :" }, { "code": "// Java Program illustrating getActions() methodimport java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1 = new FilePermission(\"GEEKS\", \"read, delete, write\"); FilePermission FP_obj2 = new FilePermission(\"ABC\", \"write, read, execute\"); FilePermission FP_obj3 = new FilePermission(\"GEEKS\", \"delete, readlink, read\"); // Use of getActions() method String str = FP_obj1.getActions(); System.out.println(\"Actions with FP_obj1 : \" + str); str = FP_obj2.getActions(); System.out.println(\"Actions with FP_obj2 : \" + str); str = FP_obj3.getActions(); System.out.println(\"Actions with FP_obj3 : \" + str); }}", "e": 31008, "s": 30217, "text": null }, { "code": null, "e": 31017, "s": 31008, "text": "Output :" }, { "code": null, "e": 31144, "s": 31017, "text": "Actions with FP_obj1 : read,write,delete\nActions with FP_obj2 : read,write,execute\nActions with FP_obj3 : read,delete,readlink" }, { "code": null, "e": 31853, "s": 31144, "text": "hashCode() : java.io.FilePermission.hashCode() returns hash code for the argumented FilePermission ObjectSyntax :public int hashCode()\nParameters : \n--------\nReturns :\nhash code value for the argumented object\nException : \n----------\nImplementation :// Java Program illustrating hashCode() method import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1=new FilePermission(\"GEEKS\", \"read, delete, write\"); // Use of hashCode() method int i = FP_obj1.hashCode(); System.out.println(\"hashCode value for FP_obj1 : \" + i); }}Output :hashCode value for FP_obj1 : 0" }, { "code": null, "e": 31975, "s": 31853, "text": "public int hashCode()\nParameters : \n--------\nReturns :\nhash code value for the argumented object\nException : \n----------\n" }, { "code": null, "e": 31992, "s": 31975, "text": "Implementation :" }, { "code": "// Java Program illustrating hashCode() method import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1=new FilePermission(\"GEEKS\", \"read, delete, write\"); // Use of hashCode() method int i = FP_obj1.hashCode(); System.out.println(\"hashCode value for FP_obj1 : \" + i); }}", "e": 32413, "s": 31992, "text": null }, { "code": null, "e": 32422, "s": 32413, "text": "Output :" }, { "code": null, "e": 32453, "s": 32422, "text": "hashCode value for FP_obj1 : 0" }, { "code": null, "e": 33654, "s": 32453, "text": "implies(Permission arg) :java.io.FilePermission.implies(Permission arg) tells whether this FilePermision has the argumented Permission or not.Syntax :public boolean implies(Permission arg)\nParameters : \narg : Permission to be checked \nReturns :\ntrue if the FilePermission object has the argumented Permission else, false\nException : \n----------\nImplementation :// Java Program illustrating implies() method import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1 = new FilePermission(\"GEEKS\", \"read\"); FilePermission FP_obj2 = new FilePermission(\"ABC\", \"write\"); FilePermission FP_obj3 = new FilePermission(\"GEEKS\", \"delete\"); // Use of implies() method boolean check = FP_obj1.implies(FP_obj2); System.out.println(\"Using implies() for FP_obj1 : \" + check); // Checked here with the same FilePermission object check = FP_obj2.implies(FP_obj2); System.out.println(\"Using implies() for FP_obj2 : \" + check); }}Output :Using implies() for FP_obj1 : false\nUsing implies() for FP_obj2 : true\n" }, { "code": null, "e": 33850, "s": 33654, "text": "public boolean implies(Permission arg)\nParameters : \narg : Permission to be checked \nReturns :\ntrue if the FilePermission object has the argumented Permission else, false\nException : \n----------\n" }, { "code": null, "e": 33867, "s": 33850, "text": "Implementation :" }, { "code": "// Java Program illustrating implies() method import java.io.*;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1 = new FilePermission(\"GEEKS\", \"read\"); FilePermission FP_obj2 = new FilePermission(\"ABC\", \"write\"); FilePermission FP_obj3 = new FilePermission(\"GEEKS\", \"delete\"); // Use of implies() method boolean check = FP_obj1.implies(FP_obj2); System.out.println(\"Using implies() for FP_obj1 : \" + check); // Checked here with the same FilePermission object check = FP_obj2.implies(FP_obj2); System.out.println(\"Using implies() for FP_obj2 : \" + check); }}", "e": 34628, "s": 33867, "text": null }, { "code": null, "e": 34637, "s": 34628, "text": "Output :" }, { "code": null, "e": 34709, "s": 34637, "text": "Using implies() for FP_obj1 : false\nUsing implies() for FP_obj2 : true\n" }, { "code": null, "e": 35881, "s": 34709, "text": "newPermissionCollection() :java.io.FilePermission.newPermissionCollection() creates PermissionCollection object having the FilePermission objects.Syntax :public PermissionCollection newPermissionCollection()\nParameters : \narg : Permission to be checked \nReturns :\nnew PermissionCollection object having the FilePermission objects.\nException : \n----------\nImplementation :// Java Program illustrating newPermissionCollection() method import java.io.*;import java.security.PermissionCollection;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1 = new FilePermission(\"GEEKS.txt\", \"read\"); // Creating new PermissionCollection // Use of newPermissionCollection() PermissionCollection FP = FP_obj1.newPermissionCollection(); // Collecting the Permissions of FP_obj1 for FP FP.add(FP_obj1); boolean check = FP.implies(new FilePermission(\"GEEKS.txt\", \"read\")); System.out.println(\"Is newPermissionCollection() working : \" + check); }}Output :Is newPermissionCollection() working : true" }, { "code": null, "e": 36083, "s": 35881, "text": "public PermissionCollection newPermissionCollection()\nParameters : \narg : Permission to be checked \nReturns :\nnew PermissionCollection object having the FilePermission objects.\nException : \n----------\n" }, { "code": null, "e": 36100, "s": 36083, "text": "Implementation :" }, { "code": "// Java Program illustrating newPermissionCollection() method import java.io.*;import java.security.PermissionCollection;public class NewClass{ public static void main(String[] args) throws IOException { // Creating new FilePermissions FilePermission FP_obj1 = new FilePermission(\"GEEKS.txt\", \"read\"); // Creating new PermissionCollection // Use of newPermissionCollection() PermissionCollection FP = FP_obj1.newPermissionCollection(); // Collecting the Permissions of FP_obj1 for FP FP.add(FP_obj1); boolean check = FP.implies(new FilePermission(\"GEEKS.txt\", \"read\")); System.out.println(\"Is newPermissionCollection() working : \" + check); }}", "e": 36850, "s": 36100, "text": null }, { "code": null, "e": 36859, "s": 36850, "text": "Output :" }, { "code": null, "e": 36903, "s": 36859, "text": "Is newPermissionCollection() working : true" }, { "code": null, "e": 37203, "s": 36903, "text": "This article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 37328, "s": 37203, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 37337, "s": 37328, "text": "Java-I/O" }, { "code": null, "e": 37342, "s": 37337, "text": "Java" }, { "code": null, "e": 37347, "s": 37342, "text": "Java" }, { "code": null, "e": 37445, "s": 37347, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37460, "s": 37445, "text": "Stream In Java" }, { "code": null, "e": 37481, "s": 37460, "text": "Constructors in Java" }, { "code": null, "e": 37500, "s": 37481, "text": "Exceptions in Java" }, { "code": null, "e": 37530, "s": 37500, "text": "Functional Interfaces in Java" }, { "code": null, "e": 37576, "s": 37530, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 37593, "s": 37576, "text": "Generics in Java" }, { "code": null, "e": 37614, "s": 37593, "text": "Introduction to Java" }, { "code": null, "e": 37657, "s": 37614, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 37693, "s": 37657, "text": "Internal Working of HashMap in Java" } ]
Node.js crypto.randomBytes() Method - GeeksforGeeks
11 Oct, 2021 The crypto.randomBytes() method is used to generate a cryptographically well-built artificial random data and the number of bytes to be generated in the written code.Syntax: crypto.randomBytes( size, callback ) Parameters: This method accept two parameters as mentioned above and described below: size: It is of type number which indicates the number of bytes to be generated. callback: It is a function which is made of two parameters namely, err and buf. However, if a callback function is available in the stated code then the bytes are generated asynchronously else these bytes are generated synchronously. Return Type: It returns a Buffer if the callback function is given.Below example illustrate the use of crypto.randomBytes() method in Node.js:Example 1: // Node.js program to demonstrate the // crypto.randomBytes() method // Including crypto moduleconst crypto = require('crypto'); // Calling randomBytes method with callbackcrypto.randomBytes(127, (err, buf) => { if (err) { // Prints error console.log(err); return; } // Prints random bytes of generated data console.log("The random data is: " + buf.toString('hex'));}); Output: Here, callback function is provided so random bytes are generated synchronously. The random data is: 074e48c8e3c0bc19f9e22dd7570037392e5d0bf80cf9dd51bb7808872a511b3c1cd91053fca873a4cb7b2549ec1010a9a1a4c2a6aceead9d115eb9d60a1630e056f3accb10574cd563371296d4e4e898941231d06d8dd5de35690c4ba94ca12729aa316365145f8a00c410a859c40a46bbb4d5d51995241eec8f6b7a90415e Example 2: // Node.js program to demonstrate the // crypto.randomBytes() method // Including crypto moduleconst crypto = require('crypto'); // Calling randomBytes method without callbackconst buf = crypto.randomBytes(60); // Prints random bytes of generated dataconsole.log("The random bytes of data generated is: " + buf.toString('utf8')); Output: Here, callback function is not provided so bytes are generated synchronously The random bytes of data generated is: _??i???Z?Z?o?i?W??bEC ?F????#?-??T??jDqmm?v??7?Q?c_G?%? Reference: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback intensefire22 Node.js-crypto-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method Node.js fs.readFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26169, "s": 26141, "text": "\n11 Oct, 2021" }, { "code": null, "e": 26345, "s": 26169, "text": "The crypto.randomBytes() method is used to generate a cryptographically well-built artificial random data and the number of bytes to be generated in the written code.Syntax: " }, { "code": null, "e": 26382, "s": 26345, "text": "crypto.randomBytes( size, callback )" }, { "code": null, "e": 26470, "s": 26382, "text": "Parameters: This method accept two parameters as mentioned above and described below: " }, { "code": null, "e": 26550, "s": 26470, "text": "size: It is of type number which indicates the number of bytes to be generated." }, { "code": null, "e": 26784, "s": 26550, "text": "callback: It is a function which is made of two parameters namely, err and buf. However, if a callback function is available in the stated code then the bytes are generated asynchronously else these bytes are generated synchronously." }, { "code": null, "e": 26939, "s": 26784, "text": "Return Type: It returns a Buffer if the callback function is given.Below example illustrate the use of crypto.randomBytes() method in Node.js:Example 1: " }, { "code": "// Node.js program to demonstrate the // crypto.randomBytes() method // Including crypto moduleconst crypto = require('crypto'); // Calling randomBytes method with callbackcrypto.randomBytes(127, (err, buf) => { if (err) { // Prints error console.log(err); return; } // Prints random bytes of generated data console.log(\"The random data is: \" + buf.toString('hex'));});", "e": 27338, "s": 26939, "text": null }, { "code": null, "e": 27429, "s": 27338, "text": "Output: Here, callback function is provided so random bytes are generated synchronously. " }, { "code": null, "e": 27704, "s": 27429, "text": "The random data is: 074e48c8e3c0bc19f9e22dd7570037392e5d0bf80cf9dd51bb7808872a511b3c1cd91053fca873a4cb7b2549ec1010a9a1a4c2a6aceead9d115eb9d60a1630e056f3accb10574cd563371296d4e4e898941231d06d8dd5de35690c4ba94ca12729aa316365145f8a00c410a859c40a46bbb4d5d51995241eec8f6b7a90415e" }, { "code": null, "e": 27717, "s": 27704, "text": "Example 2: " }, { "code": "// Node.js program to demonstrate the // crypto.randomBytes() method // Including crypto moduleconst crypto = require('crypto'); // Calling randomBytes method without callbackconst buf = crypto.randomBytes(60); // Prints random bytes of generated dataconsole.log(\"The random bytes of data generated is: \" + buf.toString('utf8'));", "e": 28066, "s": 27717, "text": null }, { "code": null, "e": 28153, "s": 28066, "text": "Output: Here, callback function is not provided so bytes are generated synchronously " }, { "code": null, "e": 28248, "s": 28153, "text": "The random bytes of data generated is: _??i???Z?Z?o?i?W??bEC\n?F????#?-??T??jDqmm?v??7?Q?c_G?%?" }, { "code": null, "e": 28335, "s": 28248, "text": "Reference: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback " }, { "code": null, "e": 28349, "s": 28335, "text": "intensefire22" }, { "code": null, "e": 28371, "s": 28349, "text": "Node.js-crypto-module" }, { "code": null, "e": 28379, "s": 28371, "text": "Node.js" }, { "code": null, "e": 28396, "s": 28379, "text": "Web Technologies" }, { "code": null, "e": 28494, "s": 28396, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28524, "s": 28494, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 28553, "s": 28524, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 28610, "s": 28553, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 28664, "s": 28610, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 28701, "s": 28664, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 28741, "s": 28701, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28786, "s": 28741, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28829, "s": 28786, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28879, "s": 28829, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Write a bash script to print a particular line from a file in C
In this program, we are given a file name text.txt. Our task is to print a particular line from the file. For this there are multiple methods in bash script, they are awk, sed, head. $> awk ‘{if(NR==LINE_NUMBER) print $0}’ filename $> sed -n LINE_NUMBERp filename $head -n LineNumber filename | tail - n + LINE_NUMBER Code to print a specific line in bash programming from file text.txt. $> awk ‘{if(NR==5) print $0}’ text.txt $>sed -n 5p text.txt $head -n 5 filename | tail - n + 5
[ { "code": null, "e": 1168, "s": 1062, "text": "In this program, we are given a file name text.txt. Our task is to print a particular line from the file." }, { "code": null, "e": 1245, "s": 1168, "text": "For this there are multiple methods in bash script, they are awk, sed, head." }, { "code": null, "e": 1380, "s": 1245, "text": "$> awk ‘{if(NR==LINE_NUMBER) print $0}’ filename\n$> sed -n LINE_NUMBERp filename\n$head -n LineNumber filename | tail - n + LINE_NUMBER" }, { "code": null, "e": 1450, "s": 1380, "text": "Code to print a specific line in bash programming from file text.txt." }, { "code": null, "e": 1489, "s": 1450, "text": "$> awk ‘{if(NR==5) print $0}’ text.txt" }, { "code": null, "e": 1510, "s": 1489, "text": "$>sed -n 5p text.txt" }, { "code": null, "e": 1545, "s": 1510, "text": "$head -n 5 filename | tail - n + 5" } ]
Spring Batch - MySQL to Flat File
In this chapter, we will create a Spring Batch application which uses an MySQL Reader and a Flatfile Writer (.txt ). Reader − The Reader we are using in the application is JdbcCursorItemReader to read data from MySQL database. Assume we have created a table in the MySQL database as shown below. CREATE TABLE details.xml_mysql( person_id int(10) NOT NULL, sales VARCHAR(20), qty int(3), staffName VARCHAR(20), date VARCHAR(20) ); Assume we have inserted the following records into it. mysql> select * from tutorialsdata; +-------------+-----------------+----------------+-----------------+ | tutorial_id | tutorial_author | tutorial_title | submission_date | +-------------+-----------------+----------------+-----------------+ | 101 | Sanjay | Learn Java | 06-05-2007 | | 102 | Abdul S | Learn MySQL | 19-04-2007 | | 103 | Krishna Kasyap | Learn JavaFX | 06-07-2017 | +-------------+-----------------+----------------+-----------------+ 3 rows in set (0.00 sec) Writer − The Writer we are using in the application is FlatFileItemWriter to write the data to flatfile (.txt). Processor − The Processor we are using in the application is a custom processor which just prints the records read from the CSV file. Following is the configuration file of our sample Spring Batch application. In this file, we will define the Job and the Steps. In addition to these, we also define the beans for ItemReader, ItemProcessor, and ItemWriter. (Here, we associate them with respective classes and pass the values for the required properties to configure them.) <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:batch = "http://www.springframework.org/schema/batch" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:util = "http://www.springframework.org/schema/util" xsi:schemaLocation = "http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> <import resource = "../jobs/context.xml" /> <bean id = "tutorial" class = "Tutorial" scope = "prototype" /> <bean id = "itemProcessor" class = "CustomItemProcessor" /> <batch:job id = "helloWorldJob"> <batch:step id = "step1"> <batch:tasklet> <batch:chunk reader = "mysqlItemReader" writer = "flatFileItemWriter" processor = "itemProcessor" commit-interval = "10"> </batch:chunk> </batch:tasklet> </batch:step> </batch:job> <bean id = "mysqlItemReader" class = "org.springframework.batch.item.database.JdbcCursorItemReader" > <property name = "dataSource" ref = "dataSource" /> <property name = "sql" value = "select * from details.tutorialsdata" /> <property name = "rowMapper"> <bean class = "TutorialRowMapper" /> </property> </bean> <bean id = "flatFileItemWriter" class = " org.springframework.batch.item.file.FlatFileItemWriter"> <property name = "resource" value = "file:target/outputfiles/employee_output.txt"/> <property name = "lineAggregator"> <bean class = " org.springframework.batch.item.file.transform.PassThroughLineAggregator"/> </property> </bean> </beans> Following is the context.xml of our Spring Batch application. In this file, we will define the beans like job repository, job launcher, and transaction manager. <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc = "http://www.springframework.org/schema/jdbc" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd "> <!-- stored job-meta in database --> <bean id = "jobRepository" class = "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean"> <property name = "dataSource" ref = "dataSource" /> <property name = "transactionManager" ref = "transactionManager" /> <property name = "databaseType" value = "mysql" /> </bean> <bean id = "transactionManager" class = "org.springframework.batch.support.transaction.ResourcelessTransactionManager" /> <bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name = "driverClassName" value = "com.mysql.jdbc.Driver" /> <property name = "url" value = "jdbc:mysql://localhost:3306/details" /> <property name = "username" value = "myuser" /> <property name = "password" value = "password" /> </bean> <bean id = "jobLauncher" class = "org.springframework.batch.core.launch.support.SimpleJobLauncher"> <property name = "jobRepository" ref = "jobRepository" /> </bean> <!-- create job-meta tables automatically --> <jdbc:initialize-database data-source = "dataSource"> <jdbc:script location = "org/springframework/batch/core/schema-drop-mysql.sql" /> <jdbc:script location = "org/springframework/batch/core/schema-mysql.sql" /> </jdbc:initialize-database> </beans> Following is the Processor class. In this class, we write the code of processing in the application. Here, we are printing the contents of each record. import org.springframework.batch.item.ItemProcessor; // Implementing the ItemProcessor interface public class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> { @Override public Tutorial process(Tutorial item) throws Exception { System.out.println("Processing..." + item); return item; } } Following is the TutorialRowMapper class which sets the data to the Tutorial class. public class TutorialRowMapper implements RowMapper<Tutorial> { @Override public Tutorial mapRow(ResultSet rs, int rowNum) throws SQLException { Tutorial tutorial = new Tutorial(); tutorial.setTutorial_id(rs.getInt("tutorial_id")); tutorial.setTutorial_title(rs.getString("tutorial_title")); tutorial.setTutorial_author(rs.getString("tutorial_author")); tutorial.setSubmission_date(rs.getString("submission_date")); return tutorial; } } Following is the Tutorial class. It is a simple Java class with setter and getter methods. In this class, we are using annotations to associate the methods of this class with the tags of the XML file. public class Tutorial { private int tutorial_id; private String tutorial_title; private String tutorial_author; private String submission_date; public int getTutorial_id() { return tutorial_id; } public void setTutorial_id(int tutorial_id) { this.tutorial_id = tutorial_id; } public String getTutorial_title() { return tutorial_title; } public void setTutorial_title(String tutorial_title) { this.tutorial_title = tutorial_title; } public String getTutorial_author() { return tutorial_author; } public void setTutorial_author(String tutorial_author) { this.tutorial_author = tutorial_author; } public String getSubmission_date() { return submission_date; } public void setSubmission_date(String submission_date) { this.submission_date = submission_date; } @Override public String toString() { return " [id=" + tutorial_id + ", title=" + tutorial_title + ", author=" + tutorial_author + ", date=" + submission_date + "]"; } } Following is the code which launces the batch process. In this class, we will launch the Batch Application by running the JobLauncher. import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) throws Exception { String[] springConfig = { "jobs/job_hello_world.xml" }; // Creating the application context object ApplicationContext context = new ClassPathXmlApplicationContext(springConfig); // Creating the job launcher JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); // Creating the job Job job = (Job) context.getBean("helloWorldJob"); // Executing the JOB JobExecution execution = jobLauncher.run(job, new JobParameters()); System.out.println("Exit Status : " + execution.getStatus()); } } On executing this application, it will produce the following output. May 09, 2017 5:44:48 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXml ApplicationContext@3d646c37: startup date [Tue May 09 17:44:48 IST 2017]; root of context hierarchy May 09, 2017 5:44:48 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions May 09, 2017 5:44:56 PM org.springframework.batch.core.launch.support.SimpleJobLauncher run INFO: Job: [FlowJob: [name=helloWorldJob]] launched with the following parameters: [{}] May 09, 2017 5:44:56 PM org.springframework.batch.core.job.SimpleStepHandler handleStep INFO: Executing step: [step1] Processing...Report [id=101, title=Learn Java, author=Sanjay, date=06-05-2007] Processing...Report [id=102, title=Learn MySQL, author=Abdul S, date=19-04-2007] Processing...Report [id=103, title=Learn JavaFX, author=Krishna Kasyap, date=0607-2017] May 09, 2017 5:44:57 PM org.springframework.batch.core.launch.support.SimpleJobLauncher run INFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters: [{}] and the following status: [COMPLETED] Hello Exit Status : COMPLETED This will generate a .txt file with the following contents. Report [id=101, title=Learn Java, author=Sanjay, date=06-05-2007] Report [id=102, title=Learn MySQL, author=Abdul S, date=19-04-2007] Report [id=103, title=Learn JavaFX, author=Krishna Kasyap, date=06-07-2017] 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2045, "s": 1928, "text": "In this chapter, we will create a Spring Batch application which uses an MySQL Reader and a Flatfile Writer (.txt )." }, { "code": null, "e": 2155, "s": 2045, "text": "Reader − The Reader we are using in the application is JdbcCursorItemReader to read data from MySQL database." }, { "code": null, "e": 2224, "s": 2155, "text": "Assume we have created a table in the MySQL database as shown below." }, { "code": null, "e": 2380, "s": 2224, "text": "CREATE TABLE details.xml_mysql( \n person_id int(10) NOT NULL, \n sales VARCHAR(20), \n qty int(3), \n staffName VARCHAR(20), \n date VARCHAR(20) \n); " }, { "code": null, "e": 2435, "s": 2380, "text": "Assume we have inserted the following records into it." }, { "code": null, "e": 2989, "s": 2435, "text": "mysql> select * from tutorialsdata; \n+-------------+-----------------+----------------+-----------------+ \n| tutorial_id | tutorial_author | tutorial_title | submission_date | \n+-------------+-----------------+----------------+-----------------+ \n| 101 | Sanjay | Learn Java | 06-05-2007 | \n| 102 | Abdul S | Learn MySQL | 19-04-2007 | \n| 103 | Krishna Kasyap | Learn JavaFX | 06-07-2017 | \n+-------------+-----------------+----------------+-----------------+ \n3 rows in set (0.00 sec) \n" }, { "code": null, "e": 3101, "s": 2989, "text": "Writer − The Writer we are using in the application is FlatFileItemWriter to write the data to flatfile (.txt)." }, { "code": null, "e": 3235, "s": 3101, "text": "Processor − The Processor we are using in the application is a custom processor which just prints the records read from the CSV file." }, { "code": null, "e": 3574, "s": 3235, "text": "Following is the configuration file of our sample Spring Batch application. In this file, we will define the Job and the Steps. In addition to these, we also define the beans for ItemReader, ItemProcessor, and ItemWriter. (Here, we associate them with respective classes and pass the values for the required properties to configure them.)" }, { "code": null, "e": 5410, "s": 3574, "text": "<beans xmlns = \"http://www.springframework.org/schema/beans\" \n xmlns:batch = \"http://www.springframework.org/schema/batch\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns:util = \"http://www.springframework.org/schema/util\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/batch \n \n http://www.springframework.org/schema/batch/spring-batch-2.2.xsd \n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.2.xsd\"> \n \n <import resource = \"../jobs/context.xml\" /> \n <bean id = \"tutorial\" class = \"Tutorial\" scope = \"prototype\" /> \n <bean id = \"itemProcessor\" class = \"CustomItemProcessor\" /> \n \n <batch:job id = \"helloWorldJob\"> \n <batch:step id = \"step1\"> \n <batch:tasklet> \n <batch:chunk reader = \"mysqlItemReader\" \n writer = \"flatFileItemWriter\" processor = \"itemProcessor\" \n commit-interval = \"10\"> \n </batch:chunk> \n </batch:tasklet> \n </batch:step> \n </batch:job> \n \n <bean id = \"mysqlItemReader\" \n class = \"org.springframework.batch.item.database.JdbcCursorItemReader\" > \n <property name = \"dataSource\" ref = \"dataSource\" /> \n <property name = \"sql\" value = \"select * from details.tutorialsdata\" /> \n <property name = \"rowMapper\"> \n <bean class = \"TutorialRowMapper\" /> \n </property> \n </bean>\n \n <bean id = \"flatFileItemWriter\" \n class = \" org.springframework.batch.item.file.FlatFileItemWriter\"> \n <property name = \"resource\" value = \"file:target/outputfiles/employee_output.txt\"/> \n <property name = \"lineAggregator\"> \n <bean class = \" org.springframework.batch.item.file.transform.PassThroughLineAggregator\"/> \n </property> \n </bean> \n</beans> " }, { "code": null, "e": 5571, "s": 5410, "text": "Following is the context.xml of our Spring Batch application. In this file, we will define the beans like job repository, job launcher, and transaction manager." }, { "code": null, "e": 7446, "s": 5571, "text": "<beans xmlns = \"http://www.springframework.org/schema/beans\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns:jdbc = \"http://www.springframework.org/schema/jdbc\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.2.xsd \n http://www.springframework.org/schema/jdbc \n http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd \"> \n \n <!-- stored job-meta in database --> \n <bean id = \"jobRepository\" \n class = \"org.springframework.batch.core.repository.support.JobRepositoryFactoryBean\"> \n <property name = \"dataSource\" ref = \"dataSource\" /> \n <property name = \"transactionManager\" ref = \"transactionManager\" /> \n <property name = \"databaseType\" value = \"mysql\" /> \n </bean> \n \n <bean id = \"transactionManager\" \n class = \"org.springframework.batch.support.transaction.ResourcelessTransactionManager\" /> \n \n <bean id = \"dataSource\" \n class = \"org.springframework.jdbc.datasource.DriverManagerDataSource\"> \n <property name = \"driverClassName\" value = \"com.mysql.jdbc.Driver\" /> \n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/details\" /> \n <property name = \"username\" value = \"myuser\" /> \n <property name = \"password\" value = \"password\" /> \n </bean> \n \n <bean id = \"jobLauncher\" \n class = \"org.springframework.batch.core.launch.support.SimpleJobLauncher\"> \n <property name = \"jobRepository\" ref = \"jobRepository\" /> \n </bean> \n \n <!-- create job-meta tables automatically --> \n <jdbc:initialize-database data-source = \"dataSource\"> \n <jdbc:script location = \"org/springframework/batch/core/schema-drop-mysql.sql\" /> \n <jdbc:script location = \"org/springframework/batch/core/schema-mysql.sql\" /> \n </jdbc:initialize-database> \n</beans> " }, { "code": null, "e": 7598, "s": 7446, "text": "Following is the Processor class. In this class, we write the code of processing in the application. Here, we are printing the contents of each record." }, { "code": null, "e": 7938, "s": 7598, "text": "import org.springframework.batch.item.ItemProcessor; \n\n// Implementing the ItemProcessor interface \npublic class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> { \n \n @Override \n public Tutorial process(Tutorial item) throws Exception { \n System.out.println(\"Processing...\" + item); \n return item; \n } \n}" }, { "code": null, "e": 8022, "s": 7938, "text": "Following is the TutorialRowMapper class which sets the data to the Tutorial class." }, { "code": null, "e": 8528, "s": 8022, "text": "public class TutorialRowMapper implements RowMapper<Tutorial> { \n \n @Override \n public Tutorial mapRow(ResultSet rs, int rowNum) throws SQLException { \n \n Tutorial tutorial = new Tutorial(); \n \n tutorial.setTutorial_id(rs.getInt(\"tutorial_id\")); \n tutorial.setTutorial_title(rs.getString(\"tutorial_title\")); \n tutorial.setTutorial_author(rs.getString(\"tutorial_author\")); \n tutorial.setSubmission_date(rs.getString(\"submission_date\")); \n return tutorial; \n } \n}" }, { "code": null, "e": 8729, "s": 8528, "text": "Following is the Tutorial class. It is a simple Java class with setter and getter methods. In this class, we are using annotations to associate the methods of this class with the tags of the XML file." }, { "code": null, "e": 9886, "s": 8729, "text": "public class Tutorial { \n private int tutorial_id; \n private String tutorial_title; \n private String tutorial_author; \n private String submission_date; \n \n public int getTutorial_id() { \n return tutorial_id; \n } \n \n public void setTutorial_id(int tutorial_id) { \n this.tutorial_id = tutorial_id; \n }\n \n public String getTutorial_title() { \n return tutorial_title; \n } \n \n public void setTutorial_title(String tutorial_title) { \n this.tutorial_title = tutorial_title; \n } \n \n public String getTutorial_author() { \n return tutorial_author; \n } \n \n public void setTutorial_author(String tutorial_author) { \n this.tutorial_author = tutorial_author; \n } \n \n public String getSubmission_date() { \n return submission_date; \n } \n public void setSubmission_date(String submission_date) { \n this.submission_date = submission_date; \n } \n \n @Override \n public String toString() { \n return \" [id=\" + tutorial_id + \", title=\" + \n tutorial_title + \", \n author=\" + tutorial_author + \", date=\" + \n submission_date + \"]\"; \n } \n} " }, { "code": null, "e": 10021, "s": 9886, "text": "Following is the code which launces the batch process. In this class, we will launch the Batch Application by running the JobLauncher." }, { "code": null, "e": 11065, "s": 10021, "text": "import org.springframework.batch.core.Job; \nimport org.springframework.batch.core.JobExecution; \nimport org.springframework.batch.core.JobParameters; \nimport org.springframework.batch.core.launch.JobLauncher; \nimport org.springframework.context.ApplicationContext; \nimport org.springframework.context.support.ClassPathXmlApplicationContext; \n\npublic class App { \n \n public static void main(String[] args) throws Exception { \n \n String[] springConfig = { \"jobs/job_hello_world.xml\" }; \n \n // Creating the application context object \n ApplicationContext context = new ClassPathXmlApplicationContext(springConfig); \n \n // Creating the job launcher \n JobLauncher jobLauncher = (JobLauncher) context.getBean(\"jobLauncher\"); \n \n // Creating the job \n Job job = (Job) context.getBean(\"helloWorldJob\"); \n \n // Executing the JOB \n JobExecution execution = jobLauncher.run(job, new JobParameters()); \n System.out.println(\"Exit Status : \" + execution.getStatus()); \n } \n}" }, { "code": null, "e": 11134, "s": 11065, "text": "On executing this application, it will produce the following output." }, { "code": null, "e": 12326, "s": 11134, "text": "May 09, 2017 5:44:48 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh \nINFO: Refreshing org.springframework.context.support.ClassPathXml\nApplicationContext@3d646c37: startup date [Tue May \n09 17:44:48 IST 2017]; root of context hierarchy \nMay 09, 2017 5:44:48 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions \nMay 09, 2017 5:44:56 PM org.springframework.batch.core.launch.support.SimpleJobLauncher run \nINFO: Job: [FlowJob: [name=helloWorldJob]] launched \nwith the following parameters: [{}] \nMay 09, 2017 5:44:56 PM org.springframework.batch.core.job.SimpleStepHandler handleStep \nINFO: Executing step: [step1] \nProcessing...Report [id=101, title=Learn Java, author=Sanjay, date=06-05-2007] \nProcessing...Report [id=102, title=Learn MySQL, author=Abdul S, date=19-04-2007] \nProcessing...Report [id=103, title=Learn JavaFX, author=Krishna Kasyap, date=0607-2017] \nMay 09, 2017 5:44:57 PM org.springframework.batch.core.launch.support.SimpleJobLauncher run \nINFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters: \n[{}] and the following status: [COMPLETED] \nHello \nExit Status : COMPLETED \n" }, { "code": null, "e": 12386, "s": 12326, "text": "This will generate a .txt file with the following contents." }, { "code": null, "e": 12600, "s": 12386, "text": "Report [id=101, title=Learn Java, author=Sanjay, date=06-05-2007] \nReport [id=102, title=Learn MySQL, author=Abdul S, date=19-04-2007] \nReport [id=103, title=Learn JavaFX, author=Krishna Kasyap, date=06-07-2017] \n" }, { "code": null, "e": 12634, "s": 12600, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 12648, "s": 12634, "text": " Karthikeya T" }, { "code": null, "e": 12681, "s": 12648, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 12696, "s": 12681, "text": " Chaand Sheikh" }, { "code": null, "e": 12731, "s": 12696, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12743, "s": 12731, "text": " Senol Atac" }, { "code": null, "e": 12778, "s": 12743, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12790, "s": 12778, "text": " Senol Atac" }, { "code": null, "e": 12825, "s": 12790, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12837, "s": 12825, "text": " Senol Atac" }, { "code": null, "e": 12870, "s": 12837, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 12882, "s": 12870, "text": " Senol Atac" }, { "code": null, "e": 12889, "s": 12882, "text": " Print" }, { "code": null, "e": 12900, "s": 12889, "text": " Add Notes" } ]
MariaDB - Update Query
The UPDATE command modifies existing fields by changing values. It uses the SET clause to specify columns for modification, and to specify the new values assigned. These values can be either an expression or the default value of the field. Setting a default value requires using the DEFAULT keyword. The command can also employ a WHERE clause to specify conditions for an update and/or an ORDER BY clause to update in a certain order. Review the following general syntax − UPDATE table_name SET field=new_value, field2=new_value2,... [WHERE ...] Execute an UPDATE command from either the command prompt or using a PHP script. At the command prompt, simply use a standard commandroot − root@host# mysql -u root -p password; Enter password:******* mysql> use PRODUCTS; Database changed mysql> UPDATE products_tbl SET nomenclature = 'Fiber Blaster 300Z' WHERE ID_number = 112; mysql> SELECT * from products_tbl WHERE ID_number='112'; +-------------+---------------------+----------------------+ | ID_number | Nomenclature | product_manufacturer | +-------------+---------------------+----------------------+ | 112 | Fiber Blaster 300Z | XYZ Corp | +-------------+---------------------+----------------------+ Employ the mysql_query() function in UPDATE command statements − <?php $dbhost = ‘localhost:3036’; $dbuser = ‘root’; $dbpass = ‘rootpassword’; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die(‘Could not connect: ‘ . mysql_error()); } $sql = ‘UPDATE products_tbl SET product_name = ”Fiber Blaster 300z” WHERE product_id = 112’; mysql_select_db(‘PRODUCTS’); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die(‘Could not update data: ‘ . mysql_error()); } echo “Updated data successfully\n”; mysql_close($conn); ?> On successful data update, you will see the following output − mysql> Updated data successfully Print Add Notes Bookmark this page
[ { "code": null, "e": 2797, "s": 2362, "text": "The UPDATE command modifies existing fields by changing values. It uses the SET clause to specify columns for modification, and to specify the new values assigned. These values can be either an expression or the default value of the field. Setting a default value requires using the DEFAULT keyword. The command can also employ a WHERE clause to specify conditions for an update and/or an ORDER BY clause to update in a certain order." }, { "code": null, "e": 2835, "s": 2797, "text": "Review the following general syntax −" }, { "code": null, "e": 2909, "s": 2835, "text": "UPDATE table_name SET field=new_value, field2=new_value2,...\n[WHERE ...]\n" }, { "code": null, "e": 2989, "s": 2909, "text": "Execute an UPDATE command from either the command prompt or using a PHP script." }, { "code": null, "e": 3048, "s": 2989, "text": "At the command prompt, simply use a standard commandroot −" }, { "code": null, "e": 3609, "s": 3048, "text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use PRODUCTS;\nDatabase changed\nmysql> UPDATE products_tbl\n SET nomenclature = 'Fiber Blaster 300Z' WHERE ID_number = 112;\nmysql> SELECT * from products_tbl WHERE ID_number='112';\n+-------------+---------------------+----------------------+\n| ID_number | Nomenclature | product_manufacturer |\n+-------------+---------------------+----------------------+\n| 112 | Fiber Blaster 300Z | XYZ Corp |\n+-------------+---------------------+----------------------+ \n" }, { "code": null, "e": 3674, "s": 3609, "text": "Employ the mysql_query() function in UPDATE command statements −" }, { "code": null, "e": 4217, "s": 3674, "text": "<?php\n $dbhost = ‘localhost:3036’;\n $dbuser = ‘root’;\n $dbpass = ‘rootpassword’;\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n\n if(! $conn ) {\n die(‘Could not connect: ‘ . mysql_error());\n }\n\n $sql = ‘UPDATE products_tbl\n SET product_name = ”Fiber Blaster 300z”\n WHERE product_id = 112’;\n\n mysql_select_db(‘PRODUCTS’);\n $retval = mysql_query( $sql, $conn );\n\n if(! $retval ) {\n die(‘Could not update data: ‘ . mysql_error());\n }\n\n echo “Updated data successfully\\n”;\n mysql_close($conn);\n?>" }, { "code": null, "e": 4280, "s": 4217, "text": "On successful data update, you will see the following output −" }, { "code": null, "e": 4314, "s": 4280, "text": "mysql> Updated data successfully\n" }, { "code": null, "e": 4321, "s": 4314, "text": " Print" }, { "code": null, "e": 4332, "s": 4321, "text": " Add Notes" } ]
Send Data Alert with Python SMTP. Sending Business Reporting and Email... | by Vincent Tatan | Towards Data Science
For data scientists, it is very important to communicate reports to the non technical users especially if there are some abnormality within the data. From my working experience, most analysts would send the users business reports manually — they would process the data, run some validations, and generate reports to send via Outlook/gmail. All of these take much time and leaves rooms for human errors. What if we could automate the business reporting and alerts through the same Python Program which analyze our data. That would save huge amount of time and hassle! Simple Mail Transfer Protocol (SMTP) lets users send mail to another. When you push the mail from Python app, the users are receiving it through Post Office Protocol (POP) and Internet Message Access Protocol (IMAP). These are the base for standard email interfaces such as Outlook and Gmail. SMTP allows the server to listen for email request through a TCP connection then send the email through port 587 (Data Flair). In this tutorial, you will learn how to generate email alerts with Python SMTP. We will visit our previous projects on Building Dashboard Web Application, with the task scheduler to web scrape data from Lazada (eCommerce) website and dump it into SQLite RDBMS Database. Based on the products that users are confirmed, we are going to check if the price drops from the original price and use it to generate alerts. Feel free to just enjoy this article or visit my Github Repo for the complete codes. Alternatively just scroll down and enjoy this article. For you who are not familiar with the Dashboard Web Application that I am referring to. I am building a dashboard based on the price changes on Lazada Scraped Products. Each time the user modifies the input dropdown, the app will alert the users if the price of the product drops. Our task is to assign a webhook which will send an email once you modify the dropdown parameters. Importing Python SMTPGenerating Email and SMTP Server PropertiesSending Email RequestsPreparing the Webhooks with our Python Dash DashboardCreating Configuration File for Email Authentication Secrets Importing Python SMTP Generating Email and SMTP Server Properties Sending Email Requests Preparing the Webhooks with our Python Dash Dashboard Creating Configuration File for Email Authentication Secrets Python smtplib is already inbuilt when you download Python packages. If you have it running, you could just import the smtplib as the following import smtplib To activate the SMTP connection, you will need to insert your authentication credentials by replacing the tags as the following: gmail_user = '<input your gmail user. No need to use @gmail.com>'gmail_password = '<input your gmail password>' That is all! Very easy. There are 2 parts you need to consider when building the emails: email properties and email send request. In the email properties, you can set up: #email propertiessent_from = gmail_userto = [<email_send_address>]subject = 'Alert for reduced in price'email_text = """Alert for reduced in price""" sent_from: the sender who sends the emailto: the addressee of the emailsubject: the email subjectemail_text: the content of the email body. sent_from: the sender who sends the email to: the addressee of the email subject: the email subject email_text: the content of the email body. In the email send request, this is where the SMTP server is set up: #email send requesttry: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.sendmail(sent_from, to, email_text) server.close() print ('Email sent!')except Exception as e: print(e) print ('Something went wrong...') The smtplib are setting up the SMTP server with gmail Secure Socket Layer (SSL) channel and port 465. This will allow us to send from our own gmail account.The ehlo() is used to identify yourself to the server. This will check the SMTP service extensions (ESMTP) to the gmail server we set up.The loginis pretty straightforward. We will use our own username and password to login into gmail server.Then we will use our account to sendmail to using the email properties we set up before.Finally, we will close the server which will free up our port 465 and memory usage for the server. The smtplib are setting up the SMTP server with gmail Secure Socket Layer (SSL) channel and port 465. This will allow us to send from our own gmail account. The ehlo() is used to identify yourself to the server. This will check the SMTP service extensions (ESMTP) to the gmail server we set up. The loginis pretty straightforward. We will use our own username and password to login into gmail server. Then we will use our account to sendmail to using the email properties we set up before. Finally, we will close the server which will free up our port 465 and memory usage for the server. Once you set up the properties, everything is set. You just need to run it. And... you encountered an issue. Chances are you would encounter this error If you encounter this error and you have double checked that your username and password are correct, then you would need to open your Gmail Settings and Toggle on the Less Secure App Access Option. This will allow Python SMTP to access your gmail account and send emails on your behalf. Of course to maintain your gmail security, you could turn it off after you are no longer using this functionality. Finally, once you run your script. You will receive this email. (Noted that currently I am using my own email to test the application). Congratulations. You just send your first automated email send request! Now that we know that our alert works, let us setup the web hooks. Web hooks are a resource-light event reactions by a server-side app to notify a client-side app to trigger an event. In this case, we will setup Dash to activate the Alert Logic anytime users modify the the Dashboard’s Dropdown. We will set an alert if there is price decrease in our product. The product_df_specific will sort the values of a specific product by date.The original_price takes the earliest date of the productThe latest_price takes the latest and most recent date of the productThen the email will be sent once we find that the latest_price is lower than the original_price. The product_df_specific will sort the values of a specific product by date. The original_price takes the earliest date of the product The latest_price takes the latest and most recent date of the product Then the email will be sent once we find that the latest_price is lower than the original_price. The end result, we will have a specific email detail that list all of the product and price alerts which the users are concerned of. Remember the credentials from step 1? gmail_user = '<input your gmail user. No need to use @gmail.com>'gmail_password = '<input your gmail password>' Let us put these sensitive information in a properties file where you can secure and configure easily. First let us create a Python Properties file called properties.ini: [EMAIL]user= <gmail username>password = <gmail password> These are the private files which you need to protect and secure. To access this, simply use the Python inbuilt configparser library. import configparserconfig = configparser.ConfigParser()config.read('properties.ini')gmail_user = config['EMAIL']['user']gmail_password = config['EMAIL']['password'] You will first initiate a config parser, this will structure your properties into a tree dir to extract. Then you will read the properties ini file and extract your username and password just like how you extract an element from 2D arrays. Congratulations!! You have created your first SMTP within your dashboard. If you did it properly, you would be able to receive this result. If not, feel free to refer back to my Github Codes or post your questions here. Now set free and create your own Dash Dashboard and Python SMTP! If you need more examples and better insights of what Python SMTP can do. Feel free to visit the following links. Real PythonTutorials PointPython For Beginners Real Python Tutorials Point Python For Beginners I really hope this has been a great read and a source of inspiration for you to develop and innovate. Please Comment out below to suggest and feedback. Just like you, I am still learning how to become a better Data Scientist and Engineer. Please help me improve so that I could help you better in my subsequent article releases. Thank you and Happy coding :) Vincent Tatan is a Data and Technology enthusiast with relevant working experiences from Visa Inc. and Lazada to implement microservice architectures, business intelligence, and analytics pipeline projects. Vincent is a native Indonesian with a record of accomplishments in problem solving with strengths in Full Stack Development, Data Analytics, and Strategic Planning. He has been actively consulting SMU BI & Analytics Club, guiding aspiring data scientists and engineers from various backgrounds, and opening up his expertise for businesses to develop their products . Please reach out to Vincent via LinkedIn , Medium or Youtube Channel
[ { "code": null, "e": 574, "s": 171, "text": "For data scientists, it is very important to communicate reports to the non technical users especially if there are some abnormality within the data. From my working experience, most analysts would send the users business reports manually — they would process the data, run some validations, and generate reports to send via Outlook/gmail. All of these take much time and leaves rooms for human errors." }, { "code": null, "e": 690, "s": 574, "text": "What if we could automate the business reporting and alerts through the same Python Program which analyze our data." }, { "code": null, "e": 738, "s": 690, "text": "That would save huge amount of time and hassle!" }, { "code": null, "e": 1031, "s": 738, "text": "Simple Mail Transfer Protocol (SMTP) lets users send mail to another. When you push the mail from Python app, the users are receiving it through Post Office Protocol (POP) and Internet Message Access Protocol (IMAP). These are the base for standard email interfaces such as Outlook and Gmail." }, { "code": null, "e": 1158, "s": 1031, "text": "SMTP allows the server to listen for email request through a TCP connection then send the email through port 587 (Data Flair)." }, { "code": null, "e": 1238, "s": 1158, "text": "In this tutorial, you will learn how to generate email alerts with Python SMTP." }, { "code": null, "e": 1572, "s": 1238, "text": "We will visit our previous projects on Building Dashboard Web Application, with the task scheduler to web scrape data from Lazada (eCommerce) website and dump it into SQLite RDBMS Database. Based on the products that users are confirmed, we are going to check if the price drops from the original price and use it to generate alerts." }, { "code": null, "e": 1712, "s": 1572, "text": "Feel free to just enjoy this article or visit my Github Repo for the complete codes. Alternatively just scroll down and enjoy this article." }, { "code": null, "e": 1993, "s": 1712, "text": "For you who are not familiar with the Dashboard Web Application that I am referring to. I am building a dashboard based on the price changes on Lazada Scraped Products. Each time the user modifies the input dropdown, the app will alert the users if the price of the product drops." }, { "code": null, "e": 2091, "s": 1993, "text": "Our task is to assign a webhook which will send an email once you modify the dropdown parameters." }, { "code": null, "e": 2291, "s": 2091, "text": "Importing Python SMTPGenerating Email and SMTP Server PropertiesSending Email RequestsPreparing the Webhooks with our Python Dash DashboardCreating Configuration File for Email Authentication Secrets" }, { "code": null, "e": 2313, "s": 2291, "text": "Importing Python SMTP" }, { "code": null, "e": 2357, "s": 2313, "text": "Generating Email and SMTP Server Properties" }, { "code": null, "e": 2380, "s": 2357, "text": "Sending Email Requests" }, { "code": null, "e": 2434, "s": 2380, "text": "Preparing the Webhooks with our Python Dash Dashboard" }, { "code": null, "e": 2495, "s": 2434, "text": "Creating Configuration File for Email Authentication Secrets" }, { "code": null, "e": 2639, "s": 2495, "text": "Python smtplib is already inbuilt when you download Python packages. If you have it running, you could just import the smtplib as the following" }, { "code": null, "e": 2654, "s": 2639, "text": "import smtplib" }, { "code": null, "e": 2783, "s": 2654, "text": "To activate the SMTP connection, you will need to insert your authentication credentials by replacing the tags as the following:" }, { "code": null, "e": 2895, "s": 2783, "text": "gmail_user = '<input your gmail user. No need to use @gmail.com>'gmail_password = '<input your gmail password>'" }, { "code": null, "e": 2919, "s": 2895, "text": "That is all! Very easy." }, { "code": null, "e": 3025, "s": 2919, "text": "There are 2 parts you need to consider when building the emails: email properties and email send request." }, { "code": null, "e": 3066, "s": 3025, "text": "In the email properties, you can set up:" }, { "code": null, "e": 3216, "s": 3066, "text": "#email propertiessent_from = gmail_userto = [<email_send_address>]subject = 'Alert for reduced in price'email_text = \"\"\"Alert for reduced in price\"\"\"" }, { "code": null, "e": 3356, "s": 3216, "text": "sent_from: the sender who sends the emailto: the addressee of the emailsubject: the email subjectemail_text: the content of the email body." }, { "code": null, "e": 3398, "s": 3356, "text": "sent_from: the sender who sends the email" }, { "code": null, "e": 3429, "s": 3398, "text": "to: the addressee of the email" }, { "code": null, "e": 3456, "s": 3429, "text": "subject: the email subject" }, { "code": null, "e": 3499, "s": 3456, "text": "email_text: the content of the email body." }, { "code": null, "e": 3567, "s": 3499, "text": "In the email send request, this is where the SMTP server is set up:" }, { "code": null, "e": 3864, "s": 3567, "text": "#email send requesttry: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.sendmail(sent_from, to, email_text) server.close() print ('Email sent!')except Exception as e: print(e) print ('Something went wrong...')" }, { "code": null, "e": 4449, "s": 3864, "text": "The smtplib are setting up the SMTP server with gmail Secure Socket Layer (SSL) channel and port 465. This will allow us to send from our own gmail account.The ehlo() is used to identify yourself to the server. This will check the SMTP service extensions (ESMTP) to the gmail server we set up.The loginis pretty straightforward. We will use our own username and password to login into gmail server.Then we will use our account to sendmail to using the email properties we set up before.Finally, we will close the server which will free up our port 465 and memory usage for the server." }, { "code": null, "e": 4606, "s": 4449, "text": "The smtplib are setting up the SMTP server with gmail Secure Socket Layer (SSL) channel and port 465. This will allow us to send from our own gmail account." }, { "code": null, "e": 4744, "s": 4606, "text": "The ehlo() is used to identify yourself to the server. This will check the SMTP service extensions (ESMTP) to the gmail server we set up." }, { "code": null, "e": 4850, "s": 4744, "text": "The loginis pretty straightforward. We will use our own username and password to login into gmail server." }, { "code": null, "e": 4939, "s": 4850, "text": "Then we will use our account to sendmail to using the email properties we set up before." }, { "code": null, "e": 5038, "s": 4939, "text": "Finally, we will close the server which will free up our port 465 and memory usage for the server." }, { "code": null, "e": 5121, "s": 5038, "text": "Once you set up the properties, everything is set. You just need to run it. And..." }, { "code": null, "e": 5147, "s": 5121, "text": "you encountered an issue." }, { "code": null, "e": 5190, "s": 5147, "text": "Chances are you would encounter this error" }, { "code": null, "e": 5477, "s": 5190, "text": "If you encounter this error and you have double checked that your username and password are correct, then you would need to open your Gmail Settings and Toggle on the Less Secure App Access Option. This will allow Python SMTP to access your gmail account and send emails on your behalf." }, { "code": null, "e": 5592, "s": 5477, "text": "Of course to maintain your gmail security, you could turn it off after you are no longer using this functionality." }, { "code": null, "e": 5728, "s": 5592, "text": "Finally, once you run your script. You will receive this email. (Noted that currently I am using my own email to test the application)." }, { "code": null, "e": 5800, "s": 5728, "text": "Congratulations. You just send your first automated email send request!" }, { "code": null, "e": 5867, "s": 5800, "text": "Now that we know that our alert works, let us setup the web hooks." }, { "code": null, "e": 6160, "s": 5867, "text": "Web hooks are a resource-light event reactions by a server-side app to notify a client-side app to trigger an event. In this case, we will setup Dash to activate the Alert Logic anytime users modify the the Dashboard’s Dropdown. We will set an alert if there is price decrease in our product." }, { "code": null, "e": 6458, "s": 6160, "text": "The product_df_specific will sort the values of a specific product by date.The original_price takes the earliest date of the productThe latest_price takes the latest and most recent date of the productThen the email will be sent once we find that the latest_price is lower than the original_price." }, { "code": null, "e": 6534, "s": 6458, "text": "The product_df_specific will sort the values of a specific product by date." }, { "code": null, "e": 6592, "s": 6534, "text": "The original_price takes the earliest date of the product" }, { "code": null, "e": 6662, "s": 6592, "text": "The latest_price takes the latest and most recent date of the product" }, { "code": null, "e": 6759, "s": 6662, "text": "Then the email will be sent once we find that the latest_price is lower than the original_price." }, { "code": null, "e": 6892, "s": 6759, "text": "The end result, we will have a specific email detail that list all of the product and price alerts which the users are concerned of." }, { "code": null, "e": 6930, "s": 6892, "text": "Remember the credentials from step 1?" }, { "code": null, "e": 7042, "s": 6930, "text": "gmail_user = '<input your gmail user. No need to use @gmail.com>'gmail_password = '<input your gmail password>'" }, { "code": null, "e": 7145, "s": 7042, "text": "Let us put these sensitive information in a properties file where you can secure and configure easily." }, { "code": null, "e": 7213, "s": 7145, "text": "First let us create a Python Properties file called properties.ini:" }, { "code": null, "e": 7270, "s": 7213, "text": "[EMAIL]user= <gmail username>password = <gmail password>" }, { "code": null, "e": 7404, "s": 7270, "text": "These are the private files which you need to protect and secure. To access this, simply use the Python inbuilt configparser library." }, { "code": null, "e": 7569, "s": 7404, "text": "import configparserconfig = configparser.ConfigParser()config.read('properties.ini')gmail_user = config['EMAIL']['user']gmail_password = config['EMAIL']['password']" }, { "code": null, "e": 7674, "s": 7569, "text": "You will first initiate a config parser, this will structure your properties into a tree dir to extract." }, { "code": null, "e": 7809, "s": 7674, "text": "Then you will read the properties ini file and extract your username and password just like how you extract an element from 2D arrays." }, { "code": null, "e": 8029, "s": 7809, "text": "Congratulations!! You have created your first SMTP within your dashboard. If you did it properly, you would be able to receive this result. If not, feel free to refer back to my Github Codes or post your questions here." }, { "code": null, "e": 8094, "s": 8029, "text": "Now set free and create your own Dash Dashboard and Python SMTP!" }, { "code": null, "e": 8208, "s": 8094, "text": "If you need more examples and better insights of what Python SMTP can do. Feel free to visit the following links." }, { "code": null, "e": 8255, "s": 8208, "text": "Real PythonTutorials PointPython For Beginners" }, { "code": null, "e": 8267, "s": 8255, "text": "Real Python" }, { "code": null, "e": 8283, "s": 8267, "text": "Tutorials Point" }, { "code": null, "e": 8304, "s": 8283, "text": "Python For Beginners" }, { "code": null, "e": 8406, "s": 8304, "text": "I really hope this has been a great read and a source of inspiration for you to develop and innovate." }, { "code": null, "e": 8633, "s": 8406, "text": "Please Comment out below to suggest and feedback. Just like you, I am still learning how to become a better Data Scientist and Engineer. Please help me improve so that I could help you better in my subsequent article releases." }, { "code": null, "e": 8663, "s": 8633, "text": "Thank you and Happy coding :)" }, { "code": null, "e": 8870, "s": 8663, "text": "Vincent Tatan is a Data and Technology enthusiast with relevant working experiences from Visa Inc. and Lazada to implement microservice architectures, business intelligence, and analytics pipeline projects." }, { "code": null, "e": 9035, "s": 8870, "text": "Vincent is a native Indonesian with a record of accomplishments in problem solving with strengths in Full Stack Development, Data Analytics, and Strategic Planning." }, { "code": null, "e": 9237, "s": 9035, "text": "He has been actively consulting SMU BI & Analytics Club, guiding aspiring data scientists and engineers from various backgrounds, and opening up his expertise for businesses to develop their products ." } ]
Top three elements in binary tree - GeeksforGeeks
30 Jun, 2021 We have a simple binary tree and we have to print the top 3 largest elements present in the binary tree.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 4 5 Output :Three largest elements are 5 4 3 Approach We can simply take three variables first, second, third to store the first largest, second largest, third largest respectively and perform preorder traversal and each time we will update the elements accordingly. This approach will take O(n) time only.Algorithm- 1- Take 3 variables first, second, third 2- Perform a preorder traversal if (root==NULL) return if root's data is larger then first update third with second second with first first with root's data else if root's data is larger then second and not equal to first update third with second second with root's data else if root's data is larger then third and not equal to first & second update third with root's data 3- call preorder for root->left 4- call preorder for root->right C++ Java Python3 C# Javascript // CPP program to find largest three elements in// a binary tree.#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node *left; struct Node *right;}; /* Helper function that allocates a new Node with the given data and NULL left and right pointers. */struct Node *newNode(int data) { struct Node *node = new Node; node->data = data; node->left = NULL; node->right = NULL; return (node);} // function to find three largest elementvoid threelargest(Node *root, int &first, int &second, int &third) { if (root == NULL) return; // if data is greater than first large number // update the top three list if (root->data > first) { third = second; second = first; first = root->data; } // if data is greater than second large number // and not equal to first update the bottom // two list else if (root->data > second && root->data != first) { third = second; second = root->data; } // if data is greater than third large number // and not equal to first & second update the // third highest list else if (root->data > third && root->data != first && root->data != second) third = root->data; threelargest(root->left, first, second, third); threelargest(root->right, first, second, third);} // driver functionint main() { struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(4); root->right->right = newNode(5); int first = 0, second = 0, third = 0; threelargest(root, first, second, third); cout << "three largest elements are " << first << " " << second << " " << third; return 0;} // Java program to find largest three elements// in a binary tree.import java.util.*; class GFG{static class Node{ int data; Node left; Node right;}; static int first, second, third; /* Helper function that allocatesa new Node with the given data andnull left and right pointers. */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // function to find three largest elementstatic void threelargest(Node root){if (root == null) return; // if data is greater than first large number// update the top three listif (root.data > first){ third = second; second = first; first = root.data;} // if data is greater than second large number// and not equal to first update the bottom// two listelse if (root.data > second && root.data != first){ third = second; second = root.data;} // if data is greater than third large number// and not equal to first & second update the// third highest listelse if (root.data > third && root.data != first && root.data != second) third = root.data; threelargest(root.left);threelargest(root.right);} // driver functionpublic static void main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(4); root.right.right = newNode(5); first = 0; second = 0; third = 0; threelargest(root); System.out.print("three largest elements are " + first + " " + second + " " + third);}} // This code is contributed by PrinciRaj1992 # Python3 program to find largest three# elements in a binary tree. # Helper function that allocates a new# Node with the given data and None# left and right pointers.class newNode: def __init__(self, data): self.data = data self.left = None self.right = None # function to find three largest elementdef threelargest(root, first, second, third): if (root == None): return # if data is greater than first large # number update the top three list if (root.data > first[0]): third[0] = second[0] second[0] = first[0] first[0] = root.data # if data is greater than second large # number and not equal to first update # the bottom two list elif (root.data > second[0] and root.data != first[0]): third[0] = second[0] second[0] = root.data # if data is greater than third large # number and not equal to first & second # update the third highest list elif (root.data > third[0] and root.data != first[0] and root.data != second[0]): third[0] = root.data threelargest(root.left, first, second, third) threelargest(root.right, first, second, third) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(4) root.right.right = newNode(5) first = [0] second = [0] third = [0] threelargest(root, first, second, third) print("three largest elements are", first[0], second[0], third[0]) # This code is contributed by PranchalK // C# program to find largest three elements// in a binary tree.using System;class GFG{public class Node{ public int data; public Node left; public Node right;}; static int first, second, third; /* Helper function that allocatesa new Node with the given data andnull left and right pointers. */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // function to find three largest elementstatic void threelargest(Node root){ if (root == null) return; // if data is greater than first large number // update the top three list if (root.data > first) { third = second; second = first; first = root.data; } // if data is greater than second large number // and not equal to first update the bottom // two list else if (root.data > second && root.data != first) { third = second; second = root.data; } // if data is greater than third large number // and not equal to first & second update the // third highest list else if (root.data > third && root.data != first && root.data != second) third = root.data; threelargest(root.left); threelargest(root.right);} // Driver Codepublic static void Main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(4); root.right.right = newNode(5); first = 0; second = 0; third = 0; threelargest(root); Console.WriteLine("three largest elements are " + first + " " + second + " " + third);}} // This code is contributed by 29AjayKumar <script> // Javascript program to find largest // three elements in a binary tree. class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let first, second, third; /* Helper function that allocates a new Node with the given data and null left and right pointers. */ function newNode(data) { let node = new Node(data); return (node); } // function to find three largest element function threelargest(root) { if (root == null) return; // if data is greater than first large number // update the top three list if (root.data > first) { third = second; second = first; first = root.data; } // if data is greater than second large number // and not equal to first update the bottom // two list else if (root.data > second && root.data != first) { third = second; second = root.data; } // if data is greater than third large number // and not equal to first & second update the // third highest list else if (root.data > third && root.data != first && root.data != second) third = root.data; threelargest(root.left); threelargest(root.right); } let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(4); root.right.right = newNode(5); first = 0; second = 0; third = 0; threelargest(root); document.write("three largest elements are " + first + " " + second + " " + third); </script> three largest elements are 5 4 3 Time Complexity: O(N) Auxiliary Space: O(1) YouTubeGeeksforGeeks500K subscribersTop three elements in binary tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=pd-5b_lXZzQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> PranchalKatiyar princiraj1992 29AjayKumar rohitsingh07052 decode2207 Order-Statistics Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) AVL Tree | Set 1 (Insertion) Level Order Binary Tree Traversal Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Write a Program to Find the Maximum Depth or Height of a Tree Binary Tree | Set 2 (Properties) A program to check if a binary tree is BST or not
[ { "code": null, "e": 35455, "s": 35427, "text": "\n30 Jun, 2021" }, { "code": null, "e": 35570, "s": 35455, "text": "We have a simple binary tree and we have to print the top 3 largest elements present in the binary tree.Examples: " }, { "code": null, "e": 35696, "s": 35570, "text": "Input : \n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 4 5\nOutput :Three largest elements are 5 4 3" }, { "code": null, "e": 35970, "s": 35696, "text": "Approach We can simply take three variables first, second, third to store the first largest, second largest, third largest respectively and perform preorder traversal and each time we will update the elements accordingly. This approach will take O(n) time only.Algorithm- " }, { "code": null, "e": 36568, "s": 35970, "text": "1- Take 3 variables first, second, third\n2- Perform a preorder traversal\n if (root==NULL)\n return\n if root's data is larger then first\n update third with second\n second with first\n first with root's data\n else if root's data is larger then \n second and not equal to first\n update third with second\n second with root's data\n else if root's data is larger then \n third and not equal to first & \n second\n update third with root's data\n3- call preorder for root->left\n4- call preorder for root->right" }, { "code": null, "e": 36572, "s": 36568, "text": "C++" }, { "code": null, "e": 36577, "s": 36572, "text": "Java" }, { "code": null, "e": 36585, "s": 36577, "text": "Python3" }, { "code": null, "e": 36588, "s": 36585, "text": "C#" }, { "code": null, "e": 36599, "s": 36588, "text": "Javascript" }, { "code": "// CPP program to find largest three elements in// a binary tree.#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node *left; struct Node *right;}; /* Helper function that allocates a new Node with the given data and NULL left and right pointers. */struct Node *newNode(int data) { struct Node *node = new Node; node->data = data; node->left = NULL; node->right = NULL; return (node);} // function to find three largest elementvoid threelargest(Node *root, int &first, int &second, int &third) { if (root == NULL) return; // if data is greater than first large number // update the top three list if (root->data > first) { third = second; second = first; first = root->data; } // if data is greater than second large number // and not equal to first update the bottom // two list else if (root->data > second && root->data != first) { third = second; second = root->data; } // if data is greater than third large number // and not equal to first & second update the // third highest list else if (root->data > third && root->data != first && root->data != second) third = root->data; threelargest(root->left, first, second, third); threelargest(root->right, first, second, third);} // driver functionint main() { struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(4); root->right->right = newNode(5); int first = 0, second = 0, third = 0; threelargest(root, first, second, third); cout << \"three largest elements are \" << first << \" \" << second << \" \" << third; return 0;}", "e": 38358, "s": 36599, "text": null }, { "code": "// Java program to find largest three elements// in a binary tree.import java.util.*; class GFG{static class Node{ int data; Node left; Node right;}; static int first, second, third; /* Helper function that allocatesa new Node with the given data andnull left and right pointers. */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // function to find three largest elementstatic void threelargest(Node root){if (root == null) return; // if data is greater than first large number// update the top three listif (root.data > first){ third = second; second = first; first = root.data;} // if data is greater than second large number// and not equal to first update the bottom// two listelse if (root.data > second && root.data != first){ third = second; second = root.data;} // if data is greater than third large number// and not equal to first & second update the// third highest listelse if (root.data > third && root.data != first && root.data != second) third = root.data; threelargest(root.left);threelargest(root.right);} // driver functionpublic static void main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(4); root.right.right = newNode(5); first = 0; second = 0; third = 0; threelargest(root); System.out.print(\"three largest elements are \" + first + \" \" + second + \" \" + third);}} // This code is contributed by PrinciRaj1992", "e": 40024, "s": 38358, "text": null }, { "code": "# Python3 program to find largest three# elements in a binary tree. # Helper function that allocates a new# Node with the given data and None# left and right pointers.class newNode: def __init__(self, data): self.data = data self.left = None self.right = None # function to find three largest elementdef threelargest(root, first, second, third): if (root == None): return # if data is greater than first large # number update the top three list if (root.data > first[0]): third[0] = second[0] second[0] = first[0] first[0] = root.data # if data is greater than second large # number and not equal to first update # the bottom two list elif (root.data > second[0] and root.data != first[0]): third[0] = second[0] second[0] = root.data # if data is greater than third large # number and not equal to first & second # update the third highest list elif (root.data > third[0] and root.data != first[0] and root.data != second[0]): third[0] = root.data threelargest(root.left, first, second, third) threelargest(root.right, first, second, third) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(4) root.right.right = newNode(5) first = [0] second = [0] third = [0] threelargest(root, first, second, third) print(\"three largest elements are\", first[0], second[0], third[0]) # This code is contributed by PranchalK", "e": 41650, "s": 40024, "text": null }, { "code": "// C# program to find largest three elements// in a binary tree.using System;class GFG{public class Node{ public int data; public Node left; public Node right;}; static int first, second, third; /* Helper function that allocatesa new Node with the given data andnull left and right pointers. */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // function to find three largest elementstatic void threelargest(Node root){ if (root == null) return; // if data is greater than first large number // update the top three list if (root.data > first) { third = second; second = first; first = root.data; } // if data is greater than second large number // and not equal to first update the bottom // two list else if (root.data > second && root.data != first) { third = second; second = root.data; } // if data is greater than third large number // and not equal to first & second update the // third highest list else if (root.data > third && root.data != first && root.data != second) third = root.data; threelargest(root.left); threelargest(root.right);} // Driver Codepublic static void Main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(4); root.right.right = newNode(5); first = 0; second = 0; third = 0; threelargest(root); Console.WriteLine(\"three largest elements are \" + first + \" \" + second + \" \" + third);}} // This code is contributed by 29AjayKumar", "e": 43452, "s": 41650, "text": null }, { "code": "<script> // Javascript program to find largest // three elements in a binary tree. class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let first, second, third; /* Helper function that allocates a new Node with the given data and null left and right pointers. */ function newNode(data) { let node = new Node(data); return (node); } // function to find three largest element function threelargest(root) { if (root == null) return; // if data is greater than first large number // update the top three list if (root.data > first) { third = second; second = first; first = root.data; } // if data is greater than second large number // and not equal to first update the bottom // two list else if (root.data > second && root.data != first) { third = second; second = root.data; } // if data is greater than third large number // and not equal to first & second update the // third highest list else if (root.data > third && root.data != first && root.data != second) third = root.data; threelargest(root.left); threelargest(root.right); } let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(4); root.right.right = newNode(5); first = 0; second = 0; third = 0; threelargest(root); document.write(\"three largest elements are \" + first + \" \" + second + \" \" + third); </script>", "e": 45304, "s": 43452, "text": null }, { "code": null, "e": 45337, "s": 45304, "text": "three largest elements are 5 4 3" }, { "code": null, "e": 45361, "s": 45339, "text": "Time Complexity: O(N)" }, { "code": null, "e": 45383, "s": 45361, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 46215, "s": 45383, "text": "YouTubeGeeksforGeeks500K subscribersTop three elements in binary tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:40•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=pd-5b_lXZzQ\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 46231, "s": 46215, "text": "PranchalKatiyar" }, { "code": null, "e": 46245, "s": 46231, "text": "princiraj1992" }, { "code": null, "e": 46257, "s": 46245, "text": "29AjayKumar" }, { "code": null, "e": 46273, "s": 46257, "text": "rohitsingh07052" }, { "code": null, "e": 46284, "s": 46273, "text": "decode2207" }, { "code": null, "e": 46301, "s": 46284, "text": "Order-Statistics" }, { "code": null, "e": 46306, "s": 46301, "text": "Tree" }, { "code": null, "e": 46311, "s": 46306, "text": "Tree" }, { "code": null, "e": 46409, "s": 46311, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46418, "s": 46409, "text": "Comments" }, { "code": null, "e": 46431, "s": 46418, "text": "Old Comments" }, { "code": null, "e": 46481, "s": 46431, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 46516, "s": 46481, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 46545, "s": 46516, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 46579, "s": 46545, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 46620, "s": 46579, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 46663, "s": 46620, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 46725, "s": 46663, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 46758, "s": 46725, "text": "Binary Tree | Set 2 (Properties)" } ]
hibernate one to many | one to many mapping in hibernate
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In OOPs each entity can have some relation with another entity. We need to find out which relationship can exist between the two entities. A one to many relationship can occurs, if an entity is related to multiple occurrences in another entity. In this tutorial, we are going to implement one to many relationship using hibernate. Hibernate provides us to represent the entities with relationships. To implement one to many relationship between the two components. we need to define the association relationship between the two classes. That is we need to have the dependency of child class in parent class. A common example for one to many relationship is, Customer and Items i.e., a customer can order multiple Items. Here the relationship between Customer to Item is one to many relationship. As this is a one to many relationship, a parent entity can have multiple child entities. In order to define the multiple child entities in the parent entity, hibernate API allows us to use Collection type (List,Set,Map) to define multiple child entities. Recommended : A complete CRUD Application Using Hibernate So that in parent entity, we need to take a reference of type Collection, it might be java.util.Set or java.util.List or java.util.Map. In parent class mapping file (customer.hbm.xml) we need to configure the same. Let us do the example for one to many relationship. Here is the complete example. Create the database tables like below : CREATE TABLE `customer` ( `custid` INT(11) NOT NULL, `custname` VARCHAR(50) NULL DEFAULT NULL, `city` VARCHAR(50) NULL DEFAULT NULL, PRIMARY KEY (`custid`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB; CREATE TABLE `item` ( `customerid_fk` INT(11) NULL DEFAULT NULL, `itemid` INT(11) NULL DEFAULT NULL, `itemname` VARCHAR(50) NULL DEFAULT NULL, `price` VARCHAR(50) NULL DEFAULT NULL, INDEX `FK_item_customer` (`customerid_fk`), CONSTRAINT `FK_item_customer` FOREIGN KEY (`customerid_fk`) REFERENCES `customer` (`custid`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB; Project Structure : Create Model classes : Customer.java package com.onlinetutorialspoint.hibernate.model; import java.util.Set; public class Customer { private int customerId; private String customerName; private String city; private Set items; public int getCustomerId() { return customerId; } public void setCustomerId(int customerId) { this.customerId = customerId; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Set getItems() { return items; } public void setItems(Set items) { this.items = items; } } Items.java package com.onlinetutorialspoint.hibernate.model; public class Items { private int itemId; private String itemName; private int price; public int getItemId() { return itemId; } public void setItemId(int itemId) { this.itemId = itemId; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } } Create Mapping Files : customer.hbm.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.onlinetutorialspoint.hibernate.model.Customer" table="customer"> <id name="customerId" column="custid"/> <property name="customerName" column="custname"/> <property name="city" column="city"/> <set name="items" cascade="all"> <key column="customerid_fk"/> <one-to-many class="com.onlinetutorialspoint.hibernate.model.Items"/> </set> </class> </hibernate-mapping> Recommended : Hibernate Difference between get() and load() items.hbm.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.onlinetutorialspoint.hibernate.model.Items" table="item"> <id name="itemId" column="itemid"/> <property name="itemName" column="itemname"/> <property name="price" column="price"/> </class> </hibernate-mapping> Create DAO Classes : OneToManyDAO.java package com.onlinetutorialspoint.hibernate.dao; import com.onlinetutorialspoint.hibernate.model.Customer; public interface OneToManyDAO { void saveCustomer(Customer customer); } OneToManyDAOImpl.java package com.onlinetutorialspoint.hibernate.dao; import com.onlinetutorialspoint.hibernate.model.Customer; import com.onlinetutorialspoint.util.HibernateUtil; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class OneToManyDAOImpl implements OneToManyDAO { public void saveCustomer(Customer customer) { SessionFactory factory = HibernateUtil.getInstnce(); Session session = factory.openSession(); Transaction tx = session.beginTransaction(); session.save(customer); tx.commit(); session.close(); } } OneToManyDAOFactory.java package com.onlinetutorialspoint.hibernate.dao; public class OneToManyDAOFactory { public static OneToManyDAO getInstance() { return new OneToManyDAOImpl(); } } Create HibernateUtility Class : HibernateUtil.java package com.onlinetutorialspoint.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private HibernateUtil() { } private static SessionFactory sessionFactory; public static synchronized SessionFactory getInstnce() { if (sessionFactory == null) { sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); } return sessionFactory; } } To Run the application create client class : Main.java import com.onlinetutorialspoint.hibernate.dao.OneToManyDAO; import com.onlinetutorialspoint.hibernate.dao.OneToManyDAOFactory; import com.onlinetutorialspoint.hibernate.model.Customer; import com.onlinetutorialspoint.hibernate.model.Items; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { Customer customer = new Customer(); customer.setCustomerId(1001); customer.setCustomerName("Dinesh"); customer.setCity("Banglore"); Items i1 = new Items(); i1.setItemId(9001); i1.setItemName("Samsung"); i1.setPrice(9000); Items i2 = new Items(); i2.setItemId(9002); i2.setItemName("LG"); i2.setPrice(6000); Set items = new HashSet(); items.add(i1); items.add(i2); customer.setItems(items); OneToManyDAO dao = OneToManyDAOFactory.getInstance(); dao.saveCustomer(customer); } } Output : Hibernate: insert into customer (custname, city, custid) values (?, ?, ?) Hibernate: insert into item (itemname, price, itemid) values (?, ?, ?) Hibernate: insert into item (itemname, price, itemid) values (?, ?, ?) Hibernate: update item set customerid_fk=? where itemid=? Hibernate: update item set customerid_fk=? where itemid=? By running the Main.class, we can observe the above output. On the above out put first hibernate performs the insert operation in customer table and after that the corresponding child tables insertion also done. But in Main.java we didn’t perform any save() operation on Items class. Based on the configuration <one-to-many> tag in customer.hbm.xml file, hibernate will understand the relationship between the Customer and Items entities. Happy Learning 🙂 Hibernate One To Many Relation Complete Example File size: 20 KB Downloads: 951 Many to One Mapping in Hibernate Example One to One Mapping in Hibernate using foreign key (XML) Hibernate Many to Many Mapping Example (XML) Hibernate One to One Mapping using primary key (XML) Hibernate Right Join Example Hibernate Left Join Example Hibernate Composite Key Mapping Example Hibernate One To Many Using Annotations Basic Hibernate Example with XML Configuration Hibernate Filter Example Xml Configuration hbm2ddl.auto Example in Hibernate XML Config Hibernate Inheritance Mapping Strategies Hibernate Named Query with Example Custom Generator Class in Hibernate Hibernate Interceptor Example Many to One Mapping in Hibernate Example One to One Mapping in Hibernate using foreign key (XML) Hibernate Many to Many Mapping Example (XML) Hibernate One to One Mapping using primary key (XML) Hibernate Right Join Example Hibernate Left Join Example Hibernate Composite Key Mapping Example Hibernate One To Many Using Annotations Basic Hibernate Example with XML Configuration Hibernate Filter Example Xml Configuration hbm2ddl.auto Example in Hibernate XML Config Hibernate Inheritance Mapping Strategies Hibernate Named Query with Example Custom Generator Class in Hibernate Hibernate Interceptor Example Sravya March 28, 2021 at 7:02 am - Reply Wow..finally found a good site for learning hibernate with best examples. Thank you so much. Sravya March 28, 2021 at 7:02 am - Reply Wow..finally found a good site for learning hibernate with best examples. Thank you so much. Wow..finally found a good site for learning hibernate with best examples. Thank you so much. Δ Hibernate – Introduction Hibernate – Advantages Hibernate – Download and Setup Hibernate – Sql Dialect list Hibernate – Helloworld – XML Hibernate – Install Tools in Eclipse Hibernate – Object States Hibernate – Helloworld – Annotations Hibernate – One to One Mapping – XML Hibernate – One to One Mapping foreign key – XML Hibernate – One To Many -XML Hibernate – One To Many – Annotations Hibernate – Many to Many Mapping – XML Hibernate – Many to One – XML Hibernate – Composite Key Mapping Hibernate – Named Query Hibernate – Native SQL Query Hibernate – load() vs get() Hibernate Criteria API with Example Hibernate – Restrictions Hibernate – Projection Hibernate – Query Language (HQL) Hibernate – Groupby Criteria HQL Hibernate – Orderby Criteria Hibernate – HQLSelect Operation Hibernate – HQL Update, Delete Hibernate – Update Query Hibernate – Update vs Merge Hibernate – Right Join Hibernate – Left Join Hibernate – Pagination Hibernate – Generator Classes Hibernate – Custom Generator Hibernate – Inheritance Mappings Hibernate – Table per Class Hibernate – Table per Sub Class Hibernate – Table per Concrete Class Hibernate – Table per Class Annotations Hibernate – Stored Procedures Hibernate – @Formula Annotation Hibernate – Singleton SessionFactory Hibernate – Interceptor hbm2ddl.auto Example in Hibernate XML Config Hibernate – First Level Cache
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 729, "s": 398, "text": "In OOPs each entity can have some relation with another entity. We need to find out which relationship can exist between the two entities. A one to many relationship can occurs, if an entity is related to multiple occurrences in another entity. In this tutorial, we are going to implement one to many relationship using hibernate." }, { "code": null, "e": 1006, "s": 729, "text": "Hibernate provides us to represent the entities with relationships. To implement one to many relationship between the two components. we need to define the association relationship between the two classes. That is we need to have the dependency of child class in parent class." }, { "code": null, "e": 1195, "s": 1006, "text": "A common example for one to many relationship is, Customer and Items i.e., a customer can order multiple Items. Here the relationship between Customer to Item is one to many relationship." }, { "code": null, "e": 1452, "s": 1197, "text": "As this is a one to many relationship, a parent entity can have multiple child entities. In order to define the multiple child entities in the parent entity, hibernate API allows us to use Collection type (List,Set,Map) to define multiple child entities." }, { "code": null, "e": 1510, "s": 1452, "text": "Recommended : A complete CRUD Application Using Hibernate" }, { "code": null, "e": 1725, "s": 1510, "text": "So that in parent entity, we need to take a reference of type Collection, it might be java.util.Set or java.util.List or java.util.Map. In parent class mapping file (customer.hbm.xml) we need to configure the same." }, { "code": null, "e": 1807, "s": 1725, "text": "Let us do the example for one to many relationship. Here is the complete example." }, { "code": null, "e": 1847, "s": 1807, "text": "Create the database tables like below :" }, { "code": null, "e": 2414, "s": 1847, "text": "\nCREATE TABLE `customer` (\n`custid` INT(11) NOT NULL,\n`custname` VARCHAR(50) NULL DEFAULT NULL,\n`city` VARCHAR(50) NULL DEFAULT NULL,\nPRIMARY KEY (`custid`)\n)\nCOLLATE='latin1_swedish_ci'\nENGINE=InnoDB;\n\nCREATE TABLE `item` (\n`customerid_fk` INT(11) NULL DEFAULT NULL,\n`itemid` INT(11) NULL DEFAULT NULL,\n`itemname` VARCHAR(50) NULL DEFAULT NULL,\n`price` VARCHAR(50) NULL DEFAULT NULL,\nINDEX `FK_item_customer` (`customerid_fk`),\nCONSTRAINT `FK_item_customer` FOREIGN KEY (`customerid_fk`) REFERENCES `customer` (`custid`)\n)\nCOLLATE='latin1_swedish_ci'\nENGINE=InnoDB;" }, { "code": null, "e": 2434, "s": 2414, "text": "Project Structure :" }, { "code": null, "e": 2457, "s": 2434, "text": "Create Model classes :" }, { "code": null, "e": 2471, "s": 2457, "text": "Customer.java" }, { "code": null, "e": 3280, "s": 2471, "text": "package com.onlinetutorialspoint.hibernate.model;\n\nimport java.util.Set;\n\npublic class Customer {\n\n private int customerId;\n private String customerName;\n private String city;\n private Set items;\n\n public int getCustomerId() {\n return customerId;\n }\n\n public void setCustomerId(int customerId) {\n this.customerId = customerId;\n }\n\n public String getCustomerName() {\n return customerName;\n }\n\n public void setCustomerName(String customerName) {\n this.customerName = customerName;\n }\n\n public String getCity() {\n return city;\n }\n\n public void setCity(String city) {\n this.city = city;\n }\n\n public Set getItems() {\n return items;\n }\n\n public void setItems(Set items) {\n this.items = items;\n }\n\n}" }, { "code": null, "e": 3291, "s": 3280, "text": "Items.java" }, { "code": null, "e": 3863, "s": 3291, "text": "package com.onlinetutorialspoint.hibernate.model;\n\npublic class Items {\n\n private int itemId;\n private String itemName;\n private int price;\n\n public int getItemId() {\n return itemId;\n }\n\n public void setItemId(int itemId) {\n this.itemId = itemId;\n }\n\n public String getItemName() {\n return itemName;\n }\n\n public void setItemName(String itemName) {\n this.itemName = itemName;\n }\n\n public int getPrice() {\n return price;\n }\n\n public void setPrice(int price) {\n this.price = price;\n }\n\n}" }, { "code": null, "e": 3886, "s": 3863, "text": "Create Mapping Files :" }, { "code": null, "e": 3903, "s": 3886, "text": "customer.hbm.xml" }, { "code": null, "e": 4561, "s": 3903, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<!DOCTYPE hibernate-mapping PUBLIC\n \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\n \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n<hibernate-mapping>\n <class name=\"com.onlinetutorialspoint.hibernate.model.Customer\" table=\"customer\">\n <id name=\"customerId\" column=\"custid\"/>\n <property name=\"customerName\" column=\"custname\"/>\n <property name=\"city\" column=\"city\"/>\n <set name=\"items\" cascade=\"all\">\n <key column=\"customerid_fk\"/>\n <one-to-many class=\"com.onlinetutorialspoint.hibernate.model.Items\"/>\n </set>\n </class>\n</hibernate-mapping>" }, { "code": null, "e": 4621, "s": 4561, "text": "Recommended : Hibernate Difference between get() and load()" }, { "code": null, "e": 4635, "s": 4621, "text": "items.hbm.xml" }, { "code": null, "e": 5100, "s": 4635, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<!DOCTYPE hibernate-mapping PUBLIC\n \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\n \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n<hibernate-mapping>\n <class name=\"com.onlinetutorialspoint.hibernate.model.Items\" table=\"item\">\n <id name=\"itemId\" column=\"itemid\"/>\n <property name=\"itemName\" column=\"itemname\"/>\n <property name=\"price\" column=\"price\"/>\n </class>\n</hibernate-mapping>" }, { "code": null, "e": 5122, "s": 5100, "text": "Create DAO Classes : " }, { "code": null, "e": 5140, "s": 5122, "text": "OneToManyDAO.java" }, { "code": null, "e": 5325, "s": 5140, "text": "package com.onlinetutorialspoint.hibernate.dao;\n\nimport com.onlinetutorialspoint.hibernate.model.Customer;\n\npublic interface OneToManyDAO {\n\n void saveCustomer(Customer customer);\n}" }, { "code": null, "e": 5347, "s": 5325, "text": "OneToManyDAOImpl.java" }, { "code": null, "e": 5966, "s": 5347, "text": "package com.onlinetutorialspoint.hibernate.dao;\n\nimport com.onlinetutorialspoint.hibernate.model.Customer;\nimport com.onlinetutorialspoint.util.HibernateUtil;\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.Transaction;\n\npublic class OneToManyDAOImpl implements OneToManyDAO {\n\n public void saveCustomer(Customer customer) {\n\n SessionFactory factory = HibernateUtil.getInstnce();\n Session session = factory.openSession();\n Transaction tx = session.beginTransaction();\n session.save(customer);\n tx.commit();\n session.close();\n }\n\n}" }, { "code": null, "e": 5991, "s": 5966, "text": "OneToManyDAOFactory.java" }, { "code": null, "e": 6170, "s": 5991, "text": "package com.onlinetutorialspoint.hibernate.dao;\n\npublic class OneToManyDAOFactory {\n\n public static OneToManyDAO getInstance() {\n return new OneToManyDAOImpl();\n }\n}" }, { "code": null, "e": 6202, "s": 6170, "text": "Create HibernateUtility Class :" }, { "code": null, "e": 6221, "s": 6202, "text": "HibernateUtil.java" }, { "code": null, "e": 6709, "s": 6221, "text": "package com.onlinetutorialspoint.util;\n\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\n\npublic class HibernateUtil {\n\n private HibernateUtil() {\n\n }\n private static SessionFactory sessionFactory;\n\n public static synchronized SessionFactory getInstnce() {\n if (sessionFactory == null) {\n sessionFactory = new Configuration().configure(\"hibernate.cfg.xml\").buildSessionFactory();\n }\n return sessionFactory;\n\n }\n}" }, { "code": null, "e": 6755, "s": 6709, "text": "To Run the application create client class : " }, { "code": null, "e": 6765, "s": 6755, "text": "Main.java" }, { "code": null, "e": 7749, "s": 6765, "text": "import com.onlinetutorialspoint.hibernate.dao.OneToManyDAO;\nimport com.onlinetutorialspoint.hibernate.dao.OneToManyDAOFactory;\nimport com.onlinetutorialspoint.hibernate.model.Customer;\nimport com.onlinetutorialspoint.hibernate.model.Items;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class Main {\n\n public static void main(String[] args) {\n Customer customer = new Customer();\n customer.setCustomerId(1001);\n customer.setCustomerName(\"Dinesh\");\n customer.setCity(\"Banglore\");\n\n Items i1 = new Items();\n i1.setItemId(9001);\n i1.setItemName(\"Samsung\");\n i1.setPrice(9000);\n\n Items i2 = new Items();\n i2.setItemId(9002);\n i2.setItemName(\"LG\");\n i2.setPrice(6000);\n\n Set items = new HashSet();\n items.add(i1);\n items.add(i2);\n\n customer.setItems(items);\n\n OneToManyDAO dao = OneToManyDAOFactory.getInstance();\n dao.saveCustomer(customer);\n }\n}" }, { "code": null, "e": 7758, "s": 7749, "text": "Output :" }, { "code": null, "e": 8090, "s": 7758, "text": "Hibernate: insert into customer (custname, city, custid) values (?, ?, ?)\nHibernate: insert into item (itemname, price, itemid) values (?, ?, ?)\nHibernate: insert into item (itemname, price, itemid) values (?, ?, ?)\nHibernate: update item set customerid_fk=? where itemid=?\nHibernate: update item set customerid_fk=? where itemid=?" }, { "code": null, "e": 8302, "s": 8090, "text": "By running the Main.class, we can observe the above output. On the above out put first hibernate performs the insert operation in customer table and after that the corresponding child tables insertion also done." }, { "code": null, "e": 8530, "s": 8302, "text": "But in Main.java we didn’t perform any save() operation on Items class. Based on the configuration <one-to-many> tag in customer.hbm.xml file, hibernate will understand the relationship between the Customer and Items entities." }, { "code": null, "e": 8547, "s": 8530, "text": "Happy Learning 🙂" }, { "code": null, "e": 8631, "s": 8547, "text": "\n\nHibernate One To Many Relation Complete Example\n\nFile size: 20 KB\nDownloads: 951\n" }, { "code": null, "e": 9242, "s": 8631, "text": "\nMany to One Mapping in Hibernate Example\nOne to One Mapping in Hibernate using foreign key (XML)\nHibernate Many to Many Mapping Example (XML)\nHibernate One to One Mapping using primary key (XML)\nHibernate Right Join Example\nHibernate Left Join Example\nHibernate Composite Key Mapping Example\nHibernate One To Many Using Annotations\nBasic Hibernate Example with XML Configuration\nHibernate Filter Example Xml Configuration\nhbm2ddl.auto Example in Hibernate XML Config\nHibernate Inheritance Mapping Strategies\nHibernate Named Query with Example\nCustom Generator Class in Hibernate\nHibernate Interceptor Example\n" }, { "code": null, "e": 9283, "s": 9242, "text": "Many to One Mapping in Hibernate Example" }, { "code": null, "e": 9339, "s": 9283, "text": "One to One Mapping in Hibernate using foreign key (XML)" }, { "code": null, "e": 9384, "s": 9339, "text": "Hibernate Many to Many Mapping Example (XML)" }, { "code": null, "e": 9437, "s": 9384, "text": "Hibernate One to One Mapping using primary key (XML)" }, { "code": null, "e": 9466, "s": 9437, "text": "Hibernate Right Join Example" }, { "code": null, "e": 9494, "s": 9466, "text": "Hibernate Left Join Example" }, { "code": null, "e": 9534, "s": 9494, "text": "Hibernate Composite Key Mapping Example" }, { "code": null, "e": 9574, "s": 9534, "text": "Hibernate One To Many Using Annotations" }, { "code": null, "e": 9621, "s": 9574, "text": "Basic Hibernate Example with XML Configuration" }, { "code": null, "e": 9664, "s": 9621, "text": "Hibernate Filter Example Xml Configuration" }, { "code": null, "e": 9709, "s": 9664, "text": "hbm2ddl.auto Example in Hibernate XML Config" }, { "code": null, "e": 9750, "s": 9709, "text": "Hibernate Inheritance Mapping Strategies" }, { "code": null, "e": 9785, "s": 9750, "text": "Hibernate Named Query with Example" }, { "code": null, "e": 9821, "s": 9785, "text": "Custom Generator Class in Hibernate" }, { "code": null, "e": 9851, "s": 9821, "text": "Hibernate Interceptor Example" }, { "code": null, "e": 9998, "s": 9851, "text": "\n\n\n\n\n\nSravya\nMarch 28, 2021 at 7:02 am - Reply \n\nWow..finally found a good site for learning hibernate with best examples.\nThank you so much.\n\n\n\n\n" }, { "code": null, "e": 10143, "s": 9998, "text": "\n\n\n\n\nSravya\nMarch 28, 2021 at 7:02 am - Reply \n\nWow..finally found a good site for learning hibernate with best examples.\nThank you so much.\n\n\n\n" }, { "code": null, "e": 10236, "s": 10143, "text": "Wow..finally found a good site for learning hibernate with best examples.\nThank you so much." }, { "code": null, "e": 10242, "s": 10240, "text": "Δ" }, { "code": null, "e": 10268, "s": 10242, "text": " Hibernate – Introduction" }, { "code": null, "e": 10292, "s": 10268, "text": " Hibernate – Advantages" }, { "code": null, "e": 10324, "s": 10292, "text": " Hibernate – Download and Setup" }, { "code": null, "e": 10354, "s": 10324, "text": " Hibernate – Sql Dialect list" }, { "code": null, "e": 10384, "s": 10354, "text": " Hibernate – Helloworld – XML" }, { "code": null, "e": 10422, "s": 10384, "text": " Hibernate – Install Tools in Eclipse" }, { "code": null, "e": 10449, "s": 10422, "text": " Hibernate – Object States" }, { "code": null, "e": 10487, "s": 10449, "text": " Hibernate – Helloworld – Annotations" }, { "code": null, "e": 10525, "s": 10487, "text": " Hibernate – One to One Mapping – XML" }, { "code": null, "e": 10575, "s": 10525, "text": " Hibernate – One to One Mapping foreign key – XML" }, { "code": null, "e": 10605, "s": 10575, "text": " Hibernate – One To Many -XML" }, { "code": null, "e": 10644, "s": 10605, "text": " Hibernate – One To Many – Annotations" }, { "code": null, "e": 10684, "s": 10644, "text": " Hibernate – Many to Many Mapping – XML" }, { "code": null, "e": 10715, "s": 10684, "text": " Hibernate – Many to One – XML" }, { "code": null, "e": 10750, "s": 10715, "text": " Hibernate – Composite Key Mapping" }, { "code": null, "e": 10775, "s": 10750, "text": " Hibernate – Named Query" }, { "code": null, "e": 10805, "s": 10775, "text": " Hibernate – Native SQL Query" }, { "code": null, "e": 10834, "s": 10805, "text": " Hibernate – load() vs get()" }, { "code": null, "e": 10871, "s": 10834, "text": " Hibernate Criteria API with Example" }, { "code": null, "e": 10897, "s": 10871, "text": " Hibernate – Restrictions" }, { "code": null, "e": 10921, "s": 10897, "text": " Hibernate – Projection" }, { "code": null, "e": 10955, "s": 10921, "text": " Hibernate – Query Language (HQL)" }, { "code": null, "e": 10989, "s": 10955, "text": " Hibernate – Groupby Criteria HQL" }, { "code": null, "e": 11019, "s": 10989, "text": " Hibernate – Orderby Criteria" }, { "code": null, "e": 11052, "s": 11019, "text": " Hibernate – HQLSelect Operation" }, { "code": null, "e": 11084, "s": 11052, "text": " Hibernate – HQL Update, Delete" }, { "code": null, "e": 11110, "s": 11084, "text": " Hibernate – Update Query" }, { "code": null, "e": 11139, "s": 11110, "text": " Hibernate – Update vs Merge" }, { "code": null, "e": 11163, "s": 11139, "text": " Hibernate – Right Join" }, { "code": null, "e": 11186, "s": 11163, "text": " Hibernate – Left Join" }, { "code": null, "e": 11210, "s": 11186, "text": " Hibernate – Pagination" }, { "code": null, "e": 11241, "s": 11210, "text": " Hibernate – Generator Classes" }, { "code": null, "e": 11271, "s": 11241, "text": " Hibernate – Custom Generator" }, { "code": null, "e": 11305, "s": 11271, "text": " Hibernate – Inheritance Mappings" }, { "code": null, "e": 11334, "s": 11305, "text": " Hibernate – Table per Class" }, { "code": null, "e": 11367, "s": 11334, "text": " Hibernate – Table per Sub Class" }, { "code": null, "e": 11405, "s": 11367, "text": " Hibernate – Table per Concrete Class" }, { "code": null, "e": 11447, "s": 11405, "text": " Hibernate – Table per Class Annotations" }, { "code": null, "e": 11478, "s": 11447, "text": " Hibernate – Stored Procedures" }, { "code": null, "e": 11511, "s": 11478, "text": " Hibernate – @Formula Annotation" }, { "code": null, "e": 11549, "s": 11511, "text": " Hibernate – Singleton SessionFactory" }, { "code": null, "e": 11574, "s": 11549, "text": " Hibernate – Interceptor" }, { "code": null, "e": 11620, "s": 11574, "text": " hbm2ddl.auto Example in Hibernate XML Config" } ]
Python Pandas - Get the quarter of the year from Period object
To get the quarter of the year component of the Period, use the period.quarter property. At first, import the required libraries − import pandas as pd The pandas.Period represents a period of time. Creating two Period objects period1 = pd.Period("2020-02-27 08:32:48") period2 = pd.Period(freq="M", year = 2021, month = 8, day = 16, hour = 2, minute = 35) Display the Period objects print("Period1...\n", period1) print("Period2...\n", period2) Get the quarter of the year from two Period objects res1 = period1.quarter res2 = period2.quarter Result is based on the following quarters of an year Quarter 1 = 1st January to 31st March Quarter 2 = 1st April to 30th June Quarter 3 = 1st July to 30th September Quarter 4 = 1st October to 31st December Following is the code import pandas as pd # The pandas.Period represents a period of time # creating two Period objects period1 = pd.Period("2020-02-27 08:32:48") period2 = pd.Period(freq="M", year = 2021, month = 8, day = 16, hour = 2, minute = 35) # display the Period objects print("Period1...\n", period1) print("Period2...\n", period2) # get the quarter of the year from two Period objects res1 = period1.quarter res2 = period2.quarter # Return the quarter from the two Period objects # Result is based on the following quarters of an year: # Quarter 1 = 1st January to 31st March # Quarter 2 = 1st April to 30th June # Quarter 3 = 1st July to 30th September # Quarter 4 = 1st October to 31st December print("\nQuarter from the 1st Period object ...\n", res1) print("\nQuarter from the 2nd Period object...\n", res2) This will produce the following code Period1... 2020-02-27 08:32:48 Period2... 2021-08 Quarter from the 1st Period object ... 1 Quarter from the 2nd Period object... 3
[ { "code": null, "e": 1193, "s": 1062, "text": "To get the quarter of the year component of the Period, use the period.quarter property. At first, import the required libraries −" }, { "code": null, "e": 1213, "s": 1193, "text": "import pandas as pd" }, { "code": null, "e": 1288, "s": 1213, "text": "The pandas.Period represents a period of time. Creating two Period objects" }, { "code": null, "e": 1418, "s": 1288, "text": "period1 = pd.Period(\"2020-02-27 08:32:48\")\nperiod2 = pd.Period(freq=\"M\", year = 2021, month = 8, day = 16, hour = 2, minute = 35)" }, { "code": null, "e": 1445, "s": 1418, "text": "Display the Period objects" }, { "code": null, "e": 1507, "s": 1445, "text": "print(\"Period1...\\n\", period1)\nprint(\"Period2...\\n\", period2)" }, { "code": null, "e": 1559, "s": 1507, "text": "Get the quarter of the year from two Period objects" }, { "code": null, "e": 1605, "s": 1559, "text": "res1 = period1.quarter\nres2 = period2.quarter" }, { "code": null, "e": 1658, "s": 1605, "text": "Result is based on the following quarters of an year" }, { "code": null, "e": 1811, "s": 1658, "text": "Quarter 1 = 1st January to 31st March\nQuarter 2 = 1st April to 30th June\nQuarter 3 = 1st July to 30th September\nQuarter 4 = 1st October to 31st December" }, { "code": null, "e": 1833, "s": 1811, "text": "Following is the code" }, { "code": null, "e": 2637, "s": 1833, "text": "import pandas as pd\n\n# The pandas.Period represents a period of time\n# creating two Period objects\nperiod1 = pd.Period(\"2020-02-27 08:32:48\")\nperiod2 = pd.Period(freq=\"M\", year = 2021, month = 8, day = 16, hour = 2, minute = 35)\n\n# display the Period objects\nprint(\"Period1...\\n\", period1)\nprint(\"Period2...\\n\", period2)\n\n# get the quarter of the year from two Period objects\nres1 = period1.quarter\nres2 = period2.quarter\n\n# Return the quarter from the two Period objects\n# Result is based on the following quarters of an year:\n# Quarter 1 = 1st January to 31st March\n# Quarter 2 = 1st April to 30th June\n# Quarter 3 = 1st July to 30th September\n# Quarter 4 = 1st October to 31st December\nprint(\"\\nQuarter from the 1st Period object ...\\n\", res1)\nprint(\"\\nQuarter from the 2nd Period object...\\n\", res2)" }, { "code": null, "e": 2674, "s": 2637, "text": "This will produce the following code" }, { "code": null, "e": 2807, "s": 2674, "text": "Period1...\n2020-02-27 08:32:48\nPeriod2...\n2021-08\n\nQuarter from the 1st Period object ...\n1\n\nQuarter from the 2nd Period object...\n3" } ]
Node.js - Global Objects
Node.js global objects are global in nature and they are available in all modules. We do not need to include these objects in our application, rather we can use them directly. These objects are modules, functions, strings and object itself as explained below. The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program, this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file. Create a js file named main.js with the following code − // Let's try to print the value of __filename console.log( __filename ); Now run the main.js to see the result − $ node main.js Based on the location of your program, it will print the main file name as follows − /web/com/1427091028_21099/main.js The __dirname represents the name of the directory that the currently executing script resides in. Create a js file named main.js with the following code − // Let's try to print the value of __dirname console.log( __dirname ); Now run the main.js to see the result − $ node main.js Based on the location of your program, it will print current directory name as follows − /web/com/1427091028_21099 The setTimeout(cb, ms) global function is used to run callback cb after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days. This function returns an opaque value that represents the timer which can be used to clear the timer. Create a js file named main.js with the following code − function printHello() { console.log( "Hello, World!"); } // Now call above function after 2 seconds setTimeout(printHello, 2000); Now run the main.js to see the result − $ node main.js Verify the output is printed after a little delay. Hello, World! The clearTimeout(t) global function is used to stop a timer that was previously created with setTimeout(). Here t is the timer returned by the setTimeout() function. Create a js file named main.js with the following code − function printHello() { console.log( "Hello, World!"); } // Now call above function after 2 seconds var t = setTimeout(printHello, 2000); // Now clear the timer clearTimeout(t); Now run the main.js to see the result − $ node main.js Verify the output where you will not find anything printed. The setInterval(cb, ms) global function is used to run callback cb repeatedly after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days. This function returns an opaque value that represents the timer which can be used to clear the timer using the function clearInterval(t). Create a js file named main.js with the following code − function printHello() { console.log( "Hello, World!"); } // Now call above function after 2 seconds setInterval(printHello, 2000); Now run the main.js to see the result − $ node main.js The above program will execute printHello() after every 2 second. Due to system limitation. The following table provides a list of other objects which we use frequently in our applications. For a more detail, you can refer to the official documentation. Used to print information on stdout and stderr. Used to get information on current process. Provides multiple events related to process activities. 44 Lectures 7.5 hours Eduonix Learning Solutions 88 Lectures 17 hours Eduonix Learning Solutions 32 Lectures 1.5 hours Richard Wells 8 Lectures 33 mins Anant Rungta 9 Lectures 2.5 hours SHIVPRASAD KOIRALA 97 Lectures 6 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2278, "s": 2018, "text": "Node.js global objects are global in nature and they are available in all modules. We do not need to include these objects in our application, rather we can use them directly. These objects are modules, functions, strings and object itself as explained below." }, { "code": null, "e": 2546, "s": 2278, "text": "The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program, this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file." }, { "code": null, "e": 2603, "s": 2546, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 2677, "s": 2603, "text": "// Let's try to print the value of __filename\n\nconsole.log( __filename );" }, { "code": null, "e": 2717, "s": 2677, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 2733, "s": 2717, "text": "$ node main.js\n" }, { "code": null, "e": 2818, "s": 2733, "text": "Based on the location of your program, it will print the main file name as follows −" }, { "code": null, "e": 2853, "s": 2818, "text": "/web/com/1427091028_21099/main.js\n" }, { "code": null, "e": 2952, "s": 2853, "text": "The __dirname represents the name of the directory that the currently executing script resides in." }, { "code": null, "e": 3009, "s": 2952, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 3081, "s": 3009, "text": "// Let's try to print the value of __dirname\n\nconsole.log( __dirname );" }, { "code": null, "e": 3121, "s": 3081, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 3137, "s": 3121, "text": "$ node main.js\n" }, { "code": null, "e": 3226, "s": 3137, "text": "Based on the location of your program, it will print current directory name as follows −" }, { "code": null, "e": 3253, "s": 3226, "text": "/web/com/1427091028_21099\n" }, { "code": null, "e": 3480, "s": 3253, "text": "The setTimeout(cb, ms) global function is used to run callback cb after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days." }, { "code": null, "e": 3582, "s": 3480, "text": "This function returns an opaque value that represents the timer which can be used to clear the timer." }, { "code": null, "e": 3639, "s": 3582, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 3773, "s": 3639, "text": "function printHello() {\n console.log( \"Hello, World!\");\n}\n\n// Now call above function after 2 seconds\nsetTimeout(printHello, 2000);" }, { "code": null, "e": 3813, "s": 3773, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 3829, "s": 3813, "text": "$ node main.js\n" }, { "code": null, "e": 3880, "s": 3829, "text": "Verify the output is printed after a little delay." }, { "code": null, "e": 3895, "s": 3880, "text": "Hello, World!\n" }, { "code": null, "e": 4061, "s": 3895, "text": "The clearTimeout(t) global function is used to stop a timer that was previously created with setTimeout(). Here t is the timer returned by the setTimeout() function." }, { "code": null, "e": 4118, "s": 4061, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 4301, "s": 4118, "text": "function printHello() {\n console.log( \"Hello, World!\");\n}\n\n// Now call above function after 2 seconds\nvar t = setTimeout(printHello, 2000);\n\n// Now clear the timer\nclearTimeout(t);" }, { "code": null, "e": 4341, "s": 4301, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 4357, "s": 4341, "text": "$ node main.js\n" }, { "code": null, "e": 4417, "s": 4357, "text": "Verify the output where you will not find anything printed." }, { "code": null, "e": 4656, "s": 4417, "text": "The setInterval(cb, ms) global function is used to run callback cb repeatedly after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days." }, { "code": null, "e": 4794, "s": 4656, "text": "This function returns an opaque value that represents the timer which can be used to clear the timer using the function clearInterval(t)." }, { "code": null, "e": 4851, "s": 4794, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 4986, "s": 4851, "text": "function printHello() {\n console.log( \"Hello, World!\");\n}\n\n// Now call above function after 2 seconds\nsetInterval(printHello, 2000);" }, { "code": null, "e": 5026, "s": 4986, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 5042, "s": 5026, "text": "$ node main.js\n" }, { "code": null, "e": 5134, "s": 5042, "text": "The above program will execute printHello() after every 2 second. Due to system limitation." }, { "code": null, "e": 5296, "s": 5134, "text": "The following table provides a list of other objects which we use frequently in our applications. For a more detail, you can refer to the official documentation." }, { "code": null, "e": 5345, "s": 5296, "text": " Used to print information on stdout and stderr." }, { "code": null, "e": 5445, "s": 5345, "text": "Used to get information on current process. Provides multiple events related to process activities." }, { "code": null, "e": 5480, "s": 5445, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5508, "s": 5480, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5542, "s": 5508, "text": "\n 88 Lectures \n 17 hours \n" }, { "code": null, "e": 5570, "s": 5542, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5605, "s": 5570, "text": "\n 32 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5620, "s": 5605, "text": " Richard Wells" }, { "code": null, "e": 5651, "s": 5620, "text": "\n 8 Lectures \n 33 mins\n" }, { "code": null, "e": 5665, "s": 5651, "text": " Anant Rungta" }, { "code": null, "e": 5699, "s": 5665, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5719, "s": 5699, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 5752, "s": 5719, "text": "\n 97 Lectures \n 6 hours \n" }, { "code": null, "e": 5772, "s": 5752, "text": " Skillbakerystudios" }, { "code": null, "e": 5779, "s": 5772, "text": " Print" }, { "code": null, "e": 5790, "s": 5779, "text": " Add Notes" } ]
Java & MySQL - Select Database Example
This chapter provides an example on how to select a Database using JDBC application. Before executing the following example, make sure you have the following in place − To execute the following example you need to replace the username and password with your actual user name and password. To execute the following example you need to replace the username and password with your actual user name and password. Your MySQL database you are using, is up and running. Your MySQL database you are using, is up and running. The following steps are required to create a new Database using JDBC application − Import the packages − Requires that you include the packages containing the JDBC classes needed for the database programming. Most often, using import java.sql.* will suffice. Import the packages − Requires that you include the packages containing the JDBC classes needed for the database programming. Most often, using import java.sql.* will suffice. Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a selected database. Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a selected database. Selection of database is made while you prepare database URL. Following example would make connection with STUDENTS database. Selection of database is made while you prepare database URL. Following example would make connection with STUDENTS database. Clean up the environment − try with resources automatically closes the resources. Clean up the environment − try with resources automatically closes the resources. Copy and paste the following example in JDBCExample.java, compile and run as follows − import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class JDBCExample { static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT"; static final String USER = "guest"; static final String PASS = "guest123"; public static void main(String[] args) { System.out.println("Connecting to a selected database..."); // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);) { System.out.println("Connected database successfully..."); } catch (SQLException e) { e.printStackTrace(); } } } Now let us compile the above example as follows − C:\>javac JDBCExample.java C:\> When you run JDBCExample, it produces the following result − C:\>java JDBCExample Connecting to a selected database... Connected database successfully... C:\> 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2855, "s": 2686, "text": "This chapter provides an example on how to select a Database using JDBC application. Before executing the following example, make sure you have the following in place −" }, { "code": null, "e": 2975, "s": 2855, "text": "To execute the following example you need to replace the username and password with your actual user name and password." }, { "code": null, "e": 3095, "s": 2975, "text": "To execute the following example you need to replace the username and password with your actual user name and password." }, { "code": null, "e": 3149, "s": 3095, "text": "Your MySQL database you are using, is up and running." }, { "code": null, "e": 3203, "s": 3149, "text": "Your MySQL database you are using, is up and running." }, { "code": null, "e": 3286, "s": 3203, "text": "The following steps are required to create a new Database using JDBC application −" }, { "code": null, "e": 3462, "s": 3286, "text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for the database programming. Most often, using import java.sql.* will suffice." }, { "code": null, "e": 3638, "s": 3462, "text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for the database programming. Most often, using import java.sql.* will suffice." }, { "code": null, "e": 3810, "s": 3638, "text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a selected database." }, { "code": null, "e": 3982, "s": 3810, "text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a selected database." }, { "code": null, "e": 4108, "s": 3982, "text": "Selection of database is made while you prepare database URL. Following example would make connection with STUDENTS database." }, { "code": null, "e": 4234, "s": 4108, "text": "Selection of database is made while you prepare database URL. Following example would make connection with STUDENTS database." }, { "code": null, "e": 4316, "s": 4234, "text": "Clean up the environment − try with resources automatically closes the resources." }, { "code": null, "e": 4398, "s": 4316, "text": "Clean up the environment − try with resources automatically closes the resources." }, { "code": null, "e": 4485, "s": 4398, "text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −" }, { "code": null, "e": 5157, "s": 4485, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n\n public static void main(String[] args) {\n System.out.println(\"Connecting to a selected database...\");\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);) {\t\t \n System.out.println(\"Connected database successfully...\"); \n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}" }, { "code": null, "e": 5207, "s": 5157, "text": "Now let us compile the above example as follows −" }, { "code": null, "e": 5240, "s": 5207, "text": "C:\\>javac JDBCExample.java\nC:\\>\n" }, { "code": null, "e": 5301, "s": 5240, "text": "When you run JDBCExample, it produces the following result −" }, { "code": null, "e": 5400, "s": 5301, "text": "C:\\>java JDBCExample\nConnecting to a selected database...\nConnected database successfully...\nC:\\>\n" }, { "code": null, "e": 5433, "s": 5400, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5449, "s": 5433, "text": " Malhar Lathkar" }, { "code": null, "e": 5482, "s": 5449, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5498, "s": 5482, "text": " Malhar Lathkar" }, { "code": null, "e": 5533, "s": 5498, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5547, "s": 5533, "text": " Anadi Sharma" }, { "code": null, "e": 5581, "s": 5547, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5595, "s": 5581, "text": " Tushar Kale" }, { "code": null, "e": 5632, "s": 5595, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5647, "s": 5632, "text": " Monica Mittal" }, { "code": null, "e": 5680, "s": 5647, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 5699, "s": 5680, "text": " Arnab Chakraborty" }, { "code": null, "e": 5706, "s": 5699, "text": " Print" }, { "code": null, "e": 5717, "s": 5706, "text": " Add Notes" } ]
What are different types of access modifiers available in C#?
Access modifiers are used to specify the scope of accessibility of a member of a class or type of the class itself. There are six different types of access modifiers. Public Public Private Private Protected Protected Internal Internal Protected Internal Protected Internal Private Protected Private Protected Objects that implement public access modifiers are accessible from everywhere in a project without any restrictions. using System; namespace MyApplication{ public class Program{ public static void Main(){ Person person = new Person(); Console.WriteLine(person.Name); //Person Name is accessible as it is public } } public class Person{ public string Name = "Mark"; } } Objects that implement private access modifier are accessible only inside a class or a structure. As a result, we can’t access them outside the class they are created. using System; namespace MyApplication{ public class Program{ public static void Main(){ Person person = new Person(); Console.WriteLine(person.Name); //Since Name is private it is not accessible in Program class. // Error: Person.Name is inaccessible due to its protection level. } } public class Person{ private string Name = "Mark"; } } The protected keyword implies that the object is accessible inside the class and in all classes that derive from that class. using System; namespace MyApplication{ public class Program{ public static void Main(){ Employee employee = new Employee(); employee.Print(); //Output: Mark Person person = new Person(); Console.WriteLine(person.Name); // Error: Person.Name is inaccessible due to its protection level. } } public class Person{ protected string Name = "Mark"; } public class Employee : Person{ public void Print(){ Console.WriteLine(Name); } } } For Internal keyword, the access is limited exclusively to classes defined within the current project assembly. Project 1 − Live Demo using System; namespace MyApplication{ public class Program{ public static void Main(){ Person person = new Person(); Console.WriteLine(person.Name); //Output: Mark } } public class Person{ internal string Name = "Mark"; } } Mark Project 2 − using MyApplication; using System; namespace Project2{ public class Project2Class{ public void Print(){ Person person = new Person(); Console.WriteLine(person.Name); // Error: Person.Name is inaccessible due to its protection level. } } } The protected internal access modifier is a combination of protected and internal. As a result, we can access the protected internal member only in the same assembly or in a derived class in other assemblies. Project 1 − Live Demo using System; namespace MyApplication{ public class Program{ public static void Main(){ Person person = new Person(); Console.WriteLine(person.Name); //Output: Mark } } public class Person{ protected internal string Name = "Mark"; } } Mark Project 2 − using MyApplication; using System; namespace Project2{ public class Project2Class : Person{ public void Print(){ Console.WriteLine(Name); //Output: Mark } } } The private protected access modifier is a combination of the private and protected keywords. We can access members inside the containing class or in a class that derives from a containing class, but only in the same assembly(project). Therefore, if we try to access it from another assembly, we will get an error. This modifier is valid in C# version 7.2 and later.
[ { "code": null, "e": 1229, "s": 1062, "text": "Access modifiers are used to specify the scope of accessibility of a member of a class or type of the class itself. There are six different types of access modifiers." }, { "code": null, "e": 1236, "s": 1229, "text": "Public" }, { "code": null, "e": 1243, "s": 1236, "text": "Public" }, { "code": null, "e": 1251, "s": 1243, "text": "Private" }, { "code": null, "e": 1259, "s": 1251, "text": "Private" }, { "code": null, "e": 1269, "s": 1259, "text": "Protected" }, { "code": null, "e": 1279, "s": 1269, "text": "Protected" }, { "code": null, "e": 1288, "s": 1279, "text": "Internal" }, { "code": null, "e": 1297, "s": 1288, "text": "Internal" }, { "code": null, "e": 1316, "s": 1297, "text": "Protected Internal" }, { "code": null, "e": 1335, "s": 1316, "text": "Protected Internal" }, { "code": null, "e": 1353, "s": 1335, "text": "Private Protected" }, { "code": null, "e": 1371, "s": 1353, "text": "Private Protected" }, { "code": null, "e": 1488, "s": 1371, "text": "Objects that implement public access modifiers are accessible from everywhere in a project without any restrictions." }, { "code": null, "e": 1797, "s": 1488, "text": "using System;\nnamespace MyApplication{\n public class Program{\n public static void Main(){\n Person person = new Person();\n Console.WriteLine(person.Name);\n //Person Name is accessible as it is public\n }\n }\n public class Person{\n public string Name = \"Mark\";\n }\n}" }, { "code": null, "e": 1965, "s": 1797, "text": "Objects that implement private access modifier are accessible only inside a class or a structure. As a result, we can’t access them outside the class they are created." }, { "code": null, "e": 2370, "s": 1965, "text": "using System;\nnamespace MyApplication{\n public class Program{\n public static void Main(){\n Person person = new Person();\n Console.WriteLine(person.Name);\n //Since Name is private it is not accessible in Program class.\n // Error: Person.Name is inaccessible due to its protection level.\n }\n }\n public class Person{\n private string Name = \"Mark\";\n }\n}" }, { "code": null, "e": 2495, "s": 2370, "text": "The protected keyword implies that the object is accessible inside the class and in all classes that derive from that class." }, { "code": null, "e": 3026, "s": 2495, "text": "using System;\nnamespace MyApplication{\n public class Program{\n public static void Main(){\n Employee employee = new Employee();\n employee.Print(); //Output: Mark\n Person person = new Person();\n Console.WriteLine(person.Name);\n // Error: Person.Name is inaccessible due to its protection level.\n }\n }\n public class Person{\n protected string Name = \"Mark\";\n }\n public class Employee : Person{\n public void Print(){\n Console.WriteLine(Name);\n }\n }\n}" }, { "code": null, "e": 3138, "s": 3026, "text": "For Internal keyword, the access is limited exclusively to classes defined within the current project assembly." }, { "code": null, "e": 3150, "s": 3138, "text": "Project 1 −" }, { "code": null, "e": 3161, "s": 3150, "text": " Live Demo" }, { "code": null, "e": 3434, "s": 3161, "text": "using System;\nnamespace MyApplication{\n public class Program{\n public static void Main(){\n Person person = new Person();\n Console.WriteLine(person.Name); //Output: Mark\n }\n }\n public class Person{\n internal string Name = \"Mark\";\n }\n}" }, { "code": null, "e": 3439, "s": 3434, "text": "Mark" }, { "code": null, "e": 3451, "s": 3439, "text": "Project 2 −" }, { "code": null, "e": 3735, "s": 3451, "text": "using MyApplication;\nusing System;\nnamespace Project2{\n public class Project2Class{\n public void Print(){\n Person person = new Person();\n Console.WriteLine(person.Name);\n // Error: Person.Name is inaccessible due to its protection level.\n }\n }\n}" }, { "code": null, "e": 3944, "s": 3735, "text": "The protected internal access modifier is a combination of protected and internal. As a result, we can access the protected internal member only in the same assembly or in a derived class in other assemblies." }, { "code": null, "e": 3956, "s": 3944, "text": "Project 1 −" }, { "code": null, "e": 3967, "s": 3956, "text": " Live Demo" }, { "code": null, "e": 4250, "s": 3967, "text": "using System;\nnamespace MyApplication{\n public class Program{\n public static void Main(){\n Person person = new Person();\n Console.WriteLine(person.Name); //Output: Mark\n }\n }\n public class Person{\n protected internal string Name = \"Mark\";\n }\n}" }, { "code": null, "e": 4255, "s": 4250, "text": "Mark" }, { "code": null, "e": 4267, "s": 4255, "text": "Project 2 −" }, { "code": null, "e": 4453, "s": 4267, "text": "using MyApplication;\nusing System;\nnamespace Project2{\n public class Project2Class : Person{\n public void Print(){\n Console.WriteLine(Name); //Output: Mark\n }\n }\n}" }, { "code": null, "e": 4820, "s": 4453, "text": "The private protected access modifier is a combination of the private and protected keywords. We can access members inside the containing class or in a class that derives from a containing class, but only in the same assembly(project). Therefore, if we try to access it from another assembly, we will get an error. This modifier is valid in C# version 7.2 and later." } ]
Scraping tweets and analyzing Social Sentiments | by Amardeep Chauhan | Towards Data Science
Natural Language Processing (NLP) is really a very interesting and broad field of Artificial Intelligence. Here I am going to use it for processing of text-based record and will give you a crash course on Scraping and Sentiment Analysis. For Scraping, I have used Selenium & tweepy and for Sentiment Analysis, I have used NLTK Classes and Methods and Naive Bayes Model. I have tried my best to cover most of the steps that should be performed while working on text data set and let me ensure you that It will be worth your time. So what is Scraping and Sentiment Analysis? Scraping — A process of getting small fragments of something. In our case, it is web scraping, so here we are taking fragments of information available on a website. Sentiment Analysis — You can deduce from the term itself that it is the process of analyzing views or opinions of people on any subject. Now the subject can be anything a Product, Movie, Political or Social Issue, Technology, any Event or some kind of Trend. People usually prefer Social Media to express their views or opinions, it can be Facebook, Twitter, Quora or any other blogging site. In this tutorial, I am going to consider Twitter as a source of information, and the subject I would like to choose is ‘AI and Deep Learning’, though the code that I will be sharing will be completely generic, so you can choose any other interesting topic as well. From the title and above description, you must have identified that the text data that is required to perform Sentiment Analysis needs to be scrapped from Twitter. So below are the major operation that I am going to perform: 1. Scraping Tweets 2. Identifying Sentiments 3. Text Pre-processing 4. Feature Extraction 5. Model Building Scraping Tweets Scraping Tweets If you have performed scraping in Python before, then you must have had used ‘Requests’ and ‘Beautiful Soup’; for those who have not heard of this before, Request is a Python HTTP library for sending HTTP requests and Beautiful Soup is an HTML parser to parse the DOM and get the desired information out of it. But we can not use these libraries to scrap tweets from the twitter, because of dynamic and progressive generation of tweets. Now we are left with two options: a). Selenium b). tweepy python library I will show you the implementation of both, By the way, Selenium is the browser mocking tool usually used for testing web pages and tweepy as I mentioned, a python library which provides access for various twitter APIs. a). Scrap using Selenium: Assuming you have already imported numpy and pandas. Below is the SeleniumClient class which will perform scraping: from selenium import webdriverfrom selenium.webdriver.common.keys import Keysclass SeleniumClient(object): def __init__(self): #Initialization method. self.chrome_options = webdriver.ChromeOptions() self.chrome_options.add_argument('--headless') self.chrome_options.add_argument('--no-sandbox') self.chrome_options.add_argument('--disable-setuid-sandbox') # you need to provide the path of chromdriver in your system self.browser = webdriver.Chrome('D:/chromedriver_win32/chromedriver', options=self.chrome_options) self.base_url = 'https://twitter.com/search?q=' def get_tweets(self, query): ''' Function to fetch tweets. ''' try: self.browser.get(self.base_url+query) time.sleep(2) body = self.browser.find_element_by_tag_name('body') for _ in range(3000): body.send_keys(Keys.PAGE_DOWN) time.sleep(0.3) timeline = self.browser.find_element_by_id('timeline') tweet_nodes = timeline.find_elements_by_css_selector('.tweet-text') return pd.DataFrame({'tweets': [tweet_node.text for tweet_node in tweet_nodes]}) except: print("Selenium - An error occured while fetching tweets.") In the above code, you need to specify the path of the desired browser’s webdriver or we can just set the environment variable and don’t pass any parameter inside webdriver.Chrome(). You can use this class: selenium_client = SeleniumClient()tweets_df = selenium_client.get_tweets('AI and Deep learning') In tweets_df, you will get the data-frame containing all the scrapped tweets. b). Fetch tweets using tweepy: We can create a TwitterClient class: import tweepyfrom tweepy import OAuthHandlerclass TwitterClient(object): def __init__(self): # Access Credentials consumer_key = 'XXXX' consumer_secret = 'XXXX' access_token = 'XXXX' access_token_secret = 'XXXX'try: # OAuthHandler object auth = OAuthHandler(consumer_key, consumer_secret) # set access token and secret auth.set_access_token(access_token, access_token_secret) # create tweepy API object to fetch tweets self.api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) except tweepy.TweepError as e: print(f"Error: Twitter Authentication Failed - \n{str(e)}") # Function to fetch tweets def get_tweets(self, query, maxTweets = 1000): # empty list to store parsed tweets tweets = [] sinceId = None max_id = -1 tweetCount = 0 tweetsPerQry = 100 while tweetCount < maxTweets: try: if (max_id <= 0): if (not sinceId): new_tweets = self.api.search(q=query, count=tweetsPerQry) else: new_tweets = self.api.search(q=query, count=tweetsPerQry, since_id=sinceId) else: if (not sinceId): new_tweets = self.api.search(q=query, count=tweetsPerQry, max_id=str(max_id - 1)) else: new_tweets = self.api.search(q=query, count=tweetsPerQry, max_id=str(max_id - 1), since_id=sinceId) if not new_tweets: print("No more tweets found") break for tweet in new_tweets: parsed_tweet = {} parsed_tweet['tweets'] = tweet.text # appending parsed tweet to tweets list if tweet.retweet_count > 0: # if tweet has retweets, ensure that it is appended only once if parsed_tweet not in tweets: tweets.append(parsed_tweet) else: tweets.append(parsed_tweet) tweetCount += len(new_tweets) print("Downloaded {0} tweets".format(tweetCount)) max_id = new_tweets[-1].id except tweepy.TweepError as e: print("Tweepy error : " + str(e)) break return pd.DataFrame(tweets) In the above code, we need ‘Access Credentials’ to make API calls, these can be obtained from Twitter's developer console, you just need to register your app and give all the valid reasons to get the access. This call can be used in the same way as we used SeleniumClient, In response, we will get a data-frame containing all the fetched tweets. Which one should you use? Yes, it is an obvious question. The answer is tweepy because it is fast and more reliable. However, if you don’t have access credentials for Twiter API’s and you don’t want to wait for Twitter approval, then you can go with SeleniumClient. It is always good to know the various approaches of doing any task. 2. Identifying Sentiment type So sentiment type is nothing but the overall reaction, it can be positive, negative or neutral. In our case, we are only going to consider positive (includes neutral) and negative. Q. Why should we identify Sentiment type? Because eventually, we will be training a model which should be capable of classifying negative and positive sentiments on tweets. For this classification, we will be using some supervised learning model, so we need to have a target variable. Sentiment type is going to be our target variable. I have identified two ways to identify: a. Using NLTK’s SentimentIntensityAnalyzer (We’ll refer as SIA)b. Using TextBlob import nltkfrom nltk.sentiment.vader import SentimentIntensityAnalyzerfrom textblob import TextBlobdef fetch_sentiment_using_SIA(text): sid = SentimentIntensityAnalyzer() polarity_scores = sid.polarity_scores(text) if polarity_scores['neg'] > polarity_scores['pos']: return 'negative' else: return 'positive'def fetch_sentiment_using_textblob(text): analysis = TextBlob(text) # set sentiment if analysis.sentiment.polarity >= 0: return 'positive' else: return 'negative' We can choose any of them, I personally prefer TextBlob, It gives better categorization. 3. Text Pre-processing Text obtained from tweets is not clean enough to be used for model training So it needs to be pre-processed first. We may not be able to make it completely clean but should try our best to pre-process as much as possible. a. Removing ‘@names’: All the ‘@anyname’ are of no use since they don’t convey any meaning. def remove_pattern(text, pattern_regex): r = re.findall(pattern_regex, text) for i in r: text = re.sub(i, '', text) return text# We are keeping cleaned tweets in a new column called 'tidy_tweets'tweets_df['tidy_tweets'] = np.vectorize(remove_pattern)(tweets_df['tweets'], "@[\w]*: | *RT*") b. Removing links (http | https) Links in the text are of no use because they don’t convey any useful information as well. cleaned_tweets = []for index, row in tweets_df.iterrows(): # Here we are filtering out all the words that contains link words_without_links = [word for word in row.tidy_tweets.split() if 'http' not in word] cleaned_tweets.append(' '.join(words_without_links))tweets_df['tidy_tweets'] = cleaned_tweets c. Dropping duplicate rows We may have duplicate tweets in our data-frame, it needs to be taken care of: tweets_df.drop_duplicates(subset=['tidy_tweets'], keep=False) d. Removing Punctuations, Numbers and Special characters tweets_df['absolute_tidy_tweets'] = tweets_df['tidy_tweets'].str.replace("[^a-zA-Z# ]", "") This step should not be followed if we also want to do sentiment analysis on __key phrases__ as well, because semantic meaning in a sentence needs to be present. So here we will create one additional column ‘absolute_tidy_tweets’ which will contain absolute tidy words which can be further used for sentiment analysis on __key words__. e. Removing Stop Words Stop words are the words in that are used just for the sake of correct sentence formations. They don’t have any meaning full information. So it needs to be removed to make our text record cleaner. from nltk.corpus import stopwordsnltk.download('stopwords')stopwords_set = set(stopwords.words("english"))cleaned_tweets = []for index, row in tweets_df.iterrows(): # filerting out all the stopwords words_without_stopwords = [word for word in row.absolute_tidy_tweets.split() if not word in stopwords_set] # finally creating tweets list of tuples containing stopwords(list) and sentimentType cleaned_tweets.append(' '.join(words_without_stopwords))tweets_df['absolute_tidy_tweets'] = cleaned_tweets f. Tokenization and lemmatization: from nltk.stem import WordNetLemmatizer# Tokenizationtokenized_tweet = tweets_df['absolute_tidy_tweets'].apply(lambda x: x.split())# Finding Lemma for each wordword_lemmatizer = WordNetLemmatizer()tokenized_tweet = tokenized_tweet.apply(lambda x: [word_lemmatizer.lemmatize(i) for i in x])#joining words into sentences (from where they came from)for i, tokens in enumerate(tokenized_tweet): tokenized_tweet[i] = ' '.join(tokens)tweets_df['absolute_tidy_tweets'] = tokenized_tweet 4. Feature Extraction We need to convert textual representation in the form of numeric features. We have two popular techniques to perform feature extraction: Bag of words (Simple vectorization)TF-IDF (Term Frequency — Inverse Document Frequency) Bag of words (Simple vectorization) TF-IDF (Term Frequency — Inverse Document Frequency) We will use extracted features from both one by one to perform sentiment analysis and will compare the result at last. Check out my below kernel to properly understand the intuition behind feature extraction techniques with examples:https://www.kaggle.com/amar09/text-pre-processing-and-feature-extraction from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer# BOW featuresbow_word_vectorizer = CountVectorizer(max_df=0.90, min_df=2, stop_words='english')# bag-of-words feature matrixbow_word_feature = bow_word_vectorizer.fit_transform(tweets_df['absolute_tidy_tweets'])# TF-IDF featurestfidf_word_vectorizer = TfidfVectorizer(max_df=0.90, min_df=2, stop_words='english')# TF-IDF feature matrixtfidf_word_feature = tfidf_word_vectorizer.fit_transform(tweets_df['absolute_tidy_tweets']) 5. Model Building Let’s map target variable to {0,1} first. target_variable = tweets_df['sentiment'].apply(lambda x: 0 if x=='negative' else 1 ) We are going to use Naive Bayes model for sentiment classification because I tried SVM, Logistic Regression and Decision Tree as well, but got the best results using Naive Bayes only. from sklearn.naive_bayes import GaussianNBfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import f1_scoredef naive_model(X_train, X_test, y_train, y_test): naive_classifier = GaussianNB() naive_classifier.fit(X_train.toarray(), y_train) # predictions over test set predictions = naive_classifier.predict(X_test.toarray()) # calculating f1 score print(f'F1 Score - {f1_score(y_test, predictions)}') Training for features extracted using Bag of Words: X_train, X_test, y_train, y_test = train_test_split(bow_word_feature, target_variable, test_size=0.3, random_state=870)naive_model(X_train, X_test, y_train, y_test) It gives F1 Score — 0.9387254901960784 Now lets train for features extracted from TF-IDF: X_train, X_test, y_train, y_test = train_test_split(tfidf_word_feature, target_variable, test_size=0.3, random_state=870)naive_model(X_train, X_test, y_train, y_test) I got F1 Score — 0.9400244798041616 TF-IDF features clearly give the better score. Conclusion: Here, for sentiment analysis, we have just used ‘key words’ only, we can use ‘key phrases’ as well. There are many other steps that we should perform, to know about them in detail check out my complete kernel. www.kaggle.com In this post, I have assumed that you already have a basic knowledge of text processing using NLTK. If you don’t have that then I will suggest you go through my below kernel that contains the explanation of all basic text operations and detailed explanation of Feature Extraction using BOW and TF-IDF. www.kaggle.com Please comment if you want more explanation on anything. All suggestions and feedbacks are always welcome. Thanks for reading, Happy Learning ;)
[ { "code": null, "e": 701, "s": 172, "text": "Natural Language Processing (NLP) is really a very interesting and broad field of Artificial Intelligence. Here I am going to use it for processing of text-based record and will give you a crash course on Scraping and Sentiment Analysis. For Scraping, I have used Selenium & tweepy and for Sentiment Analysis, I have used NLTK Classes and Methods and Naive Bayes Model. I have tried my best to cover most of the steps that should be performed while working on text data set and let me ensure you that It will be worth your time." }, { "code": null, "e": 745, "s": 701, "text": "So what is Scraping and Sentiment Analysis?" }, { "code": null, "e": 911, "s": 745, "text": "Scraping — A process of getting small fragments of something. In our case, it is web scraping, so here we are taking fragments of information available on a website." }, { "code": null, "e": 1170, "s": 911, "text": "Sentiment Analysis — You can deduce from the term itself that it is the process of analyzing views or opinions of people on any subject. Now the subject can be anything a Product, Movie, Political or Social Issue, Technology, any Event or some kind of Trend." }, { "code": null, "e": 1569, "s": 1170, "text": "People usually prefer Social Media to express their views or opinions, it can be Facebook, Twitter, Quora or any other blogging site. In this tutorial, I am going to consider Twitter as a source of information, and the subject I would like to choose is ‘AI and Deep Learning’, though the code that I will be sharing will be completely generic, so you can choose any other interesting topic as well." }, { "code": null, "e": 1794, "s": 1569, "text": "From the title and above description, you must have identified that the text data that is required to perform Sentiment Analysis needs to be scrapped from Twitter. So below are the major operation that I am going to perform:" }, { "code": null, "e": 1813, "s": 1794, "text": "1. Scraping Tweets" }, { "code": null, "e": 1839, "s": 1813, "text": "2. Identifying Sentiments" }, { "code": null, "e": 1862, "s": 1839, "text": "3. Text Pre-processing" }, { "code": null, "e": 1884, "s": 1862, "text": "4. Feature Extraction" }, { "code": null, "e": 1902, "s": 1884, "text": "5. Model Building" }, { "code": null, "e": 1918, "s": 1902, "text": "Scraping Tweets" }, { "code": null, "e": 1934, "s": 1918, "text": "Scraping Tweets" }, { "code": null, "e": 2405, "s": 1934, "text": "If you have performed scraping in Python before, then you must have had used ‘Requests’ and ‘Beautiful Soup’; for those who have not heard of this before, Request is a Python HTTP library for sending HTTP requests and Beautiful Soup is an HTML parser to parse the DOM and get the desired information out of it. But we can not use these libraries to scrap tweets from the twitter, because of dynamic and progressive generation of tweets. Now we are left with two options:" }, { "code": null, "e": 2418, "s": 2405, "text": "a). Selenium" }, { "code": null, "e": 2444, "s": 2418, "text": "b). tweepy python library" }, { "code": null, "e": 2664, "s": 2444, "text": "I will show you the implementation of both, By the way, Selenium is the browser mocking tool usually used for testing web pages and tweepy as I mentioned, a python library which provides access for various twitter APIs." }, { "code": null, "e": 2690, "s": 2664, "text": "a). Scrap using Selenium:" }, { "code": null, "e": 2806, "s": 2690, "text": "Assuming you have already imported numpy and pandas. Below is the SeleniumClient class which will perform scraping:" }, { "code": null, "e": 4104, "s": 2806, "text": "from selenium import webdriverfrom selenium.webdriver.common.keys import Keysclass SeleniumClient(object): def __init__(self): #Initialization method. self.chrome_options = webdriver.ChromeOptions() self.chrome_options.add_argument('--headless') self.chrome_options.add_argument('--no-sandbox') self.chrome_options.add_argument('--disable-setuid-sandbox') # you need to provide the path of chromdriver in your system self.browser = webdriver.Chrome('D:/chromedriver_win32/chromedriver', options=self.chrome_options) self.base_url = 'https://twitter.com/search?q=' def get_tweets(self, query): ''' Function to fetch tweets. ''' try: self.browser.get(self.base_url+query) time.sleep(2) body = self.browser.find_element_by_tag_name('body') for _ in range(3000): body.send_keys(Keys.PAGE_DOWN) time.sleep(0.3) timeline = self.browser.find_element_by_id('timeline') tweet_nodes = timeline.find_elements_by_css_selector('.tweet-text') return pd.DataFrame({'tweets': [tweet_node.text for tweet_node in tweet_nodes]}) except: print(\"Selenium - An error occured while fetching tweets.\")" }, { "code": null, "e": 4287, "s": 4104, "text": "In the above code, you need to specify the path of the desired browser’s webdriver or we can just set the environment variable and don’t pass any parameter inside webdriver.Chrome()." }, { "code": null, "e": 4311, "s": 4287, "text": "You can use this class:" }, { "code": null, "e": 4408, "s": 4311, "text": "selenium_client = SeleniumClient()tweets_df = selenium_client.get_tweets('AI and Deep learning')" }, { "code": null, "e": 4486, "s": 4408, "text": "In tweets_df, you will get the data-frame containing all the scrapped tweets." }, { "code": null, "e": 4517, "s": 4486, "text": "b). Fetch tweets using tweepy:" }, { "code": null, "e": 4554, "s": 4517, "text": "We can create a TwitterClient class:" }, { "code": null, "e": 7337, "s": 4554, "text": "import tweepyfrom tweepy import OAuthHandlerclass TwitterClient(object): def __init__(self): # Access Credentials consumer_key = 'XXXX' consumer_secret = 'XXXX' access_token = 'XXXX' access_token_secret = 'XXXX'try: # OAuthHandler object auth = OAuthHandler(consumer_key, consumer_secret) # set access token and secret auth.set_access_token(access_token, access_token_secret) # create tweepy API object to fetch tweets self.api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) except tweepy.TweepError as e: print(f\"Error: Twitter Authentication Failed - \\n{str(e)}\") # Function to fetch tweets def get_tweets(self, query, maxTweets = 1000): # empty list to store parsed tweets tweets = [] sinceId = None max_id = -1 tweetCount = 0 tweetsPerQry = 100 while tweetCount < maxTweets: try: if (max_id <= 0): if (not sinceId): new_tweets = self.api.search(q=query, count=tweetsPerQry) else: new_tweets = self.api.search(q=query, count=tweetsPerQry, since_id=sinceId) else: if (not sinceId): new_tweets = self.api.search(q=query, count=tweetsPerQry, max_id=str(max_id - 1)) else: new_tweets = self.api.search(q=query, count=tweetsPerQry, max_id=str(max_id - 1), since_id=sinceId) if not new_tweets: print(\"No more tweets found\") break for tweet in new_tweets: parsed_tweet = {} parsed_tweet['tweets'] = tweet.text # appending parsed tweet to tweets list if tweet.retweet_count > 0: # if tweet has retweets, ensure that it is appended only once if parsed_tweet not in tweets: tweets.append(parsed_tweet) else: tweets.append(parsed_tweet) tweetCount += len(new_tweets) print(\"Downloaded {0} tweets\".format(tweetCount)) max_id = new_tweets[-1].id except tweepy.TweepError as e: print(\"Tweepy error : \" + str(e)) break return pd.DataFrame(tweets)" }, { "code": null, "e": 7683, "s": 7337, "text": "In the above code, we need ‘Access Credentials’ to make API calls, these can be obtained from Twitter's developer console, you just need to register your app and give all the valid reasons to get the access. This call can be used in the same way as we used SeleniumClient, In response, we will get a data-frame containing all the fetched tweets." }, { "code": null, "e": 7709, "s": 7683, "text": "Which one should you use?" }, { "code": null, "e": 8017, "s": 7709, "text": "Yes, it is an obvious question. The answer is tweepy because it is fast and more reliable. However, if you don’t have access credentials for Twiter API’s and you don’t want to wait for Twitter approval, then you can go with SeleniumClient. It is always good to know the various approaches of doing any task." }, { "code": null, "e": 8047, "s": 8017, "text": "2. Identifying Sentiment type" }, { "code": null, "e": 8228, "s": 8047, "text": "So sentiment type is nothing but the overall reaction, it can be positive, negative or neutral. In our case, we are only going to consider positive (includes neutral) and negative." }, { "code": null, "e": 8270, "s": 8228, "text": "Q. Why should we identify Sentiment type?" }, { "code": null, "e": 8564, "s": 8270, "text": "Because eventually, we will be training a model which should be capable of classifying negative and positive sentiments on tweets. For this classification, we will be using some supervised learning model, so we need to have a target variable. Sentiment type is going to be our target variable." }, { "code": null, "e": 8604, "s": 8564, "text": "I have identified two ways to identify:" }, { "code": null, "e": 8685, "s": 8604, "text": "a. Using NLTK’s SentimentIntensityAnalyzer (We’ll refer as SIA)b. Using TextBlob" }, { "code": null, "e": 9210, "s": 8685, "text": "import nltkfrom nltk.sentiment.vader import SentimentIntensityAnalyzerfrom textblob import TextBlobdef fetch_sentiment_using_SIA(text): sid = SentimentIntensityAnalyzer() polarity_scores = sid.polarity_scores(text) if polarity_scores['neg'] > polarity_scores['pos']: return 'negative' else: return 'positive'def fetch_sentiment_using_textblob(text): analysis = TextBlob(text) # set sentiment if analysis.sentiment.polarity >= 0: return 'positive' else: return 'negative'" }, { "code": null, "e": 9299, "s": 9210, "text": "We can choose any of them, I personally prefer TextBlob, It gives better categorization." }, { "code": null, "e": 9322, "s": 9299, "text": "3. Text Pre-processing" }, { "code": null, "e": 9544, "s": 9322, "text": "Text obtained from tweets is not clean enough to be used for model training So it needs to be pre-processed first. We may not be able to make it completely clean but should try our best to pre-process as much as possible." }, { "code": null, "e": 9566, "s": 9544, "text": "a. Removing ‘@names’:" }, { "code": null, "e": 9636, "s": 9566, "text": "All the ‘@anyname’ are of no use since they don’t convey any meaning." }, { "code": null, "e": 9946, "s": 9636, "text": "def remove_pattern(text, pattern_regex): r = re.findall(pattern_regex, text) for i in r: text = re.sub(i, '', text) return text# We are keeping cleaned tweets in a new column called 'tidy_tweets'tweets_df['tidy_tweets'] = np.vectorize(remove_pattern)(tweets_df['tweets'], \"@[\\w]*: | *RT*\")" }, { "code": null, "e": 9979, "s": 9946, "text": "b. Removing links (http | https)" }, { "code": null, "e": 10069, "s": 9979, "text": "Links in the text are of no use because they don’t convey any useful information as well." }, { "code": null, "e": 10386, "s": 10069, "text": "cleaned_tweets = []for index, row in tweets_df.iterrows(): # Here we are filtering out all the words that contains link words_without_links = [word for word in row.tidy_tweets.split() if 'http' not in word] cleaned_tweets.append(' '.join(words_without_links))tweets_df['tidy_tweets'] = cleaned_tweets" }, { "code": null, "e": 10413, "s": 10386, "text": "c. Dropping duplicate rows" }, { "code": null, "e": 10491, "s": 10413, "text": "We may have duplicate tweets in our data-frame, it needs to be taken care of:" }, { "code": null, "e": 10553, "s": 10491, "text": "tweets_df.drop_duplicates(subset=['tidy_tweets'], keep=False)" }, { "code": null, "e": 10610, "s": 10553, "text": "d. Removing Punctuations, Numbers and Special characters" }, { "code": null, "e": 10702, "s": 10610, "text": "tweets_df['absolute_tidy_tweets'] = tweets_df['tidy_tweets'].str.replace(\"[^a-zA-Z# ]\", \"\")" }, { "code": null, "e": 11038, "s": 10702, "text": "This step should not be followed if we also want to do sentiment analysis on __key phrases__ as well, because semantic meaning in a sentence needs to be present. So here we will create one additional column ‘absolute_tidy_tweets’ which will contain absolute tidy words which can be further used for sentiment analysis on __key words__." }, { "code": null, "e": 11061, "s": 11038, "text": "e. Removing Stop Words" }, { "code": null, "e": 11258, "s": 11061, "text": "Stop words are the words in that are used just for the sake of correct sentence formations. They don’t have any meaning full information. So it needs to be removed to make our text record cleaner." }, { "code": null, "e": 11779, "s": 11258, "text": "from nltk.corpus import stopwordsnltk.download('stopwords')stopwords_set = set(stopwords.words(\"english\"))cleaned_tweets = []for index, row in tweets_df.iterrows(): # filerting out all the stopwords words_without_stopwords = [word for word in row.absolute_tidy_tweets.split() if not word in stopwords_set] # finally creating tweets list of tuples containing stopwords(list) and sentimentType cleaned_tweets.append(' '.join(words_without_stopwords))tweets_df['absolute_tidy_tweets'] = cleaned_tweets" }, { "code": null, "e": 11814, "s": 11779, "text": "f. Tokenization and lemmatization:" }, { "code": null, "e": 12297, "s": 11814, "text": "from nltk.stem import WordNetLemmatizer# Tokenizationtokenized_tweet = tweets_df['absolute_tidy_tweets'].apply(lambda x: x.split())# Finding Lemma for each wordword_lemmatizer = WordNetLemmatizer()tokenized_tweet = tokenized_tweet.apply(lambda x: [word_lemmatizer.lemmatize(i) for i in x])#joining words into sentences (from where they came from)for i, tokens in enumerate(tokenized_tweet): tokenized_tweet[i] = ' '.join(tokens)tweets_df['absolute_tidy_tweets'] = tokenized_tweet" }, { "code": null, "e": 12319, "s": 12297, "text": "4. Feature Extraction" }, { "code": null, "e": 12456, "s": 12319, "text": "We need to convert textual representation in the form of numeric features. We have two popular techniques to perform feature extraction:" }, { "code": null, "e": 12544, "s": 12456, "text": "Bag of words (Simple vectorization)TF-IDF (Term Frequency — Inverse Document Frequency)" }, { "code": null, "e": 12580, "s": 12544, "text": "Bag of words (Simple vectorization)" }, { "code": null, "e": 12633, "s": 12580, "text": "TF-IDF (Term Frequency — Inverse Document Frequency)" }, { "code": null, "e": 12752, "s": 12633, "text": "We will use extracted features from both one by one to perform sentiment analysis and will compare the result at last." }, { "code": null, "e": 12939, "s": 12752, "text": "Check out my below kernel to properly understand the intuition behind feature extraction techniques with examples:https://www.kaggle.com/amar09/text-pre-processing-and-feature-extraction" }, { "code": null, "e": 13443, "s": 12939, "text": "from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer# BOW featuresbow_word_vectorizer = CountVectorizer(max_df=0.90, min_df=2, stop_words='english')# bag-of-words feature matrixbow_word_feature = bow_word_vectorizer.fit_transform(tweets_df['absolute_tidy_tweets'])# TF-IDF featurestfidf_word_vectorizer = TfidfVectorizer(max_df=0.90, min_df=2, stop_words='english')# TF-IDF feature matrixtfidf_word_feature = tfidf_word_vectorizer.fit_transform(tweets_df['absolute_tidy_tweets'])" }, { "code": null, "e": 13461, "s": 13443, "text": "5. Model Building" }, { "code": null, "e": 13503, "s": 13461, "text": "Let’s map target variable to {0,1} first." }, { "code": null, "e": 13588, "s": 13503, "text": "target_variable = tweets_df['sentiment'].apply(lambda x: 0 if x=='negative' else 1 )" }, { "code": null, "e": 13772, "s": 13588, "text": "We are going to use Naive Bayes model for sentiment classification because I tried SVM, Logistic Regression and Decision Tree as well, but got the best results using Naive Bayes only." }, { "code": null, "e": 14217, "s": 13772, "text": "from sklearn.naive_bayes import GaussianNBfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import f1_scoredef naive_model(X_train, X_test, y_train, y_test): naive_classifier = GaussianNB() naive_classifier.fit(X_train.toarray(), y_train) # predictions over test set predictions = naive_classifier.predict(X_test.toarray()) # calculating f1 score print(f'F1 Score - {f1_score(y_test, predictions)}')" }, { "code": null, "e": 14269, "s": 14217, "text": "Training for features extracted using Bag of Words:" }, { "code": null, "e": 14434, "s": 14269, "text": "X_train, X_test, y_train, y_test = train_test_split(bow_word_feature, target_variable, test_size=0.3, random_state=870)naive_model(X_train, X_test, y_train, y_test)" }, { "code": null, "e": 14473, "s": 14434, "text": "It gives F1 Score — 0.9387254901960784" }, { "code": null, "e": 14524, "s": 14473, "text": "Now lets train for features extracted from TF-IDF:" }, { "code": null, "e": 14691, "s": 14524, "text": "X_train, X_test, y_train, y_test = train_test_split(tfidf_word_feature, target_variable, test_size=0.3, random_state=870)naive_model(X_train, X_test, y_train, y_test)" }, { "code": null, "e": 14727, "s": 14691, "text": "I got F1 Score — 0.9400244798041616" }, { "code": null, "e": 14774, "s": 14727, "text": "TF-IDF features clearly give the better score." }, { "code": null, "e": 14996, "s": 14774, "text": "Conclusion: Here, for sentiment analysis, we have just used ‘key words’ only, we can use ‘key phrases’ as well. There are many other steps that we should perform, to know about them in detail check out my complete kernel." }, { "code": null, "e": 15011, "s": 14996, "text": "www.kaggle.com" }, { "code": null, "e": 15313, "s": 15011, "text": "In this post, I have assumed that you already have a basic knowledge of text processing using NLTK. If you don’t have that then I will suggest you go through my below kernel that contains the explanation of all basic text operations and detailed explanation of Feature Extraction using BOW and TF-IDF." }, { "code": null, "e": 15328, "s": 15313, "text": "www.kaggle.com" }, { "code": null, "e": 15435, "s": 15328, "text": "Please comment if you want more explanation on anything. All suggestions and feedbacks are always welcome." } ]
GATE | GATE CS 2019 | Question 46 - GeeksforGeeks
18 Feb, 2019 There are n unsorted arrays: A1, A2, ....,An. Assume that n is odd. Each of A1, A2, ...., An contains n distinct elements. There are no common elements between any two arrays. The worst-case time complexity of computing the median of the medians of A1, A2, ....,An is ________ . (A) Ο(n log n)(B) Ο(n2)(C) Ο(n)(D) Ω(n2log n)Answer: (B)Explanation: Since given arrays are not sorted, so the time complexity to find median is O(n) in an unsorted array. You need to apply this apgorithm n time to find all medians and again once to find median of all these medians, so total time complexity is, = O(n)*O(n) + O(n) = O(n2) + O(n) ≈ O(n2) So, option (B) is correct.Quiz of this Question manav23lohani GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25873, "s": 25845, "text": "\n18 Feb, 2019" }, { "code": null, "e": 26152, "s": 25873, "text": "There are n unsorted arrays: A1, A2, ....,An. Assume that n is odd. Each of A1, A2, ...., An contains n distinct elements. There are no common elements between any two arrays. The worst-case time complexity of computing the median of the medians of A1, A2, ....,An is ________ ." }, { "code": null, "e": 26465, "s": 26152, "text": "(A) Ο(n log n)(B) Ο(n2)(C) Ο(n)(D) Ω(n2log n)Answer: (B)Explanation: Since given arrays are not sorted, so the time complexity to find median is O(n) in an unsorted array. You need to apply this apgorithm n time to find all medians and again once to find median of all these medians, so total time complexity is," }, { "code": null, "e": 26508, "s": 26465, "text": "= O(n)*O(n) + O(n)\n= O(n2) + O(n)\n≈ O(n2) " }, { "code": null, "e": 26556, "s": 26508, "text": "So, option (B) is correct.Quiz of this Question" }, { "code": null, "e": 26570, "s": 26556, "text": "manav23lohani" }, { "code": null, "e": 26575, "s": 26570, "text": "GATE" }, { "code": null, "e": 26673, "s": 26575, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26707, "s": 26673, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26741, "s": 26707, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26775, "s": 26741, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26808, "s": 26775, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26844, "s": 26808, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26878, "s": 26844, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26914, "s": 26878, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26948, "s": 26914, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26982, "s": 26948, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Model Fitting, Correlation, p-value, t-Statistic, Confidence Intervals and Visualization in Python | by Rashida Nasrin Sucky | Towards Data Science
Linear regression is the most commonly used regression model. The reason is it is simple to use, it can infer good information and it is easy to understand. In this article, we will discuss the fitting of the linear regression model to the data, inference from it, and some useful visualization. Python programming language and a few of its popular libraries. If you do not know all these libraries, you will still be able to follow this article and understand the concept.Jupyter Notebook environment. Python programming language and a few of its popular libraries. If you do not know all these libraries, you will still be able to follow this article and understand the concept. Jupyter Notebook environment. In my experience, the best way to learn is by using an example. I will use a dataset and keep explaining the process of fitting the model on the data and infer the information. I am using a survey dataset called NHANES dataset. It is a very good dataset for practice. Please feel free to download the dataset from this link: github.com Let’s import the packages and the dataset: %matplotlib inlineimport matplotlib.pyplot as pltimport seaborn as snsimport pandas as pdimport statsmodels.api as smimport numpy as npdf = pd.read_csv('nhanes_2015_2016.csv') This dataset is quite large and we do not need all the features for this article. We will focus on the regression model where the outcome variable will be the size of the waist. If you want to work on any other variable, please make sure that you choose a quantitative variable, not a categorical variable. Because linear regression is designed to predict a quantitative variable only not a categorical variable. But you can use categorical variables as the independent variables. Check the name of all the columns to have an idea about the dataset. df.columns#Output:Index(['SEQN', 'ALQ101', 'ALQ110', 'ALQ130', 'SMQ020', 'RIAGENDR', 'RIDAGEYR', 'RIDRETH1', 'DMDCITZN', 'DMDEDUC2', 'DMDMARTL', 'DMDHHSIZ', 'WTINT2YR', 'SDMVPSU', 'SDMVSTRA', 'INDFMPIR', 'BPXSY1', 'BPXDI1', 'BPXSY2', 'BPXDI2', 'BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML', 'BMXARMC', 'BMXWAIST', 'HIQ210'], dtype='object') So, just keep waist size and a few other variables that seem to be related to waist size and make a new smaller DataFrame. Just by instinct, anyone will guess that weight may have a strong correlation with waist size. Gender, BMI, the height may also play an important role. So, make a new smaller DataFrame with these columns only and drop any null values for the convenience. keep = ['BMXWT', 'BMXHT', 'BMXBMI', 'BMXWAIST', 'RIAGENDR']db = df[keep].dropna()db.head() We have a dataset that contains five columns: weight, height, body-mass index(BMI), waist size, and gender. As mentioned earlier, waist size is the output variable which we will try to predict using the other variables. Initially, use just one variable or one covariate to predict the waist size. Weight(BMXWT) could be a good covariate to start with because with higher weight waist size is expected to go higher. Though there are other factors like height or gender as well. But we will think about them later. We will fit the model where waist size will be expressed as a function of the weight. model = sm.OLS.from_formula("BMXWAIST ~ BMXWT", data=db)result = model.fit()result.summary() This table above may look scary to you. But most of the information is not so important for us. We only need this part of the table: In the first column, we have coefficients. Remember the linear regression formula: Y = AX + B In the table above, 42.7189 is the B, and 0.6991 is our A. And we know that A is the slope. So, our slope is 0.6991. That means that if a person has one unit of extra weight s/he will have the waist size of 0.6991 unit more and that is based on the p-value mentioned in the P>|t| column. Next, the standard error is 0.005 which indicates the distance of this estimated slope from the true slope. t-statistic says that the estimated slope 0.6991 is 144.292 standard error above the zero. The last two columns are the confidence levels. By default, it is a 95% confidence level. The confidence interval is 0.69 and 0.709 which is a very narrow range. Later we will draw a confidence interval band. db.BMXWAIST.std() The standard deviation is 16.85 which seems far higher than the regression slope of 0.6991. But the regression slope is the average change in the waist size for a single unit shift of the weight. That means if a person is 10 units overweight than the other person, s/he will have 0.6991*10 or 6.99 unit more waist size. Other than these values in the small sub-table, one more parameter from the result summary is important. That is the R-squared value in the top line of the result summary. Here R-squared value is 0.795 which means 79.5% of the waist size can be explained by the weight. Now, check this regression coefficient with the squared Pearson coefficient. cc = db[["BMXWAIST", "BMXWT"]].corr()print(cc)BMXWAIST BMXWTBMXWAIST 1.000000 0.891828BMXWT 0.891828 1.000000 To find the R-squared value: cc.BMXWAIST.BMXWT**2 This returns the R squared value of 0.795 again. The most important part, that is the predicted values of waist size as a function of the weight can be found in this way: result.fittedvalues This is just a part of the result. The original result is far bigger. Let’s add a second covariate and see how it affects the regression performance. I choose gender as a second covariate. I want to use a relabeled gender column: db["RIAGENDRx"] = db.RIAGENDR.replace({1: "Male", 2: "Female"}) Here is the model and model summary: model = sm.OLS.from_formula("BMXWAIST ~ BMXWT + RIAGENDRx", data=db)result = model.fit()result.summary() In the code above, BMXWT + RIAGENDRx does not mean that these two columns are joined or mathematically added. It just indicates that they both are included in the model. In this new model, waist size is expressed as the function of both weight and gender. From the result above, we can find that the coefficient of weight(BMXWT) is 0.7272 which is a bit higher than before. This time the coefficient implies that if the weight differs by one unit of the two people of the same gender, their waist will differ by 0.7272 unit. On the other hand, the coefficient of gender (RIAGENDRx) -5.0832 means, if we compare a man and a woman of the same weight, the man will have a 5.0832 unit less waist size than the woman. All the coefficients are expressed as mean. If we compare a man of weight 70 and a woman of weight 50, the man’s waist will be about -5.0832 +(70–50)*0.7272 times different than the woman. The regression coefficient of weight(BMXWT) changed a little, not too much after adding the gender in the model. Adding the second covariate changes the first covariate when they are somewhat correlated. Let’s check the correlation between the two covariates: db[['BMXWT', 'RIAGENDR']].corr() As you can see the correlation is -0.2375. So there is a correlation but not too strong. You can find the predicted values of waist size using the fitted-value method as I have shown before. I am not demonstrating that again. Let’s add the third covariate. I chose BMXBMI as the third covariate. You may try with some other variables as well. model = sm.OLS.from_formula("BMXWAIST ~ BMXWT + RIAGENDRx + BMXBMI", data=db)result = model.fit()result.summary() Notice that after adding the BMXBMI, the coefficient for gender variable changed significantly. We can say that BMI is working as a masking part of the association between the waist size and the gender variable. On the other hand, the coefficient for weight also changed significantly. BMI worked as a masking part in the relationship between waist and weight as well. You can add more covariates in the model and see the effect of each covariate. In this section, we will visualize the result of the regression model. We will plot the regression line that is the fitted values or the predicted values with the confidence interval. If you need a refresher on the confidence interval concepts, please check this article: towardsdatascience.com For this plot, we will fix the gender as female and the BMI as 25. Also, we need to keep one independent variable as the focus variable. We will keep it as weight(BMXWT). So, the plot will show the predicted waist size of the female of BMI 25 of all ages. from statsmodels.sandbox.predict_functional import predict_functionalvalues = {"RIAGENDRx": "Female", "RIAGENDR": 1, "BMXBMI": 25}pr, cb, fv = predict_functional(result, "BMXWT", values=values, ci_method="simultaneous")#Here, pr is the predicted values(pr), cb is the confidence band and #the fv is the function valuesax = sns.lineplot(fv, pr, lw=4)ax.fill_between(fv, cb[:, 0], cb[:, 1], color='grey', alpha=0.4)ax.set_xlabel("BMXWT")_ = ax.set_ylabel("BMXWAIST") The grey area in the picture is the confidence bands. That means the true waist size will fall in that area. The width of the grey area varies along the regression line. So, the confidence interval keeps changing with ages. You can fix the weight and see the result for a certain weight as well. Let’s fix the weight at 65 and plot the BMI vs waist for the female population. We need to change the ‘values’ parameter for that. Because we fixed the BMI value to 25 there. Now, we want to fix the weight. So, We need to delete the BMI value from the values parameter and add the weight in it. del values["BMXBMI"] # Delete this as it is now the focus variable#del values['BMXWT']values["BMXWT"] = 65pr, cb, fv = predict_functional(result, "BMXBMI", values=values, ci_method="simultaneous")ax = sns.lineplot(fv, pr, lw=4)ax.fill_between(fv, cb[:, 0], cb[:, 1], color='grey', alpha=0.4)ax.set_xlabel("BMI")_ = ax.set_ylabel("BMXWAIST") In the plots above, we plotted only the averages. The model for an average waist size for a given weight, gender, or BMI. Using this same regression model, the variance structure can also be assessed which will show how much the observed values deviated from the mean. To do just that we can plot the residuals against the fitted value. Remember, fitted values are the predicted values or observed means and the residuals are the difference between the observed means and the true value. pp = sns.scatterplot(result.fittedvalues, result.resid)pp.set_xlabel("Fitted values")_ = pp.set_ylabel("Residuals") Looks like When the observed values are lower the variance is a bit higher. It is also possible to visualize the effect of one covariate only. We can see the component plus residual plot or the partial residual plot using only one covariate to see if we keep the other covariates fixed how the dependent variables change: from statsmodels.graphics.regressionplots import plot_ccprax = plt.axes()plot_ccpr(result, "BMXWT", ax)ax.lines[0].set_alpha(0.2) # Reduce overplotting with transparency_ = ax.lines[1].set_color('orange') Now, we can see the effect of BMI in the same way when the weight variable is fixed. ax = plt.axes()plot_ccpr(result, "BMXBMI", ax)ax.lines[0].set_alpha(0.2)ax.lines[1].set_color("orange") The effect of BMI is a lot steeper than weight. In this article, you learned how to fit a linear regression model, different statistical parameters associated with the linear regression, and some good visualization techniques. Visualization techniques were involved plotting the regression line confidence band, plotting residuals, and plotting the effect of a single covariate. More reading recommendations: Hypothesis Testing, Characteristics, and Calculation Confidence Interval, Calculation, and Characteristics How to Calculate Confidence Interval of Mean and the Difference of Mean How to Perform Hypothesis Testing in Python: One Mean and The difference in Two Means How to Present the Relationships Amongst Multiple Variables in Python Master Pandas’ Groupby for Efficient Data Summarizing And Analysis Build A Complete Neural Network From Scratch in Python
[ { "code": null, "e": 468, "s": 172, "text": "Linear regression is the most commonly used regression model. The reason is it is simple to use, it can infer good information and it is easy to understand. In this article, we will discuss the fitting of the linear regression model to the data, inference from it, and some useful visualization." }, { "code": null, "e": 675, "s": 468, "text": "Python programming language and a few of its popular libraries. If you do not know all these libraries, you will still be able to follow this article and understand the concept.Jupyter Notebook environment." }, { "code": null, "e": 853, "s": 675, "text": "Python programming language and a few of its popular libraries. If you do not know all these libraries, you will still be able to follow this article and understand the concept." }, { "code": null, "e": 883, "s": 853, "text": "Jupyter Notebook environment." }, { "code": null, "e": 1208, "s": 883, "text": "In my experience, the best way to learn is by using an example. I will use a dataset and keep explaining the process of fitting the model on the data and infer the information. I am using a survey dataset called NHANES dataset. It is a very good dataset for practice. Please feel free to download the dataset from this link:" }, { "code": null, "e": 1219, "s": 1208, "text": "github.com" }, { "code": null, "e": 1262, "s": 1219, "text": "Let’s import the packages and the dataset:" }, { "code": null, "e": 1438, "s": 1262, "text": "%matplotlib inlineimport matplotlib.pyplot as pltimport seaborn as snsimport pandas as pdimport statsmodels.api as smimport numpy as npdf = pd.read_csv('nhanes_2015_2016.csv')" }, { "code": null, "e": 1988, "s": 1438, "text": "This dataset is quite large and we do not need all the features for this article. We will focus on the regression model where the outcome variable will be the size of the waist. If you want to work on any other variable, please make sure that you choose a quantitative variable, not a categorical variable. Because linear regression is designed to predict a quantitative variable only not a categorical variable. But you can use categorical variables as the independent variables. Check the name of all the columns to have an idea about the dataset." }, { "code": null, "e": 2331, "s": 1988, "text": "df.columns#Output:Index(['SEQN', 'ALQ101', 'ALQ110', 'ALQ130', 'SMQ020', 'RIAGENDR', 'RIDAGEYR', 'RIDRETH1', 'DMDCITZN', 'DMDEDUC2', 'DMDMARTL', 'DMDHHSIZ', 'WTINT2YR', 'SDMVPSU', 'SDMVSTRA', 'INDFMPIR', 'BPXSY1', 'BPXDI1', 'BPXSY2', 'BPXDI2', 'BMXWT', 'BMXHT', 'BMXBMI', 'BMXLEG', 'BMXARML', 'BMXARMC', 'BMXWAIST', 'HIQ210'], dtype='object')" }, { "code": null, "e": 2709, "s": 2331, "text": "So, just keep waist size and a few other variables that seem to be related to waist size and make a new smaller DataFrame. Just by instinct, anyone will guess that weight may have a strong correlation with waist size. Gender, BMI, the height may also play an important role. So, make a new smaller DataFrame with these columns only and drop any null values for the convenience." }, { "code": null, "e": 2800, "s": 2709, "text": "keep = ['BMXWT', 'BMXHT', 'BMXBMI', 'BMXWAIST', 'RIAGENDR']db = df[keep].dropna()db.head()" }, { "code": null, "e": 3399, "s": 2800, "text": "We have a dataset that contains five columns: weight, height, body-mass index(BMI), waist size, and gender. As mentioned earlier, waist size is the output variable which we will try to predict using the other variables. Initially, use just one variable or one covariate to predict the waist size. Weight(BMXWT) could be a good covariate to start with because with higher weight waist size is expected to go higher. Though there are other factors like height or gender as well. But we will think about them later. We will fit the model where waist size will be expressed as a function of the weight." }, { "code": null, "e": 3492, "s": 3399, "text": "model = sm.OLS.from_formula(\"BMXWAIST ~ BMXWT\", data=db)result = model.fit()result.summary()" }, { "code": null, "e": 3625, "s": 3492, "text": "This table above may look scary to you. But most of the information is not so important for us. We only need this part of the table:" }, { "code": null, "e": 3708, "s": 3625, "text": "In the first column, we have coefficients. Remember the linear regression formula:" }, { "code": null, "e": 3719, "s": 3708, "text": "Y = AX + B" }, { "code": null, "e": 4415, "s": 3719, "text": "In the table above, 42.7189 is the B, and 0.6991 is our A. And we know that A is the slope. So, our slope is 0.6991. That means that if a person has one unit of extra weight s/he will have the waist size of 0.6991 unit more and that is based on the p-value mentioned in the P>|t| column. Next, the standard error is 0.005 which indicates the distance of this estimated slope from the true slope. t-statistic says that the estimated slope 0.6991 is 144.292 standard error above the zero. The last two columns are the confidence levels. By default, it is a 95% confidence level. The confidence interval is 0.69 and 0.709 which is a very narrow range. Later we will draw a confidence interval band." }, { "code": null, "e": 4433, "s": 4415, "text": "db.BMXWAIST.std()" }, { "code": null, "e": 4753, "s": 4433, "text": "The standard deviation is 16.85 which seems far higher than the regression slope of 0.6991. But the regression slope is the average change in the waist size for a single unit shift of the weight. That means if a person is 10 units overweight than the other person, s/he will have 0.6991*10 or 6.99 unit more waist size." }, { "code": null, "e": 5100, "s": 4753, "text": "Other than these values in the small sub-table, one more parameter from the result summary is important. That is the R-squared value in the top line of the result summary. Here R-squared value is 0.795 which means 79.5% of the waist size can be explained by the weight. Now, check this regression coefficient with the squared Pearson coefficient." }, { "code": null, "e": 5221, "s": 5100, "text": "cc = db[[\"BMXWAIST\", \"BMXWT\"]].corr()print(cc)BMXWAIST BMXWTBMXWAIST 1.000000 0.891828BMXWT 0.891828 1.000000" }, { "code": null, "e": 5250, "s": 5221, "text": "To find the R-squared value:" }, { "code": null, "e": 5271, "s": 5250, "text": "cc.BMXWAIST.BMXWT**2" }, { "code": null, "e": 5442, "s": 5271, "text": "This returns the R squared value of 0.795 again. The most important part, that is the predicted values of waist size as a function of the weight can be found in this way:" }, { "code": null, "e": 5462, "s": 5442, "text": "result.fittedvalues" }, { "code": null, "e": 5532, "s": 5462, "text": "This is just a part of the result. The original result is far bigger." }, { "code": null, "e": 5692, "s": 5532, "text": "Let’s add a second covariate and see how it affects the regression performance. I choose gender as a second covariate. I want to use a relabeled gender column:" }, { "code": null, "e": 5756, "s": 5692, "text": "db[\"RIAGENDRx\"] = db.RIAGENDR.replace({1: \"Male\", 2: \"Female\"})" }, { "code": null, "e": 5793, "s": 5756, "text": "Here is the model and model summary:" }, { "code": null, "e": 5898, "s": 5793, "text": "model = sm.OLS.from_formula(\"BMXWAIST ~ BMXWT + RIAGENDRx\", data=db)result = model.fit()result.summary()" }, { "code": null, "e": 6611, "s": 5898, "text": "In the code above, BMXWT + RIAGENDRx does not mean that these two columns are joined or mathematically added. It just indicates that they both are included in the model. In this new model, waist size is expressed as the function of both weight and gender. From the result above, we can find that the coefficient of weight(BMXWT) is 0.7272 which is a bit higher than before. This time the coefficient implies that if the weight differs by one unit of the two people of the same gender, their waist will differ by 0.7272 unit. On the other hand, the coefficient of gender (RIAGENDRx) -5.0832 means, if we compare a man and a woman of the same weight, the man will have a 5.0832 unit less waist size than the woman." }, { "code": null, "e": 6800, "s": 6611, "text": "All the coefficients are expressed as mean. If we compare a man of weight 70 and a woman of weight 50, the man’s waist will be about -5.0832 +(70–50)*0.7272 times different than the woman." }, { "code": null, "e": 7060, "s": 6800, "text": "The regression coefficient of weight(BMXWT) changed a little, not too much after adding the gender in the model. Adding the second covariate changes the first covariate when they are somewhat correlated. Let’s check the correlation between the two covariates:" }, { "code": null, "e": 7093, "s": 7060, "text": "db[['BMXWT', 'RIAGENDR']].corr()" }, { "code": null, "e": 7319, "s": 7093, "text": "As you can see the correlation is -0.2375. So there is a correlation but not too strong. You can find the predicted values of waist size using the fitted-value method as I have shown before. I am not demonstrating that again." }, { "code": null, "e": 7436, "s": 7319, "text": "Let’s add the third covariate. I chose BMXBMI as the third covariate. You may try with some other variables as well." }, { "code": null, "e": 7550, "s": 7436, "text": "model = sm.OLS.from_formula(\"BMXWAIST ~ BMXWT + RIAGENDRx + BMXBMI\", data=db)result = model.fit()result.summary()" }, { "code": null, "e": 7919, "s": 7550, "text": "Notice that after adding the BMXBMI, the coefficient for gender variable changed significantly. We can say that BMI is working as a masking part of the association between the waist size and the gender variable. On the other hand, the coefficient for weight also changed significantly. BMI worked as a masking part in the relationship between waist and weight as well." }, { "code": null, "e": 7998, "s": 7919, "text": "You can add more covariates in the model and see the effect of each covariate." }, { "code": null, "e": 8270, "s": 7998, "text": "In this section, we will visualize the result of the regression model. We will plot the regression line that is the fitted values or the predicted values with the confidence interval. If you need a refresher on the confidence interval concepts, please check this article:" }, { "code": null, "e": 8293, "s": 8270, "text": "towardsdatascience.com" }, { "code": null, "e": 8549, "s": 8293, "text": "For this plot, we will fix the gender as female and the BMI as 25. Also, we need to keep one independent variable as the focus variable. We will keep it as weight(BMXWT). So, the plot will show the predicted waist size of the female of BMI 25 of all ages." }, { "code": null, "e": 9029, "s": 8549, "text": "from statsmodels.sandbox.predict_functional import predict_functionalvalues = {\"RIAGENDRx\": \"Female\", \"RIAGENDR\": 1, \"BMXBMI\": 25}pr, cb, fv = predict_functional(result, \"BMXWT\", values=values, ci_method=\"simultaneous\")#Here, pr is the predicted values(pr), cb is the confidence band and #the fv is the function valuesax = sns.lineplot(fv, pr, lw=4)ax.fill_between(fv, cb[:, 0], cb[:, 1], color='grey', alpha=0.4)ax.set_xlabel(\"BMXWT\")_ = ax.set_ylabel(\"BMXWAIST\")" }, { "code": null, "e": 9253, "s": 9029, "text": "The grey area in the picture is the confidence bands. That means the true waist size will fall in that area. The width of the grey area varies along the regression line. So, the confidence interval keeps changing with ages." }, { "code": null, "e": 9620, "s": 9253, "text": "You can fix the weight and see the result for a certain weight as well. Let’s fix the weight at 65 and plot the BMI vs waist for the female population. We need to change the ‘values’ parameter for that. Because we fixed the BMI value to 25 there. Now, we want to fix the weight. So, We need to delete the BMI value from the values parameter and add the weight in it." }, { "code": null, "e": 9976, "s": 9620, "text": "del values[\"BMXBMI\"] # Delete this as it is now the focus variable#del values['BMXWT']values[\"BMXWT\"] = 65pr, cb, fv = predict_functional(result, \"BMXBMI\", values=values, ci_method=\"simultaneous\")ax = sns.lineplot(fv, pr, lw=4)ax.fill_between(fv, cb[:, 0], cb[:, 1], color='grey', alpha=0.4)ax.set_xlabel(\"BMI\")_ = ax.set_ylabel(\"BMXWAIST\")" }, { "code": null, "e": 10464, "s": 9976, "text": "In the plots above, we plotted only the averages. The model for an average waist size for a given weight, gender, or BMI. Using this same regression model, the variance structure can also be assessed which will show how much the observed values deviated from the mean. To do just that we can plot the residuals against the fitted value. Remember, fitted values are the predicted values or observed means and the residuals are the difference between the observed means and the true value." }, { "code": null, "e": 10580, "s": 10464, "text": "pp = sns.scatterplot(result.fittedvalues, result.resid)pp.set_xlabel(\"Fitted values\")_ = pp.set_ylabel(\"Residuals\")" }, { "code": null, "e": 10656, "s": 10580, "text": "Looks like When the observed values are lower the variance is a bit higher." }, { "code": null, "e": 10902, "s": 10656, "text": "It is also possible to visualize the effect of one covariate only. We can see the component plus residual plot or the partial residual plot using only one covariate to see if we keep the other covariates fixed how the dependent variables change:" }, { "code": null, "e": 11107, "s": 10902, "text": "from statsmodels.graphics.regressionplots import plot_ccprax = plt.axes()plot_ccpr(result, \"BMXWT\", ax)ax.lines[0].set_alpha(0.2) # Reduce overplotting with transparency_ = ax.lines[1].set_color('orange')" }, { "code": null, "e": 11192, "s": 11107, "text": "Now, we can see the effect of BMI in the same way when the weight variable is fixed." }, { "code": null, "e": 11296, "s": 11192, "text": "ax = plt.axes()plot_ccpr(result, \"BMXBMI\", ax)ax.lines[0].set_alpha(0.2)ax.lines[1].set_color(\"orange\")" }, { "code": null, "e": 11344, "s": 11296, "text": "The effect of BMI is a lot steeper than weight." }, { "code": null, "e": 11675, "s": 11344, "text": "In this article, you learned how to fit a linear regression model, different statistical parameters associated with the linear regression, and some good visualization techniques. Visualization techniques were involved plotting the regression line confidence band, plotting residuals, and plotting the effect of a single covariate." }, { "code": null, "e": 11705, "s": 11675, "text": "More reading recommendations:" }, { "code": null, "e": 11758, "s": 11705, "text": "Hypothesis Testing, Characteristics, and Calculation" }, { "code": null, "e": 11812, "s": 11758, "text": "Confidence Interval, Calculation, and Characteristics" }, { "code": null, "e": 11884, "s": 11812, "text": "How to Calculate Confidence Interval of Mean and the Difference of Mean" }, { "code": null, "e": 11970, "s": 11884, "text": "How to Perform Hypothesis Testing in Python: One Mean and The difference in Two Means" }, { "code": null, "e": 12040, "s": 11970, "text": "How to Present the Relationships Amongst Multiple Variables in Python" }, { "code": null, "e": 12107, "s": 12040, "text": "Master Pandas’ Groupby for Efficient Data Summarizing And Analysis" } ]
Meteor - EJSON
EJSON is an extension of JSON syntax that supports Date and Binary types. To install EJSON package, we need to add it from the command prompt window. C:\Users\username\Desktop\meteorApp>meteor add ejson We can deserialize the date using the parse method. if (Meteor.isClient) { var myEjsonDate = '{"$date": 1455029631493}'; var myDate = EJSON.parse(myEjsonDate); console.log(myDate); } The console will log the correct date value. The same can be applied to binary types. if (Meteor.isClient) { var myEjsonBinary = '{"$binary": "c3VyZS4="}'; var myBinary = EJSON.parse(myEjsonBinary); console.log(myBinary); } You can see that the console is logging new deserialized value. We can serialize an object using the stringify method. This is the reversed process from the example above. if (Meteor.isClient) { var myObject = { myDate : new Date(), myBinary : new Uint8Array([115, 117, 114, 101, 46]) } var myEjosnData = EJSON.stringify(myObject); console.log(myEjosnData); } We can see our new values in the console. EJSON.parse(string) Used for parsing a string into EJSON value. EJSON.stringify(value) Used for serializing a value to the string. EJSON.fromJSONValue(value) Used for deserializing an EJSON value from JSON. EJSON.toJSONValue(value) Used for serializing an EJSON value into JSON. EJSON.equals(value1, value2) Used for comparing if two values are equal. EJSON.clone(value) Used for returning a deep copy of the value. EJSON.newBinary Used for assigning a binary data that EJSON can serialize. EJSON.isBinary(x) Used for checking if the value is a binary data. EJSON.addType(name, factory) Used for creating a custom EJSON type. customType.typeName() Used for returning a name of the custom type. customType.toJSONValue() Used for serializing custom types. customType.clone() Used for returning a deep copy of the custom type. customType.equals(otherValue) Used for comparison between the custom type value and other value. 73 Lectures 4 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2195, "s": 2121, "text": "EJSON is an extension of JSON syntax that supports Date and Binary types." }, { "code": null, "e": 2271, "s": 2195, "text": "To install EJSON package, we need to add it from the command prompt window." }, { "code": null, "e": 2325, "s": 2271, "text": "C:\\Users\\username\\Desktop\\meteorApp>meteor add ejson\n" }, { "code": null, "e": 2377, "s": 2325, "text": "We can deserialize the date using the parse method." }, { "code": null, "e": 2517, "s": 2377, "text": "if (Meteor.isClient) {\n var myEjsonDate = '{\"$date\": 1455029631493}';\n var myDate = EJSON.parse(myEjsonDate);\n console.log(myDate);\n}" }, { "code": null, "e": 2562, "s": 2517, "text": "The console will log the correct date value." }, { "code": null, "e": 2603, "s": 2562, "text": "The same can be applied to binary types." }, { "code": null, "e": 2750, "s": 2603, "text": "if (Meteor.isClient) {\n var myEjsonBinary = '{\"$binary\": \"c3VyZS4=\"}';\n var myBinary = EJSON.parse(myEjsonBinary);\n console.log(myBinary);\n}" }, { "code": null, "e": 2814, "s": 2750, "text": "You can see that the console is logging new deserialized value." }, { "code": null, "e": 2922, "s": 2814, "text": "We can serialize an object using the stringify method. This is the reversed process from the example above." }, { "code": null, "e": 3136, "s": 2922, "text": "if (Meteor.isClient) {\n\n var myObject = {\n myDate : new Date(),\n myBinary : new Uint8Array([115, 117, 114, 101, 46])\n }\n\n var myEjosnData = EJSON.stringify(myObject);\n console.log(myEjosnData);\n}" }, { "code": null, "e": 3178, "s": 3136, "text": "We can see our new values in the console." }, { "code": null, "e": 3198, "s": 3178, "text": "EJSON.parse(string)" }, { "code": null, "e": 3242, "s": 3198, "text": "Used for parsing a string into EJSON value." }, { "code": null, "e": 3265, "s": 3242, "text": "EJSON.stringify(value)" }, { "code": null, "e": 3309, "s": 3265, "text": "Used for serializing a value to the string." }, { "code": null, "e": 3336, "s": 3309, "text": "EJSON.fromJSONValue(value)" }, { "code": null, "e": 3385, "s": 3336, "text": "Used for deserializing an EJSON value from JSON." }, { "code": null, "e": 3410, "s": 3385, "text": "EJSON.toJSONValue(value)" }, { "code": null, "e": 3457, "s": 3410, "text": "Used for serializing an EJSON value into JSON." }, { "code": null, "e": 3486, "s": 3457, "text": "EJSON.equals(value1, value2)" }, { "code": null, "e": 3530, "s": 3486, "text": "Used for comparing if two values are equal." }, { "code": null, "e": 3549, "s": 3530, "text": "EJSON.clone(value)" }, { "code": null, "e": 3594, "s": 3549, "text": "Used for returning a deep copy of the value." }, { "code": null, "e": 3610, "s": 3594, "text": "EJSON.newBinary" }, { "code": null, "e": 3669, "s": 3610, "text": "Used for assigning a binary data that EJSON can serialize." }, { "code": null, "e": 3687, "s": 3669, "text": "EJSON.isBinary(x)" }, { "code": null, "e": 3736, "s": 3687, "text": "Used for checking if the value is a binary data." }, { "code": null, "e": 3765, "s": 3736, "text": "EJSON.addType(name, factory)" }, { "code": null, "e": 3804, "s": 3765, "text": "Used for creating a custom EJSON type." }, { "code": null, "e": 3826, "s": 3804, "text": "customType.typeName()" }, { "code": null, "e": 3872, "s": 3826, "text": "Used for returning a name of the custom type." }, { "code": null, "e": 3897, "s": 3872, "text": "customType.toJSONValue()" }, { "code": null, "e": 3932, "s": 3897, "text": "Used for serializing custom types." }, { "code": null, "e": 3951, "s": 3932, "text": "customType.clone()" }, { "code": null, "e": 4002, "s": 3951, "text": "Used for returning a deep copy of the custom type." }, { "code": null, "e": 4032, "s": 4002, "text": "customType.equals(otherValue)" }, { "code": null, "e": 4099, "s": 4032, "text": "Used for comparison between the custom type value and other value." }, { "code": null, "e": 4132, "s": 4099, "text": "\n 73 Lectures \n 4 hours \n" }, { "code": null, "e": 4152, "s": 4132, "text": " Skillbakerystudios" }, { "code": null, "e": 4159, "s": 4152, "text": " Print" }, { "code": null, "e": 4170, "s": 4159, "text": " Add Notes" } ]
Learn How To Use Spark ML and Spark Streaming | by Navid Mashinchi | Towards Data Science
In this article, I am going over an example of how we can use Spark ML to make predictions on streaming data. Note we won’t focus on comparing different models and tuning the model. The main focus will be on how we can incorporate Spark Streaming to make predictions using databricks. In addition to that, you should have some basic knowledge of how to use Spark ML. If Spark ML is new to you, check out the video below. For this example, we will predict whether someone will get a heart attack based on their age, gender, and medical conditions. A logistic regression will be trained, and we stream in unseen data to make predictions. For this project, I used a dataset that is available on Kaggle. Please click here if you want to follow along. The data consists of 303 rows and 14 columns. Each row represents the information of a patient. The features of this dataset consist of the following columns: age: age in years1. age: age in years sex: sex (1 = male; 0 = female) cp: chest pain type (1 = typical angina; 2 = atypical angina; 3 = non-anginal pain; 0 = asymptomatic) trtbps: resting blood pressure (in mm Hg on admission to the hospital) chol: serum cholesterol in mg/dl fbs: fasting blood sugar > 120 mg/dl (1 = true; 0 = false) restecg: resting electrocardiographic results (1 = normal; 2 = having ST-Twave abnormality; 0 = hypertrophy) thalachh: maximum heart rate achieved exng: exercise-induced angina (1 = yes; 0 = no) oldpeak: ST depression induced by exercise relative to rest slp: the slope of the peak exercise ST segment (2 = upsloping; 1 = flat;0 = downsloping) caa: number of major vessels (0-3) colored by fluoroscopy thall: 2 = normal; 1 = fixed defect; 3 = reversible defect The target column is the following: output: 0= less chance of heart attach 1= more change of heart attack. The first step is to create a schema to ensure that the data will consist of the correct data type when reading in the csv file. Next, we will use spark.read.format() function with “csv” as an argument, add the option to read in the header and assign the schema we created to the data frame. Last we load the data, and we also change the target column to label so that our logistic regression can identify which column the target variable is. from pyspark.ml import Pipelinefrom pyspark.sql.types import StructType,StructField,LongType, StringType,DoubleType,TimestampType# We use the following schemaschema = StructType( \ [StructField("age", LongType(),True), \ StructField("sex", LongType(), True), \ StructField("cp", LongType(), True), \ StructField('trtbps', LongType(), True), \ StructField("chol", LongType(), True), \ StructField("fbs", LongType(), True), \ StructField("restecg", LongType(), True), \ StructField("thalachh", LongType(), True),\ StructField("exng", LongType(), True), \ StructField("oldpeak", DoubleType(), True), \ StructField("slp", LongType(),True), \ StructField("caa", LongType(), True), \ StructField("thall", LongType(), True), \ StructField("output", LongType(), True), \ ])data = "dbfs:/FileStore/tables/heart.csv"df=spark.read.format('csv').option('header',True).schema(schema).load(data)df = df.withColumnRenamed("output","label")df.display()df.printSchema() Once we run the above code, we get the following output below: When it comes to data preprocessing steps, I first split the data into a training (70%) and test (30%) set. testDF, trainDF = df.randomSplit([0.3, 0.7]) After that, I created a pipeline that consists of five stages. The first stage is a vector assembler that takes in the age, trtbps, chol, thalachh, oldpeak columns and turns them into a vector. The second stage entails the scaling process of the features mentioned above. I am using the MinMaxScaler() function from the pyspark.ml.feature library. After that, I one-hot encode the sex, cp, fbs, restecg, slp, exng, caa, and thall columns, since those are nominal categorical variables. Next, I create a second vector assembler and add the one-hot encoded columns and scaled features into one vector. Last but not least, the last stage consists of a Logistic Regression with the following parameters: maxIter = 10 regParam = 0.01 I chose a logistic regression algorithm because our target consists of binary numbers (0 and 1). Once the pipeline has been created, I fit and transform the training set. After that, I select the label, probability, and prediction columns. Please see below a snippet of the pipeline construction and the predictions when training the model. from pyspark.ml.feature import OneHotEncoderfrom pyspark.ml.feature import MinMaxScalerfrom pyspark.ml.feature import StringIndexerfrom pyspark.ml.feature import VectorAssemblerfrom pyspark.ml.feature import OneHotEncoderfrom pyspark.ml.classification import LogisticRegression# Create the logistic regression modellr = LogisticRegression(maxIter=10, regParam= 0.01)# We create a one hot encoder.ohe = OneHotEncoder(inputCols = ['sex', 'cp', 'fbs', 'restecg', 'slp', 'exng', 'caa', 'thall'], outputCols=['sex_ohe', 'cp_ohe', 'fbs_ohe', 'restecg_ohe', 'slp_ohe', 'exng_ohe', 'caa_ohe', 'thall_ohe'])# Input list for scalinginputs = ['age','trtbps','chol','thalachh','oldpeak']# We scale our inputsassembler1 = VectorAssembler(inputCols=inputs, outputCol="features_scaled1")scaler = MinMaxScaler(inputCol="features_scaled1", outputCol="features_scaled")# We create a second assembler for the encoded columns.assembler2 = VectorAssembler(inputCols=['sex_ohe', 'cp_ohe', 'fbs_ohe', 'restecg_ohe', 'slp_ohe', 'exng_ohe', 'caa_ohe', 'thall_ohe','features_scaled'], outputCol="features")# Create stages listmyStages = [assembler1, scaler, ohe, assembler2,lr]# Set up the pipelinepipeline = Pipeline(stages= myStages)# We fit the model using the training data.pModel = pipeline.fit(trainDF)# We transform the data.trainingPred = pModel.transform(trainDF)# # We select the actual label, probability and predictionstrainingPred.select('label','probability','prediction').show() As we can see above, the marked yellow rows show that the lower the probability, the more confident the model is that the prediction is a 1. On the other hand, the marked red row shows the higher the probability, the more certain it predicts the output to be a zero. In addition to that, I evaluate the performance of the model, calculating the overall accuracy score. Please see below the code snippet of how I calculated the accuracy score. When training the model on the training data, the accuracy score resulted in 0.902913%, which is a satisfying result. To incorporate Spark Streaming, I repartitioned the test data set into ten different files to replicate the streaming simulation. # We now repartition the test data and break them down into 10 different files and write it to a csv file.testData = testDF.repartition(10)#Remove directory in case we rerun it multiple times.dbutils.fs.rm("FileStore/tables/HeartTest/",True)#Create a directorytestData.write.format("CSV").option("header",True).save("FileStore/tables/HeartTest/") After that, I first created a source, which consisted of the following lines of code. # SourcesourceStream=spark.readStream.format("csv").option("header",True).schema(schema).option("ignoreLeadingWhiteSpace",True).option("mode","dropMalformed").option("maxFilesPerTrigger",1).load("dbfs:/FileStore/tables/HeartTest").withColumnRenamed("output","label") As you can see above, I use spark.readStream and read in a file with the format “csv”. In addition to that, I add the schema that I created at the beginning when reading in the file, followed by multiple options such as: ignoreLeadingWhiteSpace: True → Removes the leading whitespace. mode: DropMalformed → When set to DropMalformed it ignores the whole corrupted records. maxFilesPerTrigger: 1 → Maximum number of new files to be considered in every trigger. After that, I load in the data from the directory where I repartitioned the test data to replicate the simulation of streaming. Last but not least, I change the output column to label for the implementation of the logistic regression. The last step is to set up the streaming of the test data. I use the pipeline that has been fit to the training set (pModel) and use the transform functionality with the argument “sourceStream”, which is the source I created before. Lastly, I select the label, probability, and prediction columns. Please see below for the code snippet. As we can see, the green light is on, which indicates that we are streaming in unseen data, which comes from the test data that has been repartitioned to replicate the simulation for streaming purposes. Below is a sample output of our streaming, which shows us the actual label of the test data, the probability, and the model’s prediction on the unseen data. To assess the predictions on the test data, we can see the probabilities of which class the streamed data is part of. For example, when we look at row 1, we can see the vector in the probability column, which consists of [0.06936682704327157, 0.9306331729567284]. The first element in the vector represents the probability of class 0 (no heart attack), and the second element the probability of class 1 (heart attack). The model picks the higher probability value and assigns the streamed data to the class with the higher probability. In the first example, the model predicts 1, which is correct when comparing it with the actual label. I hope this example helped you to understand better how to make predictions using streamed data using Spark. Again the main focus of this article wasn’t about the performance of the model but more about how we can use unseen streamed data in our machine learning model. If you have more questions about incorporating Spark Streaming to Spark ML, I highly suggest going over the databricks documentation. Please see the link below: docs.databricks.com If you have any questions on this topic or have some feedback, feel free to contact me. I would appreciate it if you would share this article on any social media platforms. Thank you and until next time!✌️
[ { "code": null, "e": 593, "s": 172, "text": "In this article, I am going over an example of how we can use Spark ML to make predictions on streaming data. Note we won’t focus on comparing different models and tuning the model. The main focus will be on how we can incorporate Spark Streaming to make predictions using databricks. In addition to that, you should have some basic knowledge of how to use Spark ML. If Spark ML is new to you, check out the video below." }, { "code": null, "e": 808, "s": 593, "text": "For this example, we will predict whether someone will get a heart attack based on their age, gender, and medical conditions. A logistic regression will be trained, and we stream in unseen data to make predictions." }, { "code": null, "e": 1078, "s": 808, "text": "For this project, I used a dataset that is available on Kaggle. Please click here if you want to follow along. The data consists of 303 rows and 14 columns. Each row represents the information of a patient. The features of this dataset consist of the following columns:" }, { "code": null, "e": 1116, "s": 1078, "text": "age: age in years1. age: age in years" }, { "code": null, "e": 1148, "s": 1116, "text": "sex: sex (1 = male; 0 = female)" }, { "code": null, "e": 1250, "s": 1148, "text": "cp: chest pain type (1 = typical angina; 2 = atypical angina; 3 = non-anginal pain; 0 = asymptomatic)" }, { "code": null, "e": 1321, "s": 1250, "text": "trtbps: resting blood pressure (in mm Hg on admission to the hospital)" }, { "code": null, "e": 1354, "s": 1321, "text": "chol: serum cholesterol in mg/dl" }, { "code": null, "e": 1413, "s": 1354, "text": "fbs: fasting blood sugar > 120 mg/dl (1 = true; 0 = false)" }, { "code": null, "e": 1522, "s": 1413, "text": "restecg: resting electrocardiographic results (1 = normal; 2 = having ST-Twave abnormality; 0 = hypertrophy)" }, { "code": null, "e": 1560, "s": 1522, "text": "thalachh: maximum heart rate achieved" }, { "code": null, "e": 1608, "s": 1560, "text": "exng: exercise-induced angina (1 = yes; 0 = no)" }, { "code": null, "e": 1668, "s": 1608, "text": "oldpeak: ST depression induced by exercise relative to rest" }, { "code": null, "e": 1757, "s": 1668, "text": "slp: the slope of the peak exercise ST segment (2 = upsloping; 1 = flat;0 = downsloping)" }, { "code": null, "e": 1815, "s": 1757, "text": "caa: number of major vessels (0-3) colored by fluoroscopy" }, { "code": null, "e": 1874, "s": 1815, "text": "thall: 2 = normal; 1 = fixed defect; 3 = reversible defect" }, { "code": null, "e": 1910, "s": 1874, "text": "The target column is the following:" }, { "code": null, "e": 1981, "s": 1910, "text": "output: 0= less chance of heart attach 1= more change of heart attack." }, { "code": null, "e": 2424, "s": 1981, "text": "The first step is to create a schema to ensure that the data will consist of the correct data type when reading in the csv file. Next, we will use spark.read.format() function with “csv” as an argument, add the option to read in the header and assign the schema we created to the data frame. Last we load the data, and we also change the target column to label so that our logistic regression can identify which column the target variable is." }, { "code": null, "e": 3693, "s": 2424, "text": "from pyspark.ml import Pipelinefrom pyspark.sql.types import StructType,StructField,LongType, StringType,DoubleType,TimestampType# We use the following schemaschema = StructType( \\ [StructField(\"age\", LongType(),True), \\ StructField(\"sex\", LongType(), True), \\ StructField(\"cp\", LongType(), True), \\ StructField('trtbps', LongType(), True), \\ StructField(\"chol\", LongType(), True), \\ StructField(\"fbs\", LongType(), True), \\ StructField(\"restecg\", LongType(), True), \\ StructField(\"thalachh\", LongType(), True),\\ StructField(\"exng\", LongType(), True), \\ StructField(\"oldpeak\", DoubleType(), True), \\ StructField(\"slp\", LongType(),True), \\ StructField(\"caa\", LongType(), True), \\ StructField(\"thall\", LongType(), True), \\ StructField(\"output\", LongType(), True), \\ ])data = \"dbfs:/FileStore/tables/heart.csv\"df=spark.read.format('csv').option('header',True).schema(schema).load(data)df = df.withColumnRenamed(\"output\",\"label\")df.display()df.printSchema()" }, { "code": null, "e": 3756, "s": 3693, "text": "Once we run the above code, we get the following output below:" }, { "code": null, "e": 3864, "s": 3756, "text": "When it comes to data preprocessing steps, I first split the data into a training (70%) and test (30%) set." }, { "code": null, "e": 3909, "s": 3864, "text": "testDF, trainDF = df.randomSplit([0.3, 0.7])" }, { "code": null, "e": 4609, "s": 3909, "text": "After that, I created a pipeline that consists of five stages. The first stage is a vector assembler that takes in the age, trtbps, chol, thalachh, oldpeak columns and turns them into a vector. The second stage entails the scaling process of the features mentioned above. I am using the MinMaxScaler() function from the pyspark.ml.feature library. After that, I one-hot encode the sex, cp, fbs, restecg, slp, exng, caa, and thall columns, since those are nominal categorical variables. Next, I create a second vector assembler and add the one-hot encoded columns and scaled features into one vector. Last but not least, the last stage consists of a Logistic Regression with the following parameters:" }, { "code": null, "e": 4622, "s": 4609, "text": "maxIter = 10" }, { "code": null, "e": 4638, "s": 4622, "text": "regParam = 0.01" }, { "code": null, "e": 4979, "s": 4638, "text": "I chose a logistic regression algorithm because our target consists of binary numbers (0 and 1). Once the pipeline has been created, I fit and transform the training set. After that, I select the label, probability, and prediction columns. Please see below a snippet of the pipeline construction and the predictions when training the model." }, { "code": null, "e": 6447, "s": 4979, "text": "from pyspark.ml.feature import OneHotEncoderfrom pyspark.ml.feature import MinMaxScalerfrom pyspark.ml.feature import StringIndexerfrom pyspark.ml.feature import VectorAssemblerfrom pyspark.ml.feature import OneHotEncoderfrom pyspark.ml.classification import LogisticRegression# Create the logistic regression modellr = LogisticRegression(maxIter=10, regParam= 0.01)# We create a one hot encoder.ohe = OneHotEncoder(inputCols = ['sex', 'cp', 'fbs', 'restecg', 'slp', 'exng', 'caa', 'thall'], outputCols=['sex_ohe', 'cp_ohe', 'fbs_ohe', 'restecg_ohe', 'slp_ohe', 'exng_ohe', 'caa_ohe', 'thall_ohe'])# Input list for scalinginputs = ['age','trtbps','chol','thalachh','oldpeak']# We scale our inputsassembler1 = VectorAssembler(inputCols=inputs, outputCol=\"features_scaled1\")scaler = MinMaxScaler(inputCol=\"features_scaled1\", outputCol=\"features_scaled\")# We create a second assembler for the encoded columns.assembler2 = VectorAssembler(inputCols=['sex_ohe', 'cp_ohe', 'fbs_ohe', 'restecg_ohe', 'slp_ohe', 'exng_ohe', 'caa_ohe', 'thall_ohe','features_scaled'], outputCol=\"features\")# Create stages listmyStages = [assembler1, scaler, ohe, assembler2,lr]# Set up the pipelinepipeline = Pipeline(stages= myStages)# We fit the model using the training data.pModel = pipeline.fit(trainDF)# We transform the data.trainingPred = pModel.transform(trainDF)# # We select the actual label, probability and predictionstrainingPred.select('label','probability','prediction').show()" }, { "code": null, "e": 6890, "s": 6447, "text": "As we can see above, the marked yellow rows show that the lower the probability, the more confident the model is that the prediction is a 1. On the other hand, the marked red row shows the higher the probability, the more certain it predicts the output to be a zero. In addition to that, I evaluate the performance of the model, calculating the overall accuracy score. Please see below the code snippet of how I calculated the accuracy score." }, { "code": null, "e": 7008, "s": 6890, "text": "When training the model on the training data, the accuracy score resulted in 0.902913%, which is a satisfying result." }, { "code": null, "e": 7138, "s": 7008, "text": "To incorporate Spark Streaming, I repartitioned the test data set into ten different files to replicate the streaming simulation." }, { "code": null, "e": 7485, "s": 7138, "text": "# We now repartition the test data and break them down into 10 different files and write it to a csv file.testData = testDF.repartition(10)#Remove directory in case we rerun it multiple times.dbutils.fs.rm(\"FileStore/tables/HeartTest/\",True)#Create a directorytestData.write.format(\"CSV\").option(\"header\",True).save(\"FileStore/tables/HeartTest/\")" }, { "code": null, "e": 7571, "s": 7485, "text": "After that, I first created a source, which consisted of the following lines of code." }, { "code": null, "e": 7838, "s": 7571, "text": "# SourcesourceStream=spark.readStream.format(\"csv\").option(\"header\",True).schema(schema).option(\"ignoreLeadingWhiteSpace\",True).option(\"mode\",\"dropMalformed\").option(\"maxFilesPerTrigger\",1).load(\"dbfs:/FileStore/tables/HeartTest\").withColumnRenamed(\"output\",\"label\")" }, { "code": null, "e": 8059, "s": 7838, "text": "As you can see above, I use spark.readStream and read in a file with the format “csv”. In addition to that, I add the schema that I created at the beginning when reading in the file, followed by multiple options such as:" }, { "code": null, "e": 8123, "s": 8059, "text": "ignoreLeadingWhiteSpace: True → Removes the leading whitespace." }, { "code": null, "e": 8211, "s": 8123, "text": "mode: DropMalformed → When set to DropMalformed it ignores the whole corrupted records." }, { "code": null, "e": 8298, "s": 8211, "text": "maxFilesPerTrigger: 1 → Maximum number of new files to be considered in every trigger." }, { "code": null, "e": 8533, "s": 8298, "text": "After that, I load in the data from the directory where I repartitioned the test data to replicate the simulation of streaming. Last but not least, I change the output column to label for the implementation of the logistic regression." }, { "code": null, "e": 8870, "s": 8533, "text": "The last step is to set up the streaming of the test data. I use the pipeline that has been fit to the training set (pModel) and use the transform functionality with the argument “sourceStream”, which is the source I created before. Lastly, I select the label, probability, and prediction columns. Please see below for the code snippet." }, { "code": null, "e": 9230, "s": 8870, "text": "As we can see, the green light is on, which indicates that we are streaming in unseen data, which comes from the test data that has been repartitioned to replicate the simulation for streaming purposes. Below is a sample output of our streaming, which shows us the actual label of the test data, the probability, and the model’s prediction on the unseen data." }, { "code": null, "e": 9868, "s": 9230, "text": "To assess the predictions on the test data, we can see the probabilities of which class the streamed data is part of. For example, when we look at row 1, we can see the vector in the probability column, which consists of [0.06936682704327157, 0.9306331729567284]. The first element in the vector represents the probability of class 0 (no heart attack), and the second element the probability of class 1 (heart attack). The model picks the higher probability value and assigns the streamed data to the class with the higher probability. In the first example, the model predicts 1, which is correct when comparing it with the actual label." }, { "code": null, "e": 10299, "s": 9868, "text": "I hope this example helped you to understand better how to make predictions using streamed data using Spark. Again the main focus of this article wasn’t about the performance of the model but more about how we can use unseen streamed data in our machine learning model. If you have more questions about incorporating Spark Streaming to Spark ML, I highly suggest going over the databricks documentation. Please see the link below:" }, { "code": null, "e": 10319, "s": 10299, "text": "docs.databricks.com" } ]
Perl | Appending to a File - GeeksforGeeks
05 Mar, 2019 When a file is opened in write mode using “>”, the content of the existing file is deleted and content added using the print statement is written to the file. In this mode, the writing point will be set to the end of the file. So old content of file remains intact and anything that is written to file using print statement is added to the end of the file. However, read operation cannot be performed unless the file is opened in +>> mode indicating append and read. Example: # Opening a file in read mode# to display existing content open(FH, "Hello.txt") or die "Sorry!! couldn't open"; # Reading and printing the existing# content of the fileprint"\nExisiting Content of the File:\n";while(<FH>){ print $_;} # Opening file in append mode# using >>open(FH, ">>", "Hello.txt") or die "File couldn't be opened"; # Getting the text to be appended # from the userprint "\n\nEnter text to append\n";$a = <>; # Appending the content to fileprint FH $a; # Printing the success messageprint "\nAppending to File is Successful!!!\n"; # Reading the file after appendingprint "\nAfter appending, Updated File is\n"; # Opening file in read mode to # display updated contentopen(FH, "Hello.txt") or die "Sorry!! couldn't open";while(<FH>){ print $_;}close FH or "couldn't close"; Original File: Appending to File: Updated File: Here is how the program works:-Step 1: Opening a file in read mode to see the existing content of the file.Step 2: Printing the existing content of the file.Step 3: Opening the File in Append mode to add content to the file.Step 4: Getting text from the user to be appended to a fileStep 5: Appending text to fileStep 6: Reading the file again to see the updated content.Step 7: Closing a file Perl-files Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | Arrays (push, pop, shift, unshift) Perl | Arrays Perl Tutorial - Learn Perl With Examples Perl | length() Function Perl | sleep() Function Hello World Program in Perl Introduction to Perl Perl | Boolean Values Perl | Basic Syntax of a Perl Program Perl | join() Function
[ { "code": null, "e": 24020, "s": 23992, "text": "\n05 Mar, 2019" }, { "code": null, "e": 24487, "s": 24020, "text": "When a file is opened in write mode using “>”, the content of the existing file is deleted and content added using the print statement is written to the file. In this mode, the writing point will be set to the end of the file. So old content of file remains intact and anything that is written to file using print statement is added to the end of the file. However, read operation cannot be performed unless the file is opened in +>> mode indicating append and read." }, { "code": null, "e": 24496, "s": 24487, "text": "Example:" }, { "code": "# Opening a file in read mode# to display existing content open(FH, \"Hello.txt\") or die \"Sorry!! couldn't open\"; # Reading and printing the existing# content of the fileprint\"\\nExisiting Content of the File:\\n\";while(<FH>){ print $_;} # Opening file in append mode# using >>open(FH, \">>\", \"Hello.txt\") or die \"File couldn't be opened\"; # Getting the text to be appended # from the userprint \"\\n\\nEnter text to append\\n\";$a = <>; # Appending the content to fileprint FH $a; # Printing the success messageprint \"\\nAppending to File is Successful!!!\\n\"; # Reading the file after appendingprint \"\\nAfter appending, Updated File is\\n\"; # Opening file in read mode to # display updated contentopen(FH, \"Hello.txt\") or die \"Sorry!! couldn't open\";while(<FH>){ print $_;}close FH or \"couldn't close\";", "e": 25312, "s": 24496, "text": null }, { "code": null, "e": 25328, "s": 25312, "text": "Original File: " }, { "code": null, "e": 25362, "s": 25328, "text": "Appending to File: Updated File: " }, { "code": null, "e": 25756, "s": 25362, "text": "Here is how the program works:-Step 1: Opening a file in read mode to see the existing content of the file.Step 2: Printing the existing content of the file.Step 3: Opening the File in Append mode to add content to the file.Step 4: Getting text from the user to be appended to a fileStep 5: Appending text to fileStep 6: Reading the file again to see the updated content.Step 7: Closing a file" }, { "code": null, "e": 25767, "s": 25756, "text": "Perl-files" }, { "code": null, "e": 25774, "s": 25767, "text": "Picked" }, { "code": null, "e": 25779, "s": 25774, "text": "Perl" }, { "code": null, "e": 25784, "s": 25779, "text": "Perl" }, { "code": null, "e": 25882, "s": 25784, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25924, "s": 25882, "text": "Perl | Arrays (push, pop, shift, unshift)" }, { "code": null, "e": 25938, "s": 25924, "text": "Perl | Arrays" }, { "code": null, "e": 25979, "s": 25938, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 26004, "s": 25979, "text": "Perl | length() Function" }, { "code": null, "e": 26028, "s": 26004, "text": "Perl | sleep() Function" }, { "code": null, "e": 26056, "s": 26028, "text": "Hello World Program in Perl" }, { "code": null, "e": 26077, "s": 26056, "text": "Introduction to Perl" }, { "code": null, "e": 26099, "s": 26077, "text": "Perl | Boolean Values" }, { "code": null, "e": 26137, "s": 26099, "text": "Perl | Basic Syntax of a Perl Program" } ]
How to copy certain files from one folder to another using Python?
The shutil module provides functions for copying files, as well as entire folders. For copying multiple files at once, you'll have to have a list of all files you want to copy and loop over them to copy them. Calling shutil.copy(source, destination) will copy the file at the path source to the folder at the path destination. (Both source and destination are strings.) If destination is a filename, it will be used as the new name of the copied file. This function returns a string of the path of the copied file. import shutil, os files = ['file1.txt', 'file2.txt', 'file3.txt'] for f in files: shutil.copy(f, 'dest_folder')
[ { "code": null, "e": 1271, "s": 1062, "text": "The shutil module provides functions for copying files, as well as entire folders. For copying multiple files at once, you'll have to have a list of all files you want to copy and loop over them to copy them." }, { "code": null, "e": 1579, "s": 1271, "text": "Calling shutil.copy(source, destination) will copy the file at the path source to the folder at the path destination. (Both source and destination are strings.) If destination is a filename, it will be used as the new name of the copied file. This function returns a string of the path of the copied file. " }, { "code": null, "e": 1695, "s": 1579, "text": "import shutil, os\nfiles = ['file1.txt', 'file2.txt', 'file3.txt']\nfor f in files:\n shutil.copy(f, 'dest_folder')" } ]
View stored procedure/function definition in MySQL?
To view stored procedure/function definition in MySQL, you can use show command. The syntax is as follows − SHOW CREATE PROCEDURE yourProcedureName; To understand the above syntax, you can create a procedure and check that definition. Let us create a stored procedure − mysql> delimiter // mysql> create procedure AllRecords() -> begin -> select *from student; -> end // Query OK, 0 rows affected (0.24 sec) You can call the stored procedure with the help of call command. The query is as follows − mysql> delimiter ; mysql> call AllRecords(); The following is the output − +------+-------+ | id | Name | +------+-------+ | 1 | John | | 2 | Bob | | 3 | Smith | | 6 | John | +------+-------+ 4 rows in set (0.14 sec) Query OK, 0 rows affected (0.18 sec) Now you can check the definition with the help of above syntax which we discussed in the beginning. The query is as follows − mysql> show create procedure AllRecords; Here is the output − +------------+--------------------------------------------+-----------------------------------------------------------------------+----------------------+----------------------+--------------------+ | Procedure | sql_mode | Create Procedure | character_set_client | collation_connection | Database Collation | +------------+--------------------------------------------+-----------------------------------------------------------------------+----------------------+----------------------+--------------------+ | AllRecords | STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION | CREATE DEFINER=`root`@`%` PROCEDURE `AllRecords`() begin select *from student;end | utf8 | utf8_general_ci | utf8mb4_unicode_ci | +------------+--------------------------------------------+-----------------------------------------------------------------------+----------------------+----------------------+--------------------+ 1 row in set (0.00 sec) To check the function definition in MySQL, you can use function in place of procedure. The syntax is as follows: − SHOW CREATE FUNCTION yourFunctionName;
[ { "code": null, "e": 1170, "s": 1062, "text": "To view stored procedure/function definition in MySQL, you can use show command. The syntax is as follows −" }, { "code": null, "e": 1211, "s": 1170, "text": "SHOW CREATE PROCEDURE yourProcedureName;" }, { "code": null, "e": 1332, "s": 1211, "text": "To understand the above syntax, you can create a procedure and check that definition. Let us create a stored procedure −" }, { "code": null, "e": 1479, "s": 1332, "text": "mysql> delimiter //\nmysql> create procedure AllRecords()\n -> begin\n -> select *from student;\n -> end //\nQuery OK, 0 rows affected (0.24 sec)" }, { "code": null, "e": 1570, "s": 1479, "text": "You can call the stored procedure with the help of call command. The query is as follows −" }, { "code": null, "e": 1615, "s": 1570, "text": "mysql> delimiter ;\nmysql> call AllRecords();" }, { "code": null, "e": 1645, "s": 1615, "text": "The following is the output −" }, { "code": null, "e": 1844, "s": 1645, "text": "+------+-------+\n| id | Name |\n+------+-------+\n| 1 | John |\n| 2 | Bob |\n| 3 | Smith |\n| 6 | John |\n+------+-------+\n4 rows in set (0.14 sec)\n\nQuery OK, 0 rows affected (0.18 sec)" }, { "code": null, "e": 1970, "s": 1844, "text": "Now you can check the definition with the help of above syntax which we discussed in the beginning. The query is as follows −" }, { "code": null, "e": 2011, "s": 1970, "text": "mysql> show create procedure AllRecords;" }, { "code": null, "e": 2032, "s": 2011, "text": "Here is the output −" }, { "code": null, "e": 3051, "s": 2032, "text": "+------------+--------------------------------------------+-----------------------------------------------------------------------+----------------------+----------------------+--------------------+\n| Procedure | sql_mode | Create Procedure | character_set_client | collation_connection | Database Collation |\n+------------+--------------------------------------------+-----------------------------------------------------------------------+----------------------+----------------------+--------------------+\n| AllRecords | STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION | CREATE DEFINER=`root`@`%` PROCEDURE `AllRecords`() begin select *from student;end | utf8 | utf8_general_ci | utf8mb4_unicode_ci |\n+------------+--------------------------------------------+-----------------------------------------------------------------------+----------------------+----------------------+--------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3166, "s": 3051, "text": "To check the function definition in MySQL, you can use function in place of procedure. The syntax is as follows: −" }, { "code": null, "e": 3205, "s": 3166, "text": "SHOW CREATE FUNCTION yourFunctionName;" } ]
Check if a triangle of positive area is possible with the given angles in Python
Suppose we have three angles. We have to check whether it is possible to create a triangle of positive area with these angles or not. So, if the input is like a = 40 b = 120 c = 20, then the output will be True as the sum of 40 + 120 + 20 = 180. To solve this, we will follow these steps − if a, b and c are not 0 and (a + b + c) is same as 180, thenif (a + b) >= c or (b + c) >= a or (a + c) >= b, thenreturn Trueotherwise,return False if (a + b) >= c or (b + c) >= a or (a + c) >= b, thenreturn True return True otherwise,return False return False otherwise,return False return False Let us see the following implementation to get better understanding − Live Demo def solve(a, b, c): if a != 0 and b != 0 and c != 0 and (a + b + c) == 180: if (a + b)>= c or (b + c)>= a or (a + c)>= b: return True else: return False else: return False a = 40 b = 120 c = 20 print(solve(a, b, c)) 40, 120, 20 True
[ { "code": null, "e": 1196, "s": 1062, "text": "Suppose we have three angles. We have to check whether it is possible to create a triangle of positive area with these angles or not." }, { "code": null, "e": 1308, "s": 1196, "text": "So, if the input is like a = 40 b = 120 c = 20, then the output will be True as the sum of 40 + 120 + 20 = 180." }, { "code": null, "e": 1352, "s": 1308, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1499, "s": 1352, "text": "if a, b and c are not 0 and (a + b + c) is same as 180, thenif (a + b) >= c or (b + c) >= a or (a + c) >= b, thenreturn Trueotherwise,return False" }, { "code": null, "e": 1564, "s": 1499, "text": "if (a + b) >= c or (b + c) >= a or (a + c) >= b, thenreturn True" }, { "code": null, "e": 1576, "s": 1564, "text": "return True" }, { "code": null, "e": 1599, "s": 1576, "text": "otherwise,return False" }, { "code": null, "e": 1612, "s": 1599, "text": "return False" }, { "code": null, "e": 1635, "s": 1612, "text": "otherwise,return False" }, { "code": null, "e": 1648, "s": 1635, "text": "return False" }, { "code": null, "e": 1718, "s": 1648, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1729, "s": 1718, "text": " Live Demo" }, { "code": null, "e": 1987, "s": 1729, "text": "def solve(a, b, c):\n if a != 0 and b != 0 and c != 0 and (a + b + c) == 180:\n if (a + b)>= c or (b + c)>= a or (a + c)>= b:\n return True\n else:\n return False\n else:\n return False\na = 40\nb = 120\nc = 20\nprint(solve(a, b, c))" }, { "code": null, "e": 1999, "s": 1987, "text": "40, 120, 20" }, { "code": null, "e": 2004, "s": 1999, "text": "True" } ]
Aptitude - Pipes & Cisterns Online Quiz
Following quiz provides Multiple Choice Questions (MCQs) related to Pipes & Cisterns. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz. Q 1 - In 1 minute 3/7 of a basin is filled. Whatever remains of the container can be filled in: A - 2 min B - 4/3 min C - 7/3 min D - none of these Part filled in 1 min. = 3/7. remaining part = (1- 3/7)= 4/7 Let the required time be x min. More part, more time taken. (Direct) 3/7: 4/7:: 1: x ⇒ 3x/7 = (4/7*1) ⇒ x= 4/3 min. Q 2 - A tank can be filled by a tap in 20 minutes and by another tap in an hour. Both the taps are kept open for 10 minutes and after that the first tap is shutoff. After this, the tank will be totally filled in: A - 10 min B - 12 min C - 15 min D - 20 min Part of the tank filled by both in 10 min. = 10*(1/20+1/60)= 40/60 = 2/3 Remaining part = (1-2/3) = 1/3 1/60 part is now filled in 1 min. 1/3 part is now filled in (60*1/3) min. = 20 min. Q 3 - A storage has two funnels. One can fill it with water in 8hours and the other can exhaust it in 5 hours. In how long will the reservoir be purged if both the channels are opened together when 3/4 of the storage is now loaded with water? A - 10/3 hours B - 6 hours C - 10 hours D - 40/3 hours Net part emptied by both in 1 hr = (1/5-1/8)= 3/40 3/40 part is emptied in 1 hr. 3/4 part will be emptied in (40/3*3/4) hrs = 10 hrs. Q 4 - Two channels can fill a tank in 15 hours and 12 hours separately and a third pipe can purge it in 4 hours. In the event that the channels are opened all together at 8 am, 9 am and 11am separately, the tank will be exhausted at A - 11.40 am B - 12.40 pm C - 1.40 pm D - 2.40 pm Let the tank be emptied in x hrs after 8 am. Work done by A in x hrs, by B in (x-1) hrs and C in (x-3) hrs = 0 ⇒x/15+ (x-1)/12- (x-3)/4 = 0 ⇒ 4x+5(x-1) - 15(x-3) = 0 ⇒6x= 40 ⇒x= 20/3 hrs. ⇒x= 6 hrs. 40 min after 8 am Hence the tank will be emptied at 14 hrs 40 min, i.e., 2:40 pm Q 5 - A reservoir has three channels A, B and C. A and B can fill it in 3 hrs and 4 hrs. individually while C can exhaust the totally filled reservoir in 1 hours. On the off chance that the funnels are opened all together at 3 pm, 4 pm and 5 pm individually, at what the truth will surface eventually reservoir void? A - 6.15 pm B - 7.12 pm C - 8.12 pm D - 8.35 pm Let the cistern be emptied in x hrs after 3 pm Work done by A in x hrs, by B in(x-1) hrs and by C in (x-2) hrs= 0 ⇒x/3 +x-1/4 ? (x-2) =0 ⇒ 4x+3(x-1)-12(x-2) = 0 ⇒5x=21 ⇒x= 4 hrs 12 min. Required time is 7.12 pm. Q 6 - A tap can fill a tank in 6 hours. After a large portion of the tank is filled, three more comparable taps are opened. What is the aggregate time taken to fill the tank totally? A - 3hrs 15 min. B - 3 hrs 45 min. C - 4 hrs D - 4 hrs 15 min Time taken by the tap to make the tank half full= 3 hrs. Remaining part = 1/2 Part filled by 4 taps in 1 hour= (4*1/6) = 2/3 2/3 part is filled in 1 hour. 1/2 part is filled in (3/2*1/2) hr = 3/4 hr = 45 min. Required time = 3hrs 45 min. Q 7 - A break in the base of a tank can purge the full tank in 6 hours. A channel funnel fills water at the rate of 4 liters for each moment. At the point when the tank is full, the channel is opened and because of the break, the tank is void in 8 hours. The limit of the tank is A - 5260 ltr. B - 5760 ltr. C - 5846 ltr. D - 6970 ltr. Part filled in 1 hour = (1/6-1/8)= 1/24 So, the inlet can fill the tank in 24 hours. Capacity of the tank= volume of water that flows in 24 hrs = (4*60*24) ltr. = 5760 liters. Q 8 - Two pipes A and B can ill a tank in 36 hours and 45 hours respectively. If both the pipes are opened simultaneously, how much time will be taken to fill the tank? A - 10 hours B - 15 hours C - 18 hours D - 20 hours T = xy/(x+y) = (36*45)/(36+45) = 1620/80 = 20 hours Or, Part filled by A in 1 hour = 1/36 Part filled by B in 1 hour = 1/45 Part filled by (A+B) in 1 hour = (1/36 + 1/45) = 1/20 ∴ Both the pipes can fill the tank in 20 hours. Q 9 - A cistern has two pipes. One can fill it with water in 8 hours and the other can empty it in 5 hours. In how many hours will the cistern be emptied if the both the pipes are opened together when 3/4 of the cistern is already full of water. A - 13.5 hours B - 10 hours C - 6 hours D - 3.5 hours Part if cistern emptied in 1 hour = 1/5 - 1/8 = 3/40 3/40 part is emptied in hour. ∴ 3/4 part is emptied in 40/3 * 3/4 = 10 hour Q 10 - One pipe can fill a tank three times as fast as another pipe. If together the two pipes can fill the tank in 36 minutes, the slower pipe alone will be able to fill the tank in ? A - 81 mins B - 108 min C - 192 min D - 144 min Let the time taken by faster pipe be x min ∴ 1/x + 1/3x = 1/36 Or, (3 +1)/3x = 1/36 Or, x = 48 min ∴ Time taken by slower pipe to fill the tank = 3*48min = 144 min 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 4222, "s": 3892, "text": "Following quiz provides Multiple Choice Questions (MCQs) related to Pipes & Cisterns. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz." }, { "code": null, "e": 4318, "s": 4222, "text": "Q 1 - In 1 minute 3/7 of a basin is filled. Whatever remains of the container can be filled in:" }, { "code": null, "e": 4328, "s": 4318, "text": "A - 2 min" }, { "code": null, "e": 4340, "s": 4328, "text": "B - 4/3 min" }, { "code": null, "e": 4352, "s": 4340, "text": "C - 7/3 min" }, { "code": null, "e": 4370, "s": 4352, "text": "D - none of these" }, { "code": null, "e": 4546, "s": 4370, "text": "Part filled in 1 min. = 3/7. remaining part = (1- 3/7)= 4/7\nLet the required time be x min.\nMore part, more time taken. (Direct)\n3/7: 4/7:: 1: x ⇒ 3x/7 = (4/7*1) ⇒ x= 4/3 min." }, { "code": null, "e": 4759, "s": 4546, "text": "Q 2 - A tank can be filled by a tap in 20 minutes and by another tap in an hour. Both the taps are kept open for 10 minutes and after that the first tap is shutoff. After this, the tank will be totally filled in:" }, { "code": null, "e": 4770, "s": 4759, "text": "A - 10 min" }, { "code": null, "e": 4781, "s": 4770, "text": "B - 12 min" }, { "code": null, "e": 4792, "s": 4781, "text": "C - 15 min" }, { "code": null, "e": 4803, "s": 4792, "text": "D - 20 min" }, { "code": null, "e": 4991, "s": 4803, "text": "Part of the tank filled by both in 10 min. = 10*(1/20+1/60)= 40/60 = 2/3\nRemaining part = (1-2/3) = 1/3\n1/60 part is now filled in 1 min.\n1/3 part is now filled in (60*1/3) min. = 20 min." }, { "code": null, "e": 5234, "s": 4991, "text": "Q 3 - A storage has two funnels. One can fill it with water in 8hours and the other can exhaust it in 5 hours. In how long will the reservoir be purged if both the channels are opened together when 3/4 of the storage is now loaded with water?" }, { "code": null, "e": 5249, "s": 5234, "text": "A - 10/3 hours" }, { "code": null, "e": 5261, "s": 5249, "text": "B - 6 hours" }, { "code": null, "e": 5274, "s": 5261, "text": "C - 10 hours" }, { "code": null, "e": 5289, "s": 5274, "text": "D - 40/3 hours" }, { "code": null, "e": 5423, "s": 5289, "text": "Net part emptied by both in 1 hr = (1/5-1/8)= 3/40\n3/40 part is emptied in 1 hr.\n3/4 part will be emptied in (40/3*3/4) hrs = 10 hrs." }, { "code": null, "e": 5656, "s": 5423, "text": "Q 4 - Two channels can fill a tank in 15 hours and 12 hours separately and a third pipe can purge it in 4 hours. In the event that the channels are opened all together at 8 am, 9 am and 11am separately, the tank will be exhausted at" }, { "code": null, "e": 5669, "s": 5656, "text": "A - 11.40 am" }, { "code": null, "e": 5682, "s": 5669, "text": "B - 12.40 pm" }, { "code": null, "e": 5694, "s": 5682, "text": "C - 1.40 pm" }, { "code": null, "e": 5706, "s": 5694, "text": "D - 2.40 pm" }, { "code": null, "e": 5986, "s": 5706, "text": "Let the tank be emptied in x hrs after 8 am.\nWork done by A in x hrs, by B in (x-1) hrs and C in (x-3) hrs = 0\n⇒x/15+ (x-1)/12- (x-3)/4 = 0 ⇒ 4x+5(x-1) - 15(x-3) = 0\n⇒6x= 40 ⇒x= 20/3 hrs.\n⇒x= 6 hrs. 40 min after 8 am\nHence the tank will be emptied at 14 hrs 40 min, i.e., 2:40 pm" }, { "code": null, "e": 6303, "s": 5986, "text": "Q 5 - A reservoir has three channels A, B and C. A and B can fill it in 3 hrs and 4 hrs. individually while C can exhaust the totally filled reservoir in 1 hours. On the off chance that the funnels are opened all together at 3 pm, 4 pm and 5 pm individually, at what the truth will surface eventually reservoir void?" }, { "code": null, "e": 6315, "s": 6303, "text": "A - 6.15 pm" }, { "code": null, "e": 6327, "s": 6315, "text": "B - 7.12 pm" }, { "code": null, "e": 6339, "s": 6327, "text": "C - 8.12 pm" }, { "code": null, "e": 6351, "s": 6339, "text": "D - 8.35 pm" }, { "code": null, "e": 6563, "s": 6351, "text": "Let the cistern be emptied in x hrs after 3 pm\nWork done by A in x hrs, by B in(x-1) hrs and by C in (x-2) hrs= 0\n⇒x/3 +x-1/4 ? (x-2) =0 ⇒ 4x+3(x-1)-12(x-2) = 0\n⇒5x=21 ⇒x= 4 hrs 12 min.\nRequired time is 7.12 pm." }, { "code": null, "e": 6746, "s": 6563, "text": "Q 6 - A tap can fill a tank in 6 hours. After a large portion of the tank is filled, three more comparable taps are opened. What is the aggregate time taken to fill the tank totally?" }, { "code": null, "e": 6763, "s": 6746, "text": "A - 3hrs 15 min." }, { "code": null, "e": 6781, "s": 6763, "text": "B - 3 hrs 45 min." }, { "code": null, "e": 6791, "s": 6781, "text": "C - 4 hrs" }, { "code": null, "e": 6808, "s": 6791, "text": "D - 4 hrs 15 min" }, { "code": null, "e": 7046, "s": 6808, "text": "Time taken by the tap to make the tank half full= 3 hrs.\nRemaining part = 1/2\nPart filled by 4 taps in 1 hour= (4*1/6) = 2/3\n2/3 part is filled in 1 hour.\n1/2 part is filled in (3/2*1/2) hr = 3/4 hr = 45 min.\nRequired time = 3hrs 45 min." }, { "code": null, "e": 7326, "s": 7046, "text": "Q 7 - A break in the base of a tank can purge the full tank in 6 hours. A channel funnel fills water at the rate of 4 liters for each moment. At the point when the tank is full, the channel is opened and because of the break, the tank is void in 8 hours. The limit of the tank is" }, { "code": null, "e": 7340, "s": 7326, "text": "A - 5260 ltr." }, { "code": null, "e": 7354, "s": 7340, "text": "B - 5760 ltr." }, { "code": null, "e": 7368, "s": 7354, "text": "C - 5846 ltr." }, { "code": null, "e": 7382, "s": 7368, "text": "D - 6970 ltr." }, { "code": null, "e": 7558, "s": 7382, "text": "Part filled in 1 hour = (1/6-1/8)= 1/24\nSo, the inlet can fill the tank in 24 hours.\nCapacity of the tank= volume of water that flows in 24 hrs\n= (4*60*24) ltr. = 5760 liters." }, { "code": null, "e": 7727, "s": 7558, "text": "Q 8 - Two pipes A and B can ill a tank in 36 hours and 45 hours respectively. If both the pipes are opened simultaneously, how much time will be taken to fill the tank?" }, { "code": null, "e": 7740, "s": 7727, "text": "A - 10 hours" }, { "code": null, "e": 7753, "s": 7740, "text": "B - 15 hours" }, { "code": null, "e": 7766, "s": 7753, "text": "C - 18 hours" }, { "code": null, "e": 7779, "s": 7766, "text": "D - 20 hours" }, { "code": null, "e": 8008, "s": 7779, "text": "T = xy/(x+y)\n= (36*45)/(36+45)\n= 1620/80\n= 20 hours\n\nOr,\n\nPart filled by A in 1 hour = 1/36\nPart filled by B in 1 hour = 1/45\nPart filled by (A+B) in 1 hour = (1/36 + 1/45) = 1/20\n\n∴ Both the pipes can fill the tank in 20 hours." }, { "code": null, "e": 8254, "s": 8008, "text": "Q 9 - A cistern has two pipes. One can fill it with water in 8 hours and the other can empty it in 5 hours. In how many hours will the cistern be emptied if the both the pipes are opened together when 3/4 of the cistern is already full of water." }, { "code": null, "e": 8269, "s": 8254, "text": "A - 13.5 hours" }, { "code": null, "e": 8282, "s": 8269, "text": "B - 10 hours" }, { "code": null, "e": 8294, "s": 8282, "text": "C - 6 hours" }, { "code": null, "e": 8308, "s": 8294, "text": "D - 3.5 hours" }, { "code": null, "e": 8437, "s": 8308, "text": "Part if cistern emptied in 1 hour = 1/5 - 1/8\n= 3/40\n3/40 part is emptied in hour.\n∴ 3/4 part is emptied in 40/3 * 3/4 = 10 hour" }, { "code": null, "e": 8622, "s": 8437, "text": "Q 10 - One pipe can fill a tank three times as fast as another pipe. If together the two pipes can fill the tank in 36 minutes, the slower pipe alone will be able to fill the tank in ?" }, { "code": null, "e": 8634, "s": 8622, "text": "A - 81 mins" }, { "code": null, "e": 8646, "s": 8634, "text": "B - 108 min" }, { "code": null, "e": 8658, "s": 8646, "text": "C - 192 min" }, { "code": null, "e": 8670, "s": 8658, "text": "D - 144 min" }, { "code": null, "e": 8835, "s": 8670, "text": "Let the time taken by faster pipe be x min\n∴ 1/x + 1/3x = 1/36\nOr, (3 +1)/3x = 1/36\nOr, x = 48 min\n\n∴ Time taken by slower pipe to fill the tank = 3*48min = 144 min" }, { "code": null, "e": 8871, "s": 8835, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 8889, "s": 8871, "text": " Programming Line" }, { "code": null, "e": 8896, "s": 8889, "text": " Print" }, { "code": null, "e": 8907, "s": 8896, "text": " Add Notes" } ]
Extract Tweets using GetOldTweets3 - GeeksforGeeks
29 Aug, 2020 For most text mining or classification projects, extracting tweets is one of the most important and initial steps. The well-known method is extracting tweets with tweepy and creating a developer account in twitter. Due to certain security reasons, Twitter takes nearly 15 days to verify the process of making a developer account. Thus using this python library makes the process easy. Another advantage of using this library is that the tweets are pretty recent tweets. One can get tweets from previous months or even weeks. Let’s understand the working better with a code – Installing the library GetOldTweets3 – The following command can be installed in a Jupyter Notebook or any command prompt. pip install GetOldTweets3 Specify the needed hashtag – After installing the library it will be imported with another variable. With the inbuilt method TweetCriteria() the needed specifications in our dataset of tweets can be mentioned. The method setQuerySearch() allows getting any tweets with respect to our hashtag import GetOldTweets3 as got gettweet = got.manager.TweetCriteria().setQuerySearch(hashtag) \ #'\' is similar to ', in a sentence' i.e used to separate More specifications can be added. There are many .setSince("2020-01-01") \ .setUntil("2020-05-01") \ .setMaxTweets(100)\ .setLocation("Pune")\ .setUsername("Raj")\...etc. Let’s see the complete code Python3 import GetOldTweets3 as got def extract_tweets(hashtag): gettweet= got.manager.TweetCriteria().setQuerySearch(hashtag) \ .setSince("2020-01-01") \ .setUntil("2020-05-01") \ .setMaxTweets(100) # Creation of list that contains all tweets tweets = got.manager.TweetManager.getTweets(gettweet) # Creating list of chosen tweet data text_tweets = [[tweet.text] for tweet in tweets] print(text_tweets) # calling the functionextract_tweets('COVID19') Output: GfG-GetOldTweets3 Some tweets are in different languages. One can use the translator() function of Python to convert those tweets in a distinct language. python-modules python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n29 Aug, 2020" }, { "code": null, "e": 24817, "s": 24292, "text": "For most text mining or classification projects, extracting tweets is one of the most important and initial steps. The well-known method is extracting tweets with tweepy and creating a developer account in twitter. Due to certain security reasons, Twitter takes nearly 15 days to verify the process of making a developer account. Thus using this python library makes the process easy. Another advantage of using this library is that the tweets are pretty recent tweets. One can get tweets from previous months or even weeks." }, { "code": null, "e": 24868, "s": 24817, "text": "Let’s understand the working better with a code – " }, { "code": null, "e": 24991, "s": 24868, "text": "Installing the library GetOldTweets3 – The following command can be installed in a Jupyter Notebook or any command prompt." }, { "code": null, "e": 25019, "s": 24991, "text": "pip install GetOldTweets3\n\n" }, { "code": null, "e": 25311, "s": 25019, "text": "Specify the needed hashtag – After installing the library it will be imported with another variable. With the inbuilt method TweetCriteria() the needed specifications in our dataset of tweets can be mentioned. The method setQuerySearch() allows getting any tweets with respect to our hashtag" }, { "code": null, "e": 25479, "s": 25311, "text": "import GetOldTweets3 as got\n\n gettweet = got.manager.TweetCriteria().setQuerySearch(hashtag) \\ \n #'\\' is similar to ', in a sentence' i.e \n used to separate\n\n" }, { "code": null, "e": 25528, "s": 25479, "text": "More specifications can be added. There are many" }, { "code": null, "e": 25652, "s": 25528, "text": ".setSince(\"2020-01-01\") \\\n.setUntil(\"2020-05-01\") \\\n.setMaxTweets(100)\\\n.setLocation(\"Pune\")\\\n.setUsername(\"Raj\")\\...etc.\n\n" }, { "code": null, "e": 25680, "s": 25652, "text": "Let’s see the complete code" }, { "code": null, "e": 25688, "s": 25680, "text": "Python3" }, { "code": "import GetOldTweets3 as got def extract_tweets(hashtag): gettweet= got.manager.TweetCriteria().setQuerySearch(hashtag) \\ .setSince(\"2020-01-01\") \\ .setUntil(\"2020-05-01\") \\ .setMaxTweets(100) # Creation of list that contains all tweets tweets = got.manager.TweetManager.getTweets(gettweet) # Creating list of chosen tweet data text_tweets = [[tweet.text] for tweet in tweets] print(text_tweets) # calling the functionextract_tweets('COVID19')", "e": 26190, "s": 25688, "text": null }, { "code": null, "e": 26198, "s": 26190, "text": "Output:" }, { "code": null, "e": 26216, "s": 26198, "text": "GfG-GetOldTweets3" }, { "code": null, "e": 26352, "s": 26216, "text": "Some tweets are in different languages. One can use the translator() function of Python to convert those tweets in a distinct language." }, { "code": null, "e": 26367, "s": 26352, "text": "python-modules" }, { "code": null, "e": 26382, "s": 26367, "text": "python-utility" }, { "code": null, "e": 26389, "s": 26382, "text": "Python" }, { "code": null, "e": 26487, "s": 26389, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26496, "s": 26487, "text": "Comments" }, { "code": null, "e": 26509, "s": 26496, "text": "Old Comments" }, { "code": null, "e": 26541, "s": 26509, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26597, "s": 26541, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26652, "s": 26597, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26694, "s": 26652, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26736, "s": 26694, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26767, "s": 26736, "text": "Python | os.path.join() method" }, { "code": null, "e": 26806, "s": 26767, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26835, "s": 26806, "text": "Create a directory in Python" }, { "code": null, "e": 26857, "s": 26835, "text": "Defaultdict in Python" } ]
How to perform different commands over ssh with Python?
The simplest way to use SSH using python is to use paramiko. You can install it using − $ pip install paramiko To use paramiko, ensure that you have correctly set up SSH keys(https://confluence.atlassian.com/bitbucketserver/creating-ssh-keys-776639788.html) on the host machine and when running the python script, these keys are accessible. Once that is done use the following code to connect to a remote server using ssh − from paramiko import SSHClient ssh = SSHClient() ssh.load_system_host_keys() ssh.connect('user@server:path') ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('ls') print(ssh_stdout) #print the output of ls command You can use the exec_command function to run any command supported by the server you're connected to over ssh. Running the above code will give you the directory listing on the remote server.
[ { "code": null, "e": 1150, "s": 1062, "text": "The simplest way to use SSH using python is to use paramiko. You can install it using −" }, { "code": null, "e": 1173, "s": 1150, "text": "$ pip install paramiko" }, { "code": null, "e": 1486, "s": 1173, "text": "To use paramiko, ensure that you have correctly set up SSH keys(https://confluence.atlassian.com/bitbucketserver/creating-ssh-keys-776639788.html) on the host machine and when running the python script, these keys are accessible. Once that is done use the following code to connect to a remote server using ssh −" }, { "code": null, "e": 1704, "s": 1486, "text": "from paramiko import SSHClient\nssh = SSHClient()\nssh.load_system_host_keys()\nssh.connect('user@server:path')\nssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('ls')\nprint(ssh_stdout) #print the output of ls command" }, { "code": null, "e": 1896, "s": 1704, "text": "You can use the exec_command function to run any command supported by the server you're connected to over ssh. Running the above code will give you the directory listing on the remote server." } ]
A Novel Approach to Feature Importance — Shapley Additive Explanations | by Prakhar Rathi | Towards Data Science
If you’re stuck behind a paywall, click here to get my friend link and view this article. Machine learning interpretability is a topic of growing importance in this field. Interpret means to explain or to present in understandable terms. In the context of ML systems, interpretability is the ability to explain or to present in understandable terms to a human[Finale Doshi-Velez]. When investments are at stake, institutions prefer models which are explainable over models which might be giving relatively better accuracy. Actually, a better way to say this would be that when you’re dealing with real-world problems, machine learning interpretability becomes a part of the metric for a good model. Don’t be the person who treats machine learning and deep learning as black boxes and thinks that stacking layers will increase accuracy. It’s often the case that in business case applications, companies may choose to use a simple linear model as opposed to a complex non-linear model for the sake of interpretability. When you build a model, you’ll need to be able to understand how it's making the predictions. This helps you figure out when the model will work well and when it won’t work well (and that is where it will need human intervention). Often, you might have to explain your model to your clients and investors, especially when you’re managing their money using that model. It doesn’t just stop with managing investments but goes much beyond that — when you are using AI in healthcare, security, education etc. Basically anywhere outside of your jupyter notebook, the model interpretability becomes an important factor. In this article, I will discuss one such aspect of machine learning interpretability — feature importance. However, within that, I will be discussing a more novel approach called Shapley Additives. I have given a theoretical, mathematical and code explanation of the same. Here are the different parts of this article. Feel free to skip ahead to the part which you need to access. BackgroundTheoretical ExplanationMathematical ExpressionCode ImplementationVisualisation Background Theoretical Explanation Mathematical Expression Code Implementation Visualisation There are many different ways of increasing your model understanding and feature importance is one of them. Feature importance helps you estimate how much each feature of your data contributed to the model’s prediction. After performing feature importance tests, you can figure out which features are making the most impact on your model’s decision making. You can act on this by removing the features which have a low impact on the model’s predictions and focussing on making improvements to the more significant features. This can improve model performance significantly. There are many ways to calculate feature importance. Some of the basic methods which use statmodels and scikit-learn have been discussed in the article here. However, a lot of people have written about conventional methods, hence, I want to discuss a new approach called Shapely Additive Explanations (ShAP). This method is considered somewhat better than the traditional sckit-learn methods because many of these methods can be inconsistent, which means that the features that are most important may not always be given the highest feature importance score. One example is that in the tree-based models which might give two equally important features different scores based on what level of splitting was done using the features. The features which split the model first might be given higher importance. This is the motivation for using the latest feature attribution method, Shapley Additive Explanations. Let’s start with an example to get some intuition behind this method. Let’s say you’re Mark Cuban and you own a basketball team, let’s say, Dallas Mavericks and you have 3 players —Dirk Nowitzki (A), Michael Finley (B), Jason Kidd (C). You want to determine how much each player contributes to the final score of the team and obviously this does not mean that we just calculate the number of baskets each of them scored because that might work here but won’t work from a machine learning perspective. We want to be able to quantify how much impact their presence has on their team’s performance that extends beyond just calculating the number of baskets each player might have scored. The second reason is that not all of them might be playing in the same position. One of the players might play at an offensive position and the other might play at a defensive position and we want to be able to take that into account as well. One approach is that you calculate the team’s performance with and without Player A. The impact of player A can be the difference between the team’s performance with and without player A. Impact of A = Team Performance with A - Team performance without A This can be extended to each of the players and we can calculate their importance individually. This is the main intuition behind Shapely Additive Explanations. We estimate how important a model is by seeing how well the model performs with and without that feature for every combination of features. It is important to note that Shapley Additive Explanations calculates the local feature importance for every observation which is different from the method used in scikit-learn which computes the global feature importance. You can understand that the importance of a feature may not be uniform across all data points. So, local feature importance calculates the importance of each feature for each data point. A global measure refers to a single ranking of all features for the model. Local feature importance becomes relevant in certain cases as well, like, loan application where each data point is an individual person to ensure fairness and equity. I can also think of a hybrid example, like, credit card fraud detection where each person has multiple transactions. While each person will have a different feature importance ranking, there needs to be a global measure for all transactions to detect outliers in the transactions. I am writing this article from a financial perspective in mind and for that global feature importance is more relevant. You can get the global measure by aggregating the local feature importances for each data point. Note:- This is just an example and comparing the player stats may not be the owner’s job but I like Mark Cuban on Shark Tank and, hence, the example. This method calculates something called Shapley values and based on coalition game theory. It was first introduced in 2017 by Lundberg, Scott M. and Su-In Lee [1]. The feature values of a data instance act as players in a coalition. Shapley values tell us how to fairly distribute the “payout” (= the prediction) among the features. A “player” can be an individual feature or a group of features. This value is the average marginal contribution of a feature value across all the possible combinations of features. Let’s extend the previous example and look at the number of points the team scored in every match for a season. We want to know how much Player A contributes to the points the team scores in a match. We will, hence, calculate the contribution of the feature Player A when it is added to a coalition of Player B and Player C. Note:- For this experiment, we need to have all the trials already done with and without each player. I am assuming that in a season there are matches where we can get the relevant data because there must be at least one match where each player was not picked while the other two were. Secondly, this is just an example and the metric could be anything from point difference to tournament rankings. I have just taken the total points for the ease of explanation. Step 1: Combination of Player B and Player C without Player A For this case, we can take an average of the points scored in all matches where players B and C were playing and Player A wasn’t. We can also just sample one random example but I think the average/median is a better measure. Let’s say the average was equal to 65 points. Step 2: Combination of Player B, Player A and Player C In this step, we will take an average of all those matches where Players A, B and C were playing and let’s say that value is equal to 85 points. Hence, the contribution of A is 85–65 = 20 points. Intuitive enough, right? If you took one random sample then you should perform this experiment multiple times and average the difference. The Shapley value is the average of all the marginal contributions to all possible coalitions. The computation time increases exponentially with the number of features. One solution to keep the computation time manageable is to compute contributions for only a few samples of the possible coalitions. [2] You can look at this notebook for a more detailed explanation. Enough theory! Let’s get our hands dirty with some code. Start by importing the necessary libraries. import pandas as pdimport numpy as npimport shapfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_errorfrom sklearn.linear_model import LinearRegressionfrom sklearn.tree import DecisionTreeRegressorfrom sklearn.ensemble import RandomForestRegressorfrom xgboost.sklearn import XGBRegressorfrom sklearn.preprocessing import OneHotEncoder, LabelEncoderfrom sklearn import treeimport matplotlib.pyplot as plt%matplotlib inlineimport warningswarnings.filterwarnings('ignore') Read the data and preprocess it. I am working on the House Prices Dataset but you can use this method for any dataset. I am not spending a lot of time on the preprocessing and imputation but it is highly recommended that you do. # Read the data data = pd.read_csv(‘data.csv’)# Remove features with high null values data.drop([‘PoolQC’, ‘MiscFeature’, ‘Fence’, ‘FireplaceQu’, ‘LotFrontage’], inplace=True, axis=1)# Drop null values data.dropna(inplace=True)# Prepare X and Y X = pd.get_dummies(data)X.drop([‘SalePrice’], inplace=True, axis=1)y = data[‘SalePrice’] Fit the model The next step is fitting the model on the dataset. model = XGBRegressor(n_estimators=1000, max_depth=10, learning_rate=0.001)# Fit the Modelmodel.fit(X, y) For this section, I will be using the shap library. This is a very powerful library and you should check out their different plots. Start by loading the JS visualisation code to the library. # load JS visualization code to notebookshap.initjs() Explain the model’s predictions using shap. Collect the explainer and the shap_values. explainer = shap.TreeExplainer(model)shap_values = explainer.shap_values(X) Force Plot i = 4shap.force_plot(explainer.expected_value, shap_values[i], features=X.iloc[i], feature_names=X.columns) The above explanation shows features each contributing to push the model output from the base value (the average model output over the training dataset we passed) to the model output. Features pushing the prediction higher are shown in red, those pushing the prediction lower are in blue. Note that this plot can only be made for one observation. For this example, I have taken the 4th observation. Summary Plot To get an overview of which features are most important for a model we can plot the SHAP values of every feature for every sample. The plot below sorts features by the sum of SHAP value magnitudes over all samples, and uses SHAP values to show the distribution of the impacts each feature has on the model output. The color represents the feature value (red high, blue low). shap.summary_plot(shap_values, features=X, feature_names=X.columns) Summary Bar Plot We can also just take the mean absolute value of the SHAP values for each feature to get a standard bar plot (produces stacked bars for multi-class outputs): shap.summary_plot(shap_values, features=X, feature_names=X.columns, plot_type=’bar’) These plots tell us which features are the most important for a model and hence, we can make our machine learning models more interpretable and explanatory. This is a very important step in your data science journey. I hope you learned something from this article. Looking forward to hearing your comments. Lundberg, Scott M., and Su-In Lee. “A unified approach to interpreting model predictions.” Advances in Neural Information Processing Systems. 2017.Molnar, Christoph. “Interpretable machine learning. A Guide for Making Black Box Models Explainable”, 2019. https://christophm.github.io/interpretable-ml-book/.Shapley, Lloyd S. “A value for n-person games.” Contributions to the Theory of Games 2.28 (1953): 307–317. Lundberg, Scott M., and Su-In Lee. “A unified approach to interpreting model predictions.” Advances in Neural Information Processing Systems. 2017. Molnar, Christoph. “Interpretable machine learning. A Guide for Making Black Box Models Explainable”, 2019. https://christophm.github.io/interpretable-ml-book/. Shapley, Lloyd S. “A value for n-person games.” Contributions to the Theory of Games 2.28 (1953): 307–317.
[ { "code": null, "e": 261, "s": 171, "text": "If you’re stuck behind a paywall, click here to get my friend link and view this article." }, { "code": null, "e": 870, "s": 261, "text": "Machine learning interpretability is a topic of growing importance in this field. Interpret means to explain or to present in understandable terms. In the context of ML systems, interpretability is the ability to explain or to present in understandable terms to a human[Finale Doshi-Velez]. When investments are at stake, institutions prefer models which are explainable over models which might be giving relatively better accuracy. Actually, a better way to say this would be that when you’re dealing with real-world problems, machine learning interpretability becomes a part of the metric for a good model." }, { "code": null, "e": 1007, "s": 870, "text": "Don’t be the person who treats machine learning and deep learning as black boxes and thinks that stacking layers will increase accuracy." }, { "code": null, "e": 2075, "s": 1007, "text": "It’s often the case that in business case applications, companies may choose to use a simple linear model as opposed to a complex non-linear model for the sake of interpretability. When you build a model, you’ll need to be able to understand how it's making the predictions. This helps you figure out when the model will work well and when it won’t work well (and that is where it will need human intervention). Often, you might have to explain your model to your clients and investors, especially when you’re managing their money using that model. It doesn’t just stop with managing investments but goes much beyond that — when you are using AI in healthcare, security, education etc. Basically anywhere outside of your jupyter notebook, the model interpretability becomes an important factor. In this article, I will discuss one such aspect of machine learning interpretability — feature importance. However, within that, I will be discussing a more novel approach called Shapley Additives. I have given a theoretical, mathematical and code explanation of the same." }, { "code": null, "e": 2183, "s": 2075, "text": "Here are the different parts of this article. Feel free to skip ahead to the part which you need to access." }, { "code": null, "e": 2272, "s": 2183, "text": "BackgroundTheoretical ExplanationMathematical ExpressionCode ImplementationVisualisation" }, { "code": null, "e": 2283, "s": 2272, "text": "Background" }, { "code": null, "e": 2307, "s": 2283, "text": "Theoretical Explanation" }, { "code": null, "e": 2331, "s": 2307, "text": "Mathematical Expression" }, { "code": null, "e": 2351, "s": 2331, "text": "Code Implementation" }, { "code": null, "e": 2365, "s": 2351, "text": "Visualisation" }, { "code": null, "e": 2939, "s": 2365, "text": "There are many different ways of increasing your model understanding and feature importance is one of them. Feature importance helps you estimate how much each feature of your data contributed to the model’s prediction. After performing feature importance tests, you can figure out which features are making the most impact on your model’s decision making. You can act on this by removing the features which have a low impact on the model’s predictions and focussing on making improvements to the more significant features. This can improve model performance significantly." }, { "code": null, "e": 3848, "s": 2939, "text": "There are many ways to calculate feature importance. Some of the basic methods which use statmodels and scikit-learn have been discussed in the article here. However, a lot of people have written about conventional methods, hence, I want to discuss a new approach called Shapely Additive Explanations (ShAP). This method is considered somewhat better than the traditional sckit-learn methods because many of these methods can be inconsistent, which means that the features that are most important may not always be given the highest feature importance score. One example is that in the tree-based models which might give two equally important features different scores based on what level of splitting was done using the features. The features which split the model first might be given higher importance. This is the motivation for using the latest feature attribution method, Shapley Additive Explanations." }, { "code": null, "e": 4776, "s": 3848, "text": "Let’s start with an example to get some intuition behind this method. Let’s say you’re Mark Cuban and you own a basketball team, let’s say, Dallas Mavericks and you have 3 players —Dirk Nowitzki (A), Michael Finley (B), Jason Kidd (C). You want to determine how much each player contributes to the final score of the team and obviously this does not mean that we just calculate the number of baskets each of them scored because that might work here but won’t work from a machine learning perspective. We want to be able to quantify how much impact their presence has on their team’s performance that extends beyond just calculating the number of baskets each player might have scored. The second reason is that not all of them might be playing in the same position. One of the players might play at an offensive position and the other might play at a defensive position and we want to be able to take that into account as well." }, { "code": null, "e": 4964, "s": 4776, "text": "One approach is that you calculate the team’s performance with and without Player A. The impact of player A can be the difference between the team’s performance with and without player A." }, { "code": null, "e": 5031, "s": 4964, "text": "Impact of A = Team Performance with A - Team performance without A" }, { "code": null, "e": 6483, "s": 5031, "text": "This can be extended to each of the players and we can calculate their importance individually. This is the main intuition behind Shapely Additive Explanations. We estimate how important a model is by seeing how well the model performs with and without that feature for every combination of features. It is important to note that Shapley Additive Explanations calculates the local feature importance for every observation which is different from the method used in scikit-learn which computes the global feature importance. You can understand that the importance of a feature may not be uniform across all data points. So, local feature importance calculates the importance of each feature for each data point. A global measure refers to a single ranking of all features for the model. Local feature importance becomes relevant in certain cases as well, like, loan application where each data point is an individual person to ensure fairness and equity. I can also think of a hybrid example, like, credit card fraud detection where each person has multiple transactions. While each person will have a different feature importance ranking, there needs to be a global measure for all transactions to detect outliers in the transactions. I am writing this article from a financial perspective in mind and for that global feature importance is more relevant. You can get the global measure by aggregating the local feature importances for each data point." }, { "code": null, "e": 6633, "s": 6483, "text": "Note:- This is just an example and comparing the player stats may not be the owner’s job but I like Mark Cuban on Shark Tank and, hence, the example." }, { "code": null, "e": 7030, "s": 6633, "text": "This method calculates something called Shapley values and based on coalition game theory. It was first introduced in 2017 by Lundberg, Scott M. and Su-In Lee [1]. The feature values of a data instance act as players in a coalition. Shapley values tell us how to fairly distribute the “payout” (= the prediction) among the features. A “player” can be an individual feature or a group of features." }, { "code": null, "e": 7472, "s": 7030, "text": "This value is the average marginal contribution of a feature value across all the possible combinations of features. Let’s extend the previous example and look at the number of points the team scored in every match for a season. We want to know how much Player A contributes to the points the team scores in a match. We will, hence, calculate the contribution of the feature Player A when it is added to a coalition of Player B and Player C." }, { "code": null, "e": 7935, "s": 7472, "text": "Note:- For this experiment, we need to have all the trials already done with and without each player. I am assuming that in a season there are matches where we can get the relevant data because there must be at least one match where each player was not picked while the other two were. Secondly, this is just an example and the metric could be anything from point difference to tournament rankings. I have just taken the total points for the ease of explanation." }, { "code": null, "e": 7997, "s": 7935, "text": "Step 1: Combination of Player B and Player C without Player A" }, { "code": null, "e": 8268, "s": 7997, "text": "For this case, we can take an average of the points scored in all matches where players B and C were playing and Player A wasn’t. We can also just sample one random example but I think the average/median is a better measure. Let’s say the average was equal to 65 points." }, { "code": null, "e": 8323, "s": 8268, "text": "Step 2: Combination of Player B, Player A and Player C" }, { "code": null, "e": 8468, "s": 8323, "text": "In this step, we will take an average of all those matches where Players A, B and C were playing and let’s say that value is equal to 85 points." }, { "code": null, "e": 8657, "s": 8468, "text": "Hence, the contribution of A is 85–65 = 20 points. Intuitive enough, right? If you took one random sample then you should perform this experiment multiple times and average the difference." }, { "code": null, "e": 8962, "s": 8657, "text": "The Shapley value is the average of all the marginal contributions to all possible coalitions. The computation time increases exponentially with the number of features. One solution to keep the computation time manageable is to compute contributions for only a few samples of the possible coalitions. [2]" }, { "code": null, "e": 9082, "s": 8962, "text": "You can look at this notebook for a more detailed explanation. Enough theory! Let’s get our hands dirty with some code." }, { "code": null, "e": 9126, "s": 9082, "text": "Start by importing the necessary libraries." }, { "code": null, "e": 9640, "s": 9126, "text": "import pandas as pdimport numpy as npimport shapfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_errorfrom sklearn.linear_model import LinearRegressionfrom sklearn.tree import DecisionTreeRegressorfrom sklearn.ensemble import RandomForestRegressorfrom xgboost.sklearn import XGBRegressorfrom sklearn.preprocessing import OneHotEncoder, LabelEncoderfrom sklearn import treeimport matplotlib.pyplot as plt%matplotlib inlineimport warningswarnings.filterwarnings('ignore')" }, { "code": null, "e": 9673, "s": 9640, "text": "Read the data and preprocess it." }, { "code": null, "e": 9869, "s": 9673, "text": "I am working on the House Prices Dataset but you can use this method for any dataset. I am not spending a lot of time on the preprocessing and imputation but it is highly recommended that you do." }, { "code": null, "e": 10203, "s": 9869, "text": "# Read the data data = pd.read_csv(‘data.csv’)# Remove features with high null values data.drop([‘PoolQC’, ‘MiscFeature’, ‘Fence’, ‘FireplaceQu’, ‘LotFrontage’], inplace=True, axis=1)# Drop null values data.dropna(inplace=True)# Prepare X and Y X = pd.get_dummies(data)X.drop([‘SalePrice’], inplace=True, axis=1)y = data[‘SalePrice’]" }, { "code": null, "e": 10217, "s": 10203, "text": "Fit the model" }, { "code": null, "e": 10268, "s": 10217, "text": "The next step is fitting the model on the dataset." }, { "code": null, "e": 10373, "s": 10268, "text": "model = XGBRegressor(n_estimators=1000, max_depth=10, learning_rate=0.001)# Fit the Modelmodel.fit(X, y)" }, { "code": null, "e": 10564, "s": 10373, "text": "For this section, I will be using the shap library. This is a very powerful library and you should check out their different plots. Start by loading the JS visualisation code to the library." }, { "code": null, "e": 10618, "s": 10564, "text": "# load JS visualization code to notebookshap.initjs()" }, { "code": null, "e": 10705, "s": 10618, "text": "Explain the model’s predictions using shap. Collect the explainer and the shap_values." }, { "code": null, "e": 10781, "s": 10705, "text": "explainer = shap.TreeExplainer(model)shap_values = explainer.shap_values(X)" }, { "code": null, "e": 10792, "s": 10781, "text": "Force Plot" }, { "code": null, "e": 10900, "s": 10792, "text": "i = 4shap.force_plot(explainer.expected_value, shap_values[i], features=X.iloc[i], feature_names=X.columns)" }, { "code": null, "e": 11299, "s": 10900, "text": "The above explanation shows features each contributing to push the model output from the base value (the average model output over the training dataset we passed) to the model output. Features pushing the prediction higher are shown in red, those pushing the prediction lower are in blue. Note that this plot can only be made for one observation. For this example, I have taken the 4th observation." }, { "code": null, "e": 11312, "s": 11299, "text": "Summary Plot" }, { "code": null, "e": 11687, "s": 11312, "text": "To get an overview of which features are most important for a model we can plot the SHAP values of every feature for every sample. The plot below sorts features by the sum of SHAP value magnitudes over all samples, and uses SHAP values to show the distribution of the impacts each feature has on the model output. The color represents the feature value (red high, blue low)." }, { "code": null, "e": 11755, "s": 11687, "text": "shap.summary_plot(shap_values, features=X, feature_names=X.columns)" }, { "code": null, "e": 11772, "s": 11755, "text": "Summary Bar Plot" }, { "code": null, "e": 11930, "s": 11772, "text": "We can also just take the mean absolute value of the SHAP values for each feature to get a standard bar plot (produces stacked bars for multi-class outputs):" }, { "code": null, "e": 12015, "s": 11930, "text": "shap.summary_plot(shap_values, features=X, feature_names=X.columns, plot_type=’bar’)" }, { "code": null, "e": 12232, "s": 12015, "text": "These plots tell us which features are the most important for a model and hence, we can make our machine learning models more interpretable and explanatory. This is a very important step in your data science journey." }, { "code": null, "e": 12322, "s": 12232, "text": "I hope you learned something from this article. Looking forward to hearing your comments." }, { "code": null, "e": 12736, "s": 12322, "text": "Lundberg, Scott M., and Su-In Lee. “A unified approach to interpreting model predictions.” Advances in Neural Information Processing Systems. 2017.Molnar, Christoph. “Interpretable machine learning. A Guide for Making Black Box Models Explainable”, 2019. https://christophm.github.io/interpretable-ml-book/.Shapley, Lloyd S. “A value for n-person games.” Contributions to the Theory of Games 2.28 (1953): 307–317." }, { "code": null, "e": 12884, "s": 12736, "text": "Lundberg, Scott M., and Su-In Lee. “A unified approach to interpreting model predictions.” Advances in Neural Information Processing Systems. 2017." }, { "code": null, "e": 13045, "s": 12884, "text": "Molnar, Christoph. “Interpretable machine learning. A Guide for Making Black Box Models Explainable”, 2019. https://christophm.github.io/interpretable-ml-book/." } ]
DocumentDB - SQL Server
The JSON files are a natural fit, and they may just be able to be imported as is to DocumentDB. However, importing from a relational database like SQL Server is going to require some sort of transformation, meaning we need to somehow bridge the gap between the normalized data in SQL Server and its denormalized representation in DocumentDB. Let’s take a look at a simple example in which we will see how the Migration Tool can import from a SQL Server database. In this example, we will import data from the AdventureWorks 2014 database. AdventureWorks is a popular sample database that you can download from CodePlex using the following steps. Step 1 − Go to https://www.codeplex.com/ Step 2 − Search for the AdventureWorks 2014 in the search box. Step 3 − Pick the recommended release for the sample databases. The easiest download to choose is the recommended one, which is the Full Database Backup. Step 4 − Click and save the zip file to any folder and extract the zip file which contains Database Backup file. Step 5 − Open SQL Server Management Studio, connect to my local SQL Server instance and restore the backup. Step 6 − Right-click Databases → Restore Database. Click ‘browse’ button. You will see the following window. Step 7 − Click the ‘Add’ button. Step 8 − Browse the database backup file and click OK. Then OK one more time, and off goes the restore. We've got a successful restore. Well, this is a large database, and there sure are a lot of tables, so let’s take a look at the Views instead. This looks a bit more manageable, and most of these views work by joining multiple related tables together, so let’s have a look at this one called vStoreWithAddresses, which is defined in the Sales schema. We're selecting from the view, which joins all the tables, and we're filtering on AddressType, which gives us only the Main Offices. SELECT CAST(BusinessEntityID AS varchar) AS [id], Name AS [name], AddressType AS [address.addressType], AddressLine1 AS [address.addressLine1], City AS [address.location.city], StateProvinceName AS [address.location.stateProvinceName], PostalCode AS [address.postalCode], CountryRegionName AS [address.countryRegionName] FROM Sales.vStoreWithAddresses WHERE AddressType='Main Office' When the above query is executed, you will receive the following output. Let's launch the GUI version Migration tool. Step 1 − On the Welcome page, click ‘Next’ for the Source Information page. Step 2 − Select the SQL from dropdown menu and specify the database connection string. Step 3 − Click ‘Verify’ button. If you specify the correct connection string, then it will display the successful message. Step 4 − Enter the query which you want to import. Step 5 − Click ‘Next’. Step 6 − Specify the Connection String from your DocumentDB account which can be found from the Azure Portal. Step 7 − Specify the Primary Connection String and don’t forget to add the database name at the end of connection string. Step 8 − Specify the Collections to which you want to add the JSON files. Step 9 − Click on the Advanced Options and scroll down the page. Step 10 − Specify the indexing policy, let’s say Range indexing policy. Step 11 − Click ‘Next’ to Continue. Step 12 − Click ‘Next’ again to continue. Step 13 − Here you can see the summary, now click the ‘Import’ button. It will start importing data. Once it is completed, you can see on Azure Portal. Print Add Notes Bookmark this page
[ { "code": null, "e": 2622, "s": 2280, "text": "The JSON files are a natural fit, and they may just be able to be imported as is to DocumentDB. However, importing from a relational database like SQL Server is going to require some sort of transformation, meaning we need to somehow bridge the gap between the normalized data in SQL Server and its denormalized representation in DocumentDB." }, { "code": null, "e": 2926, "s": 2622, "text": "Let’s take a look at a simple example in which we will see how the Migration Tool can import from a SQL Server database. In this example, we will import data from the AdventureWorks 2014 database. AdventureWorks is a popular sample database that you can download from CodePlex using the following steps." }, { "code": null, "e": 2967, "s": 2926, "text": "Step 1 − Go to https://www.codeplex.com/" }, { "code": null, "e": 3030, "s": 2967, "text": "Step 2 − Search for the AdventureWorks 2014 in the search box." }, { "code": null, "e": 3094, "s": 3030, "text": "Step 3 − Pick the recommended release for the sample databases." }, { "code": null, "e": 3184, "s": 3094, "text": "The easiest download to choose is the recommended one, which is the Full Database Backup." }, { "code": null, "e": 3297, "s": 3184, "text": "Step 4 − Click and save the zip file to any folder and extract the zip file which contains Database Backup file." }, { "code": null, "e": 3405, "s": 3297, "text": "Step 5 − Open SQL Server Management Studio, connect to my local SQL Server instance and restore the backup." }, { "code": null, "e": 3479, "s": 3405, "text": "Step 6 − Right-click Databases → Restore Database. Click ‘browse’ button." }, { "code": null, "e": 3514, "s": 3479, "text": "You will see the following window." }, { "code": null, "e": 3547, "s": 3514, "text": "Step 7 − Click the ‘Add’ button." }, { "code": null, "e": 3651, "s": 3547, "text": "Step 8 − Browse the database backup file and click OK. Then OK one more time, and off goes the restore." }, { "code": null, "e": 3683, "s": 3651, "text": "We've got a successful restore." }, { "code": null, "e": 3794, "s": 3683, "text": "Well, this is a large database, and there sure are a lot of tables, so let’s take a look at the Views instead." }, { "code": null, "e": 4001, "s": 3794, "text": "This looks a bit more manageable, and most of these views work by joining multiple related tables together, so let’s have a look at this one called vStoreWithAddresses, which is defined in the Sales schema." }, { "code": null, "e": 4134, "s": 4001, "text": "We're selecting from the view, which joins all the tables, and we're filtering on AddressType, which gives us only the Main Offices." }, { "code": null, "e": 4561, "s": 4134, "text": "SELECT \n CAST(BusinessEntityID AS varchar) AS [id], \n Name AS [name], \n AddressType AS [address.addressType], \n AddressLine1 AS [address.addressLine1], \n City AS [address.location.city], \n StateProvinceName AS [address.location.stateProvinceName], \n PostalCode AS [address.postalCode], \n CountryRegionName AS [address.countryRegionName] \nFROM \n Sales.vStoreWithAddresses \nWHERE \n AddressType='Main Office' " }, { "code": null, "e": 4634, "s": 4561, "text": "When the above query is executed, you will receive the following output." }, { "code": null, "e": 4679, "s": 4634, "text": "Let's launch the GUI version Migration tool." }, { "code": null, "e": 4755, "s": 4679, "text": "Step 1 − On the Welcome page, click ‘Next’ for the Source Information page." }, { "code": null, "e": 4842, "s": 4755, "text": "Step 2 − Select the SQL from dropdown menu and specify the database connection string." }, { "code": null, "e": 4874, "s": 4842, "text": "Step 3 − Click ‘Verify’ button." }, { "code": null, "e": 4965, "s": 4874, "text": "If you specify the correct connection string, then it will display the successful message." }, { "code": null, "e": 5016, "s": 4965, "text": "Step 4 − Enter the query which you want to import." }, { "code": null, "e": 5039, "s": 5016, "text": "Step 5 − Click ‘Next’." }, { "code": null, "e": 5149, "s": 5039, "text": "Step 6 − Specify the Connection String from your DocumentDB account which can be found from the Azure Portal." }, { "code": null, "e": 5271, "s": 5149, "text": "Step 7 − Specify the Primary Connection String and don’t forget to add the database name at the end of connection string." }, { "code": null, "e": 5345, "s": 5271, "text": "Step 8 − Specify the Collections to which you want to add the JSON files." }, { "code": null, "e": 5410, "s": 5345, "text": "Step 9 − Click on the Advanced Options and scroll down the page." }, { "code": null, "e": 5483, "s": 5410, "text": "Step 10 − Specify the indexing policy, let’s say Range indexing policy. " }, { "code": null, "e": 5519, "s": 5483, "text": "Step 11 − Click ‘Next’ to Continue." }, { "code": null, "e": 5561, "s": 5519, "text": "Step 12 − Click ‘Next’ again to continue." }, { "code": null, "e": 5632, "s": 5561, "text": "Step 13 − Here you can see the summary, now click the ‘Import’ button." }, { "code": null, "e": 5713, "s": 5632, "text": "It will start importing data. Once it is completed, you can see on Azure Portal." }, { "code": null, "e": 5720, "s": 5713, "text": " Print" }, { "code": null, "e": 5731, "s": 5720, "text": " Add Notes" } ]
C# Method Overloading
With method overloading, multiple methods can have the same name with different parameters: int MyMethod(int x) float MyMethod(float x) double MyMethod(double x, double y) Consider the following example, which have two methods that add numbers of different type: static int PlusMethodInt(int x, int y) { return x + y; } static double PlusMethodDouble(double x, double y) { return x + y; } static void Main(string[] args) { int myNum1 = PlusMethodInt(8, 5); double myNum2 = PlusMethodDouble(4.3, 6.26); Console.WriteLine("Int: " + myNum1); Console.WriteLine("Double: " + myNum2); } Try it Yourself » Instead of defining two methods that should do the same thing, it is better to overload one. In the example below, we overload the PlusMethod method to work for both int and double: static int PlusMethod(int x, int y) { return x + y; } static double PlusMethod(double x, double y) { return x + y; } static void Main(string[] args) { int myNum1 = PlusMethod(8, 5); double myNum2 = PlusMethod(4.3, 6.26); Console.WriteLine("Int: " + myNum1); Console.WriteLine("Double: " + myNum2); } Try it Yourself » Note: Multiple methods can have the same name as long as the number and/or type of parameters are different. 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": 92, "s": 0, "text": "With method overloading, multiple methods can have the same name with different\nparameters:" }, { "code": null, "e": 172, "s": 92, "text": "int MyMethod(int x)\nfloat MyMethod(float x)\ndouble MyMethod(double x, double y)" }, { "code": null, "e": 263, "s": 172, "text": "Consider the following example, which have two methods that add numbers of different type:" }, { "code": null, "e": 595, "s": 263, "text": "static int PlusMethodInt(int x, int y)\n{\n return x + y;\n}\n\nstatic double PlusMethodDouble(double x, double y)\n{\n return x + y;\n}\n\nstatic void Main(string[] args)\n{\n int myNum1 = PlusMethodInt(8, 5);\n double myNum2 = PlusMethodDouble(4.3, 6.26);\n Console.WriteLine(\"Int: \" + myNum1);\n Console.WriteLine(\"Double: \" + myNum2);\n}" }, { "code": null, "e": 615, "s": 595, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 709, "s": 615, "text": "Instead of defining two methods that should do the same thing, it is better to overload one. " }, { "code": null, "e": 800, "s": 709, "text": "In the example below, we overload the PlusMethod \nmethod to work for both int \nand double:" }, { "code": null, "e": 1122, "s": 800, "text": "static int PlusMethod(int x, int y)\n{\n return x + y;\n}\n\nstatic double PlusMethod(double x, double y)\n{\n return x + y;\n}\n\nstatic void Main(string[] args)\n{\n int myNum1 = PlusMethod(8, 5);\n double myNum2 = PlusMethod(4.3, 6.26);\n Console.WriteLine(\"Int: \" + myNum1);\n Console.WriteLine(\"Double: \" + myNum2);\n} \n \n \n \n" }, { "code": null, "e": 1142, "s": 1122, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1254, "s": 1142, "text": "Note: Multiple methods can have the same name \n as long as the number and/or type of parameters are different." }, { "code": null, "e": 1287, "s": 1254, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1329, "s": 1287, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1436, "s": 1329, "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": 1455, "s": 1436, "text": "[email protected]" } ]
WPF - Keyboard
There are many types of keyboard inputs such as KeyDown, KeyUp, TextInput, etc. In the following example, some of the keyboard inputs are handled. The following example defines a handler for the Click event and a handler for the KeyDown event. Let’s create a new WPF project with the name WPFKeyboardInput. Let’s create a new WPF project with the name WPFKeyboardInput. Drag a textbox and a button to a stack panel and set the following properties and events as shown in the following XAML file. Drag a textbox and a button to a stack panel and set the following properties and events as shown in the following XAML file. <Window x:Class = "WPFKeyboardInput.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:WPFKeyboardInput" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <StackPanel Orientation = "Horizontal" KeyDown = "OnTextInputKeyDown"> <TextBox Width = "400" Height = "30" Margin = "10"/> <Button Click = "OnTextInputButtonClick" Content = "Open" Margin = "10" Width = "50" Height = "30"/> </StackPanel> </Grid> </Window> Here is the C# code in which different keyboard and click events are handled. using System.Windows; using System.Windows.Input; namespace WPFKeyboardInput { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void OnTextInputKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.O && Keyboard.Modifiers == ModifierKeys.Control) { handle(); e.Handled = true; } } private void OnTextInputButtonClick(object sender, RoutedEventArgs e) { handle(); e.Handled = true; } public void handle() { MessageBox.Show("Do you want to open a file?"); } } } When the above code is compiled and executed, it will produce the following window − If you click the Open button or press CTRL+O keys inside textbox, it will display the same message. 31 Lectures 2.5 hours Anadi Sharma 30 Lectures 2.5 hours Taurius Litvinavicius Print Add Notes Bookmark this page
[ { "code": null, "e": 2264, "s": 2020, "text": "There are many types of keyboard inputs such as KeyDown, KeyUp, TextInput, etc. In the following example, some of the keyboard inputs are handled. The following example defines a handler for the Click event and a handler for the KeyDown event." }, { "code": null, "e": 2327, "s": 2264, "text": "Let’s create a new WPF project with the name WPFKeyboardInput." }, { "code": null, "e": 2390, "s": 2327, "text": "Let’s create a new WPF project with the name WPFKeyboardInput." }, { "code": null, "e": 2516, "s": 2390, "text": "Drag a textbox and a button to a stack panel and set the following properties and events as shown in the following XAML file." }, { "code": null, "e": 2642, "s": 2516, "text": "Drag a textbox and a button to a stack panel and set the following properties and events as shown in the following XAML file." }, { "code": null, "e": 3416, "s": 2642, "text": "<Window x:Class = \"WPFKeyboardInput.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFKeyboardInput\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <StackPanel Orientation = \"Horizontal\" KeyDown = \"OnTextInputKeyDown\"> \n <TextBox Width = \"400\" Height = \"30\" Margin = \"10\"/> \n <Button Click = \"OnTextInputButtonClick\"\n Content = \"Open\" Margin = \"10\" Width = \"50\" Height = \"30\"/> \n </StackPanel> \n </Grid> \n\t\n</Window> " }, { "code": null, "e": 3494, "s": 3416, "text": "Here is the C# code in which different keyboard and click events are handled." }, { "code": null, "e": 4268, "s": 3494, "text": "using System.Windows; \nusing System.Windows.Input; \n\nnamespace WPFKeyboardInput { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window { \n\t\n public MainWindow() { \n InitializeComponent(); \n } \n\t\t\n private void OnTextInputKeyDown(object sender, KeyEventArgs e) {\n\t\t\n if (e.Key == Key.O && Keyboard.Modifiers == ModifierKeys.Control) { \n handle(); \n e.Handled = true; \n } \n\t\t\t\n } \n\t\t\n private void OnTextInputButtonClick(object sender, RoutedEventArgs e) { \n handle(); \n e.Handled = true; \n } \n\t\t\n public void handle() { \n MessageBox.Show(\"Do you want to open a file?\"); \n }\n\t\t\n } \n}" }, { "code": null, "e": 4353, "s": 4268, "text": "When the above code is compiled and executed, it will produce the following window −" }, { "code": null, "e": 4453, "s": 4353, "text": "If you click the Open button or press CTRL+O keys inside textbox, it will display the same message." }, { "code": null, "e": 4488, "s": 4453, "text": "\n 31 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4502, "s": 4488, "text": " Anadi Sharma" }, { "code": null, "e": 4537, "s": 4502, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4560, "s": 4537, "text": " Taurius Litvinavicius" }, { "code": null, "e": 4567, "s": 4560, "text": " Print" }, { "code": null, "e": 4578, "s": 4567, "text": " Add Notes" } ]
C++ Program to Find ith Largest Number from a Given List Using Order-Statistic Algorithm
This is a C++ program to find ith largest number from a given list using Order-Statistic Algorithm. Begin function Insert() to insert nodes into the tree: Arguments: root, d. Body of the function: If tree is completely null then insert new node as root. If d = tmp->data, increase the count of that particular node. If d < tmp->data, move the tmp pointer to the left child. If d > tmp->data, move the tmp pointer to the right child. End Begin function AssignRank() to assign rank to each node of the tree: Arguments: Root. Body of the function: If left child of the root is not null. Then assign rank to the left child of the root. Increase the rank count. If right child of the root is not null. then assign rank to the right child of the root. End Begin function Select() to search Kth smallest element from the data stored in the tree: Arguments: Root, searched element k. Body of the function: If found to be equal, return to main and print the result. Else If it is greater then shift the temporary variable to the right child. Else shift the temporary variable to the left child. End #include<iostream> using namespace std; static int cnt = 0; struct nod //declaration of node { int data; int rank; nod *l; nod *r; }; nod* CreateNod(int d) //creation of new node { nod *newnod = new nod; newnod->data = d; newnod->rank = 0; newnod->l = NULL; newnod->r = NULL; return newnod; } nod* Insert(nod* root, int d) //perform insertion { nod *tmp = CreateNod(d); nod *t = new nod; t = root; if(root == NULL) root = tmp; else { while(t != NULL) { if(t->data < d ) { if(t->r== NULL) { t->r = tmp; break; } t = t->r; } else if(t->data > d) { if(t->l == NULL) { t->l= tmp; break; } t = t->l; } } } return root; } void AssignRank(nod *root) //assign rank to the nodes { if(root->l!= NULL) AssignRank(root->l); root->rank = cnt; cnt++; if(root->r != NULL) AssignRank(root->r); } int Select(nod* root, int k) //select kth largest element { if(root->rank == k) return root->data; else if(root->rank > k) return Select(root->l, k); else return Select(root->r, k); } void display(nod *root) //display the tree. { if(root->l != NULL) display(root->l); cout<<"\n data: "<<root->data<<" rank: "<<root->rank; if(root->r != NULL) display(root->r); } int main() { char c; int n, i, k, a[10]={4,7,6,1,10,3,2,15,16,20}; nod *root = new nod; root = NULL; for(i = 0; i < 10; i++) root = Insert(root, a[i]); //call the function insert() cout<<"Enter the value of k: "; cin>>k; AssignRank(root); //call the function Assignrank() cout<<"\nRank associated to each node:-"; display(root); //call the function display() cout<<"\n\nThe kth Largest element is: "<<Select(root, 10-k); return 0; } Enter the value of k: 7 Rank associated to each node:- data: 1 rank: 0 data: 2 rank: 1 data: 3 rank: 2 data: 4 rank: 3 data: 6 rank: 4 data: 7 rank: 5 data: 10 rank: 6 data: 15 rank: 7 data: 16 rank: 8 data: 20 rank: 9 The kth Largest element is: 4
[ { "code": null, "e": 1162, "s": 1062, "text": "This is a C++ program to find ith largest number from a given list using Order-Statistic Algorithm." }, { "code": null, "e": 2302, "s": 1162, "text": "Begin\n function Insert() to insert nodes into the tree:\n Arguments:\n root, d.\n Body of the function:\n If tree is completely null then insert new node as root.\n If d = tmp->data, increase the count of that particular node.\n If d < tmp->data, move the tmp pointer to the left child.\n If d > tmp->data, move the tmp pointer to the right child.\nEnd\nBegin\n function AssignRank() to assign rank to each node of the tree:\n Arguments:\n Root.\n Body of the function:\n If left child of the root is not null.\n Then assign rank to the left child of the root.\n Increase the rank count.\n If right child of the root is not null.\n then assign rank to the right child of the root.\nEnd\nBegin\n function Select() to search Kth smallest element from the data stored in the tree:\n Arguments:\n Root, searched element k.\n Body of the function:\n If found to be equal, return to main and print the result.\n Else If it is greater then\n shift the temporary variable to the right child.\n Else\n shift the temporary variable to the left child.\nEnd" }, { "code": null, "e": 4232, "s": 2302, "text": "#include<iostream>\nusing namespace std;\nstatic int cnt = 0;\nstruct nod //declaration of node \n{\n int data;\n int rank;\n nod *l;\n nod *r;\n};\nnod* CreateNod(int d) //creation of new node\n{\n nod *newnod = new nod;\n newnod->data = d;\n newnod->rank = 0;\n newnod->l = NULL;\n newnod->r = NULL;\n return newnod;\n}\nnod* Insert(nod* root, int d) //perform insertion\n{\n nod *tmp = CreateNod(d);\n nod *t = new nod;\n t = root;\n if(root == NULL)\n root = tmp;\n else {\n while(t != NULL) {\n if(t->data < d ) {\n if(t->r== NULL) {\n t->r = tmp;\n break;\n }\n t = t->r;\n } else if(t->data > d) {\n if(t->l == NULL) {\n t->l= tmp;\n break;\n }\n t = t->l;\n }\n }\n }\n return root;\n}\nvoid AssignRank(nod *root) //assign rank to the nodes\n{\n if(root->l!= NULL)\n AssignRank(root->l);\n root->rank = cnt;\n cnt++;\n if(root->r != NULL)\n AssignRank(root->r);\n}\nint Select(nod* root, int k) //select kth largest element\n{\n if(root->rank == k)\n return root->data;\n else if(root->rank > k)\n return Select(root->l, k);\n else\n return Select(root->r, k);\n}\nvoid display(nod *root) //display the tree.\n{\n if(root->l != NULL)\n display(root->l);\n cout<<\"\\n data: \"<<root->data<<\" rank: \"<<root->rank;\n if(root->r != NULL)\n display(root->r);\n}\nint main() {\n char c;\n int n, i, k, a[10]={4,7,6,1,10,3,2,15,16,20};\n nod *root = new nod;\n root = NULL;\n for(i = 0; i < 10; i++)\n root = Insert(root, a[i]); //call the function insert()\n cout<<\"Enter the value of k: \";\n cin>>k;\n AssignRank(root); //call the function Assignrank()\n cout<<\"\\nRank associated to each node:-\";\n display(root); //call the function display()\n cout<<\"\\n\\nThe kth Largest element is: \"<<Select(root, 10-k);\n return 0;\n}" }, { "code": null, "e": 4481, "s": 4232, "text": "Enter the value of k: 7\nRank associated to each node:-\ndata: 1 rank: 0\ndata: 2 rank: 1\ndata: 3 rank: 2\ndata: 4 rank: 3\ndata: 6 rank: 4\ndata: 7 rank: 5\ndata: 10 rank: 6\ndata: 15 rank: 7\ndata: 16 rank: 8\ndata: 20 rank: 9\nThe kth Largest element is: 4" } ]
How to Add Space Between Widgets in Flutter? - GeeksforGeeks
14 Aug, 2020 In this article, we’ll learn how to add space between widgets. There are many options available in flutter which you can use to provide space and make UI attractive. If you use Row and Column for arranging widgets, then by default limited options are available for alignment. There are many options available for the spacing of widgets like Padding, Spacer, Fractionally, SizedBox, Expanded, Flexible, etc. Here, we’ll learn about SizedBox, as it is easier to implement, provides more flexibility in alignment, and also easier to understand. A SizedBox is basically an empty box, if no constraints are provided. By default, it can become as big as it’s parent widget allows, but you can set its height and width according to your needs. Syntax: const SizedBox({ Key key, double width, double height, Widget child }) Below is the description of above-mentioned constraints:- Key key : This argument is of type key. A key is basically an identifier for widgets. A unique key can be provided to widgets to identify them.double width: This argument is of type double. You can provide double value as width to be applied to the child.double height: This argument is also of type double. The height that is to be applied to a child, is passed here as a double value.Widget child: The widget which is below this widget in the tree is passed here as a child and the above-mentioned constraints are automatically applied to it. Key key : This argument is of type key. A key is basically an identifier for widgets. A unique key can be provided to widgets to identify them. double width: This argument is of type double. You can provide double value as width to be applied to the child. double height: This argument is also of type double. The height that is to be applied to a child, is passed here as a double value. Widget child: The widget which is below this widget in the tree is passed here as a child and the above-mentioned constraints are automatically applied to it. It is not compulsory to provide a child widget to SizedBox. For instance, if you are having two Card widgets and you want to give space between them, then you can use SizedBox. You can add SizedBox between those cards and pass the required height and width values. Note: If you don’t provide a child widget to SizedBox and height and width are also null, then SizedBox would try to be as big as it’s parent widget allows. On the other hand, if the child widget is provided but height and width are null, then SizedBox would try to match it’s child’s size. Example: With SizedBox Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: Column( children: [ SizedBox( height: 20, ), Card( elevation: 10, child: Padding( padding: const EdgeInsets.all(25), child: Text('GeeksforGeeks', style: TextStyle(color: Colors.green), ), ), ), SizedBox( //Use of SizedBox height: 30, ), Card( elevation: 10, child: Padding( padding: const EdgeInsets.all(25), child: Text('GeeksforGeeks', style: TextStyle(color: Colors.green), ), ), ), ], ), ), ), ); }} Output : Here, in the above example, we have made two cards. By, default we can’t add custom space between them. So, in order to add the required amount of space, we’ve used SizedBox with custom height, which is required. Example: Without SizedBox Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: Column( children: [ // SizedBox( // height: 20, // ), Card( elevation: 10, child: Padding( padding: const EdgeInsets.all(25), child: Text('GeeksforGeeks', style: TextStyle(color: Colors.green), ), ), ), // SizedBox( // height: 30, // ), Card( elevation: 10, child: Padding( padding: const EdgeInsets.all(25), child: Text('GeeksforGeeks', style: TextStyle(color: Colors.green), ), ), ), ], ), ), ), ); }} Output : In the above output, we can see that there is very little space between the two cards. This little space between them is also because of the elevation provided to the cards. You can align them using various alignment options provided by the column, but that wouldn’t be convenient in this particular scenario. So, in such scenarios when we require custom spacing and sizing, we use SizedBox. Flutter 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 - BoxShadow Widget ListView Class in Flutter Flutter - Flexible Widget Operators in Dart Flutter - Stack Widget What is widgets in Flutter? Android Studio Setup for Flutter Development
[ { "code": null, "e": 23942, "s": 23914, "text": "\n14 Aug, 2020" }, { "code": null, "e": 24485, "s": 23942, "text": "In this article, we’ll learn how to add space between widgets. There are many options available in flutter which you can use to provide space and make UI attractive. If you use Row and Column for arranging widgets, then by default limited options are available for alignment. There are many options available for the spacing of widgets like Padding, Spacer, Fractionally, SizedBox, Expanded, Flexible, etc. Here, we’ll learn about SizedBox, as it is easier to implement, provides more flexibility in alignment, and also easier to understand. " }, { "code": null, "e": 24680, "s": 24485, "text": "A SizedBox is basically an empty box, if no constraints are provided. By default, it can become as big as it’s parent widget allows, but you can set its height and width according to your needs." }, { "code": null, "e": 24785, "s": 24680, "text": "Syntax:\nconst SizedBox({\n Key key,\n double width,\n double height,\n Widget child\n })\n" }, { "code": null, "e": 24843, "s": 24785, "text": "Below is the description of above-mentioned constraints:-" }, { "code": null, "e": 25388, "s": 24843, "text": "Key key : This argument is of type key. A key is basically an identifier for widgets. A unique key can be provided to widgets to identify them.double width: This argument is of type double. You can provide double value as width to be applied to the child.double height: This argument is also of type double. The height that is to be applied to a child, is passed here as a double value.Widget child: The widget which is below this widget in the tree is passed here as a child and the above-mentioned constraints are automatically applied to it." }, { "code": null, "e": 25532, "s": 25388, "text": "Key key : This argument is of type key. A key is basically an identifier for widgets. A unique key can be provided to widgets to identify them." }, { "code": null, "e": 25645, "s": 25532, "text": "double width: This argument is of type double. You can provide double value as width to be applied to the child." }, { "code": null, "e": 25777, "s": 25645, "text": "double height: This argument is also of type double. The height that is to be applied to a child, is passed here as a double value." }, { "code": null, "e": 25936, "s": 25777, "text": "Widget child: The widget which is below this widget in the tree is passed here as a child and the above-mentioned constraints are automatically applied to it." }, { "code": null, "e": 26201, "s": 25936, "text": "It is not compulsory to provide a child widget to SizedBox. For instance, if you are having two Card widgets and you want to give space between them, then you can use SizedBox. You can add SizedBox between those cards and pass the required height and width values." }, { "code": null, "e": 26492, "s": 26201, "text": "Note: If you don’t provide a child widget to SizedBox and height and width are also null, then SizedBox would try to be as big as it’s parent widget allows. On the other hand, if the child widget is provided but height and width are null, then SizedBox would try to match it’s child’s size." }, { "code": null, "e": 26515, "s": 26492, "text": "Example: With SizedBox" }, { "code": null, "e": 26520, "s": 26515, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: Column( children: [ SizedBox( height: 20, ), Card( elevation: 10, child: Padding( padding: const EdgeInsets.all(25), child: Text('GeeksforGeeks', style: TextStyle(color: Colors.green), ), ), ), SizedBox( //Use of SizedBox height: 30, ), Card( elevation: 10, child: Padding( padding: const EdgeInsets.all(25), child: Text('GeeksforGeeks', style: TextStyle(color: Colors.green), ), ), ), ], ), ), ), ); }}", "e": 27691, "s": 26520, "text": null }, { "code": null, "e": 27700, "s": 27691, "text": "Output :" }, { "code": null, "e": 27914, "s": 27700, "text": "Here, in the above example, we have made two cards. By, default we can’t add custom space between them. So, in order to add the required amount of space, we’ve used SizedBox with custom height, which is required. " }, { "code": null, "e": 27941, "s": 27914, "text": "Example: Without SizedBox " }, { "code": null, "e": 27946, "s": 27941, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: Column( children: [ // SizedBox( // height: 20, // ), Card( elevation: 10, child: Padding( padding: const EdgeInsets.all(25), child: Text('GeeksforGeeks', style: TextStyle(color: Colors.green), ), ), ), // SizedBox( // height: 30, // ), Card( elevation: 10, child: Padding( padding: const EdgeInsets.all(25), child: Text('GeeksforGeeks', style: TextStyle(color: Colors.green), ), ), ), ], ), ), ), ); }}", "e": 29115, "s": 27946, "text": null }, { "code": null, "e": 29124, "s": 29115, "text": "Output :" }, { "code": null, "e": 29516, "s": 29124, "text": "In the above output, we can see that there is very little space between the two cards. This little space between them is also because of the elevation provided to the cards. You can align them using various alignment options provided by the column, but that wouldn’t be convenient in this particular scenario. So, in such scenarios when we require custom spacing and sizing, we use SizedBox." }, { "code": null, "e": 29524, "s": 29516, "text": "Flutter" }, { "code": null, "e": 29529, "s": 29524, "text": "Dart" }, { "code": null, "e": 29627, "s": 29529, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29659, "s": 29627, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 29698, "s": 29659, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29724, "s": 29698, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 29751, "s": 29724, "text": "Flutter - BoxShadow Widget" }, { "code": null, "e": 29777, "s": 29751, "text": "ListView Class in Flutter" }, { "code": null, "e": 29803, "s": 29777, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 29821, "s": 29803, "text": "Operators in Dart" }, { "code": null, "e": 29844, "s": 29821, "text": "Flutter - Stack Widget" }, { "code": null, "e": 29872, "s": 29844, "text": "What is widgets in Flutter?" } ]
Ruby on Rails - Examples
In this chapter, we will create a simple but operational online library system for holding and managing the books. This application has a basic architecture and will be built using two ActiveRecord models to describe the types of data that is stored − Books, which describes an actual listing. Subject, which is used to group books together. A recommended work flow for creating Rails Application is as follows − Use the rails command to create the basic skeleton of the application. Use the rails command to create the basic skeleton of the application. Create a database on the PostgreSQL server to hold your data. Create a database on the PostgreSQL server to hold your data. Configure the application to know where your database is located and the login credentials for it. Configure the application to know where your database is located and the login credentials for it. Create Rails Active Records (Models), because they are the business objects you'll be working with in your controllers. Create Rails Active Records (Models), because they are the business objects you'll be working with in your controllers. Generate Migrations that simplify the creating and maintaining of database tables and columns. Generate Migrations that simplify the creating and maintaining of database tables and columns. Write Controller Code to put a life in your application. Write Controller Code to put a life in your application. Create Views to present your data through User Interface. Create Views to present your data through User Interface. So, let us start with creating our library application. Rails is both a runtime web application framework and a set of helper scripts that automate many of the things you do when developing a web application. In this step, we will use one such helper script to create the entire directory structure and the initial set of files to start our Library System application. Go into ruby installation directory to create your application. Go into ruby installation directory to create your application. Run the following command to create a skeleton for library application. It will create the directory structure in the current directory. Run the following command to create a skeleton for library application. It will create the directory structure in the current directory. tp> rails new library This will create a subdirectory for the library application containing a complete directory tree of folders and files for an empty Rails application. Check a complete directory structure of the application. Check Rails Directory Structure for more detail. Most of our development work will be creating and editing files in the library/app subdirectories. Here's a quick run down of how to use them − The controllers subdirectory is where Rails looks to find controller classes. A controller handles a web request from the user. The controllers subdirectory is where Rails looks to find controller classes. A controller handles a web request from the user. The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser. The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser. The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple. The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple. The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered. The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered. Rails web application can run under virtually any web server, but the most convenient way to develop a Rails web application is to use the built-in WEBrick web server. Let's start this web server and then browse to our empty library application − This server will be started from the application directory as follows. It runs on port number 3000. tp> cd ruby\library tp\ruby\library\> Rails server It generates the auto code to start the server as shown below − This will start your WEBrick web server. Now open your browser and browse to http://127.0.0.1:3000. If everything is gone fine, then you should see a greeting message from WEBrick, otherwise there is something wrong with your setting. If everything goes well it will generate the output as follows. The next chapter explains how to create databases for your application and what is the configuration required to access these created databases. Further, we will see what Rails Migration is and how it is used to maintain database tables. Print Add Notes Bookmark this page
[ { "code": null, "e": 2218, "s": 2103, "text": "In this chapter, we will create a simple but operational online library system for holding and managing the books." }, { "code": null, "e": 2355, "s": 2218, "text": "This application has a basic architecture and will be built using two ActiveRecord models to describe the types of data that is stored −" }, { "code": null, "e": 2397, "s": 2355, "text": "Books, which describes an actual listing." }, { "code": null, "e": 2446, "s": 2397, "text": "Subject, which is used to group books together." }, { "code": null, "e": 2517, "s": 2446, "text": "A recommended work flow for creating Rails Application is as follows −" }, { "code": null, "e": 2588, "s": 2517, "text": "Use the rails command to create the basic skeleton of the application." }, { "code": null, "e": 2659, "s": 2588, "text": "Use the rails command to create the basic skeleton of the application." }, { "code": null, "e": 2721, "s": 2659, "text": "Create a database on the PostgreSQL server to hold your data." }, { "code": null, "e": 2783, "s": 2721, "text": "Create a database on the PostgreSQL server to hold your data." }, { "code": null, "e": 2882, "s": 2783, "text": "Configure the application to know where your database is located and the login credentials for it." }, { "code": null, "e": 2981, "s": 2882, "text": "Configure the application to know where your database is located and the login credentials for it." }, { "code": null, "e": 3101, "s": 2981, "text": "Create Rails Active Records (Models), because they are the business objects you'll be working with in your controllers." }, { "code": null, "e": 3221, "s": 3101, "text": "Create Rails Active Records (Models), because they are the business objects you'll be working with in your controllers." }, { "code": null, "e": 3316, "s": 3221, "text": "Generate Migrations that simplify the creating and maintaining of database tables and columns." }, { "code": null, "e": 3411, "s": 3316, "text": "Generate Migrations that simplify the creating and maintaining of database tables and columns." }, { "code": null, "e": 3468, "s": 3411, "text": "Write Controller Code to put a life in your application." }, { "code": null, "e": 3525, "s": 3468, "text": "Write Controller Code to put a life in your application." }, { "code": null, "e": 3583, "s": 3525, "text": "Create Views to present your data through User Interface." }, { "code": null, "e": 3641, "s": 3583, "text": "Create Views to present your data through User Interface." }, { "code": null, "e": 3697, "s": 3641, "text": "So, let us start with creating our library application." }, { "code": null, "e": 4010, "s": 3697, "text": "Rails is both a runtime web application framework and a set of helper scripts that automate many of the things you do when developing a web application. In this step, we will use one such helper script to create the entire directory structure and the initial set of files to start our Library System application." }, { "code": null, "e": 4074, "s": 4010, "text": "Go into ruby installation directory to create your application." }, { "code": null, "e": 4138, "s": 4074, "text": "Go into ruby installation directory to create your application." }, { "code": null, "e": 4275, "s": 4138, "text": "Run the following command to create a skeleton for library application. It will create the directory structure in the current directory." }, { "code": null, "e": 4412, "s": 4275, "text": "Run the following command to create a skeleton for library application. It will create the directory structure in the current directory." }, { "code": null, "e": 4435, "s": 4412, "text": "tp> rails new library\n" }, { "code": null, "e": 4691, "s": 4435, "text": "This will create a subdirectory for the library application containing a complete directory tree of folders and files for an empty Rails application. Check a complete directory structure of the application. Check Rails Directory Structure for more detail." }, { "code": null, "e": 4835, "s": 4691, "text": "Most of our development work will be creating and editing files in the library/app subdirectories. Here's a quick run down of how to use them −" }, { "code": null, "e": 4963, "s": 4835, "text": "The controllers subdirectory is where Rails looks to find controller classes. A controller handles a web request from the user." }, { "code": null, "e": 5091, "s": 4963, "text": "The controllers subdirectory is where Rails looks to find controller classes. A controller handles a web request from the user." }, { "code": null, "e": 5236, "s": 5091, "text": "The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser." }, { "code": null, "e": 5381, "s": 5236, "text": "The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser." }, { "code": null, "e": 5625, "s": 5381, "text": "The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple." }, { "code": null, "e": 5869, "s": 5625, "text": "The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple." }, { "code": null, "e": 6064, "s": 5869, "text": "The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered." }, { "code": null, "e": 6259, "s": 6064, "text": "The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered." }, { "code": null, "e": 6506, "s": 6259, "text": "Rails web application can run under virtually any web server, but the most convenient way to develop a Rails web application is to use the built-in WEBrick web server. Let's start this web server and then browse to our empty library application −" }, { "code": null, "e": 6606, "s": 6506, "text": "This server will be started from the application directory as follows. It runs on port number 3000." }, { "code": null, "e": 6659, "s": 6606, "text": "tp> cd ruby\\library \ntp\\ruby\\library\\> Rails server\n" }, { "code": null, "e": 6723, "s": 6659, "text": "It generates the auto code to start the server as shown below −" }, { "code": null, "e": 6764, "s": 6723, "text": "This will start your WEBrick web server." }, { "code": null, "e": 7022, "s": 6764, "text": "Now open your browser and browse to http://127.0.0.1:3000. If everything is gone fine, then you should see a greeting message from WEBrick, otherwise there is something wrong with your setting. If everything goes well it will generate the output as follows." }, { "code": null, "e": 7167, "s": 7022, "text": "The next chapter explains how to create databases for your application and what is the configuration required to access these created databases." }, { "code": null, "e": 7260, "s": 7167, "text": "Further, we will see what Rails Migration is and how it is used to maintain database tables." }, { "code": null, "e": 7267, "s": 7260, "text": " Print" }, { "code": null, "e": 7278, "s": 7267, "text": " Add Notes" } ]
C# | Convert Class - GeeksforGeeks
03 Apr, 2019 Convert class provides different methods to convert a base data type to another base data type. The base types supported by the Convert class are Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime, and String. It also provides methods that support other conversions. This class is defined under System namespace. Characteristics of Convert class: It provides methods that are used to convert every base type into every other base type. It provides methods that are used to convert integer values to the non-decimal string representation, also convert the string represent the non-decimal numbers to integer values. It provides methods that are used to convert any custom object to any base type. It provide a set of methods that supports base64 encoding. An OverFlowException can occur if a narrowing conversion results in a loss of data. Field: DBNull: It is a constant which represents a database column that is absent of data i.e. database null. Example 1: // C# program to illustrate the// use of ToBase64String(Byte[])// methodusing System; class GFG { // Main method static public void Main() { // Creating and initializing // Byte array byte[] B = { 2, 4, 8, 16, 32 }; // Display the elements Console.WriteLine("BArray is :{0}", BitConverter.ToString(B)); Console.WriteLine(); // Convert the given array // into a base 64 string. String str = Convert.ToBase64String(B); // Display the string Console.WriteLine("Base 64 string is :{0}", str); }} Output: BArray is :02-04-08-10-20 Base 64 string is :AgQIECA= Example 2: // C# program to illustrate the// use of ToDecimal(Int16) methodusing System; class GFG { // Main method static public void Main() { // Creating and initializing // an array short[] ele = {1, Int16.MinValue, -00, 106, -32 }; decimal sol; // Display the elements Console.WriteLine("Elements are:"); foreach(short i in ele) { Console.WriteLine(i); } foreach(short num in ele) { // Convert the given Int16 // values into decimal values // using ToDecimal(Int16) method sol = Convert.ToDecimal(num); // Display the elements Console.WriteLine("convert value is: {0}", sol); } }} Output: Elements are: 1 -32768 0 106 -32 convert value is: 1 convert value is: -32768 convert value is: 0 convert value is: 106 convert value is: -32 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.convert?view=netframework-4.7.2 CSharp Convert Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples Difference between Ref and Out keywords in C# Introduction to .NET Framework C# | Delegates C# | String.IndexOf( ) Method | Set - 1 C# | Abstract Classes Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers Different ways to sort an array in descending order in C#
[ { "code": null, "e": 23838, "s": 23810, "text": "\n03 Apr, 2019" }, { "code": null, "e": 24207, "s": 23838, "text": "Convert class provides different methods to convert a base data type to another base data type. The base types supported by the Convert class are Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime, and String. It also provides methods that support other conversions. This class is defined under System namespace." }, { "code": null, "e": 24241, "s": 24207, "text": "Characteristics of Convert class:" }, { "code": null, "e": 24330, "s": 24241, "text": "It provides methods that are used to convert every base type into every other base type." }, { "code": null, "e": 24509, "s": 24330, "text": "It provides methods that are used to convert integer values to the non-decimal string representation, also convert the string represent the non-decimal numbers to integer values." }, { "code": null, "e": 24590, "s": 24509, "text": "It provides methods that are used to convert any custom object to any base type." }, { "code": null, "e": 24649, "s": 24590, "text": "It provide a set of methods that supports base64 encoding." }, { "code": null, "e": 24733, "s": 24649, "text": "An OverFlowException can occur if a narrowing conversion results in a loss of data." }, { "code": null, "e": 24740, "s": 24733, "text": "Field:" }, { "code": null, "e": 24843, "s": 24740, "text": "DBNull: It is a constant which represents a database column that is absent of data i.e. database null." }, { "code": null, "e": 24854, "s": 24843, "text": "Example 1:" }, { "code": "// C# program to illustrate the// use of ToBase64String(Byte[])// methodusing System; class GFG { // Main method static public void Main() { // Creating and initializing // Byte array byte[] B = { 2, 4, 8, 16, 32 }; // Display the elements Console.WriteLine(\"BArray is :{0}\", BitConverter.ToString(B)); Console.WriteLine(); // Convert the given array // into a base 64 string. String str = Convert.ToBase64String(B); // Display the string Console.WriteLine(\"Base 64 string is :{0}\", str); }}", "e": 25465, "s": 24854, "text": null }, { "code": null, "e": 25473, "s": 25465, "text": "Output:" }, { "code": null, "e": 25529, "s": 25473, "text": "BArray is :02-04-08-10-20\n\nBase 64 string is :AgQIECA=\n" }, { "code": null, "e": 25540, "s": 25529, "text": "Example 2:" }, { "code": "// C# program to illustrate the// use of ToDecimal(Int16) methodusing System; class GFG { // Main method static public void Main() { // Creating and initializing // an array short[] ele = {1, Int16.MinValue, -00, 106, -32 }; decimal sol; // Display the elements Console.WriteLine(\"Elements are:\"); foreach(short i in ele) { Console.WriteLine(i); } foreach(short num in ele) { // Convert the given Int16 // values into decimal values // using ToDecimal(Int16) method sol = Convert.ToDecimal(num); // Display the elements Console.WriteLine(\"convert value is: {0}\", sol); } }}", "e": 26325, "s": 25540, "text": null }, { "code": null, "e": 26333, "s": 26325, "text": "Output:" }, { "code": null, "e": 26476, "s": 26333, "text": "Elements are:\n1\n-32768\n0\n106\n-32\nconvert value is: 1\nconvert value is: -32768\nconvert value is: 0\nconvert value is: 106\nconvert value is: -32\n" }, { "code": null, "e": 26487, "s": 26476, "text": "Reference:" }, { "code": null, "e": 26570, "s": 26487, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.convert?view=netframework-4.7.2" }, { "code": null, "e": 26591, "s": 26570, "text": "CSharp Convert Class" }, { "code": null, "e": 26594, "s": 26591, "text": "C#" }, { "code": null, "e": 26692, "s": 26594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26720, "s": 26692, "text": "C# Dictionary with examples" }, { "code": null, "e": 26766, "s": 26720, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 26797, "s": 26766, "text": "Introduction to .NET Framework" }, { "code": null, "e": 26812, "s": 26797, "text": "C# | Delegates" }, { "code": null, "e": 26852, "s": 26812, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 26874, "s": 26852, "text": "C# | Abstract Classes" }, { "code": null, "e": 26897, "s": 26874, "text": "Extension Method in C#" }, { "code": null, "e": 26925, "s": 26897, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26965, "s": 26925, "text": "Top 50 C# Interview Questions & Answers" } ]
Perfect Binary Tree Specific Level Order Traversal - GeeksforGeeks
14 Jan, 2022 Given a Perfect Binary Tree like below: (click on image to get a clear view) Print the level order of nodes in following specific manner: 1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24 i.e. print nodes in level order but nodes should be from left and right side alternatively. Here 1st and 2nd levels are trivial. While 3rd level: 4(left), 7(right), 5(left), 6(right) are printed. While 4th level: 8(left), 15(right), 9(left), 14(right), .. are printed. While 5th level: 16(left), 31(right), 17(left), 30(right), .. are printed. We strongly recommend to minimize your browser and try this yourself first.In standard Level Order Traversal, we enqueue root into a queue 1st, then we dequeue ONE node from queue, process (print) it, enqueue its children into queue. We keep doing this until queue is empty. Approach 1: We can do standard level order traversal here too but instead of printing nodes directly, we have to store nodes in current level in a temporary array or list 1st and then take nodes from alternate ends (left and right) and print nodes. Keep repeating this for all levels. This approach takes more memory than standard traversal. Approach 2: The standard level order traversal idea will slightly change here. Instead of processing ONE node at a time, we will process TWO nodes at a time. And while pushing children into queue, the enqueue order will be: 1st node’s left child, 2nd node’s right child, 1st node’s right child and 2nd node’s left child. C++ Java Python3 C# Javascript /* C++ program for special order traversal */#include <iostream>#include <queue>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; Node *left; Node *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */Node *newNode(int data){ Node *node = new Node; node->data = data; node->right = node->left = NULL; return node;} /* Given a perfect binary tree, print its nodes in specific level order */void printSpecificLevelOrder(Node *root){ if (root == NULL) return; // Let us print root and next level first cout << root->data; // / Since it is perfect Binary Tree, right is not checked if (root->left != NULL) cout << " " << root->left->data << " " << root->right->data; // Do anything more if there are nodes at next level in // given perfect Binary Tree if (root->left->left == NULL) return; // Create a queue and enqueue left and right children of root queue <Node *> q; q.push(root->left); q.push(root->right); // We process two nodes at a time, so we need two variables // to store two front items of queue Node *first = NULL, *second = NULL; // traversal loop while (!q.empty()) { // Pop two items from queue first = q.front(); q.pop(); second = q.front(); q.pop(); // Print children of first and second in reverse order cout << " " << first->left->data << " " << second->right->data; cout << " " << first->right->data << " " << second->left->data; // If first and second have grandchildren, enqueue them // in reverse order if (first->left->left != NULL) { q.push(first->left); q.push(second->right); q.push(first->right); q.push(second->left); } }} /* Driver program to test above functions*/int main(){ //Perfect Binary Tree of Height 4 Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); root->right->left->left = newNode(12); root->right->left->right = newNode(13); root->right->right->left = newNode(14); root->right->right->right = newNode(15); root->left->left->left->left = newNode(16); root->left->left->left->right = newNode(17); root->left->left->right->left = newNode(18); root->left->left->right->right = newNode(19); root->left->right->left->left = newNode(20); root->left->right->left->right = newNode(21); root->left->right->right->left = newNode(22); root->left->right->right->right = newNode(23); root->right->left->left->left = newNode(24); root->right->left->left->right = newNode(25); root->right->left->right->left = newNode(26); root->right->left->right->right = newNode(27); root->right->right->left->left = newNode(28); root->right->right->left->right = newNode(29); root->right->right->right->left = newNode(30); root->right->right->right->right = newNode(31); cout << "Specific Level Order traversal of binary tree is \n"; printSpecificLevelOrder(root); return 0;} // Java program for special level order traversal import java.util.LinkedList;import java.util.Queue; /* Class containing left and right child of current node and key value*/class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* Given a perfect binary tree, print its nodes in specific level order */ void printSpecificLevelOrder(Node node) { if (node == null) return; // Let us print root and next level first System.out.print(node.data); // Since it is perfect Binary Tree, right is not checked if (node.left != null) System.out.print(" " + node.left.data + " " + node.right.data); // Do anything more if there are nodes at next level in // given perfect Binary Tree if (node.left.left == null) return; // Create a queue and enqueue left and right children of root Queue<Node> q = new LinkedList<Node>(); q.add(node.left); q.add(node.right); // We process two nodes at a time, so we need two variables // to store two front items of queue Node first = null, second = null; // traversal loop while (!q.isEmpty()) { // Pop two items from queue first = q.peek(); q.remove(); second = q.peek(); q.remove(); // Print children of first and second in reverse order System.out.print(" " + first.left.data + " " +second.right.data); System.out.print(" " + first.right.data + " " +second.left.data); // If first and second have grandchildren, enqueue them // in reverse order if (first.left.left != null) { q.add(first.left); q.add(second.right); q.add(first.right); q.add(second.left); } } } // Driver program to test for above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left.right = new Node(9); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(11); tree.root.right.left.left = new Node(12); tree.root.right.left.right = new Node(13); tree.root.right.right.left = new Node(14); tree.root.right.right.right = new Node(15); tree.root.left.left.left.left = new Node(16); tree.root.left.left.left.right = new Node(17); tree.root.left.left.right.left = new Node(18); tree.root.left.left.right.right = new Node(19); tree.root.left.right.left.left = new Node(20); tree.root.left.right.left.right = new Node(21); tree.root.left.right.right.left = new Node(22); tree.root.left.right.right.right = new Node(23); tree.root.right.left.left.left = new Node(24); tree.root.right.left.left.right = new Node(25); tree.root.right.left.right.left = new Node(26); tree.root.right.left.right.right = new Node(27); tree.root.right.right.left.left = new Node(28); tree.root.right.right.left.right = new Node(29); tree.root.right.right.right.left = new Node(30); tree.root.right.right.right.right = new Node(31); System.out.println("Specific Level Order traversal of binary" +"tree is "); tree.printSpecificLevelOrder(tree.root); }} // This code has been contributed by Mayank Jaiswal # Python program for special order traversal # A binary tree nodeclass Node: # A constructor for making a new node def __init__(self, key): self.data = key self.left = None self.right = None # Given a perfect binary tree print its node in# specific orderdef printSpecificLevelOrder(root): if root is None: return # Let us print root and next level first print (root.data,end=" ") # Since it is perfect Binary tree, # one of the node is needed to be checked if root.left is not None : print (root.left.data,end=" ") print (root.right.data,end=" ") # Do anything more if there are nodes at next level # in given perfect Binary Tree if root.left.left is None: return # Create a queue and enqueue left and right # children of root q = [] q.append(root.left) q.append(root.right) # We process two nodes at a time, so we need # two variables to store two front items of queue first = None second = None # Traversal loop while(len(q) > 0): # Pop two items from queue first = q.pop(0) second = q.pop(0) # Print children of first and second in reverse order print (first.left.data,end=" ") print (second.right.data,end=" ") print (first.right.data,end=" ") print (second.left.data,end=" ") # If first and second have grandchildren, # enqueue them in reverse order if first.left.left is not None: q.append(first.left) q.append(second.right) q.append(first.right) q.append(second.left) # Driver program to test above function # Perfect Binary Tree of Height 4root = Node(1) root.left= Node(2)root.right = Node(3) root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.right.right = Node(7) root.left.left.left = Node(8)root.left.left.right = Node(9)root.left.right.left = Node(10)root.left.right.right = Node(11)root.right.left.left = Node(12)root.right.left.right = Node(13)root.right.right.left = Node(14)root.right.right.right = Node(15) root.left.left.left.left = Node(16)root.left.left.left.right = Node(17)root.left.left.right.left = Node(18)root.left.left.right.right = Node(19)root.left.right.left.left = Node(20)root.left.right.left.right = Node(21)root.left.right.right.left = Node(22)root.left.right.right.right = Node(23)root.right.left.left.left = Node(24)root.right.left.left.right = Node(25)root.right.left.right.left = Node(26)root.right.left.right.right = Node(27)root.right.right.left.left = Node(28)root.right.right.left.right = Node(29)root.right.right.right.left = Node(30)root.right.right.right.right = Node(31) print ("Specific Level Order traversal of binary tree is")printSpecificLevelOrder(root); # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program for special level// order traversalusing System;using System.Collections.Generic; /* Class containing left and rightchild 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; }} class GFG{public Node root; /* Given a perfect binary tree,print its nodes in specificlevel order */public virtual void printSpecificLevelOrder(Node node){ if (node == null) { return; } // Let us print root and next level first Console.Write(node.data); // Since it is perfect Binary Tree, // right is not checked if (node.left != null) { Console.Write(" " + node.left.data + " " + node.right.data); } // Do anything more if there // are nodes at next level in // given perfect Binary Tree if (node.left.left == null) { return; } // Create a queue and enqueue left // and right children of root LinkedList<Node> q = new LinkedList<Node>(); q.AddLast(node.left); q.AddLast(node.right); // We process two nodes at a time, // so we need two variables to // store two front items of queue Node first = null, second = null; // traversal loop while (q.Count > 0) { // Pop two items from queue first = q.First.Value; q.RemoveFirst(); second = q.First.Value; q.RemoveFirst(); // Print children of first and // second in reverse order Console.Write(" " + first.left.data + " " + second.right.data); Console.Write(" " + first.right.data + " " + second.left.data); // If first and second have grandchildren, // enqueue them in reverse order if (first.left.left != null) { q.AddLast(first.left); q.AddLast(second.right); q.AddLast(first.right); q.AddLast(second.left); } }} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left.right = new Node(9); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(11); tree.root.right.left.left = new Node(12); tree.root.right.left.right = new Node(13); tree.root.right.right.left = new Node(14); tree.root.right.right.right = new Node(15); tree.root.left.left.left.left = new Node(16); tree.root.left.left.left.right = new Node(17); tree.root.left.left.right.left = new Node(18); tree.root.left.left.right.right = new Node(19); tree.root.left.right.left.left = new Node(20); tree.root.left.right.left.right = new Node(21); tree.root.left.right.right.left = new Node(22); tree.root.left.right.right.right = new Node(23); tree.root.right.left.left.left = new Node(24); tree.root.right.left.left.right = new Node(25); tree.root.right.left.right.left = new Node(26); tree.root.right.left.right.right = new Node(27); tree.root.right.right.left.left = new Node(28); tree.root.right.right.left.right = new Node(29); tree.root.right.right.right.left = new Node(30); tree.root.right.right.right.right = new Node(31); Console.WriteLine("Specific Level Order " + "traversal of binary" + "tree is "); tree.printSpecificLevelOrder(tree.root);}} // This code is contributed by Shrikant13 <script> // JavaScript program for special level// order traversal /* Class containing left and rightchild of current node and key value*/class Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} var root = null; /* Given a perfect binary tree,print its nodes in specificlevel order */function printSpecificLevelOrder(node){ if (node == null) { return; } // Let us print root and next level first document.write(node.data); // Since it is perfect Binary Tree, // right is not checked if (node.left != null) { document.write(" " + node.left.data + " " + node.right.data); } // Do anything more if there // are nodes at next level in // given perfect Binary Tree if (node.left.left == null) { return; } // Create a queue and enqueue left // and right children of root var q = []; q.push(node.left); q.push(node.right); // We process two nodes at a time, // so we need two variables to // store two front items of queue var first = null, second = null; // traversal loop while (q.length > 0) { // Pop two items from queue first = q[0]; q.shift(); second = q[0]; q.shift(); // Print children of first and // second in reverse order document.write(" " + first.left.data + " " + second.right.data); document.write(" " + first.right.data + " " + second.left.data); // If first and second have grandchildren, // enqueue them in reverse order if (first.left.left != null) { q.push(first.left); q.push(second.right); q.push(first.right); q.push(second.left); } }} // Driver Coderoot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(7);root.left.left.left = new Node(8);root.left.left.right = new Node(9);root.left.right.left = new Node(10);root.left.right.right = new Node(11);root.right.left.left = new Node(12);root.right.left.right = new Node(13);root.right.right.left = new Node(14);root.right.right.right = new Node(15);root.left.left.left.left = new Node(16);root.left.left.left.right = new Node(17);root.left.left.right.left = new Node(18);root.left.left.right.right = new Node(19);root.left.right.left.left = new Node(20);root.left.right.left.right = new Node(21);root.left.right.right.left = new Node(22);root.left.right.right.right = new Node(23);root.right.left.left.left = new Node(24);root.right.left.left.right = new Node(25);root.right.left.right.left = new Node(26);root.right.left.right.right = new Node(27);root.right.right.left.left = new Node(28);root.right.right.left.right = new Node(29);root.right.right.right.left = new Node(30);root.right.right.right.right = new Node(31);document.write("Specific Level Order " + "traversal of binary" + "tree is <br>");printSpecificLevelOrder(root); </script> Output: Specific Level Order traversal of binary tree is 1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24 YouTubeGeeksforGeeks500K subscribersPerfect Binary Tree Specific Level Order Traversal | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:52•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=cO6RsSmSjio" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Followup Questions: The above code prints specific level order from TOP to BOTTOM. How will you do specific level order traversal from BOTTOM to TOP (Amazon Interview | Set 120 – Round 1 Last Problem)What if tree is not perfect, but complete.What if tree is neither perfect, nor complete. It can be any general binary tree. The above code prints specific level order from TOP to BOTTOM. How will you do specific level order traversal from BOTTOM to TOP (Amazon Interview | Set 120 – Round 1 Last Problem) What if tree is not perfect, but complete. What if tree is neither perfect, nor complete. It can be any general binary tree. This article is contributed by Anurag Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shrikanth13 rutvik_56 arorakashish0911 adnanirshad158 amartyaghoshgfg tree-level-order Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) A program to check if a binary tree is BST or not Decision Tree Construct Tree from given Inorder and Preorder traversals Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 Binary Tree (Array implementation) BFS vs DFS for Binary Tree
[ { "code": null, "e": 24631, "s": 24603, "text": "\n14 Jan, 2022" }, { "code": null, "e": 24708, "s": 24631, "text": "Given a Perfect Binary Tree like below: (click on image to get a clear view)" }, { "code": null, "e": 24771, "s": 24708, "text": "Print the level order of nodes in following specific manner: " }, { "code": null, "e": 24858, "s": 24771, "text": " 1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24" }, { "code": null, "e": 25202, "s": 24858, "text": "i.e. print nodes in level order but nodes should be from left and right side alternatively. Here 1st and 2nd levels are trivial. While 3rd level: 4(left), 7(right), 5(left), 6(right) are printed. While 4th level: 8(left), 15(right), 9(left), 14(right), .. are printed. While 5th level: 16(left), 31(right), 17(left), 30(right), .. are printed." }, { "code": null, "e": 25477, "s": 25202, "text": "We strongly recommend to minimize your browser and try this yourself first.In standard Level Order Traversal, we enqueue root into a queue 1st, then we dequeue ONE node from queue, process (print) it, enqueue its children into queue. We keep doing this until queue is empty." }, { "code": null, "e": 25819, "s": 25477, "text": "Approach 1: We can do standard level order traversal here too but instead of printing nodes directly, we have to store nodes in current level in a temporary array or list 1st and then take nodes from alternate ends (left and right) and print nodes. Keep repeating this for all levels. This approach takes more memory than standard traversal." }, { "code": null, "e": 26140, "s": 25819, "text": "Approach 2: The standard level order traversal idea will slightly change here. Instead of processing ONE node at a time, we will process TWO nodes at a time. And while pushing children into queue, the enqueue order will be: 1st node’s left child, 2nd node’s right child, 1st node’s right child and 2nd node’s left child." }, { "code": null, "e": 26144, "s": 26140, "text": "C++" }, { "code": null, "e": 26149, "s": 26144, "text": "Java" }, { "code": null, "e": 26157, "s": 26149, "text": "Python3" }, { "code": null, "e": 26160, "s": 26157, "text": "C#" }, { "code": null, "e": 26171, "s": 26160, "text": "Javascript" }, { "code": "/* C++ program for special order traversal */#include <iostream>#include <queue>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; Node *left; Node *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */Node *newNode(int data){ Node *node = new Node; node->data = data; node->right = node->left = NULL; return node;} /* Given a perfect binary tree, print its nodes in specific level order */void printSpecificLevelOrder(Node *root){ if (root == NULL) return; // Let us print root and next level first cout << root->data; // / Since it is perfect Binary Tree, right is not checked if (root->left != NULL) cout << \" \" << root->left->data << \" \" << root->right->data; // Do anything more if there are nodes at next level in // given perfect Binary Tree if (root->left->left == NULL) return; // Create a queue and enqueue left and right children of root queue <Node *> q; q.push(root->left); q.push(root->right); // We process two nodes at a time, so we need two variables // to store two front items of queue Node *first = NULL, *second = NULL; // traversal loop while (!q.empty()) { // Pop two items from queue first = q.front(); q.pop(); second = q.front(); q.pop(); // Print children of first and second in reverse order cout << \" \" << first->left->data << \" \" << second->right->data; cout << \" \" << first->right->data << \" \" << second->left->data; // If first and second have grandchildren, enqueue them // in reverse order if (first->left->left != NULL) { q.push(first->left); q.push(second->right); q.push(first->right); q.push(second->left); } }} /* Driver program to test above functions*/int main(){ //Perfect Binary Tree of Height 4 Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); root->right->left->left = newNode(12); root->right->left->right = newNode(13); root->right->right->left = newNode(14); root->right->right->right = newNode(15); root->left->left->left->left = newNode(16); root->left->left->left->right = newNode(17); root->left->left->right->left = newNode(18); root->left->left->right->right = newNode(19); root->left->right->left->left = newNode(20); root->left->right->left->right = newNode(21); root->left->right->right->left = newNode(22); root->left->right->right->right = newNode(23); root->right->left->left->left = newNode(24); root->right->left->left->right = newNode(25); root->right->left->right->left = newNode(26); root->right->left->right->right = newNode(27); root->right->right->left->left = newNode(28); root->right->right->left->right = newNode(29); root->right->right->right->left = newNode(30); root->right->right->right->right = newNode(31); cout << \"Specific Level Order traversal of binary tree is \\n\"; printSpecificLevelOrder(root); return 0;}", "e": 29683, "s": 26171, "text": null }, { "code": "// Java program for special level order traversal import java.util.LinkedList;import java.util.Queue; /* Class containing left and right child of current node and key value*/class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* Given a perfect binary tree, print its nodes in specific level order */ void printSpecificLevelOrder(Node node) { if (node == null) return; // Let us print root and next level first System.out.print(node.data); // Since it is perfect Binary Tree, right is not checked if (node.left != null) System.out.print(\" \" + node.left.data + \" \" + node.right.data); // Do anything more if there are nodes at next level in // given perfect Binary Tree if (node.left.left == null) return; // Create a queue and enqueue left and right children of root Queue<Node> q = new LinkedList<Node>(); q.add(node.left); q.add(node.right); // We process two nodes at a time, so we need two variables // to store two front items of queue Node first = null, second = null; // traversal loop while (!q.isEmpty()) { // Pop two items from queue first = q.peek(); q.remove(); second = q.peek(); q.remove(); // Print children of first and second in reverse order System.out.print(\" \" + first.left.data + \" \" +second.right.data); System.out.print(\" \" + first.right.data + \" \" +second.left.data); // If first and second have grandchildren, enqueue them // in reverse order if (first.left.left != null) { q.add(first.left); q.add(second.right); q.add(first.right); q.add(second.left); } } } // Driver program to test for above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left.right = new Node(9); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(11); tree.root.right.left.left = new Node(12); tree.root.right.left.right = new Node(13); tree.root.right.right.left = new Node(14); tree.root.right.right.right = new Node(15); tree.root.left.left.left.left = new Node(16); tree.root.left.left.left.right = new Node(17); tree.root.left.left.right.left = new Node(18); tree.root.left.left.right.right = new Node(19); tree.root.left.right.left.left = new Node(20); tree.root.left.right.left.right = new Node(21); tree.root.left.right.right.left = new Node(22); tree.root.left.right.right.right = new Node(23); tree.root.right.left.left.left = new Node(24); tree.root.right.left.left.right = new Node(25); tree.root.right.left.right.left = new Node(26); tree.root.right.left.right.right = new Node(27); tree.root.right.right.left.left = new Node(28); tree.root.right.right.left.right = new Node(29); tree.root.right.right.right.left = new Node(30); tree.root.right.right.right.right = new Node(31); System.out.println(\"Specific Level Order traversal of binary\" +\"tree is \"); tree.printSpecificLevelOrder(tree.root); }} // This code has been contributed by Mayank Jaiswal", "e": 33642, "s": 29683, "text": null }, { "code": "# Python program for special order traversal # A binary tree nodeclass Node: # A constructor for making a new node def __init__(self, key): self.data = key self.left = None self.right = None # Given a perfect binary tree print its node in# specific orderdef printSpecificLevelOrder(root): if root is None: return # Let us print root and next level first print (root.data,end=\" \") # Since it is perfect Binary tree, # one of the node is needed to be checked if root.left is not None : print (root.left.data,end=\" \") print (root.right.data,end=\" \") # Do anything more if there are nodes at next level # in given perfect Binary Tree if root.left.left is None: return # Create a queue and enqueue left and right # children of root q = [] q.append(root.left) q.append(root.right) # We process two nodes at a time, so we need # two variables to store two front items of queue first = None second = None # Traversal loop while(len(q) > 0): # Pop two items from queue first = q.pop(0) second = q.pop(0) # Print children of first and second in reverse order print (first.left.data,end=\" \") print (second.right.data,end=\" \") print (first.right.data,end=\" \") print (second.left.data,end=\" \") # If first and second have grandchildren, # enqueue them in reverse order if first.left.left is not None: q.append(first.left) q.append(second.right) q.append(first.right) q.append(second.left) # Driver program to test above function # Perfect Binary Tree of Height 4root = Node(1) root.left= Node(2)root.right = Node(3) root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.right.right = Node(7) root.left.left.left = Node(8)root.left.left.right = Node(9)root.left.right.left = Node(10)root.left.right.right = Node(11)root.right.left.left = Node(12)root.right.left.right = Node(13)root.right.right.left = Node(14)root.right.right.right = Node(15) root.left.left.left.left = Node(16)root.left.left.left.right = Node(17)root.left.left.right.left = Node(18)root.left.left.right.right = Node(19)root.left.right.left.left = Node(20)root.left.right.left.right = Node(21)root.left.right.right.left = Node(22)root.left.right.right.right = Node(23)root.right.left.left.left = Node(24)root.right.left.left.right = Node(25)root.right.left.right.left = Node(26)root.right.left.right.right = Node(27)root.right.right.left.left = Node(28)root.right.right.left.right = Node(29)root.right.right.right.left = Node(30)root.right.right.right.right = Node(31) print (\"Specific Level Order traversal of binary tree is\")printSpecificLevelOrder(root); # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 36547, "s": 33642, "text": null }, { "code": "// C# program for special level// order traversalusing System;using System.Collections.Generic; /* Class containing left and rightchild 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; }} class GFG{public Node root; /* Given a perfect binary tree,print its nodes in specificlevel order */public virtual void printSpecificLevelOrder(Node node){ if (node == null) { return; } // Let us print root and next level first Console.Write(node.data); // Since it is perfect Binary Tree, // right is not checked if (node.left != null) { Console.Write(\" \" + node.left.data + \" \" + node.right.data); } // Do anything more if there // are nodes at next level in // given perfect Binary Tree if (node.left.left == null) { return; } // Create a queue and enqueue left // and right children of root LinkedList<Node> q = new LinkedList<Node>(); q.AddLast(node.left); q.AddLast(node.right); // We process two nodes at a time, // so we need two variables to // store two front items of queue Node first = null, second = null; // traversal loop while (q.Count > 0) { // Pop two items from queue first = q.First.Value; q.RemoveFirst(); second = q.First.Value; q.RemoveFirst(); // Print children of first and // second in reverse order Console.Write(\" \" + first.left.data + \" \" + second.right.data); Console.Write(\" \" + first.right.data + \" \" + second.left.data); // If first and second have grandchildren, // enqueue them in reverse order if (first.left.left != null) { q.AddLast(first.left); q.AddLast(second.right); q.AddLast(first.right); q.AddLast(second.left); } }} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left.right = new Node(9); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(11); tree.root.right.left.left = new Node(12); tree.root.right.left.right = new Node(13); tree.root.right.right.left = new Node(14); tree.root.right.right.right = new Node(15); tree.root.left.left.left.left = new Node(16); tree.root.left.left.left.right = new Node(17); tree.root.left.left.right.left = new Node(18); tree.root.left.left.right.right = new Node(19); tree.root.left.right.left.left = new Node(20); tree.root.left.right.left.right = new Node(21); tree.root.left.right.right.left = new Node(22); tree.root.left.right.right.right = new Node(23); tree.root.right.left.left.left = new Node(24); tree.root.right.left.left.right = new Node(25); tree.root.right.left.right.left = new Node(26); tree.root.right.left.right.right = new Node(27); tree.root.right.right.left.left = new Node(28); tree.root.right.right.left.right = new Node(29); tree.root.right.right.right.left = new Node(30); tree.root.right.right.right.right = new Node(31); Console.WriteLine(\"Specific Level Order \" + \"traversal of binary\" + \"tree is \"); tree.printSpecificLevelOrder(tree.root);}} // This code is contributed by Shrikant13", "e": 40254, "s": 36547, "text": null }, { "code": "<script> // JavaScript program for special level// order traversal /* Class containing left and rightchild of current node and key value*/class Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} var root = null; /* Given a perfect binary tree,print its nodes in specificlevel order */function printSpecificLevelOrder(node){ if (node == null) { return; } // Let us print root and next level first document.write(node.data); // Since it is perfect Binary Tree, // right is not checked if (node.left != null) { document.write(\" \" + node.left.data + \" \" + node.right.data); } // Do anything more if there // are nodes at next level in // given perfect Binary Tree if (node.left.left == null) { return; } // Create a queue and enqueue left // and right children of root var q = []; q.push(node.left); q.push(node.right); // We process two nodes at a time, // so we need two variables to // store two front items of queue var first = null, second = null; // traversal loop while (q.length > 0) { // Pop two items from queue first = q[0]; q.shift(); second = q[0]; q.shift(); // Print children of first and // second in reverse order document.write(\" \" + first.left.data + \" \" + second.right.data); document.write(\" \" + first.right.data + \" \" + second.left.data); // If first and second have grandchildren, // enqueue them in reverse order if (first.left.left != null) { q.push(first.left); q.push(second.right); q.push(first.right); q.push(second.left); } }} // Driver Coderoot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(7);root.left.left.left = new Node(8);root.left.left.right = new Node(9);root.left.right.left = new Node(10);root.left.right.right = new Node(11);root.right.left.left = new Node(12);root.right.left.right = new Node(13);root.right.right.left = new Node(14);root.right.right.right = new Node(15);root.left.left.left.left = new Node(16);root.left.left.left.right = new Node(17);root.left.left.right.left = new Node(18);root.left.left.right.right = new Node(19);root.left.right.left.left = new Node(20);root.left.right.left.right = new Node(21);root.left.right.right.left = new Node(22);root.left.right.right.right = new Node(23);root.right.left.left.left = new Node(24);root.right.left.left.right = new Node(25);root.right.left.right.left = new Node(26);root.right.left.right.right = new Node(27);root.right.right.left.left = new Node(28);root.right.right.left.right = new Node(29);root.right.right.right.left = new Node(30);root.right.right.right.right = new Node(31);document.write(\"Specific Level Order \" + \"traversal of binary\" + \"tree is <br>\");printSpecificLevelOrder(root); </script>", "e": 43378, "s": 40254, "text": null }, { "code": null, "e": 43388, "s": 43378, "text": "Output: " }, { "code": null, "e": 43521, "s": 43388, "text": "Specific Level Order traversal of binary tree is\n1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24" }, { "code": null, "e": 44370, "s": 43521, "text": "YouTubeGeeksforGeeks500K subscribersPerfect Binary Tree Specific Level Order Traversal | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:52•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=cO6RsSmSjio\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 44391, "s": 44370, "text": "Followup Questions: " }, { "code": null, "e": 44695, "s": 44391, "text": "The above code prints specific level order from TOP to BOTTOM. How will you do specific level order traversal from BOTTOM to TOP (Amazon Interview | Set 120 – Round 1 Last Problem)What if tree is not perfect, but complete.What if tree is neither perfect, nor complete. It can be any general binary tree." }, { "code": null, "e": 44876, "s": 44695, "text": "The above code prints specific level order from TOP to BOTTOM. How will you do specific level order traversal from BOTTOM to TOP (Amazon Interview | Set 120 – Round 1 Last Problem)" }, { "code": null, "e": 44919, "s": 44876, "text": "What if tree is not perfect, but complete." }, { "code": null, "e": 45001, "s": 44919, "text": "What if tree is neither perfect, nor complete. It can be any general binary tree." }, { "code": null, "e": 45172, "s": 45001, "text": "This article is contributed by Anurag Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 45184, "s": 45172, "text": "shrikanth13" }, { "code": null, "e": 45194, "s": 45184, "text": "rutvik_56" }, { "code": null, "e": 45211, "s": 45194, "text": "arorakashish0911" }, { "code": null, "e": 45226, "s": 45211, "text": "adnanirshad158" }, { "code": null, "e": 45242, "s": 45226, "text": "amartyaghoshgfg" }, { "code": null, "e": 45259, "s": 45242, "text": "tree-level-order" }, { "code": null, "e": 45264, "s": 45259, "text": "Tree" }, { "code": null, "e": 45269, "s": 45264, "text": "Tree" }, { "code": null, "e": 45367, "s": 45269, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45376, "s": 45367, "text": "Comments" }, { "code": null, "e": 45389, "s": 45376, "text": "Old Comments" }, { "code": null, "e": 45432, "s": 45389, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 45465, "s": 45432, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 45515, "s": 45465, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 45529, "s": 45515, "text": "Decision Tree" }, { "code": null, "e": 45587, "s": 45529, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 45670, "s": 45587, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 45706, "s": 45670, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 45754, "s": 45706, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 45789, "s": 45754, "text": "Binary Tree (Array implementation)" } ]
Using DELETE Expression
In the previous chapter, we have understood what an Update expression does. The next expression that we are going to learn is Delete. The delete operation can be achieved by running delete() method on target table object as given in the following statement − stmt = students.delete() In case of students table, the above line of code constructs a SQL expression as following − 'DELETE FROM students' However, this will delete all rows in students table. Usually DELETE query is associated with a logical expression specified by WHERE clause. The following statement shows where parameter − stmt = students.delete().where(students.c.id > 2) The resultant SQL expression will have a bound parameter which will be substituted at runtime when the statement is executed. 'DELETE FROM students WHERE students.id > :id_1' Following code example will delete those rows from students table having lastname as ‘Khanna’ − from sqlalchemy.sql.expression import update from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) conn = engine.connect() stmt = students.delete().where(students.c.lastname == 'Khanna') conn.execute(stmt) s = students.select() conn.execute(s).fetchall() To verify the result, refresh the data view of students table in SQLiteStudio. 21 Lectures 1.5 hours Jack Chan Print Add Notes Bookmark this page
[ { "code": null, "e": 2474, "s": 2340, "text": "In the previous chapter, we have understood what an Update expression does. The next expression that we are going to learn is Delete." }, { "code": null, "e": 2599, "s": 2474, "text": "The delete operation can be achieved by running delete() method on target table object as given in the following statement −" }, { "code": null, "e": 2624, "s": 2599, "text": "stmt = students.delete()" }, { "code": null, "e": 2717, "s": 2624, "text": "In case of students table, the above line of code constructs a SQL expression as following −" }, { "code": null, "e": 2740, "s": 2717, "text": "'DELETE FROM students'" }, { "code": null, "e": 2930, "s": 2740, "text": "However, this will delete all rows in students table. Usually DELETE query is associated with a logical expression specified by WHERE clause. The following statement shows where parameter −" }, { "code": null, "e": 2980, "s": 2930, "text": "stmt = students.delete().where(students.c.id > 2)" }, { "code": null, "e": 3106, "s": 2980, "text": "The resultant SQL expression will have a bound parameter which will be substituted at runtime when the statement is executed." }, { "code": null, "e": 3155, "s": 3106, "text": "'DELETE FROM students WHERE students.id > :id_1'" }, { "code": null, "e": 3251, "s": 3155, "text": "Following code example will delete those rows from students table having lastname as ‘Khanna’ −" }, { "code": null, "e": 3761, "s": 3251, "text": "from sqlalchemy.sql.expression import update\nfrom sqlalchemy import create_engine, MetaData, Table, Column, Integer, String\nengine = create_engine('sqlite:///college.db', echo = True)\n\nmeta = MetaData()\n\nstudents = Table(\n 'students', meta, \n Column('id', Integer, primary_key = True), \n Column('name', String), \n Column('lastname', String), \n)\n\nconn = engine.connect()\nstmt = students.delete().where(students.c.lastname == 'Khanna')\nconn.execute(stmt)\ns = students.select()\nconn.execute(s).fetchall()" }, { "code": null, "e": 3840, "s": 3761, "text": "To verify the result, refresh the data view of students table in SQLiteStudio." }, { "code": null, "e": 3875, "s": 3840, "text": "\n 21 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3886, "s": 3875, "text": " Jack Chan" }, { "code": null, "e": 3893, "s": 3886, "text": " Print" }, { "code": null, "e": 3904, "s": 3893, "text": " Add Notes" } ]
Deploying Machine Learning projects using Tkinter | by Pier Paolo Ippolito | Towards Data Science
1 2 3 4 5 6 7 8 9 10 Powered by Play.ht Create audio with Play.ht Create Audio Narrations with Play.ht Thanks to a wide variety of open-source libraries, it is relatively easy nowadays to start exploring datasets and making some first predictions using simple Machine Learning (ML) algorithms in Python. Although, to make these trained models useful in the real world, it is necessary to share them and make them easily accessible on other users machines to make predictions. Only in this way Machine Learning can be used to provide benefit to society. In this article, I will walk you through how to easily create a Graphical User Interface (GUI) for your Machine Learning project and then share your application as an executable file which can be run on other machines (whiteout needing the end-user to have Python or any library installed!). In case you are interested in finding out more, all the code used for this article (and more!) is available on my GitHub profile. In order to shift our focus on the Graphical Interface development and deployment, in this article, we are going to use the VGG16 pre-trained model available on Tensorflow to easily build a Portable Image Classifier. In Video 1, is available a quick animation demonstrating the final workflow of our application. Transfer Learning, is an area of research focused on transferring useful knowledge acquired by a Machine Learning model to another model which we are planning to use for a different (but still to some extent related) topic. This can be particularly useful when working with a limited amount of data (Figure 1). One of the most common applications of transfer learning is Computer Vision. For example, in this article, we are going to use the VGG16 model pre-trained on the ImageNet dataset in order to quickly build a robust image classifier. In fact, the ImageNet dataset comprised of a huge amount of images (14 million) and about 21 thousand classes, making it therefore quite complete for this type of task. Researchers are currently working on applying transfer learning techniques also in other fields such as Music [1] and Text classification [2]. First of all, we need to import all our necessaries dependencies. Now, we can make use of the Tkinter library in order to create our Graphical Interface (as shown in Video 1). We start first by creating the base of our window (root) and we then add on top of it different elements such as a program title (tit), a frame (frame) a button to load an image to display on the frame (chose_image) and a button to fire our image classifier (class_image). Finally, we instantiate our VGG16 model and launch our GUI (using root.mainloop()). In order to associate actions to perform when a user press either of the two GUI buttons, we can define two functions which get activated on click (load_img() and classify()). In the load_img() function, we first clear the frame in case there is any widget attached, then we let the user upload an image and finally we rescale and display the image and its filename on the window frame. In the classify() function, we instead preprocess our image (using the Keras guidelines for this pre-trained model) and finally print on the frame the top 5 predictions of our classifier and it’s percentage confidence. Once our program is perfectly functioning locally, we can then export it into an executable format. One of the easiest ways to convert a Python file into an executable (for either Windows or Linux platforms) is to use Pyinstaller (Figure 2). In the case of a project with a single file and not too many dependencies, this can be done with just one command line statement: pyinstaller my_script_name.py Although, for more complicated projects might be a better idea to create a virtual environment for the project and use a Spec file in order to give clear indications to Pyinstaller about how to create the executable and what assets to include. An example of Spec file for this project is available at this link. Finally, in case our executable might require different assets (eg. images, videos, etc...) then it could be a great idea to include everything in an installation system file using NSIS (making so easier to install the executable and all the required dependencies on another machine). In case you can be interested in using this application yourself, a download link is available on my personal website. Additionally, some alternative techniques which can be used in order to deploy Machine Learning systems are using: Cloud Services (eg. Heroku, AWS, Google Cloud) Online Dashboards (eg. Dash, R-Shiny) Application Programming Interfaces (A.P.I.) These techniques are widely used nowadays and they can make Machine Learning models easily available on the Web, although they will most likely incur in hosting charges (which are instead not needed using executables). I hope you enjoyed this article, thank you for reading! If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details: Linkedin Personal Blog Personal Website Patreon Medium Profile GitHub Kaggle [1] Transfer learning for music classification and regression tasks, Keunwoo Choi, György Fazekas. Accessed at: https://arxiv.org/abs/1703.09179 [2] A Practitioners’ Guide to Transfer Learning for Text Classification using Convolutional Neural Networks, Tushar Semwal, Gaurav Mathur. Accessed at: https://arxiv.org/abs/1801.06480 [3] Pyinstaller. Freeze (package) Python programs into stand-alone executables, Github. Accessed at: https://github.com/pyinstaller/pyinstaller
[ { "code": null, "e": 173, "s": 171, "text": "1" }, { "code": null, "e": 175, "s": 173, "text": "2" }, { "code": null, "e": 177, "s": 175, "text": "3" }, { "code": null, "e": 179, "s": 177, "text": "4" }, { "code": null, "e": 181, "s": 179, "text": "5" }, { "code": null, "e": 183, "s": 181, "text": "6" }, { "code": null, "e": 185, "s": 183, "text": "7" }, { "code": null, "e": 187, "s": 185, "text": "8" }, { "code": null, "e": 189, "s": 187, "text": "9" }, { "code": null, "e": 192, "s": 189, "text": "10" }, { "code": null, "e": 211, "s": 192, "text": "Powered by Play.ht" }, { "code": null, "e": 237, "s": 211, "text": "Create audio with Play.ht" }, { "code": null, "e": 274, "s": 237, "text": "Create Audio Narrations with Play.ht" }, { "code": null, "e": 724, "s": 274, "text": "Thanks to a wide variety of open-source libraries, it is relatively easy nowadays to start exploring datasets and making some first predictions using simple Machine Learning (ML) algorithms in Python. Although, to make these trained models useful in the real world, it is necessary to share them and make them easily accessible on other users machines to make predictions. Only in this way Machine Learning can be used to provide benefit to society." }, { "code": null, "e": 1146, "s": 724, "text": "In this article, I will walk you through how to easily create a Graphical User Interface (GUI) for your Machine Learning project and then share your application as an executable file which can be run on other machines (whiteout needing the end-user to have Python or any library installed!). In case you are interested in finding out more, all the code used for this article (and more!) is available on my GitHub profile." }, { "code": null, "e": 1459, "s": 1146, "text": "In order to shift our focus on the Graphical Interface development and deployment, in this article, we are going to use the VGG16 pre-trained model available on Tensorflow to easily build a Portable Image Classifier. In Video 1, is available a quick animation demonstrating the final workflow of our application." }, { "code": null, "e": 1770, "s": 1459, "text": "Transfer Learning, is an area of research focused on transferring useful knowledge acquired by a Machine Learning model to another model which we are planning to use for a different (but still to some extent related) topic. This can be particularly useful when working with a limited amount of data (Figure 1)." }, { "code": null, "e": 2171, "s": 1770, "text": "One of the most common applications of transfer learning is Computer Vision. For example, in this article, we are going to use the VGG16 model pre-trained on the ImageNet dataset in order to quickly build a robust image classifier. In fact, the ImageNet dataset comprised of a huge amount of images (14 million) and about 21 thousand classes, making it therefore quite complete for this type of task." }, { "code": null, "e": 2314, "s": 2171, "text": "Researchers are currently working on applying transfer learning techniques also in other fields such as Music [1] and Text classification [2]." }, { "code": null, "e": 2380, "s": 2314, "text": "First of all, we need to import all our necessaries dependencies." }, { "code": null, "e": 2847, "s": 2380, "text": "Now, we can make use of the Tkinter library in order to create our Graphical Interface (as shown in Video 1). We start first by creating the base of our window (root) and we then add on top of it different elements such as a program title (tit), a frame (frame) a button to load an image to display on the frame (chose_image) and a button to fire our image classifier (class_image). Finally, we instantiate our VGG16 model and launch our GUI (using root.mainloop())." }, { "code": null, "e": 3023, "s": 2847, "text": "In order to associate actions to perform when a user press either of the two GUI buttons, we can define two functions which get activated on click (load_img() and classify())." }, { "code": null, "e": 3234, "s": 3023, "text": "In the load_img() function, we first clear the frame in case there is any widget attached, then we let the user upload an image and finally we rescale and display the image and its filename on the window frame." }, { "code": null, "e": 3453, "s": 3234, "text": "In the classify() function, we instead preprocess our image (using the Keras guidelines for this pre-trained model) and finally print on the frame the top 5 predictions of our classifier and it’s percentage confidence." }, { "code": null, "e": 3553, "s": 3453, "text": "Once our program is perfectly functioning locally, we can then export it into an executable format." }, { "code": null, "e": 3695, "s": 3553, "text": "One of the easiest ways to convert a Python file into an executable (for either Windows or Linux platforms) is to use Pyinstaller (Figure 2)." }, { "code": null, "e": 3825, "s": 3695, "text": "In the case of a project with a single file and not too many dependencies, this can be done with just one command line statement:" }, { "code": null, "e": 3855, "s": 3825, "text": "pyinstaller my_script_name.py" }, { "code": null, "e": 4167, "s": 3855, "text": "Although, for more complicated projects might be a better idea to create a virtual environment for the project and use a Spec file in order to give clear indications to Pyinstaller about how to create the executable and what assets to include. An example of Spec file for this project is available at this link." }, { "code": null, "e": 4452, "s": 4167, "text": "Finally, in case our executable might require different assets (eg. images, videos, etc...) then it could be a great idea to include everything in an installation system file using NSIS (making so easier to install the executable and all the required dependencies on another machine)." }, { "code": null, "e": 4571, "s": 4452, "text": "In case you can be interested in using this application yourself, a download link is available on my personal website." }, { "code": null, "e": 4686, "s": 4571, "text": "Additionally, some alternative techniques which can be used in order to deploy Machine Learning systems are using:" }, { "code": null, "e": 4733, "s": 4686, "text": "Cloud Services (eg. Heroku, AWS, Google Cloud)" }, { "code": null, "e": 4771, "s": 4733, "text": "Online Dashboards (eg. Dash, R-Shiny)" }, { "code": null, "e": 4815, "s": 4771, "text": "Application Programming Interfaces (A.P.I.)" }, { "code": null, "e": 5034, "s": 4815, "text": "These techniques are widely used nowadays and they can make Machine Learning models easily available on the Web, although they will most likely incur in hosting charges (which are instead not needed using executables)." }, { "code": null, "e": 5090, "s": 5034, "text": "I hope you enjoyed this article, thank you for reading!" }, { "code": null, "e": 5248, "s": 5090, "text": "If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details:" }, { "code": null, "e": 5257, "s": 5248, "text": "Linkedin" }, { "code": null, "e": 5271, "s": 5257, "text": "Personal Blog" }, { "code": null, "e": 5288, "s": 5271, "text": "Personal Website" }, { "code": null, "e": 5296, "s": 5288, "text": "Patreon" }, { "code": null, "e": 5311, "s": 5296, "text": "Medium Profile" }, { "code": null, "e": 5318, "s": 5311, "text": "GitHub" }, { "code": null, "e": 5325, "s": 5318, "text": "Kaggle" }, { "code": null, "e": 5471, "s": 5325, "text": "[1] Transfer learning for music classification and regression tasks, Keunwoo Choi, György Fazekas. Accessed at: https://arxiv.org/abs/1703.09179" }, { "code": null, "e": 5656, "s": 5471, "text": "[2] A Practitioners’ Guide to Transfer Learning for Text Classification using Convolutional Neural Networks, Tushar Semwal, Gaurav Mathur. Accessed at: https://arxiv.org/abs/1801.06480" } ]
How to deploy your ML models into the browser | by Dweep Joshipura | Towards Data Science
When I was a beginner in AI and ML, I often had questions like why am I learning this? And could I even make a difference before landing at a job? These questions came up because I knew how to train models, but not how to deploy them. So if you’re at that stage and want to learn how to use models, you’re at the right place! I am Dweep, a passionate High Schooler who has gained a lot of Deep Learning knowledge from a variety of courses, and projects. We all know TensorFlow, and how to make models in TensorFlow (if you don’t, then I would recommend reading this blog and then coming back here.) However, it’s javaScript brother is quite lesser-known. But that doesn’t mean TensorFlow.jS, also called tfjs, is any lesser useful. Most TensorFlow models can directly turn to tfjs models, and tfjs is also capable of training models itself! I am a true believer in the fact that code is the best way to learn code. Thus, at the end of the article, you will implement a tfjs system right on your browser. By the way, I learnt most of this from the first course in the Data and Deployment Specialization on Coursera, and I reviewed it here. As the most common use case for tfjs is transfer learning, you will implement that. To make it as related to TensorFlow as possible, I will first explain the relationship between the TensorFlow Keras library and the tfjs Layers library. Like Keras is built on the TensorFlow library to provide high-level functionality, the Layers library does the same for tfjs. All jS code is in lowerCamelCase, which means that all everything is supposed to have the first letter of the first word in lowercase( like the l), and the next words with uppercase first letters( like the C). All functions and syntax follow this rule. Therefore, we should use inputShape instead of input_shape. Also, all syntax ends with a semicolon. As javaScript does not have NumPy, all data needs to be turned into tensors for tfjs to perform inference or train models. Another significant difference is that, unlike Python, all functional inputs configure inside curly braces. An exception is when you are inputting data, like the training set. There are a few more differences, but I think these would suffice. The most commonly used functions are listed below. To know more about any of them, simply click the name of the function. I recommend that you do so for every one of them, to get a better understanding. tf.tensor(data, shape) creates a tensor which tfjs can later use for training or inference, and saves it in the variable assigned to this function tf.sequential() creates a model which consists of a sequence of layers. This model saves into a const or constant variable. tf.layers.dense({units: ___, activation: ‘___’}) creates a tfjs layer that can be added to a model using model.add(). Note that like TensorFlow, the first layer has an optional additional input called inputShape, which will go inside the configuration of the first layer of the model. model.add() takes a tf.layers layer and adds it to the existing list of layers in the model. You can use tf.layers.flatten or tf.layers.conv2d also. model.compile({optimizer: ‘___’, loss: ‘___’}) compiles the model. Optimizers are at tf.train, for example, tf.train.adam and tf.train.rmsprop. model.fit(xs,ys,{epochs: ___, callbacks: {___}}) fits the dataset of xs, ys on the model. model.predict(xs) uses the trained model to predict labels. With syntax out of the way, we can now start programming. Note that the program is the customization of the Week 4 example in the Browser-based models in tfjs course in the Data & Deployment specialization. Let’s make a face recognition model using transfer learning in tfjs. This model will first take images of three people as input and will output which person the model sees from the webcam.If you just wanna check the demo out, then I have it in a website below. Check it out! djthegr8.github.io Download the 200 OK Web Server for Chrome from here. It is required to eliminate multiple HTTP requests and ensure that we get good uploads. Optionally, if you want to edit my code to play around with tfjs (and I really recommend doing this) you can download an editor like Brackets, to make your work easier. And finally, all the code is available at this GitHub repository. Please download it, and set the target of the Chrome Web Server into that folder. To run, open the link in the server application, and open the facerecgn.html file. Let us first look at importing the TensorFlow.jS library. This line is in the head section of the HTML page. <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"> </script> Now, we will skip the HTML code, and see the Tensorflow.jS code in the index.jS page. Below is the code to load the MobileNet, a pretrained tfjs network that, by itself, classifies images to about 1000 classes. This function removes its inference layer by declaring a new model which takes the output of the second last layer. Below is the most important function in the code. We are flattening the 3-dimensional outputs of the MobileNet encodings (outputs of the model declared in the loadMobilenet() function, and then passing through a small NN. The loss is categorical cross-entropy and the optimizer is adam. Another function that I will show is the function that handles the button presses that eventually lead to the creation of the dataset. It is pretty self-explanatory. The last major function is the predict() which predicts the person based on the model. This function finds predictive probabilities and outputs the one with the highest. With that done, the rps-dataset.jS is left...Rather than describing the code, I will quickly describe what it does. All it does is make a dataset that can be appended and has (one-hot) labels. The code is in the repository, of course. After all these functions, you can look at the final index.jS code. Thanks a ton for reading this, and if you find any bugs, please comment! Mail me up at my Gmail for any help or collab related to TF, Keras, TFjS or Python! Or check out my Linkedin
[ { "code": null, "e": 318, "s": 171, "text": "When I was a beginner in AI and ML, I often had questions like why am I learning this? And could I even make a difference before landing at a job?" }, { "code": null, "e": 497, "s": 318, "text": "These questions came up because I knew how to train models, but not how to deploy them. So if you’re at that stage and want to learn how to use models, you’re at the right place!" }, { "code": null, "e": 625, "s": 497, "text": "I am Dweep, a passionate High Schooler who has gained a lot of Deep Learning knowledge from a variety of courses, and projects." }, { "code": null, "e": 1012, "s": 625, "text": "We all know TensorFlow, and how to make models in TensorFlow (if you don’t, then I would recommend reading this blog and then coming back here.) However, it’s javaScript brother is quite lesser-known. But that doesn’t mean TensorFlow.jS, also called tfjs, is any lesser useful. Most TensorFlow models can directly turn to tfjs models, and tfjs is also capable of training models itself!" }, { "code": null, "e": 1394, "s": 1012, "text": "I am a true believer in the fact that code is the best way to learn code. Thus, at the end of the article, you will implement a tfjs system right on your browser. By the way, I learnt most of this from the first course in the Data and Deployment Specialization on Coursera, and I reviewed it here. As the most common use case for tfjs is transfer learning, you will implement that." }, { "code": null, "e": 1547, "s": 1394, "text": "To make it as related to TensorFlow as possible, I will first explain the relationship between the TensorFlow Keras library and the tfjs Layers library." }, { "code": null, "e": 1673, "s": 1547, "text": "Like Keras is built on the TensorFlow library to provide high-level functionality, the Layers library does the same for tfjs." }, { "code": null, "e": 2026, "s": 1673, "text": "All jS code is in lowerCamelCase, which means that all everything is supposed to have the first letter of the first word in lowercase( like the l), and the next words with uppercase first letters( like the C). All functions and syntax follow this rule. Therefore, we should use inputShape instead of input_shape. Also, all syntax ends with a semicolon." }, { "code": null, "e": 2149, "s": 2026, "text": "As javaScript does not have NumPy, all data needs to be turned into tensors for tfjs to perform inference or train models." }, { "code": null, "e": 2325, "s": 2149, "text": "Another significant difference is that, unlike Python, all functional inputs configure inside curly braces. An exception is when you are inputting data, like the training set." }, { "code": null, "e": 2392, "s": 2325, "text": "There are a few more differences, but I think these would suffice." }, { "code": null, "e": 2595, "s": 2392, "text": "The most commonly used functions are listed below. To know more about any of them, simply click the name of the function. I recommend that you do so for every one of them, to get a better understanding." }, { "code": null, "e": 2742, "s": 2595, "text": "tf.tensor(data, shape) creates a tensor which tfjs can later use for training or inference, and saves it in the variable assigned to this function" }, { "code": null, "e": 2866, "s": 2742, "text": "tf.sequential() creates a model which consists of a sequence of layers. This model saves into a const or constant variable." }, { "code": null, "e": 3151, "s": 2866, "text": "tf.layers.dense({units: ___, activation: ‘___’}) creates a tfjs layer that can be added to a model using model.add(). Note that like TensorFlow, the first layer has an optional additional input called inputShape, which will go inside the configuration of the first layer of the model." }, { "code": null, "e": 3300, "s": 3151, "text": "model.add() takes a tf.layers layer and adds it to the existing list of layers in the model. You can use tf.layers.flatten or tf.layers.conv2d also." }, { "code": null, "e": 3444, "s": 3300, "text": "model.compile({optimizer: ‘___’, loss: ‘___’}) compiles the model. Optimizers are at tf.train, for example, tf.train.adam and tf.train.rmsprop." }, { "code": null, "e": 3534, "s": 3444, "text": "model.fit(xs,ys,{epochs: ___, callbacks: {___}}) fits the dataset of xs, ys on the model." }, { "code": null, "e": 3594, "s": 3534, "text": "model.predict(xs) uses the trained model to predict labels." }, { "code": null, "e": 3652, "s": 3594, "text": "With syntax out of the way, we can now start programming." }, { "code": null, "e": 3801, "s": 3652, "text": "Note that the program is the customization of the Week 4 example in the Browser-based models in tfjs course in the Data & Deployment specialization." }, { "code": null, "e": 4076, "s": 3801, "text": "Let’s make a face recognition model using transfer learning in tfjs. This model will first take images of three people as input and will output which person the model sees from the webcam.If you just wanna check the demo out, then I have it in a website below. Check it out!" }, { "code": null, "e": 4095, "s": 4076, "text": "djthegr8.github.io" }, { "code": null, "e": 4236, "s": 4095, "text": "Download the 200 OK Web Server for Chrome from here. It is required to eliminate multiple HTTP requests and ensure that we get good uploads." }, { "code": null, "e": 4405, "s": 4236, "text": "Optionally, if you want to edit my code to play around with tfjs (and I really recommend doing this) you can download an editor like Brackets, to make your work easier." }, { "code": null, "e": 4636, "s": 4405, "text": "And finally, all the code is available at this GitHub repository. Please download it, and set the target of the Chrome Web Server into that folder. To run, open the link in the server application, and open the facerecgn.html file." }, { "code": null, "e": 4745, "s": 4636, "text": "Let us first look at importing the TensorFlow.jS library. This line is in the head section of the HTML page." }, { "code": null, "e": 4823, "s": 4745, "text": "<script src=\"https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest\"> </script>" }, { "code": null, "e": 4909, "s": 4823, "text": "Now, we will skip the HTML code, and see the Tensorflow.jS code in the index.jS page." }, { "code": null, "e": 5150, "s": 4909, "text": "Below is the code to load the MobileNet, a pretrained tfjs network that, by itself, classifies images to about 1000 classes. This function removes its inference layer by declaring a new model which takes the output of the second last layer." }, { "code": null, "e": 5437, "s": 5150, "text": "Below is the most important function in the code. We are flattening the 3-dimensional outputs of the MobileNet encodings (outputs of the model declared in the loadMobilenet() function, and then passing through a small NN. The loss is categorical cross-entropy and the optimizer is adam." }, { "code": null, "e": 5603, "s": 5437, "text": "Another function that I will show is the function that handles the button presses that eventually lead to the creation of the dataset. It is pretty self-explanatory." }, { "code": null, "e": 5773, "s": 5603, "text": "The last major function is the predict() which predicts the person based on the model. This function finds predictive probabilities and outputs the one with the highest." }, { "code": null, "e": 6008, "s": 5773, "text": "With that done, the rps-dataset.jS is left...Rather than describing the code, I will quickly describe what it does. All it does is make a dataset that can be appended and has (one-hot) labels. The code is in the repository, of course." }, { "code": null, "e": 6076, "s": 6008, "text": "After all these functions, you can look at the final index.jS code." }, { "code": null, "e": 6149, "s": 6076, "text": "Thanks a ton for reading this, and if you find any bugs, please comment!" } ]
PHP microtime() Function
The microtime() function returns the current Unix timestamp with microseconds. By default, this function returns a string value which contains microseconds and seconds separated by space (msec sec). microtime($get_as_float) get_as_float(Optional) This is a boolean value which is used to specify whether the result should be a floating point value or not. If you pass the boolean value true as a parameter, this function returns result as floating point value. PHP microtime() function returns the current Unix timestamp. By default this returns a string value in the form msec sec. If you pass the boolean value true as a parameter to this method, it returns the current time in seconds since the Unix epoch accurate to the nearest microsecond. This function was first introduced in PHP Version 4 and, works with all the later versions. Following example demonstrates the usage of the microtime() function − <?php $time = microtime(); print($time); ?> This will produce following result − 0.60664200 1589305212 Lets try to set the get_as_float value to true − <?php $time = gettimeofday(true); print_r($time); ?> This will produce following result − 1589298812.5101 <?php $time_start = microtime(true); usleep(100); $time_end = microtime(true); $time = $time_end - $time_start; echo "Did nothing in $time seconds\n"; ?> This produces the following result − Did nothing in 0.0018141269683838 seconds 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2956, "s": 2757, "text": "The microtime() function returns the current Unix timestamp with microseconds. By default, this function returns a string value which contains microseconds and seconds separated by space (msec sec)." }, { "code": null, "e": 2982, "s": 2956, "text": "microtime($get_as_float)\n" }, { "code": null, "e": 3005, "s": 2982, "text": "get_as_float(Optional)" }, { "code": null, "e": 3219, "s": 3005, "text": "This is a boolean value which is used to specify whether the result should be a floating point value or not. If you pass the boolean value true as a parameter, this function returns result as floating point value." }, { "code": null, "e": 3505, "s": 3219, "text": "PHP microtime() function returns the current Unix timestamp. By default this returns a string value in the form msec sec. If you pass the boolean value true as a parameter to this method, it returns the current time in seconds since the Unix epoch accurate to the nearest microsecond. " }, { "code": null, "e": 3597, "s": 3505, "text": "This function was first introduced in PHP Version 4 and, works with all the later versions." }, { "code": null, "e": 3668, "s": 3597, "text": "Following example demonstrates the usage of the microtime() function −" }, { "code": null, "e": 3718, "s": 3668, "text": "<?php\n $time = microtime();\n print($time);\n?>" }, { "code": null, "e": 3755, "s": 3718, "text": "This will produce following result −" }, { "code": null, "e": 3778, "s": 3755, "text": "0.60664200 1589305212\n" }, { "code": null, "e": 3827, "s": 3778, "text": "Lets try to set the get_as_float value to true −" }, { "code": null, "e": 3891, "s": 3827, "text": "<?php\n $time = gettimeofday(true); \n print_r($time); \n?>" }, { "code": null, "e": 3928, "s": 3891, "text": "This will produce following result −" }, { "code": null, "e": 3945, "s": 3928, "text": "1589298812.5101\n" }, { "code": null, "e": 4122, "s": 3945, "text": "<?php\n $time_start = microtime(true);\n usleep(100);\n \n $time_end = microtime(true);\n $time = $time_end - $time_start;\n \n echo \"Did nothing in $time seconds\\n\";\n?>" }, { "code": null, "e": 4159, "s": 4122, "text": "This produces the following result −" }, { "code": null, "e": 4202, "s": 4159, "text": "Did nothing in 0.0018141269683838 seconds\n" }, { "code": null, "e": 4235, "s": 4202, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 4251, "s": 4235, "text": " Malhar Lathkar" }, { "code": null, "e": 4284, "s": 4251, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 4295, "s": 4284, "text": " Syed Raza" }, { "code": null, "e": 4330, "s": 4295, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4347, "s": 4330, "text": " Frahaan Hussain" }, { "code": null, "e": 4380, "s": 4347, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 4395, "s": 4380, "text": " Nivedita Jain" }, { "code": null, "e": 4430, "s": 4395, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 4442, "s": 4430, "text": " Azaz Patel" }, { "code": null, "e": 4477, "s": 4442, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4505, "s": 4477, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 4512, "s": 4505, "text": " Print" }, { "code": null, "e": 4523, "s": 4512, "text": " Add Notes" } ]
C++ Increment and Decrement Operators
The increment operator ++ adds 1 to its operand, and the decrement operator -- subtracts 1 from its operand. Thus − x = x+1; is the same as x++; And similarly − x = x-1; is the same as x--; Both the increment and decrement operators can either precede (prefix) or follow (postfix) the operand. For example − x = x+1; can be written as ++x; // prefix form or as − x++; // postfix form When an increment or decrement is used as part of an expression, there is an important difference in prefix and postfix forms. If you are using prefix form then increment or decrement will be done before rest of the expression, and if you are using postfix form, then increment or decrement will be done after the complete expression is evaluated. Following is the example to understand this difference − #include <iostream> using namespace std; main() { int a = 21; int c ; // Value of a will not be increased before assignment. c = a++; cout << "Line 1 - Value of a++ is :" << c << endl ; // After expression value of a is increased cout << "Line 2 - Value of a is :" << a << endl ; // Value of a will be increased before assignment. c = ++a; cout << "Line 3 - Value of ++a is :" << c << endl ; return 0; } When the above code is compiled and executed, it produces the following result − Line 1 - Value of a++ is :21 Line 2 - Value of a is :22 Line 3 - Value of ++a is :23 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2434, "s": 2318, "text": "The increment operator ++ adds 1 to its operand, and the decrement operator -- subtracts 1 from its operand. Thus −" }, { "code": null, "e": 2468, "s": 2434, "text": "x = x+1;\n \nis the same as\n \nx++;\n" }, { "code": null, "e": 2484, "s": 2468, "text": "And similarly −" }, { "code": null, "e": 2518, "s": 2484, "text": "x = x-1;\n \nis the same as\n \nx--;\n" }, { "code": null, "e": 2636, "s": 2518, "text": "Both the increment and decrement operators can either precede (prefix) or follow (postfix) the operand. For example −" }, { "code": null, "e": 2688, "s": 2636, "text": "x = x+1;\n \ncan be written as\n \n++x; // prefix form\n" }, { "code": null, "e": 2696, "s": 2688, "text": "or as −" }, { "code": null, "e": 2718, "s": 2696, "text": "x++; // postfix form\n" }, { "code": null, "e": 3066, "s": 2718, "text": "When an increment or decrement is used as part of an expression, there is an important difference in prefix and postfix forms. If you are using prefix form then increment or decrement will be done before rest of the expression, and if you are using postfix form, then increment or decrement will be done after the complete expression is evaluated." }, { "code": null, "e": 3123, "s": 3066, "text": "Following is the example to understand this difference −" }, { "code": null, "e": 3574, "s": 3123, "text": "#include <iostream>\nusing namespace std;\n \nmain() {\n int a = 21;\n int c ;\n \n // Value of a will not be increased before assignment.\n c = a++; \n cout << \"Line 1 - Value of a++ is :\" << c << endl ;\n \n // After expression value of a is increased\n cout << \"Line 2 - Value of a is :\" << a << endl ;\n \n // Value of a will be increased before assignment.\n c = ++a; \n cout << \"Line 3 - Value of ++a is :\" << c << endl ;\n return 0;\n}" }, { "code": null, "e": 3655, "s": 3574, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3742, "s": 3655, "text": "Line 1 - Value of a++ is :21\nLine 2 - Value of a is :22\nLine 3 - Value of ++a is :23\n" }, { "code": null, "e": 3779, "s": 3742, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 3798, "s": 3779, "text": " Arnab Chakraborty" }, { "code": null, "e": 3830, "s": 3798, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 3853, "s": 3830, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 3889, "s": 3853, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 3906, "s": 3889, "text": " Frahaan Hussain" }, { "code": null, "e": 3941, "s": 3906, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3958, "s": 3941, "text": " Frahaan Hussain" }, { "code": null, "e": 3993, "s": 3958, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4010, "s": 3993, "text": " Frahaan Hussain" }, { "code": null, "e": 4045, "s": 4010, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4062, "s": 4045, "text": " Frahaan Hussain" }, { "code": null, "e": 4069, "s": 4062, "text": " Print" }, { "code": null, "e": 4080, "s": 4069, "text": " Add Notes" } ]
Using the birthday paradox to teach probability fundamentals | by Cassie Kozyrkov | Towards Data Science
Short answer: it depends how many friends you have... 1.3K plays1.3K Today’s the birthday of someone dear to me (hip hip hooray!), which is a fabulous excuse to cover some probability basics in birthday language. Our goal is figuring out this perennial stats homework chart topper together: If you have N people in a group, what’s the probability that there’s at least one shared birthday? If you haven’t thought about this one, take a moment to guess. Imagine the group has N=30 people in it. What are the chances two people get their cake on the same day? Or, if that’s daunting, just answer this: would you prefer to bet me $10 that there are birthday duplicates or $10 that there aren’t? Let’s see how well-oiled your intuition is! We’re going to get there as the punchline, but first we’ll develop all the LEGO pieces (in large font below) you need to solve The Birthday Problem yourself... For sake of pure pedantry, let’s get this eye-roll-inspiring revelation out of the way: probability lives between 0 and 1 (or 0% and 100%, if you prefer). Cool. Now you know why a sentence like, “I’m, like, a 1000% sure that, like, they’re going to be late” turns data folk an alarming shade of, like, purple. There are three main approaches to thinking about probability: Event-based (involves enumerating events and counting them) Frequency-based (involves distributions symbolizing how things would shake out if we observed our phenomenon in infinite parallel universes) Subjective (involves distributions symbolizing human belief in what’s likely, ideally as expressed in terms of bets... since putting our money where our mouth is might reduce our tendency to spew nonsense) In case you took a stats class with a professor who didn’t apply the wooden-mallet-to-the-head style of emphasizing the obvious, let me spell out where these tend to lurk in your textbook. PROBABILITY = [NUMERATOR] / [DENOMINATOR] The early chapters tend to start with the event-based approach to probability. That’s because it’s an easy playground to get some basics across and most humans probably (heh) already have an intuition for it. Examples: What are the chances your fair coin comes up tails? 1/2. What are the chances you roll a 6 on a six-sided die? 1/6. What’s happening here? NUMERATOR: number of ways the event we’re interested in can happen. DENOMINATOR: number of ways any (relevant) event can happen. On a coin, the possible relevant events are HEADS and TAILS. That’s where the 2 comes from. Easy peasy. To work with event-based probability, you need to be able to enumerate events and count them. That’s why your textbook probably drags you through combinatorics till you’re thoroughly sick of it. Combinatorics gives you the math that you need for counting the number of ways events can happen (for that nice NUMERATOR and DENOMINATOR you’re after). Welcome to a bazillion homework problems all about “How many different ways can I select 10 committee members from 100 candidates?” (17,310,309,456,440) or “How many different options can I choose from when setting a 4-digit PIN?” (10,000) In the event-based world, all building block events are equally probable so as to lend themselves to basic arithmetic unmolested by layers of messy modifiers. It’s a world where all the coins are fair, all the dice are balanced, all the cards are unscuffed, and all the birthdays are equally likely. For the birthday problem, we need to know a quick something about counting: “AND” asks you to multiply (x) counts “OR” asks you to add (+) counts Go look up a proof if you like... or satisfy yourself with a quick example and move along: If I have 2 options for a vegetarian dish OR 3 options for a meaty dish, then how many meal options do I have? 2 + 3 = 5. What if I can choose a main course AND one of 2 desserts? How many different meals am I choosing from? 5 x 2 = 10. Try it out with concrete examples of dishes and write it all out if you don’t believe me. What’s the probability a randomly selected meal is veg-friendly? NUMERATOR = 2 x 2 = 4; DENOMINATOR = 10. ANSWER = 4/10 = 40% You’re 3 chapters in and all of a sudden your textbook forgets all about combinatorics. Just when you were getting the hang of all those combinations and permutations (see illustration above), they’re never heard from again. Instead, suddenly there are distributions everywhere. What’s up with that? Consider this question: “What’s the probability you need to wait more than 10 minutes for the bus?” This is going to be tricky to count (in nanoseconds?) and a pain because counting events means you can’t work with time as a continuous thing. It gets worse if you have a bus driver who has some probability of stopping for a smoke break that’s dependent on how late the bus is already. How are you going to enumerate that? You’re not. Maybe counting events isn’t your friend here... Enter the frequency-based definition, which says something like, “If this were a random event happening in infinite parallel universes (governed by rules I specify, er, assume), in how many of them would the bus take more than 10 minutes to arrive?” (Parallel universes?! Yeah, no wonder we statisticians have the crazy eyes.) And then — usually much later — when you hit the subjective definition in your Bayesian stats textbook, you get to make the distributions up based on what you feel is likely. See what kind of twisted stuff you wind up with when we take away your ability to enumerate events? Well, luckily for the birthday problem, if we assume all 366 birthdays are equally likely*, we can stick with counting. Whew! *What, you don’t like my assumption? Get over yourself — all of statistics is about making simplifying assumptions — the universe is a terrifying place otherwise. If you don’t like my assumptions, then you need to come up with a different solution because mine is no good to you. Statistics gets creative because we’re all allowed to make any assumptions we like. To misquote George Box: “All solutions are wrong, but whichever one fits the assumptions you’re willing to live with might be useful to you.” The last building block we need for the birthday problem is complements, otherwise known as the humble NOT. P(not A) = 1 — P(A) This is read as “the probability of an event (which we’ve named event A because we’re uncreative) NOT happening equals 100% minus the probability of that event happening.” So what’s the probability of NOT getting a 6 on that die roll? 1–1/6 = 5/6 Okay, that’s all. We’re ready to solve the birthday problem! What was the question again? Ah, this: If you have N people in a group, what’s the probability that there’s at least one shared birthday? So, let’s try this with our LEGO pieces... How many birthday options do we have for one person? 366 (see above). How many birthday options do we have for N=30 people? We have 366 for the first person AND 366 for the second person AND 366 for the third person ... AND 366 for the Nth person. Put a multiply where all the ANDs are and voilà! DENOMINATOR = 366 ^ N = Holy cow that’s a lot of digits! 77 of them if N is 30. That’s more than a quattuorvigintillion. (Isn’t naming things fun?) Prepare to get dizzy. We have to count all the different ways to have at least one match in any two people. So person 1 has 366 options and person 29 has 1 option because they match person 1 but it could be person 2 and person 17 or both pairs or maybe three people share a birthday or... or... or... no, this is going to get messy too quickly while we run around trying to keep all the options straight in our heads. ...Which is what makes this such a fun homework problem. You’re supposed to bang your head against it until you see the trick. (Or beg the internet for the cheat code. Is that how you found your way to this blog post? That’s cool, I’ve got ya.) Instead of counting all the ways we can have people sharing birthdays, the trick is to rephrase the problem and count a much simpler thing: the opposite! P(At least one shared birthday) = 1 — P(All birthdays are unique) So what we need to find is the answer to this: “What’s the probability that there’s NOT any birthday sharing in the crowd?” In other words, what’s the probability all birthdays are unique? Still 366 ^ N. By working with the complementary event, we shifted our focus in the numerator. The denominator is unscathed. This is where the beautiful and glorious magic happens! The first person has 366 options for a birthday (greedy pig) AND the second person has only 365 because we force them to have a different birthday. If person 1 is born on Oct 8 and we’re forcing our room to have N unique birthdays in it, we turn all Oct 8 birthday folk away at the door. Each applicant for the room has fewer options by one. So it’s 366 options for person 1 AND 365 for person 2 AND 364 for person 3 ... AND (367— N) for person N. If N is 30, put in the multiplication signs and boom! 366 x 365 x 364 x 363 x 362 x 361 x 360 x 359 x 358 x 357 x 356 x 355 x 354 x 353 x 352 x 351 x 350 x 349 x 348 x 347 x 346 x 345 x 344 x 343 x 342 x 341 x 340 x 339 x 338 x 337 = ... Yuck, another big number with 77 digits. But, luckily for us, computers will just handle the division for us if we ask nicely. P(All 30 birthdays unique) = (366 x 365 x 364 x 363 x 362 x 361 x 360 x 359 x 358 x 357 x 356 x 355 x 354 x 353 x 352 x 351 x 350 x 349 x 348 x 347 x 346 x 345 x 344 x 343 x 342 x 341 x 340 x 339 x 338 x 337) / (366 ^ 30) = 0.3 (rounded off to the capacity of my attention span) P(Shared birthdays in a group of 30) = 1 — 0.3 = 70% With a group of 30, there’s a ~70% chance of shared birthdays. I hope you didn’t bet me $10 that having shared birthdays was less likely than everyone born on a unique day in a group of 30... but if you did, I won’t say no if you’d like to donate it to Wikipedia. Taking the wrong side of the bet comes from underestimating just how hard it is to get a room without duplicates — if you’re the bouncer at the door tasked with turning away people whose birthday slots are taken, it won’t be very long before you turn away your first disappointed soul. With 2 minutes and R open on my laptop, I can plot the answer for any every choice of N. If you’re curious to know the actual numbers (50% happens at N = 23, 99% at N = 55), go ahead and play with my ugly-but-functional little code snippet below right in your browser, no installs needed. # Initialize settings for N = 1:probability <- 0numerator <- 366denominator <- 366# Loops are terrible in R, let's make one anyways:for (N in 2:80) { numerator <- numerator * (366 + 1 - N) denominator <- denominator * 366 p <- 1 - (numerator / denominator) probability <- c(probability, p)}# Look at the answer to 2 decimal places:paste("For N =", 1:80, "prob is", round(probability, 2))# Plot!plot(1:80, probability, xlab = "Group Size", ylab = "P(Shared birthdays)", type = "l", col = "red", main = "The Birthday Solution") Besides some probability basics (like different approaches to probability, complements, and what to put in the numerator and denominator), and counting principles (rule of sum and rule of product) the thing to take away from this article is why you’re being taught certain concepts in a certain order. Why is counting such a big deal early on in your textbook and then suddenly it disappears, leaving everyone disgruntled? Turns out that it’s mostly a means to an end, since the assumption that all elementary events are equally likely is too amateurish for most pros to stomach... even for birthdays. Isn’t it funny that when nonexperts think of what we stats folks do all day, they tend to think of card counting and coin tossing? Some rumors are hard to kill! A big part of what makes the birthday problem a classic fixture of the statistics undergraduate experience is that it gives you just enough pain to rub a key point in: budding statisticians need to learn how to rephrase problems so their moving parts are easier to handle. The brute force approach is often too hard to calculate, so we learn to look sideways at things. If you opt for the statistics life, prepare for a lot of flipping and reversing. This article was intentionally different from my usual. It’s good to try new things sometimes to see if people like ‘em—if you want more where this came from, likes and shares are how you let me know. ❤ If you had fun here and you’re looking for an applied AI course designed to be fun for beginners and experts alike, here’s one I made for your amusement:
[ { "code": null, "e": 225, "s": 171, "text": "Short answer: it depends how many friends you have..." }, { "code": null, "e": 244, "s": 225, "text": "\n\n1.3K plays1.3K\n\n" }, { "code": null, "e": 466, "s": 244, "text": "Today’s the birthday of someone dear to me (hip hip hooray!), which is a fabulous excuse to cover some probability basics in birthday language. Our goal is figuring out this perennial stats homework chart topper together:" }, { "code": null, "e": 565, "s": 466, "text": "If you have N people in a group, what’s the probability that there’s at least one shared birthday?" }, { "code": null, "e": 911, "s": 565, "text": "If you haven’t thought about this one, take a moment to guess. Imagine the group has N=30 people in it. What are the chances two people get their cake on the same day? Or, if that’s daunting, just answer this: would you prefer to bet me $10 that there are birthday duplicates or $10 that there aren’t? Let’s see how well-oiled your intuition is!" }, { "code": null, "e": 1071, "s": 911, "text": "We’re going to get there as the punchline, but first we’ll develop all the LEGO pieces (in large font below) you need to solve The Birthday Problem yourself..." }, { "code": null, "e": 1381, "s": 1071, "text": "For sake of pure pedantry, let’s get this eye-roll-inspiring revelation out of the way: probability lives between 0 and 1 (or 0% and 100%, if you prefer). Cool. Now you know why a sentence like, “I’m, like, a 1000% sure that, like, they’re going to be late” turns data folk an alarming shade of, like, purple." }, { "code": null, "e": 1444, "s": 1381, "text": "There are three main approaches to thinking about probability:" }, { "code": null, "e": 1504, "s": 1444, "text": "Event-based (involves enumerating events and counting them)" }, { "code": null, "e": 1645, "s": 1504, "text": "Frequency-based (involves distributions symbolizing how things would shake out if we observed our phenomenon in infinite parallel universes)" }, { "code": null, "e": 1851, "s": 1645, "text": "Subjective (involves distributions symbolizing human belief in what’s likely, ideally as expressed in terms of bets... since putting our money where our mouth is might reduce our tendency to spew nonsense)" }, { "code": null, "e": 2040, "s": 1851, "text": "In case you took a stats class with a professor who didn’t apply the wooden-mallet-to-the-head style of emphasizing the obvious, let me spell out where these tend to lurk in your textbook." }, { "code": null, "e": 2082, "s": 2040, "text": "PROBABILITY = [NUMERATOR] / [DENOMINATOR]" }, { "code": null, "e": 2440, "s": 2082, "text": "The early chapters tend to start with the event-based approach to probability. That’s because it’s an easy playground to get some basics across and most humans probably (heh) already have an intuition for it. Examples: What are the chances your fair coin comes up tails? 1/2. What are the chances you roll a 6 on a six-sided die? 1/6. What’s happening here?" }, { "code": null, "e": 2508, "s": 2440, "text": "NUMERATOR: number of ways the event we’re interested in can happen." }, { "code": null, "e": 2569, "s": 2508, "text": "DENOMINATOR: number of ways any (relevant) event can happen." }, { "code": null, "e": 2673, "s": 2569, "text": "On a coin, the possible relevant events are HEADS and TAILS. That’s where the 2 comes from. Easy peasy." }, { "code": null, "e": 3021, "s": 2673, "text": "To work with event-based probability, you need to be able to enumerate events and count them. That’s why your textbook probably drags you through combinatorics till you’re thoroughly sick of it. Combinatorics gives you the math that you need for counting the number of ways events can happen (for that nice NUMERATOR and DENOMINATOR you’re after)." }, { "code": null, "e": 3261, "s": 3021, "text": "Welcome to a bazillion homework problems all about “How many different ways can I select 10 committee members from 100 candidates?” (17,310,309,456,440) or “How many different options can I choose from when setting a 4-digit PIN?” (10,000)" }, { "code": null, "e": 3561, "s": 3261, "text": "In the event-based world, all building block events are equally probable so as to lend themselves to basic arithmetic unmolested by layers of messy modifiers. It’s a world where all the coins are fair, all the dice are balanced, all the cards are unscuffed, and all the birthdays are equally likely." }, { "code": null, "e": 3637, "s": 3561, "text": "For the birthday problem, we need to know a quick something about counting:" }, { "code": null, "e": 3675, "s": 3637, "text": "“AND” asks you to multiply (x) counts" }, { "code": null, "e": 3707, "s": 3675, "text": "“OR” asks you to add (+) counts" }, { "code": null, "e": 4125, "s": 3707, "text": "Go look up a proof if you like... or satisfy yourself with a quick example and move along: If I have 2 options for a vegetarian dish OR 3 options for a meaty dish, then how many meal options do I have? 2 + 3 = 5. What if I can choose a main course AND one of 2 desserts? How many different meals am I choosing from? 5 x 2 = 10. Try it out with concrete examples of dishes and write it all out if you don’t believe me." }, { "code": null, "e": 4190, "s": 4125, "text": "What’s the probability a randomly selected meal is veg-friendly?" }, { "code": null, "e": 4251, "s": 4190, "text": "NUMERATOR = 2 x 2 = 4; DENOMINATOR = 10. ANSWER = 4/10 = 40%" }, { "code": null, "e": 4551, "s": 4251, "text": "You’re 3 chapters in and all of a sudden your textbook forgets all about combinatorics. Just when you were getting the hang of all those combinations and permutations (see illustration above), they’re never heard from again. Instead, suddenly there are distributions everywhere. What’s up with that?" }, { "code": null, "e": 5034, "s": 4551, "text": "Consider this question: “What’s the probability you need to wait more than 10 minutes for the bus?” This is going to be tricky to count (in nanoseconds?) and a pain because counting events means you can’t work with time as a continuous thing. It gets worse if you have a bus driver who has some probability of stopping for a smoke break that’s dependent on how late the bus is already. How are you going to enumerate that? You’re not. Maybe counting events isn’t your friend here..." }, { "code": null, "e": 5361, "s": 5034, "text": "Enter the frequency-based definition, which says something like, “If this were a random event happening in infinite parallel universes (governed by rules I specify, er, assume), in how many of them would the bus take more than 10 minutes to arrive?” (Parallel universes?! Yeah, no wonder we statisticians have the crazy eyes.)" }, { "code": null, "e": 5762, "s": 5361, "text": "And then — usually much later — when you hit the subjective definition in your Bayesian stats textbook, you get to make the distributions up based on what you feel is likely. See what kind of twisted stuff you wind up with when we take away your ability to enumerate events? Well, luckily for the birthday problem, if we assume all 366 birthdays are equally likely*, we can stick with counting. Whew!" }, { "code": null, "e": 6268, "s": 5762, "text": "*What, you don’t like my assumption? Get over yourself — all of statistics is about making simplifying assumptions — the universe is a terrifying place otherwise. If you don’t like my assumptions, then you need to come up with a different solution because mine is no good to you. Statistics gets creative because we’re all allowed to make any assumptions we like. To misquote George Box: “All solutions are wrong, but whichever one fits the assumptions you’re willing to live with might be useful to you.”" }, { "code": null, "e": 6376, "s": 6268, "text": "The last building block we need for the birthday problem is complements, otherwise known as the humble NOT." }, { "code": null, "e": 6396, "s": 6376, "text": "P(not A) = 1 — P(A)" }, { "code": null, "e": 6568, "s": 6396, "text": "This is read as “the probability of an event (which we’ve named event A because we’re uncreative) NOT happening equals 100% minus the probability of that event happening.”" }, { "code": null, "e": 6643, "s": 6568, "text": "So what’s the probability of NOT getting a 6 on that die roll? 1–1/6 = 5/6" }, { "code": null, "e": 6704, "s": 6643, "text": "Okay, that’s all. We’re ready to solve the birthday problem!" }, { "code": null, "e": 6743, "s": 6704, "text": "What was the question again? Ah, this:" }, { "code": null, "e": 6842, "s": 6743, "text": "If you have N people in a group, what’s the probability that there’s at least one shared birthday?" }, { "code": null, "e": 6885, "s": 6842, "text": "So, let’s try this with our LEGO pieces..." }, { "code": null, "e": 6955, "s": 6885, "text": "How many birthday options do we have for one person? 366 (see above)." }, { "code": null, "e": 7009, "s": 6955, "text": "How many birthday options do we have for N=30 people?" }, { "code": null, "e": 7183, "s": 7009, "text": "We have 366 for the first person AND 366 for the second person AND 366 for the third person ... AND 366 for the Nth person. Put a multiply where all the ANDs are and voilà!" }, { "code": null, "e": 7331, "s": 7183, "text": "DENOMINATOR = 366 ^ N = Holy cow that’s a lot of digits! 77 of them if N is 30. That’s more than a quattuorvigintillion. (Isn’t naming things fun?)" }, { "code": null, "e": 7749, "s": 7331, "text": "Prepare to get dizzy. We have to count all the different ways to have at least one match in any two people. So person 1 has 366 options and person 29 has 1 option because they match person 1 but it could be person 2 and person 17 or both pairs or maybe three people share a birthday or... or... or... no, this is going to get messy too quickly while we run around trying to keep all the options straight in our heads." }, { "code": null, "e": 7994, "s": 7749, "text": "...Which is what makes this such a fun homework problem. You’re supposed to bang your head against it until you see the trick. (Or beg the internet for the cheat code. Is that how you found your way to this blog post? That’s cool, I’ve got ya.)" }, { "code": null, "e": 8148, "s": 7994, "text": "Instead of counting all the ways we can have people sharing birthdays, the trick is to rephrase the problem and count a much simpler thing: the opposite!" }, { "code": null, "e": 8182, "s": 8148, "text": "P(At least one shared birthday) =" }, { "code": null, "e": 8214, "s": 8182, "text": "1 — P(All birthdays are unique)" }, { "code": null, "e": 8403, "s": 8214, "text": "So what we need to find is the answer to this: “What’s the probability that there’s NOT any birthday sharing in the crowd?” In other words, what’s the probability all birthdays are unique?" }, { "code": null, "e": 8528, "s": 8403, "text": "Still 366 ^ N. By working with the complementary event, we shifted our focus in the numerator. The denominator is unscathed." }, { "code": null, "e": 8584, "s": 8528, "text": "This is where the beautiful and glorious magic happens!" }, { "code": null, "e": 8926, "s": 8584, "text": "The first person has 366 options for a birthday (greedy pig) AND the second person has only 365 because we force them to have a different birthday. If person 1 is born on Oct 8 and we’re forcing our room to have N unique birthdays in it, we turn all Oct 8 birthday folk away at the door. Each applicant for the room has fewer options by one." }, { "code": null, "e": 9032, "s": 8926, "text": "So it’s 366 options for person 1 AND 365 for person 2 AND 364 for person 3 ... AND (367— N) for person N." }, { "code": null, "e": 9086, "s": 9032, "text": "If N is 30, put in the multiplication signs and boom!" }, { "code": null, "e": 9270, "s": 9086, "text": "366 x 365 x 364 x 363 x 362 x 361 x 360 x 359 x 358 x 357 x 356 x 355 x 354 x 353 x 352 x 351 x 350 x 349 x 348 x 347 x 346 x 345 x 344 x 343 x 342 x 341 x 340 x 339 x 338 x 337 = ..." }, { "code": null, "e": 9311, "s": 9270, "text": "Yuck, another big number with 77 digits." }, { "code": null, "e": 9397, "s": 9311, "text": "But, luckily for us, computers will just handle the division for us if we ask nicely." }, { "code": null, "e": 9619, "s": 9397, "text": "P(All 30 birthdays unique) = (366 x 365 x 364 x 363 x 362 x 361 x 360 x 359 x 358 x 357 x 356 x 355 x 354 x 353 x 352 x 351 x 350 x 349 x 348 x 347 x 346 x 345 x 344 x 343 x 342 x 341 x 340 x 339 x 338 x 337) / (366 ^ 30)" }, { "code": null, "e": 9676, "s": 9619, "text": "= 0.3 (rounded off to the capacity of my attention span)" }, { "code": null, "e": 9729, "s": 9676, "text": "P(Shared birthdays in a group of 30) = 1 — 0.3 = 70%" }, { "code": null, "e": 9792, "s": 9729, "text": "With a group of 30, there’s a ~70% chance of shared birthdays." }, { "code": null, "e": 9993, "s": 9792, "text": "I hope you didn’t bet me $10 that having shared birthdays was less likely than everyone born on a unique day in a group of 30... but if you did, I won’t say no if you’d like to donate it to Wikipedia." }, { "code": null, "e": 10279, "s": 9993, "text": "Taking the wrong side of the bet comes from underestimating just how hard it is to get a room without duplicates — if you’re the bouncer at the door tasked with turning away people whose birthday slots are taken, it won’t be very long before you turn away your first disappointed soul." }, { "code": null, "e": 10568, "s": 10279, "text": "With 2 minutes and R open on my laptop, I can plot the answer for any every choice of N. If you’re curious to know the actual numbers (50% happens at N = 23, 99% at N = 55), go ahead and play with my ugly-but-functional little code snippet below right in your browser, no installs needed." }, { "code": null, "e": 11098, "s": 10568, "text": "# Initialize settings for N = 1:probability <- 0numerator <- 366denominator <- 366# Loops are terrible in R, let's make one anyways:for (N in 2:80) { numerator <- numerator * (366 + 1 - N) denominator <- denominator * 366 p <- 1 - (numerator / denominator) probability <- c(probability, p)}# Look at the answer to 2 decimal places:paste(\"For N =\", 1:80, \"prob is\", round(probability, 2))# Plot!plot(1:80, probability, xlab = \"Group Size\", ylab = \"P(Shared birthdays)\", type = \"l\", col = \"red\", main = \"The Birthday Solution\")" }, { "code": null, "e": 11400, "s": 11098, "text": "Besides some probability basics (like different approaches to probability, complements, and what to put in the numerator and denominator), and counting principles (rule of sum and rule of product) the thing to take away from this article is why you’re being taught certain concepts in a certain order." }, { "code": null, "e": 11861, "s": 11400, "text": "Why is counting such a big deal early on in your textbook and then suddenly it disappears, leaving everyone disgruntled? Turns out that it’s mostly a means to an end, since the assumption that all elementary events are equally likely is too amateurish for most pros to stomach... even for birthdays. Isn’t it funny that when nonexperts think of what we stats folks do all day, they tend to think of card counting and coin tossing? Some rumors are hard to kill!" }, { "code": null, "e": 12312, "s": 11861, "text": "A big part of what makes the birthday problem a classic fixture of the statistics undergraduate experience is that it gives you just enough pain to rub a key point in: budding statisticians need to learn how to rephrase problems so their moving parts are easier to handle. The brute force approach is often too hard to calculate, so we learn to look sideways at things. If you opt for the statistics life, prepare for a lot of flipping and reversing." }, { "code": null, "e": 12515, "s": 12312, "text": "This article was intentionally different from my usual. It’s good to try new things sometimes to see if people like ‘em—if you want more where this came from, likes and shares are how you let me know. ❤" } ]
Advanced Python Visualizations in PowerBI | Towards Data Science
How the latest Python-PowerBI integration can be used to leverage the advanced visuals from python combined with the native data drill through and DAX functionalities The latest Python visual support completes the support for Python in Power BI, enabling you to use Python scripts to prepare your dataset, apply sophisticated analytics or machine learning in the Power BI Desktop, and then plot the results in your Power BI reports using any of the hundreds of open-source Python visualization packages. This visuals update with cross-filtering within the report and can be combined with DAX functionality. And this is a powerful combination which allows us to get the most out of the data by adding the interactivity. A Python visual can be added by selecting the Python visual icon from the Visualizations pane in the Power BI Desktop, which adds a placeholder Python script to the report. Required fields can be added from the dataset that we are working on into the values pane, which internally creates a Pandas DataFrame.We can then write custom scripts using libraries like Matplotlib and Seaborn to create the visuals. Native PowerBI functionalities such as slicers, filters can be used on top of the python visuals to make selections as required. The visuals will be updated dynamically. Here is a small tutorial on creating a custom visual in python and adding slicers to have an interactive visual experience of the story behind the data. The dataset consists of the list of movies from 2016 which had a IMdB score of 6 or more, along with the attributes — Budget, Gross, Genre and Scores.This dataset is publicly available on IMdB and other places like kaggle. A custom radial bar chart has been added into the script using Matplotlib. It takes the values from the dataframe on the fly according to the selections/filters applied. Slicers for selecting Genre, Country and score range were added directly in PowerBI and metrics like Average Score and Gross collections for the selected set are displayed. This allows us to explore the data comprehensively and make inferences as required. Code Snippet : # Import the librariesfrom matplotlib import pyplot as pltimport numpy as npdataset.sort_values('genre', inplace=True) # Creating values (budget amount) for the barsiN = len(dataset)arrCnts = dataset['budget']/10000000theta=np.arange(0,2*np.pi,2*np.pi/iN)width = (2*np.pi)/iN *0.9 # Plot size and proportionsfig = plt.figure(figsize=(20,18),frameon=False,dpi=200)# Adding radial axesax = fig.add_axes([0.05, 0.05, 0.9, 0.9], polar=True)bars = ax.bar(theta, arrCnts, width=width, bottom=15,color=dataset['Col'],alpha=0.65,edgecolor='yellow')ax.set_xticks(theta)plt.axis('off')plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)bottom = 15rotations = np.rad2deg(theta)y0,y1 = ax.get_ylim()# Adding radial tagsfor x, bar, rotation, label in zip(theta, bars, rotations, dataset['name']): offset = (bottom+bar.get_height())/(y1-y0) lab = ax.text(0, 0, label, transform=None, ha='center', va='center',alpha=0.5) renderer = ax.figure.canvas.get_renderer() bbox = lab.get_window_extent(renderer=renderer) invb = ax.transData.inverted().transform([[0,0],[bbox.width,0] ]) lab.set_position((x,offset+(invb[1][0]-invb[0][0])/2.*2.7 ) ) lab.set_transform(ax.get_xaxis_transform()) lab.set_rotation(rotation) fig.tight_layout()plt.show()---This code should be pasted in the script and the visual must be updated. This extension of python support brings a lot of possibilities as a powerful analytical framework, be it producing advanced visuals or complex machine learning algorithms using advanced python libraries and thereby making PowerBI a must in the field of data science. Check out my next blog on how to make histograms in PowerBI! https://sriharipramod.medium.com/advanced-python-visualizations-in-powerbi-histograms-and-frequency-plots-66f238684011 About the AuthorSrihari Pramod Data Analytics & Decision Science expert working on AI products and architectural technologies .Hyderabad,India.
[ { "code": null, "e": 339, "s": 172, "text": "How the latest Python-PowerBI integration can be used to leverage the advanced visuals from python combined with the native data drill through and DAX functionalities" }, { "code": null, "e": 676, "s": 339, "text": "The latest Python visual support completes the support for Python in Power BI, enabling you to use Python scripts to prepare your dataset, apply sophisticated analytics or machine learning in the Power BI Desktop, and then plot the results in your Power BI reports using any of the hundreds of open-source Python visualization packages." }, { "code": null, "e": 891, "s": 676, "text": "This visuals update with cross-filtering within the report and can be combined with DAX functionality. And this is a powerful combination which allows us to get the most out of the data by adding the interactivity." }, { "code": null, "e": 1064, "s": 891, "text": "A Python visual can be added by selecting the Python visual icon from the Visualizations pane in the Power BI Desktop, which adds a placeholder Python script to the report." }, { "code": null, "e": 1299, "s": 1064, "text": "Required fields can be added from the dataset that we are working on into the values pane, which internally creates a Pandas DataFrame.We can then write custom scripts using libraries like Matplotlib and Seaborn to create the visuals." }, { "code": null, "e": 1469, "s": 1299, "text": "Native PowerBI functionalities such as slicers, filters can be used on top of the python visuals to make selections as required. The visuals will be updated dynamically." }, { "code": null, "e": 1622, "s": 1469, "text": "Here is a small tutorial on creating a custom visual in python and adding slicers to have an interactive visual experience of the story behind the data." }, { "code": null, "e": 1845, "s": 1622, "text": "The dataset consists of the list of movies from 2016 which had a IMdB score of 6 or more, along with the attributes — Budget, Gross, Genre and Scores.This dataset is publicly available on IMdB and other places like kaggle." }, { "code": null, "e": 2015, "s": 1845, "text": "A custom radial bar chart has been added into the script using Matplotlib. It takes the values from the dataframe on the fly according to the selections/filters applied." }, { "code": null, "e": 2272, "s": 2015, "text": "Slicers for selecting Genre, Country and score range were added directly in PowerBI and metrics like Average Score and Gross collections for the selected set are displayed. This allows us to explore the data comprehensively and make inferences as required." }, { "code": null, "e": 2287, "s": 2272, "text": "Code Snippet :" }, { "code": null, "e": 3634, "s": 2287, "text": "# Import the librariesfrom matplotlib import pyplot as pltimport numpy as npdataset.sort_values('genre', inplace=True) # Creating values (budget amount) for the barsiN = len(dataset)arrCnts = dataset['budget']/10000000theta=np.arange(0,2*np.pi,2*np.pi/iN)width = (2*np.pi)/iN *0.9 # Plot size and proportionsfig = plt.figure(figsize=(20,18),frameon=False,dpi=200)# Adding radial axesax = fig.add_axes([0.05, 0.05, 0.9, 0.9], polar=True)bars = ax.bar(theta, arrCnts, width=width, bottom=15,color=dataset['Col'],alpha=0.65,edgecolor='yellow')ax.set_xticks(theta)plt.axis('off')plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)bottom = 15rotations = np.rad2deg(theta)y0,y1 = ax.get_ylim()# Adding radial tagsfor x, bar, rotation, label in zip(theta, bars, rotations, dataset['name']): offset = (bottom+bar.get_height())/(y1-y0) lab = ax.text(0, 0, label, transform=None, ha='center', va='center',alpha=0.5) renderer = ax.figure.canvas.get_renderer() bbox = lab.get_window_extent(renderer=renderer) invb = ax.transData.inverted().transform([[0,0],[bbox.width,0] ]) lab.set_position((x,offset+(invb[1][0]-invb[0][0])/2.*2.7 ) ) lab.set_transform(ax.get_xaxis_transform()) lab.set_rotation(rotation) fig.tight_layout()plt.show()---This code should be pasted in the script and the visual must be updated." }, { "code": null, "e": 3901, "s": 3634, "text": "This extension of python support brings a lot of possibilities as a powerful analytical framework, be it producing advanced visuals or complex machine learning algorithms using advanced python libraries and thereby making PowerBI a must in the field of data science." }, { "code": null, "e": 3962, "s": 3901, "text": "Check out my next blog on how to make histograms in PowerBI!" }, { "code": null, "e": 4081, "s": 3962, "text": "https://sriharipramod.medium.com/advanced-python-visualizations-in-powerbi-histograms-and-frequency-plots-66f238684011" }, { "code": null, "e": 4112, "s": 4081, "text": "About the AuthorSrihari Pramod" } ]
Some interesting facts about static member functions in C++ - GeeksforGeeks
30 Oct, 2020 1) static member functions do not have this pointer. For example following program fails in compilation with error “`this’ is unavailable for static member functions “ CPP #include<iostream>class Test { static Test * fun() { return this; // compiler error }}; int main(){ getchar(); return 0;} 2) A static member function cannot be virtual (See this G-Fact)3) Member function declarations with the same name and the name parameter-type-list cannot be overloaded if any of them is a static member function declaration. For example, following program fails in compilation with error “‘void Test::fun()’ and `static void Test::fun()’ cannot be overloaded “ CPP #include<iostream>class Test { static void fun() {} void fun() {} // compiler error}; int main(){ getchar(); return 0;} 4) A static member function can not be declared const, volatile, or const volatile. For example, following program fails in compilation with error “static member function `static void Test::fun()’ cannot have `const’ method qualifier ” CPP #include<iostream>class Test { static void fun() const { // compiler error return; }}; int main(){ getchar(); return 0;} Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.References: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf bhuvanchandra825 C++-Static Keyword Static Keyword C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Socket Programming in C/C++ Operator Overloading in C++ Multidimensional Arrays in C / C++ vector erase() and clear() in C++ rand() and srand() in C/C++ Templates in C++ with Examples unordered_map in C++ STL C++ Data Types Left Shift and Right Shift Operators in C/C++ Sorting a vector in C++
[ { "code": null, "e": 23759, "s": 23731, "text": "\n30 Oct, 2020" }, { "code": null, "e": 23927, "s": 23759, "text": "1) static member functions do not have this pointer. For example following program fails in compilation with error “`this’ is unavailable for static member functions “" }, { "code": null, "e": 23931, "s": 23927, "text": "CPP" }, { "code": "#include<iostream>class Test { static Test * fun() { return this; // compiler error }}; int main(){ getchar(); return 0;}", "e": 24071, "s": 23931, "text": null }, { "code": null, "e": 24431, "s": 24071, "text": "2) A static member function cannot be virtual (See this G-Fact)3) Member function declarations with the same name and the name parameter-type-list cannot be overloaded if any of them is a static member function declaration. For example, following program fails in compilation with error “‘void Test::fun()’ and `static void Test::fun()’ cannot be overloaded “" }, { "code": null, "e": 24435, "s": 24431, "text": "CPP" }, { "code": "#include<iostream>class Test { static void fun() {} void fun() {} // compiler error}; int main(){ getchar(); return 0;}", "e": 24564, "s": 24435, "text": null }, { "code": null, "e": 24801, "s": 24564, "text": "4) A static member function can not be declared const, volatile, or const volatile. For example, following program fails in compilation with error “static member function `static void Test::fun()’ cannot have `const’ method qualifier ” " }, { "code": null, "e": 24805, "s": 24801, "text": "CPP" }, { "code": "#include<iostream>class Test { static void fun() const { // compiler error return; }}; int main(){ getchar(); return 0;}", "e": 24944, "s": 24805, "text": null }, { "code": null, "e": 25146, "s": 24944, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.References: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf" }, { "code": null, "e": 25163, "s": 25146, "text": "bhuvanchandra825" }, { "code": null, "e": 25182, "s": 25163, "text": "C++-Static Keyword" }, { "code": null, "e": 25197, "s": 25182, "text": "Static Keyword" }, { "code": null, "e": 25201, "s": 25197, "text": "C++" }, { "code": null, "e": 25205, "s": 25201, "text": "CPP" }, { "code": null, "e": 25303, "s": 25205, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25312, "s": 25303, "text": "Comments" }, { "code": null, "e": 25325, "s": 25312, "text": "Old Comments" }, { "code": null, "e": 25353, "s": 25325, "text": "Socket Programming in C/C++" }, { "code": null, "e": 25381, "s": 25353, "text": "Operator Overloading in C++" }, { "code": null, "e": 25416, "s": 25381, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 25450, "s": 25416, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 25478, "s": 25450, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 25509, "s": 25478, "text": "Templates in C++ with Examples" }, { "code": null, "e": 25534, "s": 25509, "text": "unordered_map in C++ STL" }, { "code": null, "e": 25549, "s": 25534, "text": "C++ Data Types" }, { "code": null, "e": 25595, "s": 25549, "text": "Left Shift and Right Shift Operators in C/C++" } ]
Union of Two Sorted Arrays | Practice | GeeksforGeeks
Union of two arrays can be defined as the common and distinct elements in the two arrays. Given two sorted arrays of size n and m respectively, find their union. Example 1: Input: n = 5, arr1[] = {1, 2, 3, 4, 5} m = 3, arr2 [] = {1, 2, 3} Output: 1 2 3 4 5 Explanation: Distinct elements including both the arrays are: 1 2 3 4 5. Example 2: Input: n = 5, arr1[] = {2, 2, 3, 4, 5} m = 5, arr2[] = {1, 1, 2, 3, 4} Output: 1 2 3 4 5 Explanation: Distinct elements including both the arrays are: 1 2 3 4 5. Example 3: Input: n = 5, arr1[] = {1, 1, 1, 1, 1} m = 5, arr2[] = {2, 2, 2, 2, 2} Output: 1 2 Explanation: Distinct elements including both the arrays are: 1 2. Your Task: You do not need to read input or print anything. Complete the function findUnion() that takes two arrays arr1[], arr2[], and their size n and m as input parameters and returns a list containing the union of the two arrays. Expected Time Complexity: O(n+m). Expected Auxiliary Space: O(n+m). Constraints: 1 <= n, m <= 105 1 <= arr[i], brr[i] <= 106 0 codewithshoaib193 days ago public static ArrayList<Integer> findUnion(int arr1[], int arr2[], int n, int m) { // add your code here Set<Integer> set = new HashSet<Integer>(); ArrayList<Integer> list=new ArrayList<>(); for(int i=0;i<n;i++){ set.add(arr1[i]); } for(int i=0;i<m;i++){ set.add(arr2[i]); } list.addAll(set); Collections.sort(list); return list; } 0 harshscode1 week ago set<int> s; for(int i=0;i<n;i++) s.insert(a1[i]); for(int i=0;i<m;i++) s.insert(a2[i]); vector<int> v; for(auto x:s) v.push_back(x); return v; 0 mannukhurana103971 week ago java // all test case pass public static ArrayList<Integer> findUnion(int arr1[], int arr2[], int n, int m) { // N = m+n // time Complexity: O(N)*O(NlogN) // space 2(N) Set<Integer> set = new HashSet<Integer>(); int a=(m<n)?m:n; for(int i=0;i<a;i++){ set.addAll(arr1[i]); set.add(arr2[i]); } if(m<n) for(int i=a;i<n;i++) set.add(arr1[i]); else for(int i=a;i<m;i++) set.add(arr2[i]); ArrayList<Integer> lst = new ArrayList<Integer>(); lst.addAll(set); Collections.sort(lst); return lst; } // 90% test cases pass public static ArrayList<Integer> findUnion(int arr1[], int arr2[], int n, int m) { // time Complexity: O(m+n) // space O(m+n) ArrayList<Integer> lst = new ArrayList<Integer>(); int a = 0; int b = 0; while (a < n && b < m) { if(arr1[a]==arr2[b]){ if(!lst.contains(arr1[a])) lst.add(arr1[a]); a++;b++; } else if(arr1[a]<arr2[b]){ if(!lst.contains(arr1[a])) lst.add(arr1[a]); a++; } else{ if(!lst.contains(arr2[b])) lst.add(arr2[b]); b++; } } while (a < n) { if (!lst.contains(arr1[a])) lst.add(arr1[a]); a++; } while (b < m) { if (!lst.contains(arr2[b])) lst.add(arr2[b]); b++; } return lst; } 0 nikhilpmsnick1 week ago vector<int> findUnion(int arr1[], int arr2[], int n, int m) { //Your code here //return vector with correct order of elements vector<int> ans; set<int> s; for(int i=0;i<n;i++) { s.insert(arr1[i]); } for(int i=0;i<m;i++) { s.insert(arr2[i]); } for(auto it=s.begin() ; it!=s.end() ; it++) { ans.push_back(*it); } return ans; } 0 vishutyagi71 week ago c++ easy with stl solution map<int,int> m1; vector<int> v; int i; for(i=0;i<n;i++) { m1[arr1[i]]++; } for(i=0;i<m;i++) { m1[arr2[i]]++; } auto it=m1.begin(); while(it!=m1.end()) { v.push_back(it->first); ++it; } return v; 0 pradeepshillare1 week ago ...........JAVA......... class Solution{ public static ArrayList<Integer> findUnion(int arr1[], int arr2[], int n, int m) { HashSet<Integer> hs = new HashSet<>(); for(int i=0;i<arr1.length;i++) { hs.add(arr1[i]); } for(int i=0;i<arr2.length;i++) { if(!hs.contains(arr2[i])) { hs.add(arr2[i]); } } ArrayList<Integer> list = new ArrayList<>(hs); Collections.sort(list); return list; }} 0 nrod1231 week ago Java Solution! super easy public static ArrayList<Integer> findUnion(int arr1[], int arr2[], int n, int m) { // add your code here TreeSet<Integer> uniqueElements = new TreeSet<>(); if (n > m) { for (int i = 0; i < m; i++) { uniqueElements.add(arr1[i]); uniqueElements.add(arr2[i]); } for (int j = m; j < n; j++) { uniqueElements.add(arr1[j]); } } else { for (int i = 0; i < n; i++) { uniqueElements.add(arr1[i]); uniqueElements.add(arr2[i]); } for (int j = n - 1; j < m; j++) { uniqueElements.add(arr2[j]); } } // System.out.println(uniqueElements); return new ArrayList<>(uniqueElements); } 0 haulya2 weeks ago vector<int> findUnion(int arr1[], int arr2[], int n, int m) { //Your code here //return vector with correct order of elements int i=0; int j = 0; vector<int> res; while (i < n && j < m){ if(i > 0 && arr1[i] == arr1[i-1]) { i++; continue; } if(j > 0 && arr2[j] == arr2[j-1]){ j++; continue; } if(arr1[i] == arr2[j]) { res.push_back(arr1[i]); i++; j++; } else if(arr1[i] < arr2[j]) {res.push_back(arr1[i]); i++;} else if(arr1[i] > arr2[j]) {res.push_back(arr2[j]); j++;} } while(i < n) { if(i > 0 && arr1[i] == arr1[i-1]) { i++; continue; } res.push_back(arr1[i]); i++; } while (j < m) { if(j > 0 && arr2[j] == arr2[j-1]){ j++; continue; } res.push_back(arr2[j]); j++; } return res; } 0 mayank180919992 weeks ago vector<int> findUnion(int arr1[], int arr2[], int n, int m) { //Your code here //return vector with correct order of elements set<int>s; vector<int>nums; for(int i=0;i<n;i++){ s.insert(arr1[i]); } for(int i=0;i<m;i++){ s.insert(arr2[i]); } for(auto it:s){ nums.push_back(it); } return nums; } 0 shubham211019972 weeks ago vector<int>v; int i=0,j=0; while(i<n1&&j<n2){ if(i>0 && arr1[i]==arr1[i-1]){ i++; continue; } if(j>0 && arr2[j]==arr2[j-1]){ j++; continue; } if(arr1[i]==arr2[j]){ v.push_back(arr1[i]); i++; j++; } else if(arr1[i]<arr2[j]){ v.push_back(arr1[i]); i++; } else{ v.push_back(arr2[j]); j++; } } while(i<n1){ if(i>0 && arr1[i]==arr1[i-1]){ i++; continue; }else{ v.push_back(arr1[i]); i++; } } while(j<n2){ if(j>0 && arr2[j]==arr2[j-1]){ j++; continue; }else{ v.push_back(arr2[j]); j++; } } return v; } 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": 400, "s": 238, "text": "Union of two arrays can be defined as the common and distinct elements in the two arrays.\nGiven two sorted arrays of size n and m respectively, find their union." }, { "code": null, "e": 412, "s": 400, "text": "\nExample 1:" }, { "code": null, "e": 573, "s": 412, "text": "Input: \nn = 5, arr1[] = {1, 2, 3, 4, 5} \nm = 3, arr2 [] = {1, 2, 3}\nOutput: 1 2 3 4 5\nExplanation: Distinct elements including \nboth the arrays are: 1 2 3 4 5." }, { "code": null, "e": 586, "s": 575, "text": "Example 2:" }, { "code": null, "e": 752, "s": 586, "text": "Input: \nn = 5, arr1[] = {2, 2, 3, 4, 5} \nm = 5, arr2[] = {1, 1, 2, 3, 4}\nOutput: 1 2 3 4 5\nExplanation: Distinct elements including \nboth the arrays are: 1 2 3 4 5." }, { "code": null, "e": 765, "s": 754, "text": "Example 3:" }, { "code": null, "e": 916, "s": 765, "text": "Input:\nn = 5, arr1[] = {1, 1, 1, 1, 1}\nm = 5, arr2[] = {2, 2, 2, 2, 2}\nOutput: 1 2\nExplanation: Distinct elements including \nboth the arrays are: 1 2." }, { "code": null, "e": 1155, "s": 916, "text": "\nYour Task: \nYou do not need to read input or print anything. Complete the function findUnion() that takes two arrays arr1[], arr2[], and their size n and m as input parameters and returns a list containing the union of the two arrays. \n " }, { "code": null, "e": 1225, "s": 1155, "text": "Expected Time Complexity: O(n+m).\nExpected Auxiliary Space: O(n+m).\n " }, { "code": null, "e": 1282, "s": 1225, "text": "Constraints:\n1 <= n, m <= 105\n1 <= arr[i], brr[i] <= 106" }, { "code": null, "e": 1284, "s": 1282, "text": "0" }, { "code": null, "e": 1311, "s": 1284, "text": "codewithshoaib193 days ago" }, { "code": null, "e": 1729, "s": 1311, "text": "public static ArrayList<Integer> findUnion(int arr1[], int arr2[], int n, int m) { // add your code here Set<Integer> set = new HashSet<Integer>(); ArrayList<Integer> list=new ArrayList<>(); for(int i=0;i<n;i++){ set.add(arr1[i]); } for(int i=0;i<m;i++){ set.add(arr2[i]); } list.addAll(set); Collections.sort(list); return list; }" }, { "code": null, "e": 1731, "s": 1729, "text": "0" }, { "code": null, "e": 1752, "s": 1731, "text": "harshscode1 week ago" }, { "code": null, "e": 1972, "s": 1752, "text": " set<int> s; for(int i=0;i<n;i++) s.insert(a1[i]); for(int i=0;i<m;i++) s.insert(a2[i]); vector<int> v; for(auto x:s) v.push_back(x); return v;" }, { "code": null, "e": 1974, "s": 1972, "text": "0" }, { "code": null, "e": 2002, "s": 1974, "text": "mannukhurana103971 week ago" }, { "code": null, "e": 2007, "s": 2002, "text": "java" }, { "code": null, "e": 2031, "s": 2009, "text": "// all test case pass" }, { "code": null, "e": 2742, "s": 2031, "text": "\npublic static ArrayList<Integer> findUnion(int arr1[], int arr2[], int n, int m) {\n // N = m+n\n // time Complexity: O(N)*O(NlogN)\n // space 2(N)\n \n Set<Integer> set = new HashSet<Integer>();\n\n \n int a=(m<n)?m:n;\n\n for(int i=0;i<a;i++){ \n set.addAll(arr1[i]);\n set.add(arr2[i]);\n }\n \n if(m<n)\n for(int i=a;i<n;i++)\n set.add(arr1[i]);\n else\n for(int i=a;i<m;i++)\n set.add(arr2[i]);\n \n \n ArrayList<Integer> lst = new ArrayList<Integer>();\n lst.addAll(set);\n Collections.sort(lst);\n \n return lst;\n }" }, { "code": null, "e": 2767, "s": 2744, "text": "// 90% test cases pass" }, { "code": null, "e": 3726, "s": 2767, "text": "\npublic static ArrayList<Integer> findUnion(int arr1[], int arr2[], int n, int m) {\n\n // time Complexity: O(m+n)\n // space O(m+n)\n ArrayList<Integer> lst = new ArrayList<Integer>();\n\n int a = 0;\n int b = 0;\n\n while (a < n && b < m) { \n if(arr1[a]==arr2[b]){ \n if(!lst.contains(arr1[a]))\n \n lst.add(arr1[a]);\n a++;b++;\n }\n else if(arr1[a]<arr2[b]){ \n if(!lst.contains(arr1[a])) lst.add(arr1[a]);\n a++;\n }\n else{\n if(!lst.contains(arr2[b])) lst.add(arr2[b]);\n b++;\n }\n \n }\n\n while (a < n) {\n if (!lst.contains(arr1[a])) lst.add(arr1[a]);\n a++;\n }\n\n while (b < m) {\n if (!lst.contains(arr2[b])) lst.add(arr2[b]);\n b++;\n }\n\n \n return lst;\n }" }, { "code": null, "e": 3732, "s": 3730, "text": "0" }, { "code": null, "e": 3756, "s": 3732, "text": "nikhilpmsnick1 week ago" }, { "code": null, "e": 4220, "s": 3756, "text": "vector<int> findUnion(int arr1[], int arr2[], int n, int m) { //Your code here //return vector with correct order of elements vector<int> ans; set<int> s; for(int i=0;i<n;i++) { s.insert(arr1[i]); } for(int i=0;i<m;i++) { s.insert(arr2[i]); } for(auto it=s.begin() ; it!=s.end() ; it++) { ans.push_back(*it); } return ans; }" }, { "code": null, "e": 4222, "s": 4220, "text": "0" }, { "code": null, "e": 4244, "s": 4222, "text": "vishutyagi71 week ago" }, { "code": null, "e": 4271, "s": 4244, "text": "c++ easy with stl solution" }, { "code": null, "e": 4586, "s": 4273, "text": "map<int,int> m1; vector<int> v; int i; for(i=0;i<n;i++) { m1[arr1[i]]++; } for(i=0;i<m;i++) { m1[arr2[i]]++; } auto it=m1.begin(); while(it!=m1.end()) { v.push_back(it->first); ++it; } return v;" }, { "code": null, "e": 4588, "s": 4586, "text": "0" }, { "code": null, "e": 4614, "s": 4588, "text": "pradeepshillare1 week ago" }, { "code": null, "e": 4639, "s": 4614, "text": "...........JAVA........." }, { "code": null, "e": 5128, "s": 4639, "text": "class Solution{ public static ArrayList<Integer> findUnion(int arr1[], int arr2[], int n, int m) { HashSet<Integer> hs = new HashSet<>(); for(int i=0;i<arr1.length;i++) { hs.add(arr1[i]); } for(int i=0;i<arr2.length;i++) { if(!hs.contains(arr2[i])) { hs.add(arr2[i]); } } ArrayList<Integer> list = new ArrayList<>(hs); Collections.sort(list); return list; }} " }, { "code": null, "e": 5130, "s": 5128, "text": "0" }, { "code": null, "e": 5148, "s": 5130, "text": "nrod1231 week ago" }, { "code": null, "e": 6028, "s": 5148, "text": "Java Solution! super easy\n\n public static ArrayList<Integer> findUnion(int arr1[], int arr2[], int n, int m)\n {\n // add your code here\n TreeSet<Integer> uniqueElements = new TreeSet<>();\n if (n > m) {\n for (int i = 0; i < m; i++) {\n uniqueElements.add(arr1[i]);\n uniqueElements.add(arr2[i]);\n }\n for (int j = m; j < n; j++) {\n uniqueElements.add(arr1[j]);\n }\n } else {\n for (int i = 0; i < n; i++) {\n uniqueElements.add(arr1[i]);\n uniqueElements.add(arr2[i]);\n }\n for (int j = n - 1; j < m; j++) {\n uniqueElements.add(arr2[j]);\n }\n }\n \n // System.out.println(uniqueElements);\n \n return new ArrayList<>(uniqueElements);\n }" }, { "code": null, "e": 6030, "s": 6028, "text": "0" }, { "code": null, "e": 6048, "s": 6030, "text": "haulya2 weeks ago" }, { "code": null, "e": 7024, "s": 6048, "text": " vector<int> findUnion(int arr1[], int arr2[], int n, int m) { //Your code here //return vector with correct order of elements int i=0; int j = 0; vector<int> res; while (i < n && j < m){ if(i > 0 && arr1[i] == arr1[i-1]) { i++; continue; } if(j > 0 && arr2[j] == arr2[j-1]){ j++; continue; } if(arr1[i] == arr2[j]) { res.push_back(arr1[i]); i++; j++; } else if(arr1[i] < arr2[j]) {res.push_back(arr1[i]); i++;} else if(arr1[i] > arr2[j]) {res.push_back(arr2[j]); j++;} } while(i < n) { if(i > 0 && arr1[i] == arr1[i-1]) { i++; continue; } res.push_back(arr1[i]); i++; } while (j < m) { if(j > 0 && arr2[j] == arr2[j-1]){ j++; continue; } res.push_back(arr2[j]); j++; } return res; }" }, { "code": null, "e": 7026, "s": 7024, "text": "0" }, { "code": null, "e": 7052, "s": 7026, "text": "mayank180919992 weeks ago" }, { "code": null, "e": 7474, "s": 7052, "text": " vector<int> findUnion(int arr1[], int arr2[], int n, int m)\n {\n //Your code here\n //return vector with correct order of elements\n set<int>s;\n vector<int>nums;\n for(int i=0;i<n;i++){\n s.insert(arr1[i]);\n }\n for(int i=0;i<m;i++){\n s.insert(arr2[i]);\n }\n for(auto it:s){\n nums.push_back(it);\n }\n return nums;\n }" }, { "code": null, "e": 7476, "s": 7474, "text": "0" }, { "code": null, "e": 7503, "s": 7476, "text": "shubham211019972 weeks ago" }, { "code": null, "e": 8484, "s": 7503, "text": "vector<int>v; int i=0,j=0; while(i<n1&&j<n2){ if(i>0 && arr1[i]==arr1[i-1]){ i++; continue; } if(j>0 && arr2[j]==arr2[j-1]){ j++; continue; } if(arr1[i]==arr2[j]){ v.push_back(arr1[i]); i++; j++; } else if(arr1[i]<arr2[j]){ v.push_back(arr1[i]); i++; } else{ v.push_back(arr2[j]); j++; } } while(i<n1){ if(i>0 && arr1[i]==arr1[i-1]){ i++; continue; }else{ v.push_back(arr1[i]); i++; } } while(j<n2){ if(j>0 && arr2[j]==arr2[j-1]){ j++; continue; }else{ v.push_back(arr2[j]); j++; } } return v; }" }, { "code": null, "e": 8630, "s": 8484, "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": 8666, "s": 8630, "text": " Login to access your submissions. " }, { "code": null, "e": 8676, "s": 8666, "text": "\nProblem\n" }, { "code": null, "e": 8686, "s": 8676, "text": "\nContest\n" }, { "code": null, "e": 8749, "s": 8686, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8897, "s": 8749, "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": 9105, "s": 8897, "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": 9211, "s": 9105, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to disable MySQL foreign key checks and what are the benefits of disabling it?
We can disable foreign key checks with the help of the following statement − mysql> Set foreign_key_checks = 0; Query OK, 0 rows affected (0.00 sec) And we can enable it with the help of the following statement − mysql> Set foreign_key_checks = 1; Query OK, 0 rows affected (0.00 sec) Some benefits of disabling foreign key checks are as follows − After disabling foreign key checks we can load data into parent and child table in any order. Otherwise, we must have to load the data first in the parent table and then in the child table. Without disabling foreign key checks we cannot drop a table that is referenced by a foreign key constraint.
[ { "code": null, "e": 1139, "s": 1062, "text": "We can disable foreign key checks with the help of the following statement −" }, { "code": null, "e": 1211, "s": 1139, "text": "mysql> Set foreign_key_checks = 0;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1275, "s": 1211, "text": "And we can enable it with the help of the following statement −" }, { "code": null, "e": 1347, "s": 1275, "text": "mysql> Set foreign_key_checks = 1;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1410, "s": 1347, "text": "Some benefits of disabling foreign key checks are as follows −" }, { "code": null, "e": 1600, "s": 1410, "text": "After disabling foreign key checks we can load data into parent and child table in any order. Otherwise, we must have to load the data first in the parent table and then in the child table." }, { "code": null, "e": 1708, "s": 1600, "text": "Without disabling foreign key checks we cannot drop a table that is referenced by a foreign key constraint." } ]
Dart Programming - Map
The Map object is a simple key/value pair. Keys and values in a map may be of any type. A Map is a dynamic collection. In other words, Maps can grow and shrink at runtime. Maps can be declared in two ways − Using Map Literals Using a Map constructor To declare a map using map literals, you need to enclose the key-value pairs within a pair of curly brackets "{ }". Here is its syntax − var identifier = { key1:value1, key2:value2 [,.....,key_n:value_n] } To declare a Map using a Map constructor, we have two steps. First, declare the map and second, initialize the map. The syntax to declare a map is as follows − var identifier = new Map() Now, use the following syntax to initialize the map − map_name[key] = value void main() { var details = {'Usrname':'tom','Password':'pass@123'}; print(details); } It will produce the following output − {Usrname: tom, Password: pass@123} void main() { var details = {'Usrname':'tom','Password':'pass@123'}; details['Uid'] = 'U1oo1'; print(details); } It will produce the following output − {Usrname: tom, Password: pass@123, Uid: U1oo1} void main() { var details = new Map(); details['Usrname'] = 'admin'; details['Password'] = 'admin@123'; print(details); } It will produce the following output − {Usrname: admin, Password: admin@123} Note − A map value can be any object including NULL. The Map class in the dart:core package defines the following properties − Returns an iterable object representing keys Returns an iterable object representing values Returns the size of the Map Returns true if the Map is an empty Map Returns true if the Map is an empty Map Following are the commonly used functions for manipulating Maps in Dart. Adds all key-value pairs of other to this map. Removes all pairs from the map. Removes key and its associated value, if present, from the map. Applies f to each key-value pair of the map. 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2697, "s": 2525, "text": "The Map object is a simple key/value pair. Keys and values in a map may be of any type. A Map is a dynamic collection. In other words, Maps can grow and shrink at runtime." }, { "code": null, "e": 2732, "s": 2697, "text": "Maps can be declared in two ways −" }, { "code": null, "e": 2751, "s": 2732, "text": "Using Map Literals" }, { "code": null, "e": 2775, "s": 2751, "text": "Using a Map constructor" }, { "code": null, "e": 2892, "s": 2775, "text": "To declare a map using map literals, you need to enclose the key-value pairs within a pair of curly brackets \"{ }\"." }, { "code": null, "e": 2913, "s": 2892, "text": "Here is its syntax −" }, { "code": null, "e": 2983, "s": 2913, "text": "var identifier = { key1:value1, key2:value2 [,.....,key_n:value_n] }\n" }, { "code": null, "e": 3099, "s": 2983, "text": "To declare a Map using a Map constructor, we have two steps. First, declare the map and second, initialize the map." }, { "code": null, "e": 3143, "s": 3099, "text": "The syntax to declare a map is as follows −" }, { "code": null, "e": 3171, "s": 3143, "text": "var identifier = new Map()\n" }, { "code": null, "e": 3225, "s": 3171, "text": "Now, use the following syntax to initialize the map −" }, { "code": null, "e": 3248, "s": 3225, "text": "map_name[key] = value\n" }, { "code": null, "e": 3344, "s": 3248, "text": "void main() { \n var details = {'Usrname':'tom','Password':'pass@123'}; \n print(details); \n}" }, { "code": null, "e": 3383, "s": 3344, "text": "It will produce the following output −" }, { "code": null, "e": 3419, "s": 3383, "text": "{Usrname: tom, Password: pass@123}\n" }, { "code": null, "e": 3546, "s": 3419, "text": "void main() { \n var details = {'Usrname':'tom','Password':'pass@123'}; \n details['Uid'] = 'U1oo1'; \n print(details); \n} " }, { "code": null, "e": 3585, "s": 3546, "text": "It will produce the following output −" }, { "code": null, "e": 3633, "s": 3585, "text": "{Usrname: tom, Password: pass@123, Uid: U1oo1}\n" }, { "code": null, "e": 3773, "s": 3633, "text": "void main() { \n var details = new Map(); \n details['Usrname'] = 'admin'; \n details['Password'] = 'admin@123'; \n print(details); \n} " }, { "code": null, "e": 3812, "s": 3773, "text": "It will produce the following output −" }, { "code": null, "e": 3851, "s": 3812, "text": "{Usrname: admin, Password: admin@123}\n" }, { "code": null, "e": 3904, "s": 3851, "text": "Note − A map value can be any object including NULL." }, { "code": null, "e": 3978, "s": 3904, "text": "The Map class in the dart:core package defines the following properties −" }, { "code": null, "e": 4023, "s": 3978, "text": "Returns an iterable object representing keys" }, { "code": null, "e": 4070, "s": 4023, "text": "Returns an iterable object representing values" }, { "code": null, "e": 4098, "s": 4070, "text": "Returns the size of the Map" }, { "code": null, "e": 4138, "s": 4098, "text": "Returns true if the Map is an empty Map" }, { "code": null, "e": 4178, "s": 4138, "text": "Returns true if the Map is an empty Map" }, { "code": null, "e": 4251, "s": 4178, "text": "Following are the commonly used functions for manipulating Maps in Dart." }, { "code": null, "e": 4298, "s": 4251, "text": "Adds all key-value pairs of other to this map." }, { "code": null, "e": 4330, "s": 4298, "text": "Removes all pairs from the map." }, { "code": null, "e": 4394, "s": 4330, "text": "Removes key and its associated value, if present, from the map." }, { "code": null, "e": 4439, "s": 4394, "text": "Applies f to each key-value pair of the map." }, { "code": null, "e": 4474, "s": 4439, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4494, "s": 4474, "text": " Sriyank Siddhartha" }, { "code": null, "e": 4527, "s": 4494, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 4547, "s": 4527, "text": " Sriyank Siddhartha" }, { "code": null, "e": 4580, "s": 4547, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 4597, "s": 4580, "text": " Frahaan Hussain" }, { "code": null, "e": 4632, "s": 4597, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 4649, "s": 4632, "text": " Frahaan Hussain" }, { "code": null, "e": 4684, "s": 4649, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4704, "s": 4684, "text": " Pranjal Srivastava" }, { "code": null, "e": 4737, "s": 4704, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 4757, "s": 4737, "text": " Pranjal Srivastava" }, { "code": null, "e": 4764, "s": 4757, "text": " Print" }, { "code": null, "e": 4775, "s": 4764, "text": " Add Notes" } ]
C# Bitwise and Bit Shift Operators
Bitwise operator works on bits and performs bit by bit operation. The Bitwise operators supported by C# are listed in the following table. Assume variable A holds 60 and variable B holds 13 − The following is an example showing how to implement the Bitwise operators in C#. Live Demo using System; namespace MyApplication { class Program { static void Main(string[] args) { int a = 60; /* 60 = 0011 1100 */ int b = 13; /* 13 = 0000 1101 */ int c = 0; // Bitwise AND Operator c = a &amp; b; /* 12 = 0000 1100 */ Console.WriteLine("Line 1 - Value of c is {0}", c ); // Bitwise OR Operator c = a | b; /* 61 = 0011 1101 */ Console.WriteLine("Line 2 - Value of c is {0}", c); // Bitwise XOR Operator c = a ^ b; /* 49 = 0011 0001 */ Console.WriteLine("Line 3 - Value of c is {0}", c); // Bitwise Complement Operator c = ~a; /*-61 = 1100 0011 */ Console.WriteLine("Line 4 - Value of c is {0}", c); // Bitwise Left Shift Operator c = a << 2; /* 240 = 1111 0000 */ Console.WriteLine("Line 5 - Value of c is {0}", c); // Bitwise Right Shift Operator c = a >> 2; /* 15 = 0000 1111 */ Console.WriteLine("Line 6 - Value of c is {0}", c); Console.ReadLine(); } } } Line 1 - Value of c is 12 Line 2 - Value of c is 61 Line 3 - Value of c is 49 Line 4 - Value of c is -61 Line 5 - Value of c is 240 Line 6 - Value of c is 15
[ { "code": null, "e": 1128, "s": 1062, "text": "Bitwise operator works on bits and performs bit by bit operation." }, { "code": null, "e": 1254, "s": 1128, "text": "The Bitwise operators supported by C# are listed in the following table. Assume variable A holds 60 and variable B holds 13 −" }, { "code": null, "e": 1336, "s": 1254, "text": "The following is an example showing how to implement the Bitwise operators in C#." }, { "code": null, "e": 1346, "s": 1336, "text": "Live Demo" }, { "code": null, "e": 2429, "s": 1346, "text": "using System;\nnamespace MyApplication {\n class Program {\n static void Main(string[] args) {\n int a = 60; /* 60 = 0011 1100 */\n int b = 13; /* 13 = 0000 1101 */\n int c = 0;\n // Bitwise AND Operator\n c = a &amp; b; /* 12 = 0000 1100 */\n Console.WriteLine(\"Line 1 - Value of c is {0}\", c );\n // Bitwise OR Operator\n c = a | b; /* 61 = 0011 1101 */\n Console.WriteLine(\"Line 2 - Value of c is {0}\", c);\n // Bitwise XOR Operator\n c = a ^ b; /* 49 = 0011 0001 */\n Console.WriteLine(\"Line 3 - Value of c is {0}\", c);\n // Bitwise Complement Operator\n c = ~a; /*-61 = 1100 0011 */\n Console.WriteLine(\"Line 4 - Value of c is {0}\", c);\n // Bitwise Left Shift Operator\n c = a << 2; /* 240 = 1111 0000 */\n Console.WriteLine(\"Line 5 - Value of c is {0}\", c);\n // Bitwise Right Shift Operator\n c = a >> 2; /* 15 = 0000 1111 */\n Console.WriteLine(\"Line 6 - Value of c is {0}\", c);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2587, "s": 2429, "text": "Line 1 - Value of c is 12\nLine 2 - Value of c is 61\nLine 3 - Value of c is 49\nLine 4 - Value of c is -61\nLine 5 - Value of c is 240\nLine 6 - Value of c is 15" } ]
IPC using Message Queues
Why do we need message queues when we already have the shared memory? It would be for multiple reasons, let us try to break this into multiple points for simplification − As understood, once the message is received by a process it would be no longer available for any other process. Whereas in shared memory, the data is available for multiple processes to access. As understood, once the message is received by a process it would be no longer available for any other process. Whereas in shared memory, the data is available for multiple processes to access. If we want to communicate with small message formats. If we want to communicate with small message formats. Shared memory data need to be protected with synchronization when multiple processes communicating at the same time. Shared memory data need to be protected with synchronization when multiple processes communicating at the same time. Frequency of writing and reading using the shared memory is high, then it would be very complex to implement the functionality. Not worth with regard to utilization in this kind of cases. Frequency of writing and reading using the shared memory is high, then it would be very complex to implement the functionality. Not worth with regard to utilization in this kind of cases. What if all the processes do not need to access the shared memory but very few processes only need it, it would be better to implement with message queues. What if all the processes do not need to access the shared memory but very few processes only need it, it would be better to implement with message queues. If we want to communicate with different data packets, say process A is sending message type 1 to process B, message type 10 to process C, and message type 20 to process D. In this case, it is simplier to implement with message queues. To simplify the given message type as 1, 10, 20, it can be either 0 or +ve or –ve as discussed below. If we want to communicate with different data packets, say process A is sending message type 1 to process B, message type 10 to process C, and message type 20 to process D. In this case, it is simplier to implement with message queues. To simplify the given message type as 1, 10, 20, it can be either 0 or +ve or –ve as discussed below. Ofcourse, the order of message queue is FIFO (First In First Out). The first message inserted in the queue is the first one to be retrieved. Ofcourse, the order of message queue is FIFO (First In First Out). The first message inserted in the queue is the first one to be retrieved. Using Shared Memory or Message Queues depends on the need of the application and how effectively it can be utilized. Communication using message queues can happen in the following ways − Writing into the shared memory by one process and reading from the shared memory by another process. As we are aware, reading can be done with multiple processes as well. Writing into the shared memory by one process and reading from the shared memory by another process. As we are aware, reading can be done with multiple processes as well. Writing into the shared memory by one process with different data packets and reading from it by multiple processes, i.e., as per message type. Having seen certain information on message queues, now it is time to check for the system call (System V) which supports the message queues. To perform communication using message queues, following are the steps − Step 1 − Create a message queue or connect to an already existing message queue (msgget()) Step 2 − Write into message queue (msgsnd()) Step 3 − Read from the message queue (msgrcv()) Step 4 − Perform control operations on the message queue (msgctl()) Here we will create two processes. One can write and another can read. Let us see how the reader and writer processes are working using shared memory. #include <stdio.h> #include <sys/ipc.h> #include <sys/msg.h> // structure for message queue struct msg_buffer { long msg_type; char msg[100]; } message; main() { key_t my_key; int msg_id; my_key = ftok("progfile", 65); //create unique key msg_id = msgget(my_key, 0666 | IPC_CREAT); //create message queue and return id message.msg_type = 1; printf("Write Message : "); fgets(message.msg, 100, stdin); msgsnd(msg_id, &message, sizeof(message), 0); //send message printf("Sent message is : %s \n", message.msg); } #include <stdio.h> #include <sys/ipc.h> #include <sys/msg.h> // Define message queue structure struct msg_buffer { long msg_type; char msg[100]; } message; main() { key_t my_key; int msg_id; my_key = ftok("progfile", 65); //create unique key msg_id = msgget(my_key, 0666 | IPC_CREAT); //create message queue and return id msgrcv(msg_id, &message, sizeof(message), 1, 0); //used to receive message // display the message printf("Received Message is : %s \n", message.msg); msgctl(msg_id, IPC_RMID, NULL); //destroy the message queue return 0; }
[ { "code": null, "e": 1233, "s": 1062, "text": "Why do we need message queues when we already have the shared memory? It would be for multiple reasons, let us try to break this into multiple points for simplification −" }, { "code": null, "e": 1427, "s": 1233, "text": "As understood, once the message is received by a process it would be no longer available for any other process. Whereas in shared memory, the data is available for multiple processes to access." }, { "code": null, "e": 1621, "s": 1427, "text": "As understood, once the message is received by a process it would be no longer available for any other process. Whereas in shared memory, the data is available for multiple processes to access." }, { "code": null, "e": 1675, "s": 1621, "text": "If we want to communicate with small message formats." }, { "code": null, "e": 1729, "s": 1675, "text": "If we want to communicate with small message formats." }, { "code": null, "e": 1846, "s": 1729, "text": "Shared memory data need to be protected with synchronization when multiple processes communicating at the same time." }, { "code": null, "e": 1963, "s": 1846, "text": "Shared memory data need to be protected with synchronization when multiple processes communicating at the same time." }, { "code": null, "e": 2151, "s": 1963, "text": "Frequency of writing and reading using the shared memory is high, then it would be very complex to implement the functionality. Not worth with regard to utilization in this kind of cases." }, { "code": null, "e": 2339, "s": 2151, "text": "Frequency of writing and reading using the shared memory is high, then it would be very complex to implement the functionality. Not worth with regard to utilization in this kind of cases." }, { "code": null, "e": 2495, "s": 2339, "text": "What if all the processes do not need to access the shared memory but very few processes only need it, it would be better to implement with message queues." }, { "code": null, "e": 2651, "s": 2495, "text": "What if all the processes do not need to access the shared memory but very few processes only need it, it would be better to implement with message queues." }, { "code": null, "e": 2989, "s": 2651, "text": "If we want to communicate with different data packets, say process A is sending message type 1 to process B, message type 10 to process C, and message type 20 to process D. In this case, it is simplier to implement with message queues. To simplify the given message type as 1, 10, 20, it can be either 0 or +ve or –ve as discussed below." }, { "code": null, "e": 3327, "s": 2989, "text": "If we want to communicate with different data packets, say process A is sending message type 1 to process B, message type 10 to process C, and message type 20 to process D. In this case, it is simplier to implement with message queues. To simplify the given message type as 1, 10, 20, it can be either 0 or +ve or –ve as discussed below." }, { "code": null, "e": 3468, "s": 3327, "text": "Ofcourse, the order of message queue is FIFO (First In First Out). The first message inserted in the queue is the first one to be retrieved." }, { "code": null, "e": 3609, "s": 3468, "text": "Ofcourse, the order of message queue is FIFO (First In First Out). The first message inserted in the queue is the first one to be retrieved." }, { "code": null, "e": 3726, "s": 3609, "text": "Using Shared Memory or Message Queues depends on the need of the application and how effectively it can be utilized." }, { "code": null, "e": 3796, "s": 3726, "text": "Communication using message queues can happen in the following ways −" }, { "code": null, "e": 3967, "s": 3796, "text": "Writing into the shared memory by one process and reading from the shared memory by another process. As we are aware, reading can be done with multiple processes as well." }, { "code": null, "e": 4138, "s": 3967, "text": "Writing into the shared memory by one process and reading from the shared memory by another process. As we are aware, reading can be done with multiple processes as well." }, { "code": null, "e": 4282, "s": 4138, "text": "Writing into the shared memory by one process with different data packets and reading from it by multiple processes, i.e., as per message type." }, { "code": null, "e": 4423, "s": 4282, "text": "Having seen certain information on message queues, now it is time to check for the system call (System V) which supports the message queues." }, { "code": null, "e": 4496, "s": 4423, "text": "To perform communication using message queues, following are the steps −" }, { "code": null, "e": 4587, "s": 4496, "text": "Step 1 − Create a message queue or connect to an already existing message queue (msgget())" }, { "code": null, "e": 4632, "s": 4587, "text": "Step 2 − Write into message queue (msgsnd())" }, { "code": null, "e": 4680, "s": 4632, "text": "Step 3 − Read from the message queue (msgrcv())" }, { "code": null, "e": 4748, "s": 4680, "text": "Step 4 − Perform control operations on the message queue (msgctl())" }, { "code": null, "e": 4899, "s": 4748, "text": "Here we will create two processes. One can write and another can read. Let us see how the reader and writer processes are working using shared memory." }, { "code": null, "e": 5444, "s": 4899, "text": "#include <stdio.h>\n#include <sys/ipc.h>\n#include <sys/msg.h>\n// structure for message queue\nstruct msg_buffer {\n long msg_type;\n char msg[100];\n} message;\nmain() {\n key_t my_key;\n int msg_id;\n my_key = ftok(\"progfile\", 65); //create unique key\n msg_id = msgget(my_key, 0666 | IPC_CREAT); //create message queue and return id\n message.msg_type = 1;\n printf(\"Write Message : \");\n fgets(message.msg, 100, stdin);\n msgsnd(msg_id, &message, sizeof(message), 0); //send message\n printf(\"Sent message is : %s \\n\", message.msg);\n}" }, { "code": null, "e": 6021, "s": 5444, "text": "#include <stdio.h>\n#include <sys/ipc.h>\n#include <sys/msg.h>\n// Define message queue structure\nstruct msg_buffer {\n long msg_type;\n char msg[100];\n} message;\nmain() {\n key_t my_key;\n int msg_id;\n my_key = ftok(\"progfile\", 65); //create unique key\n msg_id = msgget(my_key, 0666 | IPC_CREAT); //create message queue and return id\n msgrcv(msg_id, &message, sizeof(message), 1, 0); //used to receive message\n // display the message\n printf(\"Received Message is : %s \\n\", message.msg);\n msgctl(msg_id, IPC_RMID, NULL); //destroy the message queue\n return 0;\n}" } ]
Genetic Programming applied to AI Heuristic Optimization | by Ryan Shrott | Towards Data Science
My interest in genetic programming began in 2015 when I studied the iterated ultimatum game. More recently, I have been using genetic algorithms to optimize parameters in a risk management system at work. In this short article, I will discuss the high level idea and the necessary ingredients to build your own genetic algorithm. I will also give a simple implementation of a genetic algorithm used to optimize the heuristic function for a general game playing AI agent using alpha beta pruning and minimax with iterative deepening. Finally, I will discuss several drawbacks to genetic programming in AI. Genetic programming (GP) is a type of evolutionary algorithm that can compute solutions to general problems which humans do not know how to solve directly. The machine is tasked with generating a working computer program from a high-level implementation of the problem. The idea is to randomly generate thousands of computer programs and use Darwinian natural selection to evolve the programs until the population converges to a global maxima/minima. It is often used in the field of Machine Learning to determine relationships between features in data. GP has also been applied in various financial areas: building automated trading strategies, risk management systems and credit card detection. Other areas of interest include quantum computing, design of electric circuits and antennae. I’ve also recently heard of genetic algorithms being used to debug code in large scale programs. All evolutionary algorithms must have a mechanism for breeding, mutating and evolving. Additionally, if you wish to use true genetic programming, you must define a genetic representation of the parameters. For example, a simple representation of a float data type would be a binary string representation. One could then apply evolution to each bit of the string. With regards to breeding, crossover is the most popular method by which genomes of the binary data are combined in a random way. Defining a robust breeding and mutation mechanism are crucial to ensure that the solution converges to a global maxima/minima. Suppose we are tasked with building an AI system to play a general game (chess for example). If we applied the standard methods of minimax and alpha beta pruning we would be tasked with generating a heuristic function to determine the relative “strength” of a move. Suppose we choose something of the form: V(w) = w * white_pieces — (1-w)*black_pieces where w in [0,1]. Genetic programming will be tasked with choosing the parameter, w, for our AI agent. Note that in the code below I will be using my AlphaBetaPlayer class as a representation of the individuals in the population. The genetic score function is defined to be the simple heuristic above. Out first task is to define an individual agent as follows: def individual(weight): # creates an individual return AlphaBetaPlayer(score_fn=genetic, weight=weight) The initial population is just a group of individuals who have random weights. We can implement it as follows: def population(count): # creates a list of individuals return [ individual(random.uniform(0,1)) for x in range(count) ] We may now define the breeding process as computing a random number between the mother’s weight and the father’s weight, and increase the range slightly to keep more genetic diversity. We don’t allow the mother and father to be the same individual. def breed(mother, father): if mother != father: if father.w > mother.w: childWeight = random.uniform(mother.w*.95, father.w*1.05) else: childWeight = random.uniform(father.w*.95, mother.w*1.05) if childWeight < 0: childWeight = 0 if childWeight > 1: childWeight = 1 child = individual(childWeight) return child else: print('Cannot breed with itself: Error: Mother == Father') Keep in mind that the breeding process chosen here is completely arbitrary and may be defined differently. For example, we may consider taking the arithmetic average of the mother and father or even the geometric average. You should be trying to mimic Darwinian evolution to the best of your knowledge. Again, to reiterate my comments above, the most robust method would be to use some type of binary string representation and apply true crossover on the genotypes. This will not be discussed in this short example. We adjust for trivial border cases in the obvious way. Our next task is to define the mutation process. A simple implementation would be shift the weights up or down by a random amount. We do something slightly more clever to ensure genetic diversity. def mutate_agent(agent): if agent.w < 0.5: newWeight = (1-agent.w) + random.uniform(-0.5, 0.1) else: newWeight = (1-agent.w) + random.uniform(-0.1, 0.5) if newWeight < 0: newWeight = 0 if newWeight > 1: newWeight = 1 mutated_agent = individual(newWeight) return mutated_agent In particular, we shift the probability distribution to move weights, which are either close to 0 or 1 to something closer to 1 or 0, respectively. Again, we adjust for trivial border cases in the obvious way. Our final task is to combine the functions above to evolve the current population. Our approach involved letting the agents play against each other for a set number of games and then choosing the top 20% of the performers to use in the next evolution cycles. We also randomly select some of the lesser performing agents to ensure genetic diversity. We effectively kill off the rest of the agents. Finally, we create the children using our breeding process and mutate 5% of the population using our mutation function discussed above. The parameters in the function define the number of games to be played, the percentage of the parents to retain, the random selection size of the bottom performers and the mutation rate. def evolve(pop, gamesFactor=2, retain=0.2, random_select=0.05, mutate=0.01): # Determine the parents to breed from the population agent_score = {} numGames = len(pop) * gamesFactor bar = progressbar.ProgressBar()for game in bar(range(numGames)): competitors = random.sample(pop, 2) game = Board(competitors[0], competitors[1]) winner, history, outcome = game.play() competitors.remove(winner) loser = competitors[0] if winner not in agent_score.keys(): agent_score[winner] = 1 else: agent_score[winner] += 1 if loser not in agent_score.keys(): agent_score[loser] = -1 else: agent_score[loser] -= 1 top_performers_size = int(retain * len(pop)) bottom_performers_size = len(pop) - top_performers_size rand_select_size = int(len(pop) * random_select) top_perfomers = heapq.nlargest(top_performers_size, agent_score, key=agent_score.get) bottom_performers = heapq.nsmallest(bottom_performers_size, agent_score, key=agent_score.get) parents = top_perfomers + random.sample(bottom_performers, rand_select_size) random.shuffle(parents)# Create children numChildren = len(pop) - len(parents) children = [] for i in range(numChildren): par = random.sample(parents, 2) father = par[0] mother = par[1] child = breed(mother, father) children.append(child) new_pop = parents + childrenmutated_pop = [] # Randomly mutate some of the new population for agent in new_pop: if mutate > random.uniform(0,1): print('Mutate') mutated_agent = mutate_agent(agent) mutated_pop.append(mutated_agent) else: mutated_pop.append(agent) return mutated_pop Combining everything into our main program, we can continuously evolve the population until we have converged to a global maxima/minima. The simulation took 17 hours to run on my machine. if __name__ == "__main__": pop_count = 100 evolution_cyles = 12 pop = population(pop_count) history = [] for i in range(evolution_cyles): print(i) pop = evolve(pop, gamesFactor=10, retain=0.2, random_select=0.05, mutate=0.05) best_weights = [i.w for i in pop] print(stats.describe(best_weights)) history.append(best_weights) print('Evolution Results:') [stats.describe(x) for x in history] At the end of the day you will be interested in observing the final population after a suitable number of evolution cycles. The descriptive statistics should have a small standard deviation and a tight inter-quartile range. You should see that all the agents have similar weights. For the chess-playing agent, the genetic algorithm gives an optimal weight of approximately 0.3452. One simple drawback to genetic programming is the computational cost. One needs to evolve many populations before convergence is reached. Another drawback is that the solution is not guaranteed to converge to the global maxima/minima. It’s also often difficult to determine breeding and mutation procedures. Finally, a large number of parameters usually require a large number of evolution cycles. Game playing heuristic functions are often designed to balance complexity and insight into the game. It’s often important to design the heuristic to be as simple as possible. For that reason, genetic programming works quite well for AI game playing agents. [1] https://zhanggw.wordpress.com/2009/11/08/a-simple-genetic-programming-in-python-4/ [2] https://lethain.com/genetic-algorithms-cool-name-damn-simple/ [3] https://en.wikipedia.org/wiki/Genetic_programming [4] http://www.genetic-programming.org/ [5] Ben Lande during summer of 2015
[ { "code": null, "e": 777, "s": 172, "text": "My interest in genetic programming began in 2015 when I studied the iterated ultimatum game. More recently, I have been using genetic algorithms to optimize parameters in a risk management system at work. In this short article, I will discuss the high level idea and the necessary ingredients to build your own genetic algorithm. I will also give a simple implementation of a genetic algorithm used to optimize the heuristic function for a general game playing AI agent using alpha beta pruning and minimax with iterative deepening. Finally, I will discuss several drawbacks to genetic programming in AI." }, { "code": null, "e": 1664, "s": 777, "text": "Genetic programming (GP) is a type of evolutionary algorithm that can compute solutions to general problems which humans do not know how to solve directly. The machine is tasked with generating a working computer program from a high-level implementation of the problem. The idea is to randomly generate thousands of computer programs and use Darwinian natural selection to evolve the programs until the population converges to a global maxima/minima. It is often used in the field of Machine Learning to determine relationships between features in data. GP has also been applied in various financial areas: building automated trading strategies, risk management systems and credit card detection. Other areas of interest include quantum computing, design of electric circuits and antennae. I’ve also recently heard of genetic algorithms being used to debug code in large scale programs." }, { "code": null, "e": 2283, "s": 1664, "text": "All evolutionary algorithms must have a mechanism for breeding, mutating and evolving. Additionally, if you wish to use true genetic programming, you must define a genetic representation of the parameters. For example, a simple representation of a float data type would be a binary string representation. One could then apply evolution to each bit of the string. With regards to breeding, crossover is the most popular method by which genomes of the binary data are combined in a random way. Defining a robust breeding and mutation mechanism are crucial to ensure that the solution converges to a global maxima/minima." }, { "code": null, "e": 2590, "s": 2283, "text": "Suppose we are tasked with building an AI system to play a general game (chess for example). If we applied the standard methods of minimax and alpha beta pruning we would be tasked with generating a heuristic function to determine the relative “strength” of a move. Suppose we choose something of the form:" }, { "code": null, "e": 2653, "s": 2590, "text": "V(w) = w * white_pieces — (1-w)*black_pieces where w in [0,1]." }, { "code": null, "e": 2937, "s": 2653, "text": "Genetic programming will be tasked with choosing the parameter, w, for our AI agent. Note that in the code below I will be using my AlphaBetaPlayer class as a representation of the individuals in the population. The genetic score function is defined to be the simple heuristic above." }, { "code": null, "e": 2997, "s": 2937, "text": "Out first task is to define an individual agent as follows:" }, { "code": null, "e": 3108, "s": 2997, "text": "def individual(weight): # creates an individual return AlphaBetaPlayer(score_fn=genetic, weight=weight)" }, { "code": null, "e": 3219, "s": 3108, "text": "The initial population is just a group of individuals who have random weights. We can implement it as follows:" }, { "code": null, "e": 3346, "s": 3219, "text": "def population(count): # creates a list of individuals return [ individual(random.uniform(0,1)) for x in range(count) ]" }, { "code": null, "e": 3595, "s": 3346, "text": "We may now define the breeding process as computing a random number between the mother’s weight and the father’s weight, and increase the range slightly to keep more genetic diversity. We don’t allow the mother and father to be the same individual." }, { "code": null, "e": 4073, "s": 3595, "text": "def breed(mother, father): if mother != father: if father.w > mother.w: childWeight = random.uniform(mother.w*.95, father.w*1.05) else: childWeight = random.uniform(father.w*.95, mother.w*1.05) if childWeight < 0: childWeight = 0 if childWeight > 1: childWeight = 1 child = individual(childWeight) return child else: print('Cannot breed with itself: Error: Mother == Father')" }, { "code": null, "e": 4644, "s": 4073, "text": "Keep in mind that the breeding process chosen here is completely arbitrary and may be defined differently. For example, we may consider taking the arithmetic average of the mother and father or even the geometric average. You should be trying to mimic Darwinian evolution to the best of your knowledge. Again, to reiterate my comments above, the most robust method would be to use some type of binary string representation and apply true crossover on the genotypes. This will not be discussed in this short example. We adjust for trivial border cases in the obvious way." }, { "code": null, "e": 4841, "s": 4644, "text": "Our next task is to define the mutation process. A simple implementation would be shift the weights up or down by a random amount. We do something slightly more clever to ensure genetic diversity." }, { "code": null, "e": 5164, "s": 4841, "text": "def mutate_agent(agent): if agent.w < 0.5: newWeight = (1-agent.w) + random.uniform(-0.5, 0.1) else: newWeight = (1-agent.w) + random.uniform(-0.1, 0.5) if newWeight < 0: newWeight = 0 if newWeight > 1: newWeight = 1 mutated_agent = individual(newWeight) return mutated_agent" }, { "code": null, "e": 5374, "s": 5164, "text": "In particular, we shift the probability distribution to move weights, which are either close to 0 or 1 to something closer to 1 or 0, respectively. Again, we adjust for trivial border cases in the obvious way." }, { "code": null, "e": 6094, "s": 5374, "text": "Our final task is to combine the functions above to evolve the current population. Our approach involved letting the agents play against each other for a set number of games and then choosing the top 20% of the performers to use in the next evolution cycles. We also randomly select some of the lesser performing agents to ensure genetic diversity. We effectively kill off the rest of the agents. Finally, we create the children using our breeding process and mutate 5% of the population using our mutation function discussed above. The parameters in the function define the number of games to be played, the percentage of the parents to retain, the random selection size of the bottom performers and the mutation rate." }, { "code": null, "e": 7903, "s": 6094, "text": "def evolve(pop, gamesFactor=2, retain=0.2, random_select=0.05, mutate=0.01): # Determine the parents to breed from the population agent_score = {} numGames = len(pop) * gamesFactor bar = progressbar.ProgressBar()for game in bar(range(numGames)): competitors = random.sample(pop, 2) game = Board(competitors[0], competitors[1]) winner, history, outcome = game.play() competitors.remove(winner) loser = competitors[0] if winner not in agent_score.keys(): agent_score[winner] = 1 else: agent_score[winner] += 1 if loser not in agent_score.keys(): agent_score[loser] = -1 else: agent_score[loser] -= 1 top_performers_size = int(retain * len(pop)) bottom_performers_size = len(pop) - top_performers_size rand_select_size = int(len(pop) * random_select) top_perfomers = heapq.nlargest(top_performers_size, agent_score, key=agent_score.get) bottom_performers = heapq.nsmallest(bottom_performers_size, agent_score, key=agent_score.get) parents = top_perfomers + random.sample(bottom_performers, rand_select_size) random.shuffle(parents)# Create children numChildren = len(pop) - len(parents) children = [] for i in range(numChildren): par = random.sample(parents, 2) father = par[0] mother = par[1] child = breed(mother, father) children.append(child) new_pop = parents + childrenmutated_pop = [] # Randomly mutate some of the new population for agent in new_pop: if mutate > random.uniform(0,1): print('Mutate') mutated_agent = mutate_agent(agent) mutated_pop.append(mutated_agent) else: mutated_pop.append(agent) return mutated_pop" }, { "code": null, "e": 8091, "s": 7903, "text": "Combining everything into our main program, we can continuously evolve the population until we have converged to a global maxima/minima. The simulation took 17 hours to run on my machine." }, { "code": null, "e": 8543, "s": 8091, "text": "if __name__ == \"__main__\": pop_count = 100 evolution_cyles = 12 pop = population(pop_count) history = [] for i in range(evolution_cyles): print(i) pop = evolve(pop, gamesFactor=10, retain=0.2, random_select=0.05, mutate=0.05) best_weights = [i.w for i in pop] print(stats.describe(best_weights)) history.append(best_weights) print('Evolution Results:') [stats.describe(x) for x in history]" }, { "code": null, "e": 8924, "s": 8543, "text": "At the end of the day you will be interested in observing the final population after a suitable number of evolution cycles. The descriptive statistics should have a small standard deviation and a tight inter-quartile range. You should see that all the agents have similar weights. For the chess-playing agent, the genetic algorithm gives an optimal weight of approximately 0.3452." }, { "code": null, "e": 9579, "s": 8924, "text": "One simple drawback to genetic programming is the computational cost. One needs to evolve many populations before convergence is reached. Another drawback is that the solution is not guaranteed to converge to the global maxima/minima. It’s also often difficult to determine breeding and mutation procedures. Finally, a large number of parameters usually require a large number of evolution cycles. Game playing heuristic functions are often designed to balance complexity and insight into the game. It’s often important to design the heuristic to be as simple as possible. For that reason, genetic programming works quite well for AI game playing agents." }, { "code": null, "e": 9666, "s": 9579, "text": "[1] https://zhanggw.wordpress.com/2009/11/08/a-simple-genetic-programming-in-python-4/" }, { "code": null, "e": 9732, "s": 9666, "text": "[2] https://lethain.com/genetic-algorithms-cool-name-damn-simple/" }, { "code": null, "e": 9786, "s": 9732, "text": "[3] https://en.wikipedia.org/wiki/Genetic_programming" }, { "code": null, "e": 9826, "s": 9786, "text": "[4] http://www.genetic-programming.org/" } ]
How to serialize a null field using Gson library in Java?
By default, the Gson object does not serialize the fields with null values to JSON. If a field in a Java object is null, Gson excludes it. We can force Gson to serialize null values via the GsonBuilder class. We need to call the serializeNulls() method on the GsonBuilder instance before creating the Gson object. Once serializeNulls() has been called the Gson instance created by the GsonBuilder can include null fields in the serialized JSON. public GsonBuilder serializeNulls() import com.google.gson.*; import com.google.gson.annotations.*; public class NullFieldTest { public static void main(String args[]) { GsonBuilder builder = new GsonBuilder(); builder.serializeNulls(); Gson gson = builder.setPrettyPrinting().create(); Employee emp = new Employee(null, 25, 40000.00); String jsonEmp = gson.toJson(emp); System.out.println(jsonEmp); } } // Employee class class Employee { @Since(1.0) public String name; @Since(1.0) public int age; @Since(2.0) public double salary; public Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } } { "name": null, "age": 25, "salary": 40000.0 }
[ { "code": null, "e": 1507, "s": 1062, "text": "By default, the Gson object does not serialize the fields with null values to JSON. If a field in a Java object is null, Gson excludes it. We can force Gson to serialize null values via the GsonBuilder class. We need to call the serializeNulls() method on the GsonBuilder instance before creating the Gson object. Once serializeNulls() has been called the Gson instance created by the GsonBuilder can include null fields in the serialized JSON." }, { "code": null, "e": 1543, "s": 1507, "text": "public GsonBuilder serializeNulls()" }, { "code": null, "e": 2239, "s": 1543, "text": "import com.google.gson.*;\nimport com.google.gson.annotations.*;\npublic class NullFieldTest {\n public static void main(String args[]) {\n GsonBuilder builder = new GsonBuilder();\n builder.serializeNulls();\n Gson gson = builder.setPrettyPrinting().create();\n Employee emp = new Employee(null, 25, 40000.00);\n String jsonEmp = gson.toJson(emp);\n System.out.println(jsonEmp);\n }\n}\n// Employee class\nclass Employee {\n @Since(1.0)\n public String name;\n @Since(1.0)\n public int age;\n @Since(2.0)\n public double salary;\n public Employee(String name, int age, double salary) {\n this.name = name;\n this.age = age;\n this.salary = salary;\n }\n}" }, { "code": null, "e": 2295, "s": 2239, "text": "{\n \"name\": null,\n \"age\": 25,\n \"salary\": 40000.0\n}" } ]
C library function - mblen()
The C library function int mblen(const char *str, size_t n) returns the length of a multi-byte character pointed to, by the argument str. Following is the declaration for mblen() function. int mblen(const char *str, size_t n) str − This is the pointer to the first byte of a multibyte character. str − This is the pointer to the first byte of a multibyte character. n − This is the maximum number of bytes to be checked for character length. n − This is the maximum number of bytes to be checked for character length. The mblen() function returns the number of bytes passed from the multi-byte sequence starting at str, if a non-null wide character was recognized. It returns 0, if a null wide character was recognized. It returns -1, if an invalid multi-byte sequence was encountered or if it could not parse a complete multi-byte character. The following example shows the usage of mblen() function. #include <stdio.h> #include <stdlib.h> #include <string.h> int main () { int len; char *pmbnull = NULL; char *pmb = (char *)malloc( MB_CUR_MAX ); wchar_t *pwc = L"Hi"; wchar_t *pwcs = (wchar_t *)malloc( sizeof( wchar_t )); printf("Converting to multibyte string\n"); len = wcstombs( pmb, pwc, MB_CUR_MAX); printf("Characters converted %d\n", len); printf("Hex value of first multibyte character: %#.4x\n", pmb); len = mblen( pmb, MB_CUR_MAX ); printf( "Length in bytes of multibyte character %x: %u\n", pmb, len ); pmb = NULL; len = mblen( pmb, MB_CUR_MAX ); printf( "Length in bytes of multibyte character %x: %u\n", pmb, len ); return(0); } Let us compile and run the above program that will produce the following result − Converting to multibyte string Characters converted 1 Hex value of first multibyte character: 0x168c6010 Length in bytes of multibyte character 168c6010: 1 Length in bytes of multibyte character 0: 0 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2145, "s": 2007, "text": "The C library function int mblen(const char *str, size_t n) returns the length of a multi-byte character pointed to, by the argument str." }, { "code": null, "e": 2196, "s": 2145, "text": "Following is the declaration for mblen() function." }, { "code": null, "e": 2233, "s": 2196, "text": "int mblen(const char *str, size_t n)" }, { "code": null, "e": 2303, "s": 2233, "text": "str − This is the pointer to the first byte of a multibyte character." }, { "code": null, "e": 2373, "s": 2303, "text": "str − This is the pointer to the first byte of a multibyte character." }, { "code": null, "e": 2449, "s": 2373, "text": "n − This is the maximum number of bytes to be checked for character length." }, { "code": null, "e": 2525, "s": 2449, "text": "n − This is the maximum number of bytes to be checked for character length." }, { "code": null, "e": 2853, "s": 2525, "text": " The mblen() function returns the number of bytes passed from the multi-byte sequence starting at str, if a non-null wide character was recognized. It returns 0, if a null wide character was recognized. It returns -1, if an invalid multi-byte sequence was encountered or if it could not parse a complete multi-byte character." }, { "code": null, "e": 2912, "s": 2853, "text": "The following example shows the usage of mblen() function." }, { "code": null, "e": 3619, "s": 2912, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main () {\n int len;\n char *pmbnull = NULL;\n char *pmb = (char *)malloc( MB_CUR_MAX );\n wchar_t *pwc = L\"Hi\";\n wchar_t *pwcs = (wchar_t *)malloc( sizeof( wchar_t ));\n\n printf(\"Converting to multibyte string\\n\");\n len = wcstombs( pmb, pwc, MB_CUR_MAX);\n printf(\"Characters converted %d\\n\", len);\n printf(\"Hex value of first multibyte character: %#.4x\\n\", pmb);\n \n len = mblen( pmb, MB_CUR_MAX );\n printf( \"Length in bytes of multibyte character %x: %u\\n\", pmb, len );\n \n pmb = NULL;\n \n len = mblen( pmb, MB_CUR_MAX );\n printf( \"Length in bytes of multibyte character %x: %u\\n\", pmb, len );\n \n return(0);\n}" }, { "code": null, "e": 3701, "s": 3619, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 3902, "s": 3701, "text": "Converting to multibyte string\nCharacters converted 1\nHex value of first multibyte character: 0x168c6010\nLength in bytes of multibyte character 168c6010: 1\nLength in bytes of multibyte character 0: 0\n" }, { "code": null, "e": 3935, "s": 3902, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3950, "s": 3935, "text": " Nishant Malik" }, { "code": null, "e": 3985, "s": 3950, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4000, "s": 3985, "text": " Nishant Malik" }, { "code": null, "e": 4035, "s": 4000, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4049, "s": 4035, "text": " Asif Hussain" }, { "code": null, "e": 4082, "s": 4049, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4100, "s": 4082, "text": " Richa Maheshwari" }, { "code": null, "e": 4135, "s": 4100, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4154, "s": 4135, "text": " Vandana Annavaram" }, { "code": null, "e": 4187, "s": 4154, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 4199, "s": 4187, "text": " Amit Diwan" }, { "code": null, "e": 4206, "s": 4199, "text": " Print" }, { "code": null, "e": 4217, "s": 4206, "text": " Add Notes" } ]
While loop with Compile time constants - GeeksforGeeks
14 Dec, 2020 While loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. It is mostly used in situations where the exact number of iterations beforehand. Below is the image to illustrate the while loop: Syntax: while(test_expression) { // statements update_expression; } Program 1: Below is the program to implement the basic while loop: Java // Java program to illustrate the// while loop class GFG { // Driver Code public static void main(String args[]) { // Initialization expression int i = 1; // Test expression while (i < 6) { System.out.println("Hello World"); // Update the expression i++; } }} Hello World Hello World Hello World Hello World Hello World Program 1: Below is the example of another while Loop where a boolean variable is used in the test_expression part: Java // Java program to demonstrate while loopimport java.io.*; class GFG { // Driver Code public static void main(String[] args) { boolean flag = false; while (flag) { System.out.println( "While Loop Executed"); } System.out.println("Done!"); }} Done! Explanation: The above code works fine because the flag is not a compile-time constant. The value of the flag is false so the while loop is not be executed. Program 2: Below is the example of a while loop where a constant boolean value is used in the test_expression part instead of using a boolean variable as done in the above example. Java // Java program to demonstrate the// above statement import java.io.*;class GFG { // Driver Code public static void main(String[] args) { while (false) { System.out.println( "While Loop Executed"); } System.out.println("Done!"); }} Output: Explanation: The above code fails to compile as the code inside while loop is unreachable. Program 3: Below is the program to demonstrate the scenario when the test_expression is “true”: Java // Java program to demonstrate the// above statementimport java.io.*; class GFG { // Driver Code public static void main(String[] args) { while (true) { System.out.println( "While Loop Executed"); } System.out.println("Done!"); }} Output: Explanation: In the above code, the while loop will be compiled successfully, but it would end up in an infinite loop and because of that the code after the while loop is unreachable. Therefore, it would also end up compilation error. Program 4: Below is another version of the above program with a break statement inside the while loop: Java // Java program to demonstrate the// above approachimport java.io.*; class GFG { // Driver Code public static void main(String[] args) { while (true) { System.out.println( "Inside Loop"); break; } System.out.println("Done!"); }} Inside Loop Done! Explanation: In the above program, if the while loop contained a break statement then the compilation will not fail because there would be some cases where the code after the loop would be reachable. Here, we are coming out of the while loop and the print statement will be executed. Compile-time constants are the constants whose respective values are known at compile time. Final variables of primitive data types and strings can be compile-time constants. They must be initialized with their declaration. Below is an example of compile-time constants: final int i = 100; final String str = "Hello"; Following are not compile-time constants: final int j; j = 10; final Integer k = 20; Program 1: Suppose a final variable as a condition variable inside the while loop is used. Below is the program to illustrate the same: Java // Java program to demonstrate the// while loop with compile-time// constantimport java.io.*; class GFG { // Driver Code public static void main(String[] args) { final boolean flag = false; while (flag) { System.out.println( "Inside Loop"); } System.out.println("Done!"); }} Output Explanation: As the flag is a final variable, it is a compile-time constant. As the value of the flag cannot be changed, the code inside the while loop is unreachable. That is why this fails to compile. Program 2: If the final variable is not initialized when it is declared, then it is not a compile-time constant. Below is the program to illustrate the same: Java // Java program to demonstrate the// above statementimport java.io.*; class GFG { // Driver Code public static void main(String[] args) { final boolean flag; flag = false; while (flag) { System.out.println("Inside Loop"); } System.out.println("Done!"); }} Done! Explanation: In the above program, there would not be any compilation error as the flag is not initialized when it is declared. It is initialized on a separate line. So in this case flag is not a compile-time constant and there would not be any compilation error. Note: Similarly, if the value of the final flag variable is true and it is initialized when it is declared, then the code after the while block will fail to compile. But, if the value of the final boolean flag is initialized on a separate line with the value ‘true’, then there would not be any compilation error. That means, if the condition variable used inside the while loop is a compile-time constant, then the code may or may not compile depending on the context. The final variable that is not initialized on the same line is not a compile-time constant. So in that case there is no issue. Program 3: Java // Java program to demonstrate the while// loop with compiled time constantimport java.io.*; class GFG { // Driver Code public static void main(String[] args) { boolean anotherFlag = false; final boolean flag = anotherFlag; // While loop while (flag) { System.out.println("Inside Loop"); } System.out.println("Done!"); }} Done! Explanation: In the above code, there would not be any compilation error, though the flag is a final variable and it is initialized on the same line, ‘anotherFlag’ is not a final variable and that’s why the flag is not a compile-time constant and thus there are no issues with the compilation. Program 4: If the ‘anotherFlag’ was a final variable, then the results would have been different. Below is the program to illustrate the same: Java // Java program to demonstrate the// above statementimport java.io.*; class GFG { // Driver Code public static void main(String[] args) { final boolean anotherFlag = false; final boolean flag = anotherFlag; while (flag) { System.out.println("Inside Loop"); } System.out.println("Done!"); }} Output Explanation: In the above code, the flag is a compile-time constant. So, the code inside the while loop is unreachable, resulting in the compilation error. Loops & Control Structure Articles Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Docker - COPY Instruction Time complexities of different data structures Difference between Class and Object SQL | Date functions Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Stream In Java
[ { "code": null, "e": 25751, "s": 25723, "text": "\n14 Dec, 2020" }, { "code": null, "e": 26061, "s": 25751, "text": "While loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. It is mostly used in situations where the exact number of iterations beforehand. Below is the image to illustrate the while loop:" }, { "code": null, "e": 26069, "s": 26061, "text": "Syntax:" }, { "code": null, "e": 26136, "s": 26069, "text": "while(test_expression)\n{\n // statements \n update_expression;\n}" }, { "code": null, "e": 26203, "s": 26136, "text": "Program 1: Below is the program to implement the basic while loop:" }, { "code": null, "e": 26208, "s": 26203, "text": "Java" }, { "code": "// Java program to illustrate the// while loop class GFG { // Driver Code public static void main(String args[]) { // Initialization expression int i = 1; // Test expression while (i < 6) { System.out.println(\"Hello World\"); // Update the expression i++; } }}", "e": 26555, "s": 26208, "text": null }, { "code": null, "e": 26616, "s": 26555, "text": "Hello World\nHello World\nHello World\nHello World\nHello World\n" }, { "code": null, "e": 26732, "s": 26616, "text": "Program 1: Below is the example of another while Loop where a boolean variable is used in the test_expression part:" }, { "code": null, "e": 26737, "s": 26732, "text": "Java" }, { "code": "// Java program to demonstrate while loopimport java.io.*; class GFG { // Driver Code public static void main(String[] args) { boolean flag = false; while (flag) { System.out.println( \"While Loop Executed\"); } System.out.println(\"Done!\"); }}", "e": 27050, "s": 26737, "text": null }, { "code": null, "e": 27057, "s": 27050, "text": "Done!\n" }, { "code": null, "e": 27216, "s": 27057, "text": "Explanation: The above code works fine because the flag is not a compile-time constant. The value of the flag is false so the while loop is not be executed. " }, { "code": null, "e": 27397, "s": 27216, "text": "Program 2: Below is the example of a while loop where a constant boolean value is used in the test_expression part instead of using a boolean variable as done in the above example." }, { "code": null, "e": 27402, "s": 27397, "text": "Java" }, { "code": "// Java program to demonstrate the// above statement import java.io.*;class GFG { // Driver Code public static void main(String[] args) { while (false) { System.out.println( \"While Loop Executed\"); } System.out.println(\"Done!\"); }}", "e": 27694, "s": 27402, "text": null }, { "code": null, "e": 27702, "s": 27694, "text": "Output:" }, { "code": null, "e": 27793, "s": 27702, "text": "Explanation: The above code fails to compile as the code inside while loop is unreachable." }, { "code": null, "e": 27889, "s": 27793, "text": "Program 3: Below is the program to demonstrate the scenario when the test_expression is “true”:" }, { "code": null, "e": 27894, "s": 27889, "text": "Java" }, { "code": "// Java program to demonstrate the// above statementimport java.io.*; class GFG { // Driver Code public static void main(String[] args) { while (true) { System.out.println( \"While Loop Executed\"); } System.out.println(\"Done!\"); }}", "e": 28187, "s": 27894, "text": null }, { "code": null, "e": 28195, "s": 28187, "text": "Output:" }, { "code": null, "e": 28431, "s": 28195, "text": "Explanation: In the above code, the while loop will be compiled successfully, but it would end up in an infinite loop and because of that the code after the while loop is unreachable. Therefore, it would also end up compilation error. " }, { "code": null, "e": 28534, "s": 28431, "text": "Program 4: Below is another version of the above program with a break statement inside the while loop:" }, { "code": null, "e": 28539, "s": 28534, "text": "Java" }, { "code": "// Java program to demonstrate the// above approachimport java.io.*; class GFG { // Driver Code public static void main(String[] args) { while (true) { System.out.println( \"Inside Loop\"); break; } System.out.println(\"Done!\"); }}", "e": 28841, "s": 28539, "text": null }, { "code": null, "e": 28860, "s": 28841, "text": "Inside Loop\nDone!\n" }, { "code": null, "e": 29144, "s": 28860, "text": "Explanation: In the above program, if the while loop contained a break statement then the compilation will not fail because there would be some cases where the code after the loop would be reachable. Here, we are coming out of the while loop and the print statement will be executed." }, { "code": null, "e": 29415, "s": 29144, "text": "Compile-time constants are the constants whose respective values are known at compile time. Final variables of primitive data types and strings can be compile-time constants. They must be initialized with their declaration. Below is an example of compile-time constants:" }, { "code": null, "e": 29462, "s": 29415, "text": "final int i = 100;\nfinal String str = \"Hello\";" }, { "code": null, "e": 29504, "s": 29462, "text": "Following are not compile-time constants:" }, { "code": null, "e": 29547, "s": 29504, "text": "final int j;\nj = 10;\nfinal Integer k = 20;" }, { "code": null, "e": 29683, "s": 29547, "text": "Program 1: Suppose a final variable as a condition variable inside the while loop is used. Below is the program to illustrate the same:" }, { "code": null, "e": 29688, "s": 29683, "text": "Java" }, { "code": "// Java program to demonstrate the// while loop with compile-time// constantimport java.io.*; class GFG { // Driver Code public static void main(String[] args) { final boolean flag = false; while (flag) { System.out.println( \"Inside Loop\"); } System.out.println(\"Done!\"); }}", "e": 30034, "s": 29688, "text": null }, { "code": null, "e": 30041, "s": 30034, "text": "Output" }, { "code": null, "e": 30244, "s": 30041, "text": "Explanation: As the flag is a final variable, it is a compile-time constant. As the value of the flag cannot be changed, the code inside the while loop is unreachable. That is why this fails to compile." }, { "code": null, "e": 30402, "s": 30244, "text": "Program 2: If the final variable is not initialized when it is declared, then it is not a compile-time constant. Below is the program to illustrate the same:" }, { "code": null, "e": 30407, "s": 30402, "text": "Java" }, { "code": "// Java program to demonstrate the// above statementimport java.io.*; class GFG { // Driver Code public static void main(String[] args) { final boolean flag; flag = false; while (flag) { System.out.println(\"Inside Loop\"); } System.out.println(\"Done!\"); }}", "e": 30726, "s": 30407, "text": null }, { "code": null, "e": 30733, "s": 30726, "text": "Done!\n" }, { "code": null, "e": 30998, "s": 30733, "text": "Explanation: In the above program, there would not be any compilation error as the flag is not initialized when it is declared. It is initialized on a separate line. So in this case flag is not a compile-time constant and there would not be any compilation error. " }, { "code": null, "e": 31596, "s": 30998, "text": "Note: Similarly, if the value of the final flag variable is true and it is initialized when it is declared, then the code after the while block will fail to compile. But, if the value of the final boolean flag is initialized on a separate line with the value ‘true’, then there would not be any compilation error. That means, if the condition variable used inside the while loop is a compile-time constant, then the code may or may not compile depending on the context. The final variable that is not initialized on the same line is not a compile-time constant. So in that case there is no issue. " }, { "code": null, "e": 31607, "s": 31596, "text": "Program 3:" }, { "code": null, "e": 31612, "s": 31607, "text": "Java" }, { "code": "// Java program to demonstrate the while// loop with compiled time constantimport java.io.*; class GFG { // Driver Code public static void main(String[] args) { boolean anotherFlag = false; final boolean flag = anotherFlag; // While loop while (flag) { System.out.println(\"Inside Loop\"); } System.out.println(\"Done!\"); }}", "e": 32004, "s": 31612, "text": null }, { "code": null, "e": 32011, "s": 32004, "text": "Done!\n" }, { "code": null, "e": 32305, "s": 32011, "text": "Explanation: In the above code, there would not be any compilation error, though the flag is a final variable and it is initialized on the same line, ‘anotherFlag’ is not a final variable and that’s why the flag is not a compile-time constant and thus there are no issues with the compilation." }, { "code": null, "e": 32448, "s": 32305, "text": "Program 4: If the ‘anotherFlag’ was a final variable, then the results would have been different. Below is the program to illustrate the same:" }, { "code": null, "e": 32453, "s": 32448, "text": "Java" }, { "code": "// Java program to demonstrate the// above statementimport java.io.*; class GFG { // Driver Code public static void main(String[] args) { final boolean anotherFlag = false; final boolean flag = anotherFlag; while (flag) { System.out.println(\"Inside Loop\"); } System.out.println(\"Done!\"); }}", "e": 32807, "s": 32453, "text": null }, { "code": null, "e": 32814, "s": 32807, "text": "Output" }, { "code": null, "e": 32970, "s": 32814, "text": "Explanation: In the above code, the flag is a compile-time constant. So, the code inside the while loop is unreachable, resulting in the compilation error." }, { "code": null, "e": 32996, "s": 32970, "text": "Loops & Control Structure" }, { "code": null, "e": 33005, "s": 32996, "text": "Articles" }, { "code": null, "e": 33010, "s": 33005, "text": "Java" }, { "code": null, "e": 33015, "s": 33010, "text": "Java" }, { "code": null, "e": 33113, "s": 33015, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33150, "s": 33113, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 33176, "s": 33150, "text": "Docker - COPY Instruction" }, { "code": null, "e": 33223, "s": 33176, "text": "Time complexities of different data structures" }, { "code": null, "e": 33259, "s": 33223, "text": "Difference between Class and Object" }, { "code": null, "e": 33280, "s": 33259, "text": "SQL | Date functions" }, { "code": null, "e": 33295, "s": 33280, "text": "Arrays in Java" }, { "code": null, "e": 33339, "s": 33295, "text": "Split() String method in Java with examples" }, { "code": null, "e": 33361, "s": 33339, "text": "For-each loop in Java" }, { "code": null, "e": 33412, "s": 33361, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
How to create an inline frame using HTML5 ? - GeeksforGeeks
30 Jun, 2020 In this article, we will create an inline iframe by using a <iframe> tag in a document.It represents a fixed rectangular area within the document in which the browser can display a separate document along with scroll bars and borders. Inline frames are used to embed another document within the current HTML page.Syntax : <iframe src="URL"></iframe> Example: <!DOCTYPE html><html> <head> <title> How to create an inline frame using HTML5? </title></head> <body> <h2>Hlo GeeksForGeeks</h2> <h2> How to create an inline frame using HTML5? </h2> <p>Content goes here</p> <iframe src="https://ide.geeksforgeeks.org/tryit.php" height="300" width="400"> </iframe> </body> </html> Output: Example 2: <!DOCTYPE html><html> <head> <title> How to create an inline frame using HTML5? </title></head> <body> <h2>Hlo GeeksForGeeks</h2> <h2> How to create an inline frame using HTML5? </h2> <iframe height="300" width="350" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190717121605/Screenshot-from-2019-07-17-12-12-55.png" name="iframe_a"></iframe> </body> </html> Output: Supported Browser are listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Misc HTML5 CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML
[ { "code": null, "e": 26277, "s": 26249, "text": "\n30 Jun, 2020" }, { "code": null, "e": 26599, "s": 26277, "text": "In this article, we will create an inline iframe by using a <iframe> tag in a document.It represents a fixed rectangular area within the document in which the browser can display a separate document along with scroll bars and borders. Inline frames are used to embed another document within the current HTML page.Syntax :" }, { "code": null, "e": 26627, "s": 26599, "text": "<iframe src=\"URL\"></iframe>" }, { "code": null, "e": 26636, "s": 26627, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to create an inline frame using HTML5? </title></head> <body> <h2>Hlo GeeksForGeeks</h2> <h2> How to create an inline frame using HTML5? </h2> <p>Content goes here</p> <iframe src=\"https://ide.geeksforgeeks.org/tryit.php\" height=\"300\" width=\"400\"> </iframe> </body> </html> ", "e": 27024, "s": 26636, "text": null }, { "code": null, "e": 27032, "s": 27024, "text": "Output:" }, { "code": null, "e": 27043, "s": 27032, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to create an inline frame using HTML5? </title></head> <body> <h2>Hlo GeeksForGeeks</h2> <h2> How to create an inline frame using HTML5? </h2> <iframe height=\"300\" width=\"350\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190717121605/Screenshot-from-2019-07-17-12-12-55.png\" name=\"iframe_a\"></iframe> </body> </html>", "e": 27488, "s": 27043, "text": null }, { "code": null, "e": 27496, "s": 27488, "text": "Output:" }, { "code": null, "e": 27532, "s": 27496, "text": "Supported Browser are listed below:" }, { "code": null, "e": 27546, "s": 27532, "text": "Google Chrome" }, { "code": null, "e": 27564, "s": 27546, "text": "Internet Explorer" }, { "code": null, "e": 27572, "s": 27564, "text": "Firefox" }, { "code": null, "e": 27578, "s": 27572, "text": "Opera" }, { "code": null, "e": 27585, "s": 27578, "text": "Safari" }, { "code": null, "e": 27722, "s": 27585, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27732, "s": 27722, "text": "HTML-Misc" }, { "code": null, "e": 27738, "s": 27732, "text": "HTML5" }, { "code": null, "e": 27742, "s": 27738, "text": "CSS" }, { "code": null, "e": 27747, "s": 27742, "text": "HTML" }, { "code": null, "e": 27764, "s": 27747, "text": "Web Technologies" }, { "code": null, "e": 27791, "s": 27764, "text": "Web technologies Questions" }, { "code": null, "e": 27796, "s": 27791, "text": "HTML" }, { "code": null, "e": 27894, "s": 27796, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27942, "s": 27894, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27997, "s": 27942, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 28034, "s": 27997, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28098, "s": 28034, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28137, "s": 28098, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28185, "s": 28137, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28245, "s": 28185, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28298, "s": 28245, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28322, "s": 28298, "text": "REST API (Introduction)" } ]
D3.js zoom.scaleExtent() Function - GeeksforGeeks
09 Sep, 2020 The zoom.scaleExtent() Function in D3.js is used to set the scale extends to the specified array of numbers [k0, k1]. The k0 is the minimum allowed scale factor and k1 is the maximum allowed scale factor Syntax: zoom.scaleExtent([extent]) Parameters: This function accepts a single parameter as mentioned above and described below extent: This parameter can be defined as specified as a function which returns such an array. Return Value: This function returns the zoom behaviour. Below programs illustrate the zoom.scaleExtent() function in D3.js Example 1: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"> </script> </head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | zoom.scaleExtent() Function</h3> <svg height="200px" width="400px"> <g id="main" transform="translate(25, 25) scale(0.25)"></g> </svg> <script> var svg = d3.select("#main"); svg.append("rect").attr({"x":0, "y":0, "height":100, "width":100, "fill":"red"}) svg.append("rect").attr({"x":100, "y":100, "height":100, "width":100, "fill":"blue"}) svg.append("rect").attr({"x":0, "y":100, "height":100, "width":100, "fill":"green"}) svg.append("rect").attr({"x":100, "y":0, "height":100, "width":100, "fill":"purple"}) var zoom = d3.behavior.zoom().on("zoom", function(){ var t = d3.event.translate; var s = d3.event.scale; svg.attr("transform", "translate("+t[0]+", "+t[1]+") scale("+s+")") }) .scaleExtent([1, 10]).scale(1).translate([0, 0]) d3.select("svg").call(zoom) d3.selectAll("rect").on("mousedown", function(){ var scale = Math.random()*3; var translate = [Math.random()*100, Math.random()*100] zoom.scale(scale); zoom.translate(translate); //new transition var T = svg.transition().duration(5000) zoom.event(T); }) </script> </center></body> </html> Output: Example 2: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v5.js"> </script> <style> circle { fill: green; opacity: 0.2; stroke: black; stroke-width: 1px; } svg { border: 1px solid; font: 13px sans-serif; text-anchor: middle; } </style> </head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | zoom.scaleExtent() Function</h3> <div id="gfg" style="width: 400px; margin: auto"> </div> <script> function zoom_filter(divId) { var width = 400, height=250, maxR=30; var svg = d3.select(divId) .append('svg') .attr('width', width) .attr('height', height) var g = svg.append('g') // create 15 circles var numCircles = 55; var circles = []; for (var i = 0; i < numCircles; i++) circles.push({'x': 1+Math.floor(Math.random() * width), 'y': 1+Math.floor(Math.random() * height), 'r': 1+Math.floor(Math.random() * maxR)}); g.selectAll('circle') .data(circles) .enter() .append('circle') .attr('cx', function(d) { return d.x; }) .attr('cy', function(d) { return d.y; }) .attr('r', function(d) { return d.r; }) .classed('no-zoom', true) var zoom = d3.zoom() .scaleExtent([1, 10]) .on('zoom', function(d) { g.attr('transform', d3.event.transform); }); svg.call(zoom); } </script> <script> zoom_filter('#gfg'); </script> </center></body> </html> Output: D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n09 Sep, 2020" }, { "code": null, "e": 26749, "s": 26545, "text": "The zoom.scaleExtent() Function in D3.js is used to set the scale extends to the specified array of numbers [k0, k1]. The k0 is the minimum allowed scale factor and k1 is the maximum allowed scale factor" }, { "code": null, "e": 26757, "s": 26749, "text": "Syntax:" }, { "code": null, "e": 26784, "s": 26757, "text": "zoom.scaleExtent([extent])" }, { "code": null, "e": 26876, "s": 26784, "text": "Parameters: This function accepts a single parameter as mentioned above and described below" }, { "code": null, "e": 26970, "s": 26876, "text": "extent: This parameter can be defined as specified as a function which returns such an array." }, { "code": null, "e": 27026, "s": 26970, "text": "Return Value: This function returns the zoom behaviour." }, { "code": null, "e": 27093, "s": 27026, "text": "Below programs illustrate the zoom.scaleExtent() function in D3.js" }, { "code": null, "e": 27104, "s": 27093, "text": "Example 1:" }, { "code": "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js\"> </script> </head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | zoom.scaleExtent() Function</h3> <svg height=\"200px\" width=\"400px\"> <g id=\"main\" transform=\"translate(25, 25) scale(0.25)\"></g> </svg> <script> var svg = d3.select(\"#main\"); svg.append(\"rect\").attr({\"x\":0, \"y\":0, \"height\":100, \"width\":100, \"fill\":\"red\"}) svg.append(\"rect\").attr({\"x\":100, \"y\":100, \"height\":100, \"width\":100, \"fill\":\"blue\"}) svg.append(\"rect\").attr({\"x\":0, \"y\":100, \"height\":100, \"width\":100, \"fill\":\"green\"}) svg.append(\"rect\").attr({\"x\":100, \"y\":0, \"height\":100, \"width\":100, \"fill\":\"purple\"}) var zoom = d3.behavior.zoom().on(\"zoom\", function(){ var t = d3.event.translate; var s = d3.event.scale; svg.attr(\"transform\", \"translate(\"+t[0]+\", \"+t[1]+\") scale(\"+s+\")\") }) .scaleExtent([1, 10]).scale(1).translate([0, 0]) d3.select(\"svg\").call(zoom) d3.selectAll(\"rect\").on(\"mousedown\", function(){ var scale = Math.random()*3; var translate = [Math.random()*100, Math.random()*100] zoom.scale(scale); zoom.translate(translate); //new transition var T = svg.transition().duration(5000) zoom.event(T); }) </script> </center></body> </html>", "e": 28928, "s": 27104, "text": null }, { "code": null, "e": 28936, "s": 28928, "text": "Output:" }, { "code": null, "e": 28947, "s": 28936, "text": "Example 2:" }, { "code": "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"> <script src=\"https://d3js.org/d3.v5.js\"> </script> <style> circle { fill: green; opacity: 0.2; stroke: black; stroke-width: 1px; } svg { border: 1px solid; font: 13px sans-serif; text-anchor: middle; } </style> </head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | zoom.scaleExtent() Function</h3> <div id=\"gfg\" style=\"width: 400px; margin: auto\"> </div> <script> function zoom_filter(divId) { var width = 400, height=250, maxR=30; var svg = d3.select(divId) .append('svg') .attr('width', width) .attr('height', height) var g = svg.append('g') // create 15 circles var numCircles = 55; var circles = []; for (var i = 0; i < numCircles; i++) circles.push({'x': 1+Math.floor(Math.random() * width), 'y': 1+Math.floor(Math.random() * height), 'r': 1+Math.floor(Math.random() * maxR)}); g.selectAll('circle') .data(circles) .enter() .append('circle') .attr('cx', function(d) { return d.x; }) .attr('cy', function(d) { return d.y; }) .attr('r', function(d) { return d.r; }) .classed('no-zoom', true) var zoom = d3.zoom() .scaleExtent([1, 10]) .on('zoom', function(d) { g.attr('transform', d3.event.transform); }); svg.call(zoom); } </script> <script> zoom_filter('#gfg'); </script> </center></body> </html> ", "e": 31085, "s": 28947, "text": null }, { "code": null, "e": 31093, "s": 31085, "text": "Output:" }, { "code": null, "e": 31099, "s": 31093, "text": "D3.js" }, { "code": null, "e": 31110, "s": 31099, "text": "JavaScript" }, { "code": null, "e": 31127, "s": 31110, "text": "Web Technologies" }, { "code": null, "e": 31225, "s": 31127, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31265, "s": 31225, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31326, "s": 31265, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31367, "s": 31326, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 31389, "s": 31367, "text": "JavaScript | Promises" }, { "code": null, "e": 31443, "s": 31389, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 31483, "s": 31443, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31516, "s": 31483, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31559, "s": 31516, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31609, "s": 31559, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Count of different ways to express N as the sum of 1, 3 and 4 - GeeksforGeeks
CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More Competitive Programming Data Structures with C++ Data Science Explore More Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more School Guide Python Programming Learn To Make Apps Explore more All Courses TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data ScienceMachine LearningData Science Machine Learning Data Science CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software DesignsSoftware Design PatternsSystem Design Tutorial Software Design Patterns System Design Tutorial School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes School Programming MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers JobsApply for JobsPost a JobJOB-A-THON Apply for Jobs Post a Job JOB-A-THON PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri Geeks Digest Quizzes Geeks Campus Gblog Articles IDE Campus Mantri Sign In Sign In Home Saved Videos Courses For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Explore more Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial School Learning School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Curated DSA Lists Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Practice All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Explore more School Guide Python Programming Learn To Make Apps Explore more Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial Software Design Patterns System Design Tutorial School Learning School Programming School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Curated DSA Lists Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Apply for Jobs Post a Job JOB-A-THON Practice All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet GBlog Puzzles What's New ? Array Matrix Strings Hashing Linked List Stack Queue Binary Tree Binary Search Tree Heap Graph Searching Sorting Divide & Conquer Mathematical Geometric Bitwise Greedy Backtracking Branch and Bound Dynamic Programming Pattern Searching Randomized Count of different ways to express N as the sum of 1, 3 and 4 Count ways to build street under given constraints Count Balanced Binary Trees of Height h Maximum number of envelopes that can be put inside other bigger envelopes Minimize number of boxes by putting small box inside bigger one Number of visible boxes after putting one inside another Maximum number of teams that can be formed with given persons Minimum and Maximum number of pairs in m teams of n people Counting pairs when a person can form pair with at most one Counts paths from a point to reach Origin Count number of ways to cover a distance Find the longest path in a matrix with given constraints Top 20 Dynamic Programming Interview Questions Longest Common Subsequence | DP-4 Maximum size rectangle binary sub-matrix with all 1s Maximum size square sub-matrix with all 1s Longest Increasing Subsequence | DP-3 Longest Increasing Subsequence Size (N log N) Median in a stream of integers (running integers) Median of Stream of Running Integers using STL Minimum product of k integers in an array of positive Integers K-th Largest Sum Contiguous Subarray K maximum sum combinations from two arrays K maximum sums of overlapping contiguous sub-arrays K maximum sums of non-overlapping contiguous sub-arrays Write a program to print all permutations of a given string Permutation and Combination in Python Factorial of a large number itertools.combinations() module in Python to print all possible combinations Program to calculate value of nCr Count of different ways to express N as the sum of 1, 3 and 4 Count ways to build street under given constraints Count Balanced Binary Trees of Height h Maximum number of envelopes that can be put inside other bigger envelopes Minimize number of boxes by putting small box inside bigger one Number of visible boxes after putting one inside another Maximum number of teams that can be formed with given persons Minimum and Maximum number of pairs in m teams of n people Counting pairs when a person can form pair with at most one Counts paths from a point to reach Origin Count number of ways to cover a distance Find the longest path in a matrix with given constraints Top 20 Dynamic Programming Interview Questions Longest Common Subsequence | DP-4 Maximum size rectangle binary sub-matrix with all 1s Maximum size square sub-matrix with all 1s Longest Increasing Subsequence | DP-3 Longest Increasing Subsequence Size (N log N) Median in a stream of integers (running integers) Median of Stream of Running Integers using STL Minimum product of k integers in an array of positive Integers K-th Largest Sum Contiguous Subarray K maximum sum combinations from two arrays K maximum sums of overlapping contiguous sub-arrays K maximum sums of non-overlapping contiguous sub-arrays Write a program to print all permutations of a given string Permutation and Combination in Python Factorial of a large number itertools.combinations() module in Python to print all possible combinations Program to calculate value of nCr Difficulty Level : Easy Given N, count the number of ways to express N as sum of 1, 3 and 4. Examples: Input : N = 4 Output : 4 Explanation: 1+1+1+1 1+3 3+1 4 Input : N = 5 Output : 6 Explanation: 1 + 1 + 1 + 1 + 1 1 + 4 4 + 1 1 + 1 + 3 1 + 3 + 1 3 + 1 + 1 Approach : Divide the problem into sub-problems for solving it. Let DP[n] be the be the number of ways to write N as the sum of 1, 3, and 4. Consider one possible solution with n = x1 + x2 + x3 + ... xn. If the last number is 1, then sum of the remaining numbers is n-1. So the number that ends with 1 is equal to DP[n-1]. Taking other cases into account where the last number is 3 and 4. The final recurrence would be: DPn = DPn-1 + DPn-3 + DPn-4 Base case : DP[0] = DP[1] = DP[2] = 1 and DP[3] = 2 C++ Java Python3 C# PHP Javascript // C++ program to illustrate the number of// ways to represent N as sum of 1, 3 and 4.#include <bits/stdc++.h>using namespace std; // function to count the number of// ways to represent n as sum of 1, 3 and 4int countWays(int n){ int DP[n + 1]; // base cases DP[0] = DP[1] = DP[2] = 1; DP[3] = 2; // iterate for all values from 4 to n for (int i = 4; i <= n; i++) DP[i] = DP[i - 1] + DP[i - 3] + DP[i - 4]; return DP[n];} // driver codeint main(){ int n = 10; cout << countWays(n); return 0;} // Java program to illustrate// the number of ways to represent// N as sum of 1, 3 and 4. class GFG { // Function to count the // number of ways to represent // n as sum of 1, 3 and 4 static int countWays(int n) { int DP[] = new int[n + 1]; // base cases DP[0] = DP[1] = DP[2] = 1; DP[3] = 2; // iterate for all values from 4 to n for (int i = 4; i <= n; i++) DP[i] = DP[i - 1] + DP[i - 3] + DP[i - 4]; return DP[n]; } // driver code public static void main(String[] args) { int n = 10; System.out.println(countWays(n)); }} // This code is contributed// by prerna saini. # Python program to illustrate the number of# ways to represent N as sum of 1, 3 and 4. # Function to count the number of# ways to represent n as sum of 1, 3 and 4def countWays(n): DP = [0 for i in range(0, n + 1)] # base cases DP[0] = DP[1] = DP[2] = 1 DP[3] = 2 # Iterate for all values from 4 to n for i in range(4, n + 1): DP[i] = DP[i - 1] + DP[i - 3] + DP[i - 4] return DP[n] # Driver coden = 10print (countWays(n)) # This code is contributed by Gitanjali. // C# program to illustrate// the number of ways to represent// N as sum of 1, 3 and 4.using System; class GFG { // Function to count the // number of ways to represent // n as sum of 1, 3 and 4 static int countWays(int n) { int []DP = new int[n + 1]; // base cases DP[0] = DP[1] = DP[2] = 1; DP[3] = 2; // iterate for all values from 4 to n for (int i = 4; i <= n; i++) DP[i] = DP[i - 1] + DP[i - 3] + DP[i - 4]; return DP[n]; } // Driver code public static void Main() { int n = 10; Console.WriteLine(countWays(n)); }} // This code is contributed// by vt_m. <?php// PHP program to illustrate// the number of ways to// represent N as sum of// 1, 3 and 4. // function to count the// number of ways to// represent n as sum of// 1, 3 and 4function countWays($n){ $DP = array(); // base cases $DP[0] = $DP[1] = $DP[2] = 1; $DP[3] = 2; // iterate for all // values from 4 to n for ($i = 4; $i <= $n; $i++) $DP[$i] = $DP[$i - 1] + $DP[$i - 3] + $DP[$i - 4]; return $DP[$n];} // Driver Code$n = 10;echo countWays($n); // This code is contributed// by Sam007?> <script> // Javascript program to illustrate// the number of ways to represent// N as sum of 1, 3 and 4. // Function to count the// number of ways to represent// n as sum of 1, 3 and 4function countWays(n){ var DP = []; DP.length = 10; DP.fill(0); // Base cases DP[0] = DP[1] = DP[2] = 1; DP[3] = 2; // Iterate for all values from 4 to n for(var i = 4; i <= n; i++) DP[i] = DP[i - 1] + DP[i - 3] + DP[i - 4]; return DP[n];} // Driver codevar n = 10; document.write(countWays(n)); // This code is contributed by bunnyram19 </script> Output: 64 Time Complexity : O(n) Auxiliary Space : O(n) Sam007 bunnyram19 Combinatorial Dynamic Programming Dynamic Programming Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Combinational Sum Count ways to reach the nth stair using step 1, 2 or 3 Print all possible strings of length k that can be formed from a set of n characters Count of subsets with sum equal to X Python program to get all subsets of given size of a set 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Largest Sum Contiguous Subarray Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 419, "s": 0, "text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses" }, { "code": null, "e": 600, "s": 419, "text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 685, "s": 600, "text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More" }, { "code": null, "e": 702, "s": 685, "text": "DSA Live Classes" }, { "code": null, "e": 716, "s": 702, "text": "System Design" }, { "code": null, "e": 741, "s": 716, "text": "Java Backend Development" }, { "code": null, "e": 757, "s": 741, "text": "Full Stack LIVE" }, { "code": null, "e": 770, "s": 757, "text": "Explore More" }, { "code": null, "e": 842, "s": 770, "text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 858, "s": 842, "text": "DSA- Self Paced" }, { "code": null, "e": 869, "s": 858, "text": "SDE Theory" }, { "code": null, "e": 894, "s": 869, "text": "Must-Do Coding Questions" }, { "code": null, "e": 907, "s": 894, "text": "Explore More" }, { "code": null, "e": 1054, "s": 907, "text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1130, "s": 1054, "text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More" }, { "code": null, "e": 1154, "s": 1130, "text": "Competitive Programming" }, { "code": null, "e": 1179, "s": 1154, "text": "Data Structures with C++" }, { "code": null, "e": 1192, "s": 1179, "text": "Data Science" }, { "code": null, "e": 1205, "s": 1192, "text": "Explore More" }, { "code": null, "e": 1265, "s": 1205, "text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1281, "s": 1265, "text": "DSA- Self Paced" }, { "code": null, "e": 1285, "s": 1281, "text": "CIP" }, { "code": null, "e": 1305, "s": 1285, "text": "JAVA / Python / C++" }, { "code": null, "e": 1318, "s": 1305, "text": "Explore More" }, { "code": null, "e": 1393, "s": 1318, "text": "School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more" }, { "code": null, "e": 1406, "s": 1393, "text": "School Guide" }, { "code": null, "e": 1425, "s": 1406, "text": "Python Programming" }, { "code": null, "e": 1444, "s": 1425, "text": "Learn To Make Apps" }, { "code": null, "e": 1457, "s": 1444, "text": "Explore more" }, { "code": null, "e": 1469, "s": 1457, "text": "All Courses" }, { "code": null, "e": 3985, "s": 1469, "text": "TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers" }, { "code": null, "e": 4566, "s": 3985, "text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms" }, { "code": null, "e": 4899, "s": 4566, "text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question" }, { "code": null, "e": 4919, "s": 4899, "text": "Asymptotic Analysis" }, { "code": null, "e": 4949, "s": 4919, "text": "Worst, Average and Best Cases" }, { "code": null, "e": 4970, "s": 4949, "text": "Asymptotic Notations" }, { "code": null, "e": 5006, "s": 4970, "text": "Little o and little omega notations" }, { "code": null, "e": 5035, "s": 5006, "text": "Lower and Upper Bound Theory" }, { "code": null, "e": 5053, "s": 5035, "text": "Analysis of Loops" }, { "code": null, "e": 5073, "s": 5053, "text": "Solving Recurrences" }, { "code": null, "e": 5092, "s": 5073, "text": "Amortized Analysis" }, { "code": null, "e": 5128, "s": 5092, "text": "What does 'Space Complexity' mean ?" }, { "code": null, "e": 5157, "s": 5128, "text": "Pseudo-polynomial Algorithms" }, { "code": null, "e": 5194, "s": 5157, "text": "Polynomial Time Approximation Scheme" }, { "code": null, "e": 5221, "s": 5194, "text": "A Time Complexity Question" }, { "code": null, "e": 5242, "s": 5221, "text": "Searching Algorithms" }, { "code": null, "e": 5261, "s": 5242, "text": "Sorting Algorithms" }, { "code": null, "e": 5278, "s": 5261, "text": "Graph Algorithms" }, { "code": null, "e": 5296, "s": 5278, "text": "Pattern Searching" }, { "code": null, "e": 5317, "s": 5296, "text": "Geometric Algorithms" }, { "code": null, "e": 5330, "s": 5317, "text": "Mathematical" }, { "code": null, "e": 5349, "s": 5330, "text": "Bitwise Algorithms" }, { "code": null, "e": 5371, "s": 5349, "text": "Randomized Algorithms" }, { "code": null, "e": 5389, "s": 5371, "text": "Greedy Algorithms" }, { "code": null, "e": 5409, "s": 5389, "text": "Dynamic Programming" }, { "code": null, "e": 5428, "s": 5409, "text": "Divide and Conquer" }, { "code": null, "e": 5441, "s": 5428, "text": "Backtracking" }, { "code": null, "e": 5458, "s": 5441, "text": "Branch and Bound" }, { "code": null, "e": 5473, "s": 5458, "text": "All Algorithms" }, { "code": null, "e": 5616, "s": 5473, "text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures" }, { "code": null, "e": 5623, "s": 5616, "text": "Arrays" }, { "code": null, "e": 5635, "s": 5623, "text": "Linked List" }, { "code": null, "e": 5641, "s": 5635, "text": "Stack" }, { "code": null, "e": 5647, "s": 5641, "text": "Queue" }, { "code": null, "e": 5659, "s": 5647, "text": "Binary Tree" }, { "code": null, "e": 5678, "s": 5659, "text": "Binary Search Tree" }, { "code": null, "e": 5683, "s": 5678, "text": "Heap" }, { "code": null, "e": 5691, "s": 5683, "text": "Hashing" }, { "code": null, "e": 5697, "s": 5691, "text": "Graph" }, { "code": null, "e": 5721, "s": 5697, "text": "Advanced Data Structure" }, { "code": null, "e": 5728, "s": 5721, "text": "Matrix" }, { "code": null, "e": 5736, "s": 5728, "text": "Strings" }, { "code": null, "e": 5756, "s": 5736, "text": "All Data Structures" }, { "code": null, "e": 5976, "s": 5756, "text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes" }, { "code": null, "e": 5996, "s": 5976, "text": "Company Preparation" }, { "code": null, "e": 6007, "s": 5996, "text": "Top Topics" }, { "code": null, "e": 6034, "s": 6007, "text": "Practice Company Questions" }, { "code": null, "e": 6056, "s": 6034, "text": "Interview Experiences" }, { "code": null, "e": 6079, "s": 6056, "text": "Experienced Interviews" }, { "code": null, "e": 6101, "s": 6079, "text": "Internship Interviews" }, { "code": null, "e": 6126, "s": 6101, "text": "Competititve Programming" }, { "code": null, "e": 6142, "s": 6126, "text": "Design Patterns" }, { "code": null, "e": 6165, "s": 6142, "text": "System Design Tutorial" }, { "code": null, "e": 6189, "s": 6165, "text": "Multiple Choice Quizzes" }, { "code": null, "e": 6270, "s": 6189, "text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin" }, { "code": null, "e": 6272, "s": 6270, "text": "C" }, { "code": null, "e": 6276, "s": 6272, "text": "C++" }, { "code": null, "e": 6281, "s": 6276, "text": "Java" }, { "code": null, "e": 6288, "s": 6281, "text": "Python" }, { "code": null, "e": 6291, "s": 6288, "text": "C#" }, { "code": null, "e": 6302, "s": 6291, "text": "JavaScript" }, { "code": null, "e": 6309, "s": 6302, "text": "jQuery" }, { "code": null, "e": 6313, "s": 6309, "text": "SQL" }, { "code": null, "e": 6317, "s": 6313, "text": "PHP" }, { "code": null, "e": 6323, "s": 6317, "text": "Scala" }, { "code": null, "e": 6328, "s": 6323, "text": "Perl" }, { "code": null, "e": 6340, "s": 6328, "text": "Go Language" }, { "code": null, "e": 6345, "s": 6340, "text": "HTML" }, { "code": null, "e": 6349, "s": 6345, "text": "CSS" }, { "code": null, "e": 6356, "s": 6349, "text": "Kotlin" }, { "code": null, "e": 6402, "s": 6356, "text": "ML & Data ScienceMachine LearningData Science" }, { "code": null, "e": 6419, "s": 6402, "text": "Machine Learning" }, { "code": null, "e": 6432, "s": 6419, "text": "Data Science" }, { "code": null, "e": 6599, "s": 6432, "text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering" }, { "code": null, "e": 6611, "s": 6599, "text": "Mathematics" }, { "code": null, "e": 6628, "s": 6611, "text": "Operating System" }, { "code": null, "e": 6633, "s": 6628, "text": "DBMS" }, { "code": null, "e": 6651, "s": 6633, "text": "Computer Networks" }, { "code": null, "e": 6690, "s": 6651, "text": "Computer Organization and Architecture" }, { "code": null, "e": 6712, "s": 6690, "text": "Theory of Computation" }, { "code": null, "e": 6728, "s": 6712, "text": "Compiler Design" }, { "code": null, "e": 6742, "s": 6728, "text": "Digital Logic" }, { "code": null, "e": 6763, "s": 6742, "text": "Software Engineering" }, { "code": null, "e": 6938, "s": 6763, "text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS" }, { "code": null, "e": 6966, "s": 6938, "text": "GATE Computer Science Notes" }, { "code": null, "e": 6984, "s": 6966, "text": "Last Minute Notes" }, { "code": null, "e": 7006, "s": 6984, "text": "GATE CS Solved Papers" }, { "code": null, "e": 7048, "s": 7006, "text": "GATE CS Original Papers and Official Keys" }, { "code": null, "e": 7064, "s": 7048, "text": "GATE 2021 Dates" }, { "code": null, "e": 7086, "s": 7064, "text": "GATE CS 2021 Syllabus" }, { "code": null, "e": 7115, "s": 7086, "text": "Important Topics for GATE CS" }, { "code": null, "e": 7189, "s": 7115, "text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP" }, { "code": null, "e": 7194, "s": 7189, "text": "HTML" }, { "code": null, "e": 7198, "s": 7194, "text": "CSS" }, { "code": null, "e": 7209, "s": 7198, "text": "JavaScript" }, { "code": null, "e": 7219, "s": 7209, "text": "AngularJS" }, { "code": null, "e": 7227, "s": 7219, "text": "ReactJS" }, { "code": null, "e": 7234, "s": 7227, "text": "NodeJS" }, { "code": null, "e": 7244, "s": 7234, "text": "Bootstrap" }, { "code": null, "e": 7251, "s": 7244, "text": "jQuery" }, { "code": null, "e": 7255, "s": 7251, "text": "PHP" }, { "code": null, "e": 7318, "s": 7255, "text": "Software DesignsSoftware Design PatternsSystem Design Tutorial" }, { "code": null, "e": 7343, "s": 7318, "text": "Software Design Patterns" }, { "code": null, "e": 7366, "s": 7343, "text": "System Design Tutorial" }, { "code": null, "e": 7923, "s": 7366, "text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 7942, "s": 7923, "text": "School Programming" }, { "code": null, "e": 8034, "s": 7942, "text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus" }, { "code": null, "e": 8048, "s": 8034, "text": "Number System" }, { "code": null, "e": 8056, "s": 8048, "text": "Algebra" }, { "code": null, "e": 8069, "s": 8056, "text": "Trigonometry" }, { "code": null, "e": 8080, "s": 8069, "text": "Statistics" }, { "code": null, "e": 8092, "s": 8080, "text": "Probability" }, { "code": null, "e": 8101, "s": 8092, "text": "Geometry" }, { "code": null, "e": 8113, "s": 8101, "text": "Mensuration" }, { "code": null, "e": 8122, "s": 8113, "text": "Calculus" }, { "code": null, "e": 8215, "s": 8122, "text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes" }, { "code": null, "e": 8229, "s": 8215, "text": "Class 8 Notes" }, { "code": null, "e": 8243, "s": 8229, "text": "Class 9 Notes" }, { "code": null, "e": 8258, "s": 8243, "text": "Class 10 Notes" }, { "code": null, "e": 8273, "s": 8258, "text": "Class 11 Notes" }, { "code": null, "e": 8288, "s": 8273, "text": "Class 12 Notes" }, { "code": null, "e": 8417, "s": 8288, "text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8440, "s": 8417, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8463, "s": 8440, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8487, "s": 8463, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8511, "s": 8487, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8535, "s": 8511, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8668, "s": 8535, "text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8691, "s": 8668, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8714, "s": 8691, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8738, "s": 8714, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8762, "s": 8738, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8786, "s": 8762, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8867, "s": 8786, "text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 8881, "s": 8867, "text": "Class 8 Notes" }, { "code": null, "e": 8895, "s": 8881, "text": "Class 9 Notes" }, { "code": null, "e": 8910, "s": 8895, "text": "Class 10 Notes" }, { "code": null, "e": 8925, "s": 8910, "text": "Class 11 Notes" }, { "code": null, "e": 9131, "s": 8925, "text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9242, "s": 9131, "text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9284, "s": 9242, "text": "ISRO CS Original Papers and Official Keys" }, { "code": null, "e": 9306, "s": 9284, "text": "ISRO CS Solved Papers" }, { "code": null, "e": 9351, "s": 9306, "text": "ISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9434, "s": 9351, "text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9460, "s": 9434, "text": "UGC NET CS Notes Paper II" }, { "code": null, "e": 9487, "s": 9460, "text": "UGC NET CS Notes Paper III" }, { "code": null, "e": 9512, "s": 9487, "text": "UGC NET CS Solved Papers" }, { "code": null, "e": 9717, "s": 9512, "text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers" }, { "code": null, "e": 9743, "s": 9717, "text": "Campus Ambassador Program" }, { "code": null, "e": 9769, "s": 9743, "text": "School Ambassador Program" }, { "code": null, "e": 9777, "s": 9769, "text": "Project" }, { "code": null, "e": 9795, "s": 9777, "text": "Geek of the Month" }, { "code": null, "e": 9820, "s": 9795, "text": "Campus Geek of the Month" }, { "code": null, "e": 9837, "s": 9820, "text": "Placement Course" }, { "code": null, "e": 9862, "s": 9837, "text": "Competititve Programming" }, { "code": null, "e": 9875, "s": 9862, "text": "Testimonials" }, { "code": null, "e": 9891, "s": 9875, "text": "Student Chapter" }, { "code": null, "e": 9907, "s": 9891, "text": "Geek on the Top" }, { "code": null, "e": 9918, "s": 9907, "text": "Internship" }, { "code": null, "e": 9926, "s": 9918, "text": "Careers" }, { "code": null, "e": 9965, "s": 9926, "text": "JobsApply for JobsPost a JobJOB-A-THON" }, { "code": null, "e": 9980, "s": 9965, "text": "Apply for Jobs" }, { "code": null, "e": 9991, "s": 9980, "text": "Post a Job" }, { "code": null, "e": 10002, "s": 9991, "text": "JOB-A-THON" }, { "code": null, "e": 10267, "s": 10002, "text": "PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems" }, { "code": null, "e": 10284, "s": 10267, "text": "All DSA Problems" }, { "code": null, "e": 10303, "s": 10284, "text": "Problem of the Day" }, { "code": null, "e": 10337, "s": 10303, "text": "Interview Series: Weekly Contests" }, { "code": null, "e": 10371, "s": 10337, "text": "Bi-Wizard Coding: School Contests" }, { "code": null, "e": 10391, "s": 10371, "text": "Contests and Events" }, { "code": null, "e": 10410, "s": 10391, "text": "Practice SDE Sheet" }, { "code": null, "e": 10530, "s": 10410, "text": "Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems" }, { "code": null, "e": 10552, "s": 10530, "text": "Top 50 Array Problems" }, { "code": null, "e": 10575, "s": 10552, "text": "Top 50 String Problems" }, { "code": null, "e": 10596, "s": 10575, "text": "Top 50 Tree Problems" }, { "code": null, "e": 10618, "s": 10596, "text": "Top 50 Graph Problems" }, { "code": null, "e": 10637, "s": 10618, "text": "Top 50 DP Problems" }, { "code": null, "e": 10908, "s": 10641, "text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri" }, { "code": null, "e": 10921, "s": 10908, "text": "Geeks Digest" }, { "code": null, "e": 10929, "s": 10921, "text": "Quizzes" }, { "code": null, "e": 10942, "s": 10929, "text": "Geeks Campus" }, { "code": null, "e": 10957, "s": 10942, "text": "Gblog Articles" }, { "code": null, "e": 10961, "s": 10957, "text": "IDE" }, { "code": null, "e": 10975, "s": 10961, "text": "Campus Mantri" }, { "code": null, "e": 10983, "s": 10975, "text": "Sign In" }, { "code": null, "e": 10991, "s": 10983, "text": "Sign In" }, { "code": null, "e": 10996, "s": 10991, "text": "Home" }, { "code": null, "e": 11009, "s": 10996, "text": "Saved Videos" }, { "code": null, "e": 11017, "s": 11009, "text": "Courses" }, { "code": null, "e": 15482, "s": 11017, "text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n\n\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n\n\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n" }, { "code": null, "e": 15536, "s": 15482, "text": "\nFor Working Professionals\n \n\n" }, { "code": null, "e": 15659, "s": 15536, "text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n" }, { "code": null, "e": 15678, "s": 15659, "text": "\nDSA Live Classes\n" }, { "code": null, "e": 15694, "s": 15678, "text": "\nSystem Design\n" }, { "code": null, "e": 15721, "s": 15694, "text": "\nJava Backend Development\n" }, { "code": null, "e": 15739, "s": 15721, "text": "\nFull Stack LIVE\n" }, { "code": null, "e": 15754, "s": 15739, "text": "\nExplore More\n" }, { "code": null, "e": 15862, "s": 15754, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n" }, { "code": null, "e": 15880, "s": 15862, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15893, "s": 15880, "text": "\nSDE Theory\n" }, { "code": null, "e": 15920, "s": 15893, "text": "\nMust-Do Coding Questions\n" }, { "code": null, "e": 15935, "s": 15920, "text": "\nExplore More\n" }, { "code": null, "e": 15976, "s": 15935, "text": "\nFor Students\n \n\n" }, { "code": null, "e": 16088, "s": 15976, "text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n" }, { "code": null, "e": 16114, "s": 16088, "text": "\nCompetitive Programming\n" }, { "code": null, "e": 16141, "s": 16114, "text": "\nData Structures with C++\n" }, { "code": null, "e": 16156, "s": 16141, "text": "\nData Science\n" }, { "code": null, "e": 16171, "s": 16156, "text": "\nExplore More\n" }, { "code": null, "e": 16267, "s": 16171, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n" }, { "code": null, "e": 16285, "s": 16267, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 16291, "s": 16285, "text": "\nCIP\n" }, { "code": null, "e": 16313, "s": 16291, "text": "\nJAVA / Python / C++\n" }, { "code": null, "e": 16328, "s": 16313, "text": "\nExplore More\n" }, { "code": null, "e": 16439, "s": 16328, "text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n" }, { "code": null, "e": 16454, "s": 16439, "text": "\nSchool Guide\n" }, { "code": null, "e": 16475, "s": 16454, "text": "\nPython Programming\n" }, { "code": null, "e": 16496, "s": 16475, "text": "\nLearn To Make Apps\n" }, { "code": null, "e": 16511, "s": 16496, "text": "\nExplore more\n" }, { "code": null, "e": 16816, "s": 16511, "text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n" }, { "code": null, "e": 16839, "s": 16816, "text": "\nSearching Algorithms\n" }, { "code": null, "e": 16860, "s": 16839, "text": "\nSorting Algorithms\n" }, { "code": null, "e": 16879, "s": 16860, "text": "\nGraph Algorithms\n" }, { "code": null, "e": 16899, "s": 16879, "text": "\nPattern Searching\n" }, { "code": null, "e": 16922, "s": 16899, "text": "\nGeometric Algorithms\n" }, { "code": null, "e": 16937, "s": 16922, "text": "\nMathematical\n" }, { "code": null, "e": 16958, "s": 16937, "text": "\nBitwise Algorithms\n" }, { "code": null, "e": 16982, "s": 16958, "text": "\nRandomized Algorithms\n" }, { "code": null, "e": 17002, "s": 16982, "text": "\nGreedy Algorithms\n" }, { "code": null, "e": 17024, "s": 17002, "text": "\nDynamic Programming\n" }, { "code": null, "e": 17045, "s": 17024, "text": "\nDivide and Conquer\n" }, { "code": null, "e": 17060, "s": 17045, "text": "\nBacktracking\n" }, { "code": null, "e": 17079, "s": 17060, "text": "\nBranch and Bound\n" }, { "code": null, "e": 17096, "s": 17079, "text": "\nAll Algorithms\n" }, { "code": null, "e": 17481, "s": 17096, "text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n" }, { "code": null, "e": 17503, "s": 17481, "text": "\nAsymptotic Analysis\n" }, { "code": null, "e": 17535, "s": 17503, "text": "\nWorst, Average and Best Cases\n" }, { "code": null, "e": 17558, "s": 17535, "text": "\nAsymptotic Notations\n" }, { "code": null, "e": 17596, "s": 17558, "text": "\nLittle o and little omega notations\n" }, { "code": null, "e": 17627, "s": 17596, "text": "\nLower and Upper Bound Theory\n" }, { "code": null, "e": 17647, "s": 17627, "text": "\nAnalysis of Loops\n" }, { "code": null, "e": 17669, "s": 17647, "text": "\nSolving Recurrences\n" }, { "code": null, "e": 17690, "s": 17669, "text": "\nAmortized Analysis\n" }, { "code": null, "e": 17728, "s": 17690, "text": "\nWhat does 'Space Complexity' mean ?\n" }, { "code": null, "e": 17759, "s": 17728, "text": "\nPseudo-polynomial Algorithms\n" }, { "code": null, "e": 17798, "s": 17759, "text": "\nPolynomial Time Approximation Scheme\n" }, { "code": null, "e": 17827, "s": 17798, "text": "\nA Time Complexity Question\n" }, { "code": null, "e": 18024, "s": 17827, "text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n" }, { "code": null, "e": 18033, "s": 18024, "text": "\nArrays\n" }, { "code": null, "e": 18047, "s": 18033, "text": "\nLinked List\n" }, { "code": null, "e": 18055, "s": 18047, "text": "\nStack\n" }, { "code": null, "e": 18063, "s": 18055, "text": "\nQueue\n" }, { "code": null, "e": 18077, "s": 18063, "text": "\nBinary Tree\n" }, { "code": null, "e": 18098, "s": 18077, "text": "\nBinary Search Tree\n" }, { "code": null, "e": 18105, "s": 18098, "text": "\nHeap\n" }, { "code": null, "e": 18115, "s": 18105, "text": "\nHashing\n" }, { "code": null, "e": 18123, "s": 18115, "text": "\nGraph\n" }, { "code": null, "e": 18149, "s": 18123, "text": "\nAdvanced Data Structure\n" }, { "code": null, "e": 18158, "s": 18149, "text": "\nMatrix\n" }, { "code": null, "e": 18168, "s": 18158, "text": "\nStrings\n" }, { "code": null, "e": 18190, "s": 18168, "text": "\nAll Data Structures\n" }, { "code": null, "e": 18458, "s": 18190, "text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n" }, { "code": null, "e": 18480, "s": 18458, "text": "\nCompany Preparation\n" }, { "code": null, "e": 18493, "s": 18480, "text": "\nTop Topics\n" }, { "code": null, "e": 18522, "s": 18493, "text": "\nPractice Company Questions\n" }, { "code": null, "e": 18546, "s": 18522, "text": "\nInterview Experiences\n" }, { "code": null, "e": 18571, "s": 18546, "text": "\nExperienced Interviews\n" }, { "code": null, "e": 18595, "s": 18571, "text": "\nInternship Interviews\n" }, { "code": null, "e": 18622, "s": 18595, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 18640, "s": 18622, "text": "\nDesign Patterns\n" }, { "code": null, "e": 18665, "s": 18640, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 18691, "s": 18665, "text": "\nMultiple Choice Quizzes\n" }, { "code": null, "e": 18830, "s": 18691, "text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n" }, { "code": null, "e": 18834, "s": 18830, "text": "\nC\n" }, { "code": null, "e": 18840, "s": 18834, "text": "\nC++\n" }, { "code": null, "e": 18847, "s": 18840, "text": "\nJava\n" }, { "code": null, "e": 18856, "s": 18847, "text": "\nPython\n" }, { "code": null, "e": 18861, "s": 18856, "text": "\nC#\n" }, { "code": null, "e": 18874, "s": 18861, "text": "\nJavaScript\n" }, { "code": null, "e": 18883, "s": 18874, "text": "\njQuery\n" }, { "code": null, "e": 18889, "s": 18883, "text": "\nSQL\n" }, { "code": null, "e": 18895, "s": 18889, "text": "\nPHP\n" }, { "code": null, "e": 18903, "s": 18895, "text": "\nScala\n" }, { "code": null, "e": 18910, "s": 18903, "text": "\nPerl\n" }, { "code": null, "e": 18924, "s": 18910, "text": "\nGo Language\n" }, { "code": null, "e": 18931, "s": 18924, "text": "\nHTML\n" }, { "code": null, "e": 18937, "s": 18931, "text": "\nCSS\n" }, { "code": null, "e": 18946, "s": 18937, "text": "\nKotlin\n" }, { "code": null, "e": 19024, "s": 18946, "text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n" }, { "code": null, "e": 19043, "s": 19024, "text": "\nMachine Learning\n" }, { "code": null, "e": 19058, "s": 19043, "text": "\nData Science\n" }, { "code": null, "e": 19271, "s": 19058, "text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n" }, { "code": null, "e": 19285, "s": 19271, "text": "\nMathematics\n" }, { "code": null, "e": 19304, "s": 19285, "text": "\nOperating System\n" }, { "code": null, "e": 19311, "s": 19304, "text": "\nDBMS\n" }, { "code": null, "e": 19331, "s": 19311, "text": "\nComputer Networks\n" }, { "code": null, "e": 19372, "s": 19331, "text": "\nComputer Organization and Architecture\n" }, { "code": null, "e": 19396, "s": 19372, "text": "\nTheory of Computation\n" }, { "code": null, "e": 19414, "s": 19396, "text": "\nCompiler Design\n" }, { "code": null, "e": 19430, "s": 19414, "text": "\nDigital Logic\n" }, { "code": null, "e": 19453, "s": 19430, "text": "\nSoftware Engineering\n" }, { "code": null, "e": 19670, "s": 19453, "text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19700, "s": 19670, "text": "\nGATE Computer Science Notes\n" }, { "code": null, "e": 19720, "s": 19700, "text": "\nLast Minute Notes\n" }, { "code": null, "e": 19744, "s": 19720, "text": "\nGATE CS Solved Papers\n" }, { "code": null, "e": 19788, "s": 19744, "text": "\nGATE CS Original Papers and Official Keys\n" }, { "code": null, "e": 19806, "s": 19788, "text": "\nGATE 2021 Dates\n" }, { "code": null, "e": 19830, "s": 19806, "text": "\nGATE CS 2021 Syllabus\n" }, { "code": null, "e": 19861, "s": 19830, "text": "\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19981, "s": 19861, "text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n" }, { "code": null, "e": 19988, "s": 19981, "text": "\nHTML\n" }, { "code": null, "e": 19994, "s": 19988, "text": "\nCSS\n" }, { "code": null, "e": 20007, "s": 19994, "text": "\nJavaScript\n" }, { "code": null, "e": 20019, "s": 20007, "text": "\nAngularJS\n" }, { "code": null, "e": 20029, "s": 20019, "text": "\nReactJS\n" }, { "code": null, "e": 20038, "s": 20029, "text": "\nNodeJS\n" }, { "code": null, "e": 20050, "s": 20038, "text": "\nBootstrap\n" }, { "code": null, "e": 20059, "s": 20050, "text": "\njQuery\n" }, { "code": null, "e": 20065, "s": 20059, "text": "\nPHP\n" }, { "code": null, "e": 20160, "s": 20065, "text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n" }, { "code": null, "e": 20187, "s": 20160, "text": "\nSoftware Design Patterns\n" }, { "code": null, "e": 20212, "s": 20187, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 20276, "s": 20212, "text": "\nSchool Learning\n \n\n\nSchool Programming\n" }, { "code": null, "e": 20297, "s": 20276, "text": "\nSchool Programming\n" }, { "code": null, "e": 20433, "s": 20297, "text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n" }, { "code": null, "e": 20449, "s": 20433, "text": "\nNumber System\n" }, { "code": null, "e": 20459, "s": 20449, "text": "\nAlgebra\n" }, { "code": null, "e": 20474, "s": 20459, "text": "\nTrigonometry\n" }, { "code": null, "e": 20487, "s": 20474, "text": "\nStatistics\n" }, { "code": null, "e": 20501, "s": 20487, "text": "\nProbability\n" }, { "code": null, "e": 20512, "s": 20501, "text": "\nGeometry\n" }, { "code": null, "e": 20526, "s": 20512, "text": "\nMensuration\n" }, { "code": null, "e": 20537, "s": 20526, "text": "\nCalculus\n" }, { "code": null, "e": 20668, "s": 20537, "text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n" }, { "code": null, "e": 20684, "s": 20668, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20700, "s": 20684, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20717, "s": 20700, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20734, "s": 20717, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20751, "s": 20734, "text": "\nClass 12 Notes\n" }, { "code": null, "e": 20918, "s": 20751, "text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 20943, "s": 20918, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20968, "s": 20943, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20994, "s": 20968, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 21020, "s": 20994, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 21046, "s": 21020, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 21217, "s": 21046, "text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 21242, "s": 21217, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 21267, "s": 21242, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 21293, "s": 21267, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 21319, "s": 21293, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 21345, "s": 21319, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 21462, "s": 21345, "text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n" }, { "code": null, "e": 21478, "s": 21462, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 21494, "s": 21478, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 21511, "s": 21494, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 21528, "s": 21511, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 21570, "s": 21528, "text": "\nCS Exams/PSUs\n \n\n" }, { "code": null, "e": 21715, "s": 21570, "text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21759, "s": 21715, "text": "\nISRO CS Original Papers and Official Keys\n" }, { "code": null, "e": 21783, "s": 21759, "text": "\nISRO CS Solved Papers\n" }, { "code": null, "e": 21830, "s": 21783, "text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21947, "s": 21830, "text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 21975, "s": 21947, "text": "\nUGC NET CS Notes Paper II\n" }, { "code": null, "e": 22004, "s": 21975, "text": "\nUGC NET CS Notes Paper III\n" }, { "code": null, "e": 22031, "s": 22004, "text": "\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 22288, "s": 22031, "text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n" }, { "code": null, "e": 22316, "s": 22288, "text": "\nCampus Ambassador Program\n" }, { "code": null, "e": 22344, "s": 22316, "text": "\nSchool Ambassador Program\n" }, { "code": null, "e": 22354, "s": 22344, "text": "\nProject\n" }, { "code": null, "e": 22374, "s": 22354, "text": "\nGeek of the Month\n" }, { "code": null, "e": 22401, "s": 22374, "text": "\nCampus Geek of the Month\n" }, { "code": null, "e": 22420, "s": 22401, "text": "\nPlacement Course\n" }, { "code": null, "e": 22447, "s": 22420, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 22462, "s": 22447, "text": "\nTestimonials\n" }, { "code": null, "e": 22480, "s": 22462, "text": "\nStudent Chapter\n" }, { "code": null, "e": 22498, "s": 22480, "text": "\nGeek on the Top\n" }, { "code": null, "e": 22511, "s": 22498, "text": "\nInternship\n" }, { "code": null, "e": 22521, "s": 22511, "text": "\nCareers\n" }, { "code": null, "e": 22679, "s": 22521, "text": "\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n" }, { "code": null, "e": 22703, "s": 22679, "text": "\nTop 50 Array Problems\n" }, { "code": null, "e": 22728, "s": 22703, "text": "\nTop 50 String Problems\n" }, { "code": null, "e": 22751, "s": 22728, "text": "\nTop 50 Tree Problems\n" }, { "code": null, "e": 22775, "s": 22751, "text": "\nTop 50 Graph Problems\n" }, { "code": null, "e": 22796, "s": 22775, "text": "\nTop 50 DP Problems\n" }, { "code": null, "e": 22834, "s": 22796, "text": "\nTutorials\n \n\n" }, { "code": null, "e": 22907, "s": 22834, "text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 22924, "s": 22907, "text": "\nApply for Jobs\n" }, { "code": null, "e": 22937, "s": 22924, "text": "\nPost a Job\n" }, { "code": null, "e": 22950, "s": 22937, "text": "\nJOB-A-THON\n" }, { "code": null, "e": 23136, "s": 22950, "text": "\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n" }, { "code": null, "e": 23155, "s": 23136, "text": "\nAll DSA Problems\n" }, { "code": null, "e": 23176, "s": 23155, "text": "\nProblem of the Day\n" }, { "code": null, "e": 23212, "s": 23176, "text": "\nInterview Series: Weekly Contests\n" }, { "code": null, "e": 23248, "s": 23212, "text": "\nBi-Wizard Coding: School Contests\n" }, { "code": null, "e": 23270, "s": 23248, "text": "\nContests and Events\n" }, { "code": null, "e": 23291, "s": 23270, "text": "\nPractice SDE Sheet\n" }, { "code": null, "e": 23297, "s": 23291, "text": "GBlog" }, { "code": null, "e": 23305, "s": 23297, "text": "Puzzles" }, { "code": null, "e": 23318, "s": 23305, "text": "What's New ?" }, { "code": null, "e": 23324, "s": 23318, "text": "Array" }, { "code": null, "e": 23331, "s": 23324, "text": "Matrix" }, { "code": null, "e": 23339, "s": 23331, "text": "Strings" }, { "code": null, "e": 23347, "s": 23339, "text": "Hashing" }, { "code": null, "e": 23359, "s": 23347, "text": "Linked List" }, { "code": null, "e": 23365, "s": 23359, "text": "Stack" }, { "code": null, "e": 23371, "s": 23365, "text": "Queue" }, { "code": null, "e": 23383, "s": 23371, "text": "Binary Tree" }, { "code": null, "e": 23402, "s": 23383, "text": "Binary Search Tree" }, { "code": null, "e": 23407, "s": 23402, "text": "Heap" }, { "code": null, "e": 23413, "s": 23407, "text": "Graph" }, { "code": null, "e": 23423, "s": 23413, "text": "Searching" }, { "code": null, "e": 23431, "s": 23423, "text": "Sorting" }, { "code": null, "e": 23448, "s": 23431, "text": "Divide & Conquer" }, { "code": null, "e": 23461, "s": 23448, "text": "Mathematical" }, { "code": null, "e": 23471, "s": 23461, "text": "Geometric" }, { "code": null, "e": 23479, "s": 23471, "text": "Bitwise" }, { "code": null, "e": 23486, "s": 23479, "text": "Greedy" }, { "code": null, "e": 23499, "s": 23486, "text": "Backtracking" }, { "code": null, "e": 23516, "s": 23499, "text": "Branch and Bound" }, { "code": null, "e": 23536, "s": 23516, "text": "Dynamic Programming" }, { "code": null, "e": 23554, "s": 23536, "text": "Pattern Searching" }, { "code": null, "e": 23565, "s": 23554, "text": "Randomized" }, { "code": null, "e": 23627, "s": 23565, "text": "Count of different ways to express N as the sum of 1, 3 and 4" }, { "code": null, "e": 23678, "s": 23627, "text": "Count ways to build street under given constraints" }, { "code": null, "e": 23718, "s": 23678, "text": "Count Balanced Binary Trees of Height h" }, { "code": null, "e": 23792, "s": 23718, "text": "Maximum number of envelopes that can be put inside other bigger envelopes" }, { "code": null, "e": 23856, "s": 23792, "text": "Minimize number of boxes by putting small box inside bigger one" }, { "code": null, "e": 23913, "s": 23856, "text": "Number of visible boxes after putting one inside another" }, { "code": null, "e": 23975, "s": 23913, "text": "Maximum number of teams that can be formed with given persons" }, { "code": null, "e": 24034, "s": 23975, "text": "Minimum and Maximum number of pairs in m teams of n people" }, { "code": null, "e": 24094, "s": 24034, "text": "Counting pairs when a person can form pair with at most one" }, { "code": null, "e": 24136, "s": 24094, "text": "Counts paths from a point to reach Origin" }, { "code": null, "e": 24177, "s": 24136, "text": "Count number of ways to cover a distance" }, { "code": null, "e": 24234, "s": 24177, "text": "Find the longest path in a matrix with given constraints" }, { "code": null, "e": 24281, "s": 24234, "text": "Top 20 Dynamic Programming Interview Questions" }, { "code": null, "e": 24315, "s": 24281, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 24368, "s": 24315, "text": "Maximum size rectangle binary sub-matrix with all 1s" }, { "code": null, "e": 24411, "s": 24368, "text": "Maximum size square sub-matrix with all 1s" }, { "code": null, "e": 24449, "s": 24411, "text": "Longest Increasing Subsequence | DP-3" }, { "code": null, "e": 24495, "s": 24449, "text": "Longest Increasing Subsequence Size (N log N)" }, { "code": null, "e": 24545, "s": 24495, "text": "Median in a stream of integers (running integers)" }, { "code": null, "e": 24592, "s": 24545, "text": "Median of Stream of Running Integers using STL" }, { "code": null, "e": 24655, "s": 24592, "text": "Minimum product of k integers in an array of positive Integers" }, { "code": null, "e": 24692, "s": 24655, "text": "K-th Largest Sum Contiguous Subarray" }, { "code": null, "e": 24735, "s": 24692, "text": "K maximum sum combinations from two arrays" }, { "code": null, "e": 24787, "s": 24735, "text": "K maximum sums of overlapping contiguous sub-arrays" }, { "code": null, "e": 24843, "s": 24787, "text": "K maximum sums of non-overlapping contiguous sub-arrays" }, { "code": null, "e": 24903, "s": 24843, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 24941, "s": 24903, "text": "Permutation and Combination in Python" }, { "code": null, "e": 24969, "s": 24941, "text": "Factorial of a large number" }, { "code": null, "e": 25046, "s": 24969, "text": "itertools.combinations() module in Python to print all possible combinations" }, { "code": null, "e": 25080, "s": 25046, "text": "Program to calculate value of nCr" }, { "code": null, "e": 25142, "s": 25080, "text": "Count of different ways to express N as the sum of 1, 3 and 4" }, { "code": null, "e": 25193, "s": 25142, "text": "Count ways to build street under given constraints" }, { "code": null, "e": 25233, "s": 25193, "text": "Count Balanced Binary Trees of Height h" }, { "code": null, "e": 25307, "s": 25233, "text": "Maximum number of envelopes that can be put inside other bigger envelopes" }, { "code": null, "e": 25371, "s": 25307, "text": "Minimize number of boxes by putting small box inside bigger one" }, { "code": null, "e": 25428, "s": 25371, "text": "Number of visible boxes after putting one inside another" }, { "code": null, "e": 25490, "s": 25428, "text": "Maximum number of teams that can be formed with given persons" }, { "code": null, "e": 25549, "s": 25490, "text": "Minimum and Maximum number of pairs in m teams of n people" }, { "code": null, "e": 25609, "s": 25549, "text": "Counting pairs when a person can form pair with at most one" }, { "code": null, "e": 25651, "s": 25609, "text": "Counts paths from a point to reach Origin" }, { "code": null, "e": 25692, "s": 25651, "text": "Count number of ways to cover a distance" }, { "code": null, "e": 25749, "s": 25692, "text": "Find the longest path in a matrix with given constraints" }, { "code": null, "e": 25796, "s": 25749, "text": "Top 20 Dynamic Programming Interview Questions" }, { "code": null, "e": 25830, "s": 25796, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 25883, "s": 25830, "text": "Maximum size rectangle binary sub-matrix with all 1s" }, { "code": null, "e": 25926, "s": 25883, "text": "Maximum size square sub-matrix with all 1s" }, { "code": null, "e": 25964, "s": 25926, "text": "Longest Increasing Subsequence | DP-3" }, { "code": null, "e": 26010, "s": 25964, "text": "Longest Increasing Subsequence Size (N log N)" }, { "code": null, "e": 26060, "s": 26010, "text": "Median in a stream of integers (running integers)" }, { "code": null, "e": 26107, "s": 26060, "text": "Median of Stream of Running Integers using STL" }, { "code": null, "e": 26170, "s": 26107, "text": "Minimum product of k integers in an array of positive Integers" }, { "code": null, "e": 26207, "s": 26170, "text": "K-th Largest Sum Contiguous Subarray" }, { "code": null, "e": 26250, "s": 26207, "text": "K maximum sum combinations from two arrays" }, { "code": null, "e": 26302, "s": 26250, "text": "K maximum sums of overlapping contiguous sub-arrays" }, { "code": null, "e": 26358, "s": 26302, "text": "K maximum sums of non-overlapping contiguous sub-arrays" }, { "code": null, "e": 26418, "s": 26358, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 26456, "s": 26418, "text": "Permutation and Combination in Python" }, { "code": null, "e": 26484, "s": 26456, "text": "Factorial of a large number" }, { "code": null, "e": 26561, "s": 26484, "text": "itertools.combinations() module in Python to print all possible combinations" }, { "code": null, "e": 26595, "s": 26561, "text": "Program to calculate value of nCr" }, { "code": null, "e": 26619, "s": 26595, "text": "Difficulty Level :\nEasy" }, { "code": null, "e": 26688, "s": 26619, "text": "Given N, count the number of ways to express N as sum of 1, 3 and 4." }, { "code": null, "e": 26699, "s": 26688, "text": "Examples: " }, { "code": null, "e": 26964, "s": 26699, "text": "Input : N = 4\nOutput : 4 \nExplanation: 1+1+1+1 \n 1+3\n 3+1 \n 4 \n\nInput : N = 5 \nOutput : 6\nExplanation: 1 + 1 + 1 + 1 + 1\n 1 + 4\n 4 + 1\n 1 + 1 + 3\n 1 + 3 + 1\n 3 + 1 + 1" }, { "code": null, "e": 27385, "s": 26964, "text": "Approach : Divide the problem into sub-problems for solving it. Let DP[n] be the be the number of ways to write N as the sum of 1, 3, and 4. Consider one possible solution with n = x1 + x2 + x3 + ... xn. If the last number is 1, then sum of the remaining numbers is n-1. So the number that ends with 1 is equal to DP[n-1]. Taking other cases into account where the last number is 3 and 4. The final recurrence would be: " }, { "code": null, "e": 27413, "s": 27385, "text": "DPn = DPn-1 + DPn-3 + DPn-4" }, { "code": null, "e": 27465, "s": 27413, "text": "Base case :\nDP[0] = DP[1] = DP[2] = 1 and DP[3] = 2" }, { "code": null, "e": 27469, "s": 27465, "text": "C++" }, { "code": null, "e": 27474, "s": 27469, "text": "Java" }, { "code": null, "e": 27482, "s": 27474, "text": "Python3" }, { "code": null, "e": 27485, "s": 27482, "text": "C#" }, { "code": null, "e": 27489, "s": 27485, "text": "PHP" }, { "code": null, "e": 27500, "s": 27489, "text": "Javascript" }, { "code": "// C++ program to illustrate the number of// ways to represent N as sum of 1, 3 and 4.#include <bits/stdc++.h>using namespace std; // function to count the number of// ways to represent n as sum of 1, 3 and 4int countWays(int n){ int DP[n + 1]; // base cases DP[0] = DP[1] = DP[2] = 1; DP[3] = 2; // iterate for all values from 4 to n for (int i = 4; i <= n; i++) DP[i] = DP[i - 1] + DP[i - 3] + DP[i - 4]; return DP[n];} // driver codeint main(){ int n = 10; cout << countWays(n); return 0;}", "e": 28037, "s": 27500, "text": null }, { "code": "// Java program to illustrate// the number of ways to represent// N as sum of 1, 3 and 4. class GFG { // Function to count the // number of ways to represent // n as sum of 1, 3 and 4 static int countWays(int n) { int DP[] = new int[n + 1]; // base cases DP[0] = DP[1] = DP[2] = 1; DP[3] = 2; // iterate for all values from 4 to n for (int i = 4; i <= n; i++) DP[i] = DP[i - 1] + DP[i - 3] + DP[i - 4]; return DP[n]; } // driver code public static void main(String[] args) { int n = 10; System.out.println(countWays(n)); }} // This code is contributed// by prerna saini.", "e": 28736, "s": 28037, "text": null }, { "code": "# Python program to illustrate the number of# ways to represent N as sum of 1, 3 and 4. # Function to count the number of# ways to represent n as sum of 1, 3 and 4def countWays(n): DP = [0 for i in range(0, n + 1)] # base cases DP[0] = DP[1] = DP[2] = 1 DP[3] = 2 # Iterate for all values from 4 to n for i in range(4, n + 1): DP[i] = DP[i - 1] + DP[i - 3] + DP[i - 4] return DP[n] # Driver coden = 10print (countWays(n)) # This code is contributed by Gitanjali.", "e": 29244, "s": 28736, "text": null }, { "code": "// C# program to illustrate// the number of ways to represent// N as sum of 1, 3 and 4.using System; class GFG { // Function to count the // number of ways to represent // n as sum of 1, 3 and 4 static int countWays(int n) { int []DP = new int[n + 1]; // base cases DP[0] = DP[1] = DP[2] = 1; DP[3] = 2; // iterate for all values from 4 to n for (int i = 4; i <= n; i++) DP[i] = DP[i - 1] + DP[i - 3] + DP[i - 4]; return DP[n]; } // Driver code public static void Main() { int n = 10; Console.WriteLine(countWays(n)); }} // This code is contributed// by vt_m.", "e": 29932, "s": 29244, "text": null }, { "code": "<?php// PHP program to illustrate// the number of ways to// represent N as sum of// 1, 3 and 4. // function to count the// number of ways to// represent n as sum of// 1, 3 and 4function countWays($n){ $DP = array(); // base cases $DP[0] = $DP[1] = $DP[2] = 1; $DP[3] = 2; // iterate for all // values from 4 to n for ($i = 4; $i <= $n; $i++) $DP[$i] = $DP[$i - 1] + $DP[$i - 3] + $DP[$i - 4]; return $DP[$n];} // Driver Code$n = 10;echo countWays($n); // This code is contributed// by Sam007?>", "e": 30498, "s": 29932, "text": null }, { "code": "<script> // Javascript program to illustrate// the number of ways to represent// N as sum of 1, 3 and 4. // Function to count the// number of ways to represent// n as sum of 1, 3 and 4function countWays(n){ var DP = []; DP.length = 10; DP.fill(0); // Base cases DP[0] = DP[1] = DP[2] = 1; DP[3] = 2; // Iterate for all values from 4 to n for(var i = 4; i <= n; i++) DP[i] = DP[i - 1] + DP[i - 3] + DP[i - 4]; return DP[n];} // Driver codevar n = 10; document.write(countWays(n)); // This code is contributed by bunnyram19 </script>", "e": 31084, "s": 30498, "text": null }, { "code": null, "e": 31093, "s": 31084, "text": "Output: " }, { "code": null, "e": 31096, "s": 31093, "text": "64" }, { "code": null, "e": 31143, "s": 31096, "text": "Time Complexity : O(n) Auxiliary Space : O(n) " }, { "code": null, "e": 31150, "s": 31143, "text": "Sam007" }, { "code": null, "e": 31161, "s": 31150, "text": "bunnyram19" }, { "code": null, "e": 31175, "s": 31161, "text": "Combinatorial" }, { "code": null, "e": 31195, "s": 31175, "text": "Dynamic Programming" }, { "code": null, "e": 31215, "s": 31195, "text": "Dynamic Programming" }, { "code": null, "e": 31229, "s": 31215, "text": "Combinatorial" }, { "code": null, "e": 31327, "s": 31229, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31345, "s": 31327, "text": "Combinational Sum" }, { "code": null, "e": 31400, "s": 31345, "text": "Count ways to reach the nth stair using step 1, 2 or 3" }, { "code": null, "e": 31485, "s": 31400, "text": "Print all possible strings of length k that can be formed from a set of n characters" }, { "code": null, "e": 31522, "s": 31485, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 31579, "s": 31522, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 31608, "s": 31579, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 31638, "s": 31608, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31670, "s": 31638, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 31701, "s": 31670, "text": "Bellman–Ford Algorithm | DP-23" } ]
Scala | Arrays - GeeksforGeeks
11 Mar, 2019 Array is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. The index of the first element of an array is zero and the last element is the total number of elements minus one. It is a collection of mutable values. It corresponds to arrays(in terms of syntax) in java but at the same time it’s different(in terms of functionalities) from java. Some Important Points: Scala arrays can be generic. which mean we can have an Array[T], where T is a type parameter or abstract type. Scala arrays are compatible with Scala sequences – we can pass an Array[T] where a Seq[T] is required. Scala arrays also support all sequence operations. The following figure shows how values can be stored in array sequentially : Scala supports both one as well as multi-dimension arrays. A single dimension array is one having only one row and n columns whereas two dimension array is actually a matrix of dimension (n * m). In this array contains only one row for storing the values. All values of this array are stored contiguously starting from 0 to the array size.Syntax: var arrayname = new Array[datatype](size) Here, datatype specifies the type of data being allocated, size specifies the number of elements in the array, and var is the name of array variable that is linked to the array.Example: // Scala program to creating an array // of the string as week days, store // day values in the weekdays, // and prints each value. object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var days = Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ) println("Array elements are : ") for ( m1 <-days ) { println(m1 ) } }} Array elements are : Sunday Monday Tuesday Wednesday Thursday Friday Saturday Here, we are creating an array to store the days of the week and printing all days. Accessing array elements:Example:// Scala program to accessing an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var name = Array("gfg", "geeks", "GeeksQuize", "geeksforgeeks" ) println("second element of an array is: ") // Accessing an array element println(name(1) ) }}Output:second element of an array is: geeksUpdating an element in array:Example:// Scala program to updating an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var name = Array("gfg", "geeks", "GeeksQuize", "geeksforgeeks" ) // Updating anelement in an array name(1)="employee" println("After updation array elements are: ") for ( m1 <-name ) { println(m1 ) } }}Output:After updation array elements are: gfg employee GeeksQuize geeksforgeeksAdding elements in an array:Example:// Scala program to adding elements in an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { var name = new Array[String](4) // Adding element in an array name(0)="gfg" name(1)="geeks" name(2)="GeeksQuize" name(3)="geeksforgeeks" println("After adding array elements : ") for ( m1 <-name ) { println(m1 ) } }}Output:After adding array elements : gfg geeks GeeksQuize geeksforgeeksConcatenate Arrays:We can concatenate two arrays by using concat() method. In concat() method we can pass more than one array as arguments.Example:// Scala program to concatenate two array // by using concat() methodimport Array._ // Creating objectobject GFG{ // Main methoddef main(args: Array[String]){ var arr1 = Array(1, 2, 3, 4) var arr2 = Array(5, 6, 7, 8) var arr3 = concat( arr1, arr2) // Print all the array elements for ( x <- arr3 ) { println( x ) }}}Output:1 2 3 4 5 6 7 8Here, arr1 is an array of four elements and arr2 is another array of four elements now we concatenate these two array in arr3 by using concat() method. Accessing array elements:Example:// Scala program to accessing an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var name = Array("gfg", "geeks", "GeeksQuize", "geeksforgeeks" ) println("second element of an array is: ") // Accessing an array element println(name(1) ) }}Output:second element of an array is: geeks // Scala program to accessing an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var name = Array("gfg", "geeks", "GeeksQuize", "geeksforgeeks" ) println("second element of an array is: ") // Accessing an array element println(name(1) ) }} Output: second element of an array is: geeks Updating an element in array:Example:// Scala program to updating an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var name = Array("gfg", "geeks", "GeeksQuize", "geeksforgeeks" ) // Updating anelement in an array name(1)="employee" println("After updation array elements are: ") for ( m1 <-name ) { println(m1 ) } }}Output:After updation array elements are: gfg employee GeeksQuize geeksforgeeks // Scala program to updating an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var name = Array("gfg", "geeks", "GeeksQuize", "geeksforgeeks" ) // Updating anelement in an array name(1)="employee" println("After updation array elements are: ") for ( m1 <-name ) { println(m1 ) } }} Output: After updation array elements are: gfg employee GeeksQuize geeksforgeeks Adding elements in an array:Example:// Scala program to adding elements in an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { var name = new Array[String](4) // Adding element in an array name(0)="gfg" name(1)="geeks" name(2)="GeeksQuize" name(3)="geeksforgeeks" println("After adding array elements : ") for ( m1 <-name ) { println(m1 ) } }}Output:After adding array elements : gfg geeks GeeksQuize geeksforgeeks // Scala program to adding elements in an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { var name = new Array[String](4) // Adding element in an array name(0)="gfg" name(1)="geeks" name(2)="GeeksQuize" name(3)="geeksforgeeks" println("After adding array elements : ") for ( m1 <-name ) { println(m1 ) } }} Output: After adding array elements : gfg geeks GeeksQuize geeksforgeeks Concatenate Arrays:We can concatenate two arrays by using concat() method. In concat() method we can pass more than one array as arguments.Example:// Scala program to concatenate two array // by using concat() methodimport Array._ // Creating objectobject GFG{ // Main methoddef main(args: Array[String]){ var arr1 = Array(1, 2, 3, 4) var arr2 = Array(5, 6, 7, 8) var arr3 = concat( arr1, arr2) // Print all the array elements for ( x <- arr3 ) { println( x ) }}}Output:1 2 3 4 5 6 7 8Here, arr1 is an array of four elements and arr2 is another array of four elements now we concatenate these two array in arr3 by using concat() method. // Scala program to concatenate two array // by using concat() methodimport Array._ // Creating objectobject GFG{ // Main methoddef main(args: Array[String]){ var arr1 = Array(1, 2, 3, 4) var arr2 = Array(5, 6, 7, 8) var arr3 = concat( arr1, arr2) // Print all the array elements for ( x <- arr3 ) { println( x ) }}} Output: 1 2 3 4 5 6 7 8 Here, arr1 is an array of four elements and arr2 is another array of four elements now we concatenate these two array in arr3 by using concat() method. The Multidimensional arrays contains more than one row to store the values. Scala has a method Array.ofDim to create Multidimensional arrays in Scala . In structures like matrices and tables multi-dimensional arrays can be used.Syntax: var array_name = Array.ofDim[ArrayType](N, M) or var array_name = Array(Array(elements), Array(elements) This is a Two-Dimension array. Here N is no. of rows and M is no. of Columns. Example: // Scala program to creating a // multidimension array of the // string as names, store // values in the names, // and prints each value. object GFG{ // Main method def main(args:Array[String]) { val rows = 2 val cols = 3 // Declaring Multidimension array val names = Array.ofDim[String](rows, cols) // Allocating values names(0)(0) = "gfg" names(0)(1) = "Geeks" names(0)(2) = "GeeksQuize" names(1)(0) = "GeeksForGeeks" names(1)(1) = "Employee" names(1)(2) = "Author" for { i <- 0 until rows j <- 0 until cols } // Printing values println(s"($i)($j) = ${names(i)(j)}") }} (0)(0) = gfg (0)(1) = Geeks (0)(2) = GeeksQuize (1)(0) = GeeksForGeeks (1)(1) = Employee (1)(2) = Author Use these operators (methods) to append and prepend elements to an array while assigning the result to a new variable: Examples to show how to use the above methods to append and prepend elements to an Array: object GFG{ // Main method def main(args: Array[String]) { // Declaring an array val a = Array(45, 52, 61) println("Array a ") for ( x <- a ) { println( x ) } // Appending 1 item val b = a :+ 27 println("Array b ") for ( x <- b ) { println( x ) } // Appending 2 item val c = b ++ Array(1, 2) println("Array c ") for ( x <- c ) { println( x ) } // Prepending 1 item val d = 3 +: c println("Array d ") for ( x <- d ) { println( x ) } // Prepending 2 item println("Array e ") val e = Array(10, 25) ++: d for ( x <- e ) { println( x ) } }} Output : Array a 45 52 61 Array b 45 52 61 27 Array c 45 52 61 27 1 2 Array d 3 45 52 61 27 1 2 Array e 10 25 3 45 52 61 27 1 2 Marketing Picked Scala Scala-Arrays Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. For Loop in Scala Scala | flatMap Method Scala | map() method Scala List filter() method with example Scala | reduce() Function String concatenation in Scala Type Casting in Scala Scala List contains() method with example Scala Tutorial – Learn Scala with Step By Step Guide How to get the first element of List in Scala
[ { "code": null, "e": 26614, "s": 26586, "text": "\n11 Mar, 2019" }, { "code": null, "e": 27022, "s": 26614, "text": "Array is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. The index of the first element of an array is zero and the last element is the total number of elements minus one. It is a collection of mutable values. It corresponds to arrays(in terms of syntax) in java but at the same time it’s different(in terms of functionalities) from java." }, { "code": null, "e": 27045, "s": 27022, "text": "Some Important Points:" }, { "code": null, "e": 27156, "s": 27045, "text": "Scala arrays can be generic. which mean we can have an Array[T], where T is a type parameter or abstract type." }, { "code": null, "e": 27259, "s": 27156, "text": "Scala arrays are compatible with Scala sequences – we can pass an Array[T] where a Seq[T] is required." }, { "code": null, "e": 27310, "s": 27259, "text": "Scala arrays also support all sequence operations." }, { "code": null, "e": 27386, "s": 27310, "text": "The following figure shows how values can be stored in array sequentially :" }, { "code": null, "e": 27582, "s": 27386, "text": "Scala supports both one as well as multi-dimension arrays. A single dimension array is one having only one row and n columns whereas two dimension array is actually a matrix of dimension (n * m)." }, { "code": null, "e": 27733, "s": 27582, "text": "In this array contains only one row for storing the values. All values of this array are stored contiguously starting from 0 to the array size.Syntax:" }, { "code": null, "e": 27775, "s": 27733, "text": "var arrayname = new Array[datatype](size)" }, { "code": null, "e": 27961, "s": 27775, "text": "Here, datatype specifies the type of data being allocated, size specifies the number of elements in the array, and var is the name of array variable that is linked to the array.Example:" }, { "code": "// Scala program to creating an array // of the string as week days, store // day values in the weekdays, // and prints each value. object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var days = Array(\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\" ) println(\"Array elements are : \") for ( m1 <-days ) { println(m1 ) } }}", "e": 28486, "s": 27961, "text": null }, { "code": null, "e": 28566, "s": 28486, "text": "Array elements are : \nSunday\nMonday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\n" }, { "code": null, "e": 28650, "s": 28566, "text": "Here, we are creating an array to store the days of the week and printing all days." }, { "code": null, "e": 31029, "s": 28650, "text": "Accessing array elements:Example:// Scala program to accessing an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var name = Array(\"gfg\", \"geeks\", \"GeeksQuize\", \"geeksforgeeks\" ) println(\"second element of an array is: \") // Accessing an array element println(name(1) ) }}Output:second element of an array is: \ngeeksUpdating an element in array:Example:// Scala program to updating an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var name = Array(\"gfg\", \"geeks\", \"GeeksQuize\", \"geeksforgeeks\" ) // Updating anelement in an array name(1)=\"employee\" println(\"After updation array elements are: \") for ( m1 <-name ) { println(m1 ) } }}Output:After updation array elements are: \ngfg\nemployee\nGeeksQuize\ngeeksforgeeksAdding elements in an array:Example:// Scala program to adding elements in an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { var name = new Array[String](4) // Adding element in an array name(0)=\"gfg\" name(1)=\"geeks\" name(2)=\"GeeksQuize\" name(3)=\"geeksforgeeks\" println(\"After adding array elements : \") for ( m1 <-name ) { println(m1 ) } }}Output:After adding array elements : \ngfg\ngeeks\nGeeksQuize\ngeeksforgeeksConcatenate Arrays:We can concatenate two arrays by using concat() method. In concat() method we can pass more than one array as arguments.Example:// Scala program to concatenate two array // by using concat() methodimport Array._ // Creating objectobject GFG{ // Main methoddef main(args: Array[String]){ var arr1 = Array(1, 2, 3, 4) var arr2 = Array(5, 6, 7, 8) var arr3 = concat( arr1, arr2) // Print all the array elements for ( x <- arr3 ) { println( x ) }}}Output:1\n2\n3\n4\n5\n6\n7\n8Here, arr1 is an array of four elements and arr2 is another array of four elements now we concatenate these two array in arr3 by using concat() method." }, { "code": null, "e": 31517, "s": 31029, "text": "Accessing array elements:Example:// Scala program to accessing an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var name = Array(\"gfg\", \"geeks\", \"GeeksQuize\", \"geeksforgeeks\" ) println(\"second element of an array is: \") // Accessing an array element println(name(1) ) }}Output:second element of an array is: \ngeeks" }, { "code": "// Scala program to accessing an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var name = Array(\"gfg\", \"geeks\", \"GeeksQuize\", \"geeksforgeeks\" ) println(\"second element of an array is: \") // Accessing an array element println(name(1) ) }}", "e": 31928, "s": 31517, "text": null }, { "code": null, "e": 31936, "s": 31928, "text": "Output:" }, { "code": null, "e": 31974, "s": 31936, "text": "second element of an array is: \ngeeks" }, { "code": null, "e": 32606, "s": 31974, "text": "Updating an element in array:Example:// Scala program to updating an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var name = Array(\"gfg\", \"geeks\", \"GeeksQuize\", \"geeksforgeeks\" ) // Updating anelement in an array name(1)=\"employee\" println(\"After updation array elements are: \") for ( m1 <-name ) { println(m1 ) } }}Output:After updation array elements are: \ngfg\nemployee\nGeeksQuize\ngeeksforgeeks" }, { "code": "// Scala program to updating an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var name = Array(\"gfg\", \"geeks\", \"GeeksQuize\", \"geeksforgeeks\" ) // Updating anelement in an array name(1)=\"employee\" println(\"After updation array elements are: \") for ( m1 <-name ) { println(m1 ) } }}", "e": 33121, "s": 32606, "text": null }, { "code": null, "e": 33129, "s": 33121, "text": "Output:" }, { "code": null, "e": 33203, "s": 33129, "text": "After updation array elements are: \ngfg\nemployee\nGeeksQuize\ngeeksforgeeks" }, { "code": null, "e": 33781, "s": 33203, "text": "Adding elements in an array:Example:// Scala program to adding elements in an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { var name = new Array[String](4) // Adding element in an array name(0)=\"gfg\" name(1)=\"geeks\" name(2)=\"GeeksQuize\" name(3)=\"geeksforgeeks\" println(\"After adding array elements : \") for ( m1 <-name ) { println(m1 ) } }}Output:After adding array elements : \ngfg\ngeeks\nGeeksQuize\ngeeksforgeeks" }, { "code": "// Scala program to adding elements in an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { var name = new Array[String](4) // Adding element in an array name(0)=\"gfg\" name(1)=\"geeks\" name(2)=\"GeeksQuize\" name(3)=\"geeksforgeeks\" println(\"After adding array elements : \") for ( m1 <-name ) { println(m1 ) } }}", "e": 34251, "s": 33781, "text": null }, { "code": null, "e": 34259, "s": 34251, "text": "Output:" }, { "code": null, "e": 34325, "s": 34259, "text": "After adding array elements : \ngfg\ngeeks\nGeeksQuize\ngeeksforgeeks" }, { "code": null, "e": 35009, "s": 34325, "text": "Concatenate Arrays:We can concatenate two arrays by using concat() method. In concat() method we can pass more than one array as arguments.Example:// Scala program to concatenate two array // by using concat() methodimport Array._ // Creating objectobject GFG{ // Main methoddef main(args: Array[String]){ var arr1 = Array(1, 2, 3, 4) var arr2 = Array(5, 6, 7, 8) var arr3 = concat( arr1, arr2) // Print all the array elements for ( x <- arr3 ) { println( x ) }}}Output:1\n2\n3\n4\n5\n6\n7\n8Here, arr1 is an array of four elements and arr2 is another array of four elements now we concatenate these two array in arr3 by using concat() method." }, { "code": "// Scala program to concatenate two array // by using concat() methodimport Array._ // Creating objectobject GFG{ // Main methoddef main(args: Array[String]){ var arr1 = Array(1, 2, 3, 4) var arr2 = Array(5, 6, 7, 8) var arr3 = concat( arr1, arr2) // Print all the array elements for ( x <- arr3 ) { println( x ) }}}", "e": 35373, "s": 35009, "text": null }, { "code": null, "e": 35381, "s": 35373, "text": "Output:" }, { "code": null, "e": 35397, "s": 35381, "text": "1\n2\n3\n4\n5\n6\n7\n8" }, { "code": null, "e": 35549, "s": 35397, "text": "Here, arr1 is an array of four elements and arr2 is another array of four elements now we concatenate these two array in arr3 by using concat() method." }, { "code": null, "e": 35785, "s": 35549, "text": "The Multidimensional arrays contains more than one row to store the values. Scala has a method Array.ofDim to create Multidimensional arrays in Scala . In structures like matrices and tables multi-dimensional arrays can be used.Syntax:" }, { "code": null, "e": 35893, "s": 35785, "text": "var array_name = Array.ofDim[ArrayType](N, M)\n or \nvar array_name = Array(Array(elements), Array(elements)" }, { "code": null, "e": 35971, "s": 35893, "text": "This is a Two-Dimension array. Here N is no. of rows and M is no. of Columns." }, { "code": null, "e": 35980, "s": 35971, "text": "Example:" }, { "code": "// Scala program to creating a // multidimension array of the // string as names, store // values in the names, // and prints each value. object GFG{ // Main method def main(args:Array[String]) { val rows = 2 val cols = 3 // Declaring Multidimension array val names = Array.ofDim[String](rows, cols) // Allocating values names(0)(0) = \"gfg\" names(0)(1) = \"Geeks\" names(0)(2) = \"GeeksQuize\" names(1)(0) = \"GeeksForGeeks\" names(1)(1) = \"Employee\" names(1)(2) = \"Author\" for { i <- 0 until rows j <- 0 until cols } // Printing values println(s\"($i)($j) = ${names(i)(j)}\") }}", "e": 36730, "s": 35980, "text": null }, { "code": null, "e": 36836, "s": 36730, "text": "(0)(0) = gfg\n(0)(1) = Geeks\n(0)(2) = GeeksQuize\n(1)(0) = GeeksForGeeks\n(1)(1) = Employee\n(1)(2) = Author\n" }, { "code": null, "e": 36955, "s": 36836, "text": "Use these operators (methods) to append and prepend elements to an array while assigning the result to a new variable:" }, { "code": null, "e": 37045, "s": 36955, "text": "Examples to show how to use the above methods to append and prepend elements to an Array:" }, { "code": "object GFG{ // Main method def main(args: Array[String]) { // Declaring an array val a = Array(45, 52, 61) println(\"Array a \") for ( x <- a ) { println( x ) } // Appending 1 item val b = a :+ 27 println(\"Array b \") for ( x <- b ) { println( x ) } // Appending 2 item val c = b ++ Array(1, 2) println(\"Array c \") for ( x <- c ) { println( x ) } // Prepending 1 item val d = 3 +: c println(\"Array d \") for ( x <- d ) { println( x ) } // Prepending 2 item println(\"Array e \") val e = Array(10, 25) ++: d for ( x <- e ) { println( x ) } }}", "e": 37728, "s": 37045, "text": null }, { "code": null, "e": 37737, "s": 37728, "text": "Output :" }, { "code": null, "e": 37862, "s": 37737, "text": "Array a \n45\n52\n61\nArray b \n45\n52\n61\n27\nArray c \n45\n52\n61\n27\n1\n2\nArray d \n3\n45\n52\n61\n27\n1\n2\nArray e \n10\n25\n3\n45\n52\n61\n27\n1\n2\n" }, { "code": null, "e": 37872, "s": 37862, "text": "Marketing" }, { "code": null, "e": 37879, "s": 37872, "text": "Picked" }, { "code": null, "e": 37885, "s": 37879, "text": "Scala" }, { "code": null, "e": 37898, "s": 37885, "text": "Scala-Arrays" }, { "code": null, "e": 37904, "s": 37898, "text": "Scala" }, { "code": null, "e": 38002, "s": 37904, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38020, "s": 38002, "text": "For Loop in Scala" }, { "code": null, "e": 38043, "s": 38020, "text": "Scala | flatMap Method" }, { "code": null, "e": 38064, "s": 38043, "text": "Scala | map() method" }, { "code": null, "e": 38104, "s": 38064, "text": "Scala List filter() method with example" }, { "code": null, "e": 38130, "s": 38104, "text": "Scala | reduce() Function" }, { "code": null, "e": 38160, "s": 38130, "text": "String concatenation in Scala" }, { "code": null, "e": 38182, "s": 38160, "text": "Type Casting in Scala" }, { "code": null, "e": 38224, "s": 38182, "text": "Scala List contains() method with example" }, { "code": null, "e": 38277, "s": 38224, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" } ]
C++ Assignment Operators
Try the following example to understand all the assignment operators available in C++. Copy and paste the following C++ program in test.cpp file and compile and run this program. #include <iostream> using namespace std; main() { int a = 21; int c ; c = a; cout << "Line 1 - = Operator, Value of c = : " <<c<< endl ; c += a; cout << "Line 2 - += Operator, Value of c = : " <<c<< endl ; c -= a; cout << "Line 3 - -= Operator, Value of c = : " <<c<< endl ; c *= a; cout << "Line 4 - *= Operator, Value of c = : " <<c<< endl ; c /= a; cout << "Line 5 - /= Operator, Value of c = : " <<c<< endl ; c = 200; c %= a; cout << "Line 6 - %= Operator, Value of c = : " <<c<< endl ; c <<= 2; cout << "Line 7 - <<= Operator, Value of c = : " <<c<< endl ; c >>= 2; cout << "Line 8 - >>= Operator, Value of c = : " <<c<< endl ; c &= 2; cout << "Line 9 - &= Operator, Value of c = : " <<c<< endl ; c ^= 2; cout << "Line 10 - ^= Operator, Value of c = : " <<c<< endl ; c |= 2; cout << "Line 11 - |= Operator, Value of c = : " <<c<< endl ; return 0; } When the above code is compiled and executed, it produces the following result − Line 1 - = Operator, Value of c = : 21 Line 2 - += Operator, Value of c = : 42 Line 3 - -= Operator, Value of c = : 21 Line 4 - *= Operator, Value of c = : 441 Line 5 - /= Operator, Value of c = : 21 Line 6 - %= Operator, Value of c = : 11 Line 7 - <<= Operator, Value of c = : 44 Line 8 - >>= Operator, Value of c = : 11 Line 9 - &= Operator, Value of c = : 2 Line 10 - ^= Operator, Value of c = : 0 Line 11 - |= Operator, Value of c = : 2 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2405, "s": 2318, "text": "Try the following example to understand all the assignment operators available in C++." }, { "code": null, "e": 2497, "s": 2405, "text": "Copy and paste the following C++ program in test.cpp file and compile and run this program." }, { "code": null, "e": 3455, "s": 2497, "text": "#include <iostream>\nusing namespace std;\n\nmain() {\n int a = 21;\n int c ;\n\n c = a;\n cout << \"Line 1 - = Operator, Value of c = : \" <<c<< endl ;\n\n c += a;\n cout << \"Line 2 - += Operator, Value of c = : \" <<c<< endl ;\n\n c -= a;\n cout << \"Line 3 - -= Operator, Value of c = : \" <<c<< endl ;\n\n c *= a;\n cout << \"Line 4 - *= Operator, Value of c = : \" <<c<< endl ;\n\n c /= a;\n cout << \"Line 5 - /= Operator, Value of c = : \" <<c<< endl ;\n\n c = 200;\n c %= a;\n cout << \"Line 6 - %= Operator, Value of c = : \" <<c<< endl ;\n\n c <<= 2;\n cout << \"Line 7 - <<= Operator, Value of c = : \" <<c<< endl ;\n\n c >>= 2;\n cout << \"Line 8 - >>= Operator, Value of c = : \" <<c<< endl ;\n\n c &= 2;\n cout << \"Line 9 - &= Operator, Value of c = : \" <<c<< endl ;\n\n c ^= 2;\n cout << \"Line 10 - ^= Operator, Value of c = : \" <<c<< endl ;\n\n c |= 2;\n cout << \"Line 11 - |= Operator, Value of c = : \" <<c<< endl ;\n\n return 0;\n}" }, { "code": null, "e": 3536, "s": 3455, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3979, "s": 3536, "text": "Line 1 - = Operator, Value of c = : 21\nLine 2 - += Operator, Value of c = : 42\nLine 3 - -= Operator, Value of c = : 21\nLine 4 - *= Operator, Value of c = : 441\nLine 5 - /= Operator, Value of c = : 21\nLine 6 - %= Operator, Value of c = : 11\nLine 7 - <<= Operator, Value of c = : 44\nLine 8 - >>= Operator, Value of c = : 11\nLine 9 - &= Operator, Value of c = : 2\nLine 10 - ^= Operator, Value of c = : 0\nLine 11 - |= Operator, Value of c = : 2\n" }, { "code": null, "e": 4016, "s": 3979, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 4035, "s": 4016, "text": " Arnab Chakraborty" }, { "code": null, "e": 4067, "s": 4035, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 4090, "s": 4067, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 4126, "s": 4090, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 4143, "s": 4126, "text": " Frahaan Hussain" }, { "code": null, "e": 4178, "s": 4143, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4195, "s": 4178, "text": " Frahaan Hussain" }, { "code": null, "e": 4230, "s": 4195, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4247, "s": 4230, "text": " Frahaan Hussain" }, { "code": null, "e": 4282, "s": 4247, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4299, "s": 4282, "text": " Frahaan Hussain" }, { "code": null, "e": 4306, "s": 4299, "text": " Print" }, { "code": null, "e": 4317, "s": 4306, "text": " Add Notes" } ]
Can static variables be called using className.variableName in Java?
Class variables also known as static variables are declared with the static keyword There would only be one copy of each class variable per class, regardless of how many objects are created from it. You can access a class variable without instantiation using the class name as className.variableName. Live Demo public class Test{ static int num = 92; public static void main(String args[]) throws Exception { System.out.println(Test.num); } } 92
[ { "code": null, "e": 1363, "s": 1062, "text": "Class variables also known as static variables are declared with the static keyword There would only be one copy of each class variable per class, regardless of how many objects are created from it. You can access a class variable without instantiation using the class name as className.variableName." }, { "code": null, "e": 1374, "s": 1363, "text": " Live Demo" }, { "code": null, "e": 1525, "s": 1374, "text": "public class Test{\n static int num = 92;\n \n public static void main(String args[]) throws Exception {\n System.out.println(Test.num);\n }\n}" }, { "code": null, "e": 1529, "s": 1525, "text": "92\n" } ]
Format double type in Java
Let’s say we have the following three values − double val1 = 15.546; double val2 = 25.87; double val3 = Math.PI; Let us now format these double-type numbers. Firstly, we are formatting Euler’s number with Math.exp(). After that, we have also evaluated log. The %.3f you can see here is what we used for formatting the numbers. System.out.printf("exp(%.3f) = %.3f%n", val1, Math.exp(val1)); System.out.printf("log = %.3f%n", val1, Math.log(val1)); The following is an example where we have also shown other ways to format double in Java. Live Demo public class Demo { public static void main(String args[]) { double val1 = 15.546; double val2 = 25.87; double val3 = Math.PI; System.out.format("%f%n", val1); System.out.printf("exp(%.3f) = %.3f%n", val1, Math.exp(val1)); System.out.printf("log = %.3f%n", val1, Math.log(val1)); System.out.format("%3f%n", val2); System.out.format("%+3f%n", val2); System.out.format("%f%n", val3); System.out.format("%.3f%n", val3); System.out.printf("pow(%.3f, %.3f) = %.3f%n", val1, val2, Math.pow(val1, val2)); } } 15.546000 exp(15.546) = 5643415.357 log = 15.546 25.870000 +25.870000 3.141593 3.142 pow(15.546, 25.870) = 6716991850252629000000000000000.000
[ { "code": null, "e": 1109, "s": 1062, "text": "Let’s say we have the following three values −" }, { "code": null, "e": 1175, "s": 1109, "text": "double val1 = 15.546;\ndouble val2 = 25.87;\ndouble val3 = Math.PI;" }, { "code": null, "e": 1389, "s": 1175, "text": "Let us now format these double-type numbers. Firstly, we are formatting Euler’s number with Math.exp(). After that, we have also evaluated log. The %.3f you can see here is what we used for formatting the numbers." }, { "code": null, "e": 1509, "s": 1389, "text": "System.out.printf(\"exp(%.3f) = %.3f%n\", val1, Math.exp(val1));\nSystem.out.printf(\"log = %.3f%n\", val1, Math.log(val1));" }, { "code": null, "e": 1599, "s": 1509, "text": "The following is an example where we have also shown other ways to format double in Java." }, { "code": null, "e": 1610, "s": 1599, "text": " Live Demo" }, { "code": null, "e": 2184, "s": 1610, "text": "public class Demo {\n public static void main(String args[]) {\n double val1 = 15.546;\n double val2 = 25.87;\n double val3 = Math.PI;\n System.out.format(\"%f%n\", val1);\n System.out.printf(\"exp(%.3f) = %.3f%n\", val1, Math.exp(val1));\n System.out.printf(\"log = %.3f%n\", val1, Math.log(val1));\n System.out.format(\"%3f%n\", val2);\n System.out.format(\"%+3f%n\", val2);\n System.out.format(\"%f%n\", val3);\n System.out.format(\"%.3f%n\", val3);\n System.out.printf(\"pow(%.3f, %.3f) = %.3f%n\", val1, val2, Math.pow(val1, val2));\n }\n}" }, { "code": null, "e": 2327, "s": 2184, "text": "15.546000\nexp(15.546) = 5643415.357\nlog = 15.546\n25.870000\n+25.870000\n3.141593\n3.142\npow(15.546, 25.870) = 6716991850252629000000000000000.000" } ]
How can I show image rollover with a mouse event in JavaScript?
To show image rollover with a mouse event, you can try to run the following code − <html> <head> <title>Rollover with a Mouse Event</title> <script> <!-- if(document.images) { var image1 = new Image(); // Preload an image image1.src = "/images/html.gif"; var image2 = new Image(); // Preload second image image2.src = "/images/http.gif"; } //--> </script> </head> <body> <p>Move your mouse over the image to see the result</p> <a href = "#" onMouseOver = "document.myImage.src = image2.src;" onMouseOut = "document.myImage.src = image1.src;"> <img name = "myImage" src = "/images/html.gif" /> </a> </body> </html> Let's see what we have used in the above example to automate animation − At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed. The Image() constructor creates and preloads a new image object called image1. The src property is assigned the name of the external image file called /images/html.gif. Similarly, we have created an image2 object and assigned /images/http.gif in this object. The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image. The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is triggered when the user's mouse moves away from the link (image).
[ { "code": null, "e": 1145, "s": 1062, "text": "To show image rollover with a mouse event, you can try to run the following code −" }, { "code": null, "e": 1836, "s": 1145, "text": "<html>\n <head>\n <title>Rollover with a Mouse Event</title>\n <script>\n <!--\n if(document.images) {\n var image1 = new Image(); // Preload an image\n image1.src = \"/images/html.gif\";\n var image2 = new Image(); // Preload second image\n image2.src = \"/images/http.gif\";\n }\n //-->\n </script>\n </head>\n <body>\n <p>Move your mouse over the image to see the result</p>\n\n <a href = \"#\" onMouseOver = \"document.myImage.src = image2.src;\" onMouseOut = \"document.myImage.src = image1.src;\">\n <img name = \"myImage\" src = \"/images/html.gif\" />\n </a>\n </body>\n</html>" }, { "code": null, "e": 1909, "s": 1836, "text": "Let's see what we have used in the above example to automate animation −" }, { "code": null, "e": 2077, "s": 1909, "text": "At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed." }, { "code": null, "e": 2156, "s": 2077, "text": "The Image() constructor creates and preloads a new image object called image1." }, { "code": null, "e": 2246, "s": 2156, "text": "The src property is assigned the name of the external image file called /images/html.gif." }, { "code": null, "e": 2336, "s": 2246, "text": "Similarly, we have created an image2 object and assigned /images/http.gif in this object." }, { "code": null, "e": 2457, "s": 2336, "text": "The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image." }, { "code": null, "e": 2645, "s": 2457, "text": "The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is triggered when the user's mouse moves away from the link (image)." } ]
Multiplication Table | Practice | GeeksforGeeks
Print the multiplication table of a given number N. Example 1: Input: N = 9 Output: 9 18 27 36 45 54 63 72 81 90 Explanation: The table of 9 is the output whose 1st term is 9 and the 10th term is 90. Example 2: Input: N = 2 Output: 2 4 6 8 10 12 14 16 18 20 Your Task: You don't need to read input. Your task is to complete the function getTable() which takes an integer N as input parameter and returns a list of integers denoting the multiplication of table of N from 1 to 10. Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 106 0 rsbly7300951 week ago getTable(N) { let table = []; for(let i = 1; i <= 10; i++) { table.push(N*i); } return table; } } 0 p66ldbtsyygxakejw499ya21le3xno52xzcotukc2 weeks ago [...Array(10)].map((_, i) => i < 10 ? String((i + 1)*N) : '' ) 0 avijit1126be203 weeks ago class Solution{ static ArrayList<Integer> getTable(int N){ // code here ArrayList<Integer> val = new ArrayList<Integer>(); for(int i=1;i<=10;i++) { val.add(i*N); } return val; }} 0 fmurga3 weeks ago class Solution { getTable(N) { //code here let res = []; for (let i=1;i<=10;i++){ res.push(i*N) } return res }} 0 jayprakashdhananjay4 weeks ago class Solution: def getTable(self,N): return map(lambda x:x*N,range(1,11)) 0 satyabratasbr1 month ago def printpat(n) : for i in range(1, 11) : print(i*n) printpat(9) 0 jabirmohammad210720021 month ago All Test cases Passes ! code. vector<int> getTable(int N) { vector<int>v; for(int i=1;i<=10;i++) { v.push_back(i*N); } return v; } 0 amrendra0871 month ago class Solution{ static ArrayList<Integer> getTable(int N){ // Write Your Code here ArrayList<Integer> numberTable = new ArrayList<>(); for(int i=1;i<=10;i++){ //System.out.print(N*i+" "); int tableCalculation = i*N; numberTable.add(tableCalculation); } return numberTable; }} 0 syedabdulwasay71 month ago Python solution class Solution: def getTable(self,N): c=0 for i in range(1, 11): c = i * N print(c,end=" ") 0 mohammadtanveer75401 month ago class Solution { public: vector<int> getTable(int N) { vector<int> v(0); for(int i=1;i<=10;i++) cout<<N*i<<" "; return v; } }; 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": 279, "s": 226, "text": "Print the multiplication table of a given number N. " }, { "code": null, "e": 291, "s": 279, "text": "\nExample 1:" }, { "code": null, "e": 431, "s": 291, "text": "Input:\nN = 9\n\nOutput:\n9 18 27 36 45 54 63 72 81 90\n\nExplanation:\nThe table of 9 is the output whose 1st \nterm is 9 and the 10th term is 90." }, { "code": null, "e": 443, "s": 431, "text": "\nExample 2:" }, { "code": null, "e": 494, "s": 443, "text": "Input:\nN = 2\n\nOutput:\n2 4 6 8 10 12 14 16 18 20\n\n\n" }, { "code": null, "e": 781, "s": 494, "text": "Your Task: \nYou don't need to read input. Your task is to complete the function getTable() which takes an integer N as input parameter and returns a list of integers denoting the multiplication of table of N from 1 to 10. \n\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 810, "s": 781, "text": "\nConstraints: \n1 <= N <= 106" }, { "code": null, "e": 812, "s": 810, "text": "0" }, { "code": null, "e": 834, "s": 812, "text": "rsbly7300951 week ago" }, { "code": null, "e": 969, "s": 834, "text": " getTable(N) {\n let table = [];\n \n for(let i = 1; i <= 10; i++) {\n table.push(N*i);\n }\n return table;\n }\n}" }, { "code": null, "e": 971, "s": 969, "text": "0" }, { "code": null, "e": 1023, "s": 971, "text": "p66ldbtsyygxakejw499ya21le3xno52xzcotukc2 weeks ago" }, { "code": null, "e": 1086, "s": 1023, "text": "[...Array(10)].map((_, i) => i < 10 ? String((i + 1)*N) : '' )" }, { "code": null, "e": 1088, "s": 1086, "text": "0" }, { "code": null, "e": 1114, "s": 1088, "text": "avijit1126be203 weeks ago" }, { "code": null, "e": 1350, "s": 1114, "text": "class Solution{ static ArrayList<Integer> getTable(int N){ // code here ArrayList<Integer> val = new ArrayList<Integer>(); for(int i=1;i<=10;i++) { val.add(i*N); } return val; }}" }, { "code": null, "e": 1352, "s": 1350, "text": "0" }, { "code": null, "e": 1370, "s": 1352, "text": "fmurga3 weeks ago" }, { "code": null, "e": 1498, "s": 1370, "text": "class Solution { getTable(N) { //code here let res = []; for (let i=1;i<=10;i++){ res.push(i*N) } return res }}" }, { "code": null, "e": 1500, "s": 1498, "text": "0" }, { "code": null, "e": 1531, "s": 1500, "text": "jayprakashdhananjay4 weeks ago" }, { "code": null, "e": 1618, "s": 1531, "text": "class Solution:\n def getTable(self,N):\n return map(lambda x:x*N,range(1,11))" }, { "code": null, "e": 1620, "s": 1618, "text": "0" }, { "code": null, "e": 1645, "s": 1620, "text": "satyabratasbr1 month ago" }, { "code": null, "e": 1663, "s": 1645, "text": "def printpat(n) :" }, { "code": null, "e": 1695, "s": 1663, "text": " for i in range(1, 11) :" }, { "code": null, "e": 1725, "s": 1695, "text": " print(i*n) " }, { "code": null, "e": 1738, "s": 1725, "text": "printpat(9) " }, { "code": null, "e": 1742, "s": 1740, "text": "0" }, { "code": null, "e": 1775, "s": 1742, "text": "jabirmohammad210720021 month ago" }, { "code": null, "e": 1805, "s": 1775, "text": "All Test cases Passes ! code." }, { "code": null, "e": 1953, "s": 1805, "text": "vector<int> getTable(int N) { vector<int>v; for(int i=1;i<=10;i++) { v.push_back(i*N); } return v; }" }, { "code": null, "e": 1955, "s": 1953, "text": "0" }, { "code": null, "e": 1978, "s": 1955, "text": "amrendra0871 month ago" }, { "code": null, "e": 2325, "s": 1978, "text": "class Solution{ static ArrayList<Integer> getTable(int N){ // Write Your Code here ArrayList<Integer> numberTable = new ArrayList<>(); for(int i=1;i<=10;i++){ //System.out.print(N*i+\" \"); int tableCalculation = i*N; numberTable.add(tableCalculation); } return numberTable; }}" }, { "code": null, "e": 2327, "s": 2325, "text": "0" }, { "code": null, "e": 2354, "s": 2327, "text": "syedabdulwasay71 month ago" }, { "code": null, "e": 2370, "s": 2354, "text": "Python solution" }, { "code": null, "e": 2503, "s": 2372, "text": "class Solution: def getTable(self,N): c=0 for i in range(1, 11): c = i * N print(c,end=\" \")" }, { "code": null, "e": 2505, "s": 2503, "text": "0" }, { "code": null, "e": 2536, "s": 2505, "text": "mohammadtanveer75401 month ago" }, { "code": null, "e": 2712, "s": 2536, "text": "class Solution\n{\npublic:\n vector<int> getTable(int N)\n {\n vector<int> v(0);\n for(int i=1;i<=10;i++)\n cout<<N*i<<\" \";\n return v;\n }\n};\n" }, { "code": null, "e": 2858, "s": 2712, "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": 2894, "s": 2858, "text": " Login to access your submissions. " }, { "code": null, "e": 2904, "s": 2894, "text": "\nProblem\n" }, { "code": null, "e": 2914, "s": 2904, "text": "\nContest\n" }, { "code": null, "e": 2977, "s": 2914, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3125, "s": 2977, "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": 3333, "s": 3125, "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": 3439, "s": 3333, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Restricting and Sorting Data Questions
1. Which of the following clause is used to limit the number of rows retrieved from a SELECT query? LIMIT WHERE AND FROM LIMIT WHERE AND FROM Answer: B. The WHERE clause is used to restrict the number of rows returned from a SELECT query. 2. Choose the database elements whose values can be compared in a WHERE clause of a SELECT query. Column Sequence Procedure Literal Column Sequence Procedure Literal Answer: A, D. The WHERE clause can be used to compare the values from columns, literals, arithmetic functions and functions. 3. What are the elements NOT contained in the WHERE clause predicate of the SELECT query? Comparison operator Comparison condition Column Name Table Name Comparison operator Comparison condition Column Name Table Name Answer: D. Table Name is not required in the WHERE clause predicate. 4. Which of the following values can NOT be returned after evaluation of WHERE clause condition? UNKNOWN TRUE FALSE NULL UNKNOWN TRUE FALSE NULL Answer: A. If the result of the condition in WHERE clause is not known, NULL is returned. In all other scenarios, either TRUE or FALSE is returned. 5. What is the minimum number of WHERE clauses that must be present in a SELECT query? 1 2 0 3 1 2 0 3 Answer: C. The WHERE clause is an optional clause in the SELECT query which is only used to restrict the number of rows. 6. What is the maximum number of WHERE clauses that can be included in a SELECT query? 1 2 0 3 1 2 0 3 Answer: A. The WHERE clause is an optional clause in the SELECT query which can be used only once to restrict the number of rows. 7. Which of the following statements are correct about the WHERE clause? Column Alias can be used in WHERE clause to refer a column Comparison operator is an optional element in WHERE clause condition Functions can be used as operands in the WHERE clause There can be multiple WHERE clause in a SELECT query Column Alias can be used in WHERE clause to refer a column Comparison operator is an optional element in WHERE clause condition Functions can be used as operands in the WHERE clause There can be multiple WHERE clause in a SELECT query Answer: C. The WHERE clause must have comparison operator to evaluate the condition. It can use function as one of the operand. Only one WHERE clause is allowed in a SELECT query. 8. Write a SELECT query to list down unique departments from EMP table? SELECT deptno FROM emp; SELECT DISTINCT deptno FROM emp; SELECT DISTINCT (deptno) FROM emp; SELECT empno, DISTINCT deptno FROM emp; SELECT deptno FROM emp; SELECT deptno FROM emp; SELECT DISTINCT deptno FROM emp; SELECT DISTINCT deptno FROM emp; SELECT DISTINCT (deptno) FROM emp; SELECT DISTINCT (deptno) FROM emp; SELECT empno, DISTINCT deptno FROM emp; SELECT empno, DISTINCT deptno FROM emp; Answer: B & C. The keyword DISTINCT is used to filter out the duplicate rows from the SELECT query. 9. Which of the following operations are permitted for date and timestamp columns? Division Addition Subtraction Concatenation Division Addition Subtraction Concatenation Answer: B, C, and D. Addition, subtraction and Concatenation are the operations permitted for date and timestamp columns. 10. From the below operators, which one of them holds the highest precedence level? Division (/) Multiplication (*) Brackets ( () ) Subtraction Division (/) Multiplication (*) Brackets ( () ) Subtraction Answer: C. Expressions within the brackets hold the highest precedence level. 11. Interpret the output returned by the below SELECT query SELECT ename, (sysdate - hiredate) FROM emp; Number of days in the current year Number of days in the year when an employee was hired Number of days spent by employee with the company The query raises exception "ORA-00932: inconsistent datatypes: expected NUMBER got DATE" Number of days in the current year Number of days in the year when an employee was hired Number of days spent by employee with the company The query raises exception "ORA-00932: inconsistent datatypes: expected NUMBER got DATE" Answer: C. The expression (sysdate-hiredate) returns the number of employment days of an employee with the company. 12. Which of the below statements correctly describle the DUAL table in Oracle? DUAL table is a temporary table in Oracle database DUAL table contains only one character type column known as DUMMY DUAL table owned by SYS cannot be dropped A table with the name DUAL can be created by a user in its own schema DUAL table is a temporary table in Oracle database DUAL table contains only one character type column known as DUMMY DUAL table owned by SYS cannot be dropped A table with the name DUAL can be created by a user in its own schema Answer: B, C, D. The DUAL table in Oracle is owned by SYS and contains one column DUMMY of type VARCHAR2(1). 13. Determine the type of output returned by the below query SELECT sysdate - hiredate FROM emp WHERE empno=7369; DATE data type NUMBER data type VARCHAR2 data type The query raises error since arithmetic operations cannot be performed on date columns DATE data type NUMBER data type VARCHAR2 data type The query raises error since arithmetic operations cannot be performed on date columns Answer: B. Subtraction between two dates results in numeric difference of days between the two dates 14. Which expressions do NOT return NULL values? SELECT ((10 + 20) * 50) + null from dual; SELECT 'this is a '||null||'test with nulls' from dual; SELECT null/0 from dual; SELECT null||'test'||null as “Test” from dual; SELECT ((10 + 20) * 50) + null from dual; SELECT ((10 + 20) * 50) + null from dual; SELECT 'this is a '||null||'test with nulls' from dual; SELECT 'this is a '||null||'test with nulls' from dual; SELECT null/0 from dual; SELECT null/0 from dual; SELECT null||'test'||null as “Test” from dual; SELECT null||'test'||null as “Test” from dual; Answer: B, D. Any arithmetic operation with NULL results in NULL. 15. Determine the output of the below query SELECT 'Tutorial''s Point compiles technical tutorials' FROM DUAL; Tutorial''s Point compiles technical tutorials Tutorial's Point compiles technical tutorials 'Tutorial''s Point compiles technical tutorials' Raises exception "ORA-01756: quoted string not properly terminated" Tutorial''s Point compiles technical tutorials Tutorial's Point compiles technical tutorials 'Tutorial''s Point compiles technical tutorials' Raises exception "ORA-01756: quoted string not properly terminated" Answer: B. 16. Examine the TRAINING table as given below: Name Null? Type ----------------------------------------- -------- ------------- TRAINING_ID NOT NULL NUMBER(5) TRAINING_LOCATION NUMBER(7,2) START_DATE DATE END_DATE DATE SELECT NVL (ADD_MONTHS (END_DATE,1),SYSDATE) FROM training; SELECT TO_DATE (NVL(SYSDATE-END_DATE,SYSDATE)) FROM training; SELECT NVL(MONTHS_BETWEEN(START_DATE,END_DATE),’In Progress’) FROM training; SELECT NVL(TO_CHAR(MONTHS_BETWEEN(START_DATE,END_DATE)),’In Progress’) FROM training; SELECT NVL (ADD_MONTHS (END_DATE,1),SYSDATE) FROM training; SELECT NVL (ADD_MONTHS (END_DATE,1),SYSDATE) FROM training; SELECT TO_DATE (NVL(SYSDATE-END_DATE,SYSDATE)) FROM training; SELECT TO_DATE (NVL(SYSDATE-END_DATE,SYSDATE)) FROM training; SELECT NVL(MONTHS_BETWEEN(START_DATE,END_DATE),’In Progress’) FROM training; SELECT NVL(MONTHS_BETWEEN(START_DATE,END_DATE),’In Progress’) FROM training; SELECT NVL(TO_CHAR(MONTHS_BETWEEN(START_DATE,END_DATE)),’In Progress’) FROM training; SELECT NVL(TO_CHAR(MONTHS_BETWEEN(START_DATE,END_DATE)),’In Progress’) FROM training; Answer: A, D. Use NVL function to provide an alternate value to a column when NULL. 17. What does the selection of columns in a SELECT statement known as? Retrieval Selection Projection Limiting Retrieval Selection Projection Limiting Answer: C. Projection is the ability to select only the required columns in SELECT statement. 18. What does the restriction of rows returned by a SELECT statement known as Retrieval Projection Restricting Selection Retrieval Projection Restricting Selection Answer: C. Restricting is the ability to limit the number of rows by putting certain conditions. 19. Which of the following is true about the query given below? SELECT col1, col2 FROM tab1 ORDER BY col1; All the rows for the column COL1 will be sorted in the Descending order. All the rows for the column COL1 will be sorted in the Ascending order. The query will give an error as there is no WHERE clause in the query. The query will give an error as the ORDER BY clause should include all the columns in the SELECT clause. All the rows for the column COL1 will be sorted in the Descending order. All the rows for the column COL1 will be sorted in the Ascending order. The query will give an error as there is no WHERE clause in the query. The query will give an error as the ORDER BY clause should include all the columns in the SELECT clause. Answer: B. By default, the ORDER BY clause sorts the values in ascending order. 20. Which of the following is true about the SQL query given below? SELECT col1,col2 FROM tab1 WHERE col1 = 'A' ORDER BY col2 DESC, col1; It will display the row which has the col1 value as 'A' ordered by the col1 in the descending order and then col2 in the descending order. The ORDER BY clause will not work as the keyword DESC should be always written in the end of the ORDER BY clause and not in between as given in the query. The above query will be sorted in descending order on the basis of col2 only and the use of col1 in the ORDER BY clause will be discarded. It will display the row which has the col1 value as 'A' ordered by the col1 and then followed by col2 as the execution of the ORDER BY clause happens from the order of columns in the SELECT statement. It will display the row which has the col1 value as 'A' ordered by the col1 in the descending order and then col2 in the descending order. The ORDER BY clause will not work as the keyword DESC should be always written in the end of the ORDER BY clause and not in between as given in the query. The above query will be sorted in descending order on the basis of col2 only and the use of col1 in the ORDER BY clause will be discarded. It will display the row which has the col1 value as 'A' ordered by the col1 and then followed by col2 as the execution of the ORDER BY clause happens from the order of columns in the SELECT statement. Answer: C. Since the COL1 is already filtered and fixed in the query as a scalar value, no sorting will happen on the basis of COL1. 21. What is true regarding the query given below? SELECT col1, col2 FROM tab1 ORDER BY col1,col2 WHERE col2 = 'B'; It executes successfully It gives the required result with the COL2 value as 'B' but no ordering by the columns COL1 and COL2 because ORDER BY clause appears before the WHERE clause. It will display the row which has the COL2 value as 'B' ordered by the COL1, COL2. It throws an error as the ORDER BY clause cannot be written before the WHERE clause in Oracle. It executes successfully It gives the required result with the COL2 value as 'B' but no ordering by the columns COL1 and COL2 because ORDER BY clause appears before the WHERE clause. It will display the row which has the COL2 value as 'B' ordered by the COL1, COL2. It throws an error as the ORDER BY clause cannot be written before the WHERE clause in Oracle. Answer: D. The ORDER BY clause must appear after the WHERE clause in the SELECT statement 22. Which two clauses of the SELECT statement are necessary for Selection and Projection? SELECT, FROM ORDER BY, WHERE SELECT, WHERE SELECT, ORDER BY SELECT, FROM ORDER BY, WHERE SELECT, WHERE SELECT, ORDER BY Answer: C. 23. Which of the following WHERE clauses will NOT fit in the below SELECT query? SELECT ename, deptno, sal FROM emp; WHERE HIREDATE IN ('02-JUN-2004'); WHERE SAL IN ('1000','4000','2000'); WHERE JOB IN (SALES,CLERK); WHERE COMM BETWEEN 0.1 AND 0.5; WHERE HIREDATE IN ('02-JUN-2004'); WHERE SAL IN ('1000','4000','2000'); WHERE JOB IN (SALES,CLERK); WHERE COMM BETWEEN 0.1 AND 0.5; Answer: C. Character literals must be enclosed within single quotes 24. Choose the WHERE clause that extracts the DNAME values containing the character literal “er” from the DEPT table. WHERE DNAME IN ('%e%r'); WHERE DNAME LIKE '%er%'; WHERE DNAME BETWEEN 'e' AND 'r'; WHERE DNAME CONTAINS 'e%r'; WHERE DNAME IN ('%e%r'); WHERE DNAME LIKE '%er%'; WHERE DNAME BETWEEN 'e' AND 'r'; WHERE DNAME CONTAINS 'e%r'; Answer: B. The LIKE operator is used to perform wild card search in SQL queries. 25. Which two of the following conditions are equivalent to each other? WHERE comm IS NULL WHERE comm = NULL WHERE comm IN (NULL) WHERE NOT(comm IS NOT NULL) WHERE comm IS NULL WHERE comm = NULL WHERE comm IN (NULL) WHERE NOT(comm IS NOT NULL) Answer: A, D. The NOT operator can be used to negate the effect of its operand. Therefore (COMM IS NULL) is equivalent to (NOT (COMM IS NOT NULL)). 26. Which of the following clauses are mandatory in an SQL query? SELECT, FROM SELECT,FROM,WHERE SELECT,WHERE SELECT,WHERE,ORDER BY SELECT, FROM SELECT,FROM,WHERE SELECT,WHERE SELECT,WHERE,ORDER BY Answer: A. SELECT and FROM are the mandatory clauses in a SELECT query. 27. Which three of the following WHERE clause conditions are equivalent to each other? WHERE SAL <=5000 AND SAL >=2000 WHERE SAL IN (2000,3000,4000,5000) WHERE SAL BETWEEN 2000 AND 5000 WHERE SAL > 1999 AND SAL < 5001 WHERE SAL <=5000 AND SAL >=2000 WHERE SAL IN (2000,3000,4000,5000) WHERE SAL BETWEEN 2000 AND 5000 WHERE SAL > 1999 AND SAL < 5001 Answer: A, C, D. The conditions can be made equivalent with the use of IN, BETWEEN and relational operators 28. Which of the following is true with respect to the below query? SELECT empno, ename, job FROM emp WHERE ename like '_ith%'; It fetches the employee id, name and job of those employees who have 'ith' appearing anywhere in their name. It fetches the employee id, name and job of those employees whose name starts with 'ith'. The query throws an error as two expressions for string matching cannot be written together. It fetches the employee id, name and job of those employees whose name starts with any alphanumeric character followed by 'ith' and any alphanumeric characters after 'ith'. It fetches the employee id, name and job of those employees who have 'ith' appearing anywhere in their name. It fetches the employee id, name and job of those employees whose name starts with 'ith'. The query throws an error as two expressions for string matching cannot be written together. It fetches the employee id, name and job of those employees whose name starts with any alphanumeric character followed by 'ith' and any alphanumeric characters after 'ith'. Answer: D. 29. Which of the following is used to end a SQL query? : ; . / : ; . / Answer: B, D. A semicolon (;) or backslash (/) is used to terminate a query in SQL* Plus and SQL Developer. 30. The employees JAMES and MILLER want to know their department id by querying the database. Which of the following queries will give the required result? SELECT ename, deptno FROM emp WHERE ename = 'JAMES'; SELECT ename, deptno FROM emp WHERE ename = 'MILLER'; SELECT ename, deptno FROM dept SELECT ename, deptno FROM emp WHERE ename = 'JAMES' OR ename = 'MILLER' SELECT ename, deptno FROM emp WHERE ename = 'JAMES'; SELECT ename, deptno FROM emp WHERE ename = 'JAMES'; SELECT ename, deptno FROM emp WHERE ename = 'MILLER'; SELECT ename, deptno FROM emp WHERE ename = 'MILLER'; SELECT ename, deptno FROM dept SELECT ename, deptno FROM dept SELECT ename, deptno FROM emp WHERE ename = 'JAMES' OR ename = 'MILLER' SELECT ename, deptno FROM emp WHERE ename = 'JAMES' OR ename = 'MILLER' Answer: D. Multiple conditions can be joined using OR clause. Query execution is successful if either of the two is true. 31. Which of the following is false regarding the WHERE clause? The WHERE can compare values in columns, literal, arithmetic expressions, or functions. The WHERE clause contains column name Column aliases can be used in the WHERE clause. The WHERE clause cannot contain list of values or constants. The WHERE can compare values in columns, literal, arithmetic expressions, or functions. The WHERE clause contains column name Column aliases can be used in the WHERE clause. The WHERE clause cannot contain list of values or constants. Answer: C, D. 32. What is the default date format in Oracle? DD-MON-YY DD-MON-YYYY DD-MM-RR DD-MON-RR DD-MON-YY DD-MON-YYYY DD-MM-RR DD-MON-RR Answer: D. DD-MON-RR is the default date format in Oracle. 33. Predict the output of the below SQL query. SELECT ename, deptno, sal, comm FROM emp WHERE job = 'SALES' AND hiredate = ”01-JAN-97”; It fetches the employee data for all SALES employees It throws an error "ORA-00904: "01-JAN-13": invalid identifier" Query executes successfully but no results are returned It fetches the data for all SALES employees who were hired on 01st Jan, 1997 It fetches the employee data for all SALES employees It throws an error "ORA-00904: "01-JAN-13": invalid identifier" Query executes successfully but no results are returned It fetches the data for all SALES employees who were hired on 01st Jan, 1997 Answer: B. Date literals must be enclosed within single quotes. 34. You need to display the names of all the employees having the first name as "GARRY" from the EMPLOYEES table. Which of the following queries will fulfill the requirement? SELECT first_name FROM employees WHERE first_name LIKE 'GARRY%'; SELECT first_name FROM employees WHERE first_name LIKE '%GARRY%'; SELECT first_name FROM employees WHERE first_name LIKE 'GARRY'; SELECT first_name FROM employees WHERE first_name LIKE '_ARRY%'; SELECT first_name FROM employees WHERE first_name LIKE 'GARRY%'; SELECT first_name FROM employees WHERE first_name LIKE 'GARRY%'; SELECT first_name FROM employees WHERE first_name LIKE '%GARRY%'; SELECT first_name FROM employees WHERE first_name LIKE '%GARRY%'; SELECT first_name FROM employees WHERE first_name LIKE 'GARRY'; SELECT first_name FROM employees WHERE first_name LIKE 'GARRY'; SELECT first_name FROM employees WHERE first_name LIKE '_ARRY%'; SELECT first_name FROM employees WHERE first_name LIKE '_ARRY%'; Answer: C. Wild Cards can be used if certain characters of the search string are unknown. 35. You need to display the employee ID of all the employees who contain a letter 's' in their last name at second position and department ID as 100. Which of the following queries will fetch the required results? SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '%s%'; SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '%s_'; SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '_s_%'; SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '_s%'; SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '%s%'; SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '%s%'; SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '%s_'; SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '%s_'; SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '_s_%'; SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '_s_%'; SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '_s%'; SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '_s%'; Answer: D. The wildcard character underscore (_) is used to substitute a single character. 36. What will be the outcome of the below query? SELECT first_name, last_name, dept_id FROM employees WHERE hire_date LIKE '%98'; The first name, last name and the department ID for all the employees who joined in the year 1998 will be displayed. The first name, last name and the department ID for all the employees who joined in the year 2098 will be displayed. No results will be returned. The first name, last name and the department ID for all the employees who joined in the year 1998 between 1st January, 1998 and 31st December, 1998 will be displayed. The first name, last name and the department ID for all the employees who joined in the year 1998 will be displayed. The first name, last name and the department ID for all the employees who joined in the year 2098 will be displayed. No results will be returned. The first name, last name and the department ID for all the employees who joined in the year 1998 between 1st January, 1998 and 31st December, 1998 will be displayed. Answer: D. The LIKE operator is used to perform wild card search on character and date literals. 37. Which of the following is used to get rows based on a range of values? UNION ALL IN BETWEEN LIKE UNION ALL IN BETWEEN LIKE Answer: C. The BETWEEN operator is used to retrieve rows based on range of values. 38. You need to display the employee IDs of the employees who have their salaries between 20000 (inclusive) and 50000(inclusive). Which of the following queries will fetch the required results? SELECT emp_id FROM employees WHERE salary >=20000 AND salary <=50000; SELECT emp_id FROM employees WHERE salary IN (20000, 50000); SELECT emp_id FROM employees WHERE salary >20000 AND salary <50000; SELECT emp_id FROM employees WHERE salary between 20000 AND 50000; SELECT emp_id FROM employees WHERE salary >=20000 AND salary <=50000; SELECT emp_id FROM employees WHERE salary >=20000 AND salary <=50000; SELECT emp_id FROM employees WHERE salary IN (20000, 50000); SELECT emp_id FROM employees WHERE salary IN (20000, 50000); SELECT emp_id FROM employees WHERE salary >20000 AND salary <50000; SELECT emp_id FROM employees WHERE salary >20000 AND salary <50000; SELECT emp_id FROM employees WHERE salary between 20000 AND 50000; SELECT emp_id FROM employees WHERE salary between 20000 AND 50000; Answer: A, D. For larger ranges of values, BETWEEN and relational operators are best suited in the queries. IN operator is not recommended for large range of values. 39. What is true with respect to the below query? SELECT first_name, last_name FROM employees WHERE last_name BETWEEN 'B%' AND 'E%'; It will display all the employees having last names starting with the alphabets 'B' till 'E' inclusive of B and exclusive of E. It will throw an error as BETWEEN can only be used for Numbers and not strings. It will display all the employees having last names starting from 'B' and ending with 'E'. It will display all the employees having last names in the range of starting alphabets as 'B' and 'E' excluding the names starting with 'B' and 'E'. It will display all the employees having last names starting with the alphabets 'B' till 'E' inclusive of B and exclusive of E. It will throw an error as BETWEEN can only be used for Numbers and not strings. It will display all the employees having last names starting from 'B' and ending with 'E'. It will display all the employees having last names in the range of starting alphabets as 'B' and 'E' excluding the names starting with 'B' and 'E'. Answer: A. The BETWEEN operator works with the range of character values also. 40. What will be the outcome of the query mentioned below? SELECT employee_id, last_name, first_name, salary, manager_id FROM employees WHERE manager_id IN (200,100,300); It will show all the employees who are under the managers having IDs in the range starting from 100 to 300. It will show all the employees who are under the managers having IDs 100, 200 or 300. It will throw an error as the manager IDs should be put in quotes. It will throw an error as the sorting of manager_id in the WHERE clause conflicts with the ORDER BY clause. It will show all the employees who are under the managers having IDs in the range starting from 100 to 300. It will show all the employees who are under the managers having IDs 100, 200 or 300. It will throw an error as the manager IDs should be put in quotes. It will throw an error as the sorting of manager_id in the WHERE clause conflicts with the ORDER BY clause. Answer: B. The IN operator can be used to provide small and limited number of range. 41. Which of the following clause defines a Membership condition? BETWEEN LIKE IS NULL IN (NOT IN) BETWEEN LIKE IS NULL IN (NOT IN) Answer: D. The IN operator defines a Membership condition which may use a range of values or a subquery. 42. Which of the following data types can be used within IN operator? VARCHAR2 NUMBER DATE ALL VARCHAR2 NUMBER DATE ALL Answer: D. The IN operator works with all types of values. 43. You need to display the list of all the employees whose first name starts with “Bryan” or “Jason”. Which of the following queries will fulfill the requirement? SELECT emp_id, last_name, first_name FROM employees WHERE first_name LIKE 'Bryan%' OR first_name LIKE 'Jason%'; SELECT emp_id, last_name, first_name FROM employees WHERE first_name BETWEEN 'Bryan' and 'Jason' ; SELECT emp_id, last_name, first_name FROM employees WHERE first_name IN ('Bryan', 'Jason'); SELECT emp_id, last_name, first_name FROM employees WHERE first_name = 'Bryan' OR first_name = 'Jason' SELECT emp_id, last_name, first_name FROM employees WHERE first_name LIKE 'Bryan%' OR first_name LIKE 'Jason%'; SELECT emp_id, last_name, first_name FROM employees WHERE first_name LIKE 'Bryan%' OR first_name LIKE 'Jason%'; SELECT emp_id, last_name, first_name FROM employees WHERE first_name BETWEEN 'Bryan' and 'Jason' ; SELECT emp_id, last_name, first_name FROM employees WHERE first_name BETWEEN 'Bryan' and 'Jason' ; SELECT emp_id, last_name, first_name FROM employees WHERE first_name IN ('Bryan', 'Jason'); SELECT emp_id, last_name, first_name FROM employees WHERE first_name IN ('Bryan', 'Jason'); SELECT emp_id, last_name, first_name FROM employees WHERE first_name = 'Bryan' OR first_name = 'Jason' SELECT emp_id, last_name, first_name FROM employees WHERE first_name = 'Bryan' OR first_name = 'Jason' Answer: C, D. The IN operator checks for ANY values defined as membership condition. 44. You need to extract details of those departments whose name contains the string '_DXX'. Which of the below WHERE clauses could be used in the SELECT statement to get the required output? WHERE dept_id LIKE '%_DXX%' ESCAPE '_' WHERE dept_id LIKE '%\_DXX%' ESCAPE '\' WHERE dept_id LIKE '%_D123%' ESCAPE '%_' WHERE dept_id LIKE '%\_D123%' ESCAPE '\_' WHERE dept_id LIKE '%_DXX%' ESCAPE '_' WHERE dept_id LIKE '%\_DXX%' ESCAPE '\' WHERE dept_id LIKE '%_D123%' ESCAPE '%_' WHERE dept_id LIKE '%\_D123%' ESCAPE '\_' Answer: B. 45. Which statement is true regarding the default behavior of the ORDER BY clause? In a character sort, the values are case-sensitive. NULL values are not considered at all by the sort operation. Only those columns that are specified in the SELECT list can be used in the ORDER BY clause. Numeric values are displayed from the maximum to the minimum value if they have decimal positions. In a character sort, the values are case-sensitive. NULL values are not considered at all by the sort operation. Only those columns that are specified in the SELECT list can be used in the ORDER BY clause. Numeric values are displayed from the maximum to the minimum value if they have decimal positions. Answer: A. The ORDER BY clause does a case sensitive sorting with character values. 46. You need to generate a report of all employees from the EMPLOYEES table based on the following conditions: 1. The Employee first name should not begin with 'T' or 'N'. 2. The Employee's salary should be more than 20000. 3. The Employee should have been hired after 1st January 2010. Which WHERE clause would give the required result? WHERE first_name NOT LIKE 'T%' OR first_name NOT LIKE 'N%' AND salary > 20000 AND hire_date > '1-JAN-10' WHERE (first_name NOT LIKE 'T%' AND first_name NOT LIKE 'N%')OR salary > 20000 OR hire_date > '1-JAN-10' WHERE first_name NOT LIKE 'T%' AND first_name NOT LIKE 'N%' AND salary > 20000 AND hire_date > '1-JAN-10' WHERE (first_name NOT LIKE '%T%' OR first_name NOT LIKE '%N%') AND(salary > 20000 AND hire_date > '1-JAN-10') WHERE first_name NOT LIKE 'T%' OR first_name NOT LIKE 'N%' AND salary > 20000 AND hire_date > '1-JAN-10' WHERE (first_name NOT LIKE 'T%' AND first_name NOT LIKE 'N%')OR salary > 20000 OR hire_date > '1-JAN-10' WHERE first_name NOT LIKE 'T%' AND first_name NOT LIKE 'N%' AND salary > 20000 AND hire_date > '1-JAN-10' WHERE (first_name NOT LIKE '%T%' OR first_name NOT LIKE '%N%') AND(salary > 20000 AND hire_date > '1-JAN-10') Answer: C. 47. Using the EMPLOYEES table, you need to display the names of all employees hired after January 1, 2013, starting with the freshers. Which query would give the required result? (Choose all that apply.) SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY 2 DESC; SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY first_name DESC; SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY 1 DESC; SELECT first_name, hire_date "START DATE" FROM employees WHERE hire_date > '01-JAN-13' ORDER BY "START DATE" DESC; SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY 2 DESC; SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY 2 DESC; SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY first_name DESC; SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY first_name DESC; SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY 1 DESC; SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY 1 DESC; SELECT first_name, hire_date "START DATE" FROM employees WHERE hire_date > '01-JAN-13' ORDER BY "START DATE" DESC; SELECT first_name, hire_date "START DATE" FROM employees WHERE hire_date > '01-JAN-13' ORDER BY "START DATE" DESC; Answer: A, D. 48. Using the EMPLOYEES table, you need to find out the names and salaries of all the employees hired in departments 100 and 101 in the time interval 15th March '12 to 15th October '13. Which two queries would give the required result? (Choose two.) SELECT first_name, salary FROM employees WHERE dept_id IN (100,101) AND hire_date BETWEEN '15-MAR-12' AND '15-OCT-12'; SELECT first_name, salary FROM employees WHERE dept_id = 100 OR dept_id =101 AND hire_date >='15-MAR-12' OR hire_date <='15-OCT-12'; SELECT first_name, salary FROM employees WHERE (dept_id BETWEEN 100 AND 101) AND (hire_date IN ('15-MAR-12','15-OCT-12')); SELECT first_name, salary FROM employees WHERE (dept_id = 100 OR dept_id =101) AND (hire_date >='15-MAR-12' AND hire_date <='15-OCT-12'); SELECT first_name, salary FROM employees WHERE dept_id IN (100,101) AND hire_date BETWEEN '15-MAR-12' AND '15-OCT-12'; SELECT first_name, salary FROM employees WHERE dept_id IN (100,101) AND hire_date BETWEEN '15-MAR-12' AND '15-OCT-12'; SELECT first_name, salary FROM employees WHERE dept_id = 100 OR dept_id =101 AND hire_date >='15-MAR-12' OR hire_date <='15-OCT-12'; SELECT first_name, salary FROM employees WHERE dept_id = 100 OR dept_id =101 AND hire_date >='15-MAR-12' OR hire_date <='15-OCT-12'; SELECT first_name, salary FROM employees WHERE (dept_id BETWEEN 100 AND 101) AND (hire_date IN ('15-MAR-12','15-OCT-12')); SELECT first_name, salary FROM employees WHERE (dept_id BETWEEN 100 AND 101) AND (hire_date IN ('15-MAR-12','15-OCT-12')); SELECT first_name, salary FROM employees WHERE (dept_id = 100 OR dept_id =101) AND (hire_date >='15-MAR-12' AND hire_date <='15-OCT-12'); SELECT first_name, salary FROM employees WHERE (dept_id = 100 OR dept_id =101) AND (hire_date >='15-MAR-12' AND hire_date <='15-OCT-12'); Answer: A, D. 49. Using the EMPLOYEES table, you issue the following query to generate the names, current salary and the salary increased after an appraisal by 25%. The increased salary for all the employees should be above 30000. SELECT first_name, salary, salary + (salary *0.25) "INCREASED_SALARY" FROM employees WHERE increased_salary >30000; The query throws an error ORA-00904. What is the reason for the error? The parenthesis is missing in the expression used in SELECT statement. Single quotes must be used to define a column alias. Column alias cannot be used in the WHERE clause. Column alias in the WHERE clause must be enclosed within double quotation marks. The parenthesis is missing in the expression used in SELECT statement. Single quotes must be used to define a column alias. Column alias cannot be used in the WHERE clause. Column alias in the WHERE clause must be enclosed within double quotation marks. Answer: C. A column alias cannot be used in WHERE clause conditions but can be used in SELECT statement and ORDER BY clause. 50. You need to display employee names from the EMPLOYEES table that belong to the Department id 100 with minimum salary as either 2000 or 4000 and no job_id. You issue the following query. SELECT first_name, dept_id, salary FROM employees WHERE dept_id = 100 AND (salary = 2000 OR salary = 4000) AND job_id <> ''; Which statement is true regarding the above query? It executes successfully but returns no result. It executes successfully and returns the required result. It generates an error because the condition specified for job_id is not valid. It generates an error because the condition specified for the salary column is not valid. It executes successfully but returns no result. It executes successfully and returns the required result. It generates an error because the condition specified for job_id is not valid. It generates an error because the condition specified for the salary column is not valid. Answer: A. The condition (salary = 2000 OR salary = 4000) results in FALSE because an employee cannot held multiple salaries at a time. 51. Which three tasks can be performed using SQL functions built into Oracle Database? (Choose three.) Displaying a date in a non-default format Finding the number of characters in an expression Substituting a character string in a text expression with a specified string Combining more than two columns or expressions into a single column in the output Displaying a date in a non-default format Finding the number of characters in an expression Substituting a character string in a text expression with a specified string Combining more than two columns or expressions into a single column in the output Answer: A, B, C. Use formatting functions (TO_CHAR, TO_DATE), and character functions (LENGTH, REPLACE) to achieve the objectives. 52. You need to generate a report that displays the IDs of all employees in the EMPLOYEES table whose salary is at least 25% more than the value 20000. The details should be displayed in the descending order of the salary. You issue the following query. SELECT emp_id FROM employees WHERE salary>=20000*0.25 ORDER BY salary*0.25 DESC; Which statement is true regarding the above query? It executes and produces the required result. It produces an error because an expression cannot be used in the ORDER BY clause. It produces an error because the DESC option cannot be used with an expression in the ORDER BY clause. It produces an error because the expression in the ORDER BY clause should also be specified in the SELECT clause. It executes and produces the required result. It produces an error because an expression cannot be used in the ORDER BY clause. It produces an error because the DESC option cannot be used with an expression in the ORDER BY clause. It produces an error because the expression in the ORDER BY clause should also be specified in the SELECT clause. Answer: A. The ORDER BY clause can contain column expressions. 53. Examine the structure and data of the TRAININGS table: Name Null? Type ----------------------------------------- -------- ------------- TRAINING_ID NOT NULL NUMBER(5) TRAINING_LOCATION NUMBER(7,2) START_DATE DATE END_DATE DATE TRAINING_ID START_DATE TRAINING_COST ------ ---------------- ------------------------------------------------- 11 01-JAN-10 1000 22 01-FEB-10 2000 33 01-MAR-10 3000 Dates are stored in the default date format dd-mon-rr in the TRAININGS table. Which three SQL statements would execute successfully? (Choose three.) SELECT start_date + '10' FROM trainings; SELECT * FROM trainings WHERE start_date = '01-01-10'; SELECT training_cost FROM trainings WHERE training_id > '11'; SELECT * FROM trainings WHERE start_date ='01-JANUARY-10'; SELECT start_date + '10' FROM trainings; SELECT start_date + '10' FROM trainings; SELECT * FROM trainings WHERE start_date = '01-01-10'; SELECT * FROM trainings WHERE start_date = '01-01-10'; SELECT training_cost FROM trainings WHERE training_id > '11'; SELECT training_cost FROM trainings WHERE training_id > '11'; SELECT * FROM trainings WHERE start_date ='01-JANUARY-10'; SELECT * FROM trainings WHERE start_date ='01-JANUARY-10'; Answer: A, C, D. 54. Which of the following statements is/are true with respect to the below query? SELECT emp_id, first_name FROM employees ORDER BY dept_id; ORDER BY clause should contain only those columns which are in the SELECT statement. The above query will sort the result set in descending order. ORDER BY clause can contain any column in the related table, not necessarily the columns in the SELECT statement. It throws an error on execution. ORDER BY clause should contain only those columns which are in the SELECT statement. The above query will sort the result set in descending order. ORDER BY clause can contain any column in the related table, not necessarily the columns in the SELECT statement. It throws an error on execution. Answer: C. The ORDER BY clause can use a column to sort the data which is not selected in the column list but is contained in the table used in FROM clause. 55. Which feature of ORDER BY clause is demonstrated in the below query? SELECT emp_id, first_name “EmpName” FROM employees ORDER BY "EmpName"; ORDER BY clause should contain only those columns which are in the SELECT statement. The above query will sort the result set in descending order of first names of employees. ORDER BY clause works with column aliases. The SELECT query throws an error on execution because column alias cannot be used in ORDER BY clause. ORDER BY clause should contain only those columns which are in the SELECT statement. The above query will sort the result set in descending order of first names of employees. ORDER BY clause works with column aliases. The SELECT query throws an error on execution because column alias cannot be used in ORDER BY clause. Answer: C. The ORDER BY clauses works fine with the column aliases used in SELECT statement. 56. What is true about the query given below? SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY 2; It executes successfully sorting the query results based on the JOB_ID. The ORDER BY clause cannot contain a numeric. The ORDER BY clause will not function as none of the columns in the SELECT statement are used in the ORDER BY clause. The query throws an error on execution. It executes successfully sorting the query results based on the JOB_ID. The ORDER BY clause cannot contain a numeric. The ORDER BY clause will not function as none of the columns in the SELECT statement are used in the ORDER BY clause. The query throws an error on execution. Answer: A. Numeric position of the column can be used in the ORDER BY clause. 57. You need to list the employees details for different jobs but only one at a time. SELECT emp_id, first_name, last_name FROM employees WHERE job_id....; Which of the following is an easier way to achieve the same in SQL* Plus? Substitute each Job Id at a time Use * to list details of all employees Use &JOB to prompt for user input every time the query is executed Declare session variables to substitute Job Id values in the query Substitute each Job Id at a time Use * to list details of all employees Use &JOB to prompt for user input every time the query is executed Declare session variables to substitute Job Id values in the query Answer: C. The &X notation haults the query execution and prompts for user input every time the query is executed. 58. Which of the following statements is true regarding substitution variables in SQL? The same query can be executed for different values using the substitution variables. Using the substitution variables, one needs to alter the WHERE clause every time. Substitution variables are not supported in Oracle. There is a limitation that a value is supposed to be entered in the substitution variables every time during the execution of a query. The same query can be executed for different values using the substitution variables. Using the substitution variables, one needs to alter the WHERE clause every time. Substitution variables are not supported in Oracle. There is a limitation that a value is supposed to be entered in the substitution variables every time during the execution of a query. Answer: A. 59. Which of the following data type is assigned to Substitution variables? VARCHAR2 DATE NO DATA TYPE NUMBER VARCHAR2 DATE NO DATA TYPE NUMBER Answer: C. Substitution variables do not have the data type of their own but comply with the column's data type with whom they are used. 60. Which among the following is true about substitution variables? The value entered in the variables remains constant and the user cannot change the values after the execution of the query for the first time. The value is stored in the variables after the query executes once. The substitution variables only support NUMBERS. The value stored in the substitution variables (using a single ampersand) is used for the first execution and gets discarded. The value entered in the variables remains constant and the user cannot change the values after the execution of the query for the first time. The value is stored in the variables after the query executes once. The substitution variables only support NUMBERS. The value stored in the substitution variables (using a single ampersand) is used for the first execution and gets discarded. Answer: D. 61. Which of the following is a correct syntax for Substitution variables in SQL* Plus? :var $var &var &&var :var $var &var &&var Answer: C, D. 62. Which of the following Substitution variables will take the entered value once and then keeps it for the rest of the session? &&var &var :var ::var &&var &var :var ::var Answer: A. A substitution variable with double ampersand repeatedly uses the value once provided by the user. 63. Which of the following is true about substitution variables? Only NUMBERS can be entered as values. Only Character strings can be entered as values. Both Numbers and Characters can be entered as values. None of the above. Only NUMBERS can be entered as values. Only Character strings can be entered as values. Both Numbers and Characters can be entered as values. None of the above. Answer: C. 64. What is true about the query given below? SELECT first_name, last_name, employee_id, salary FROM employees WHERE employee_id = &eid; It throws an error "ORA-00904: "&eid": invalid identifier" It executes successfully. The WHERE clause can't have substitution variables. The query prompts for a value to be entered for the variable &eid and executes successfully taking a valid value of employee_id. It throws an error "ORA-00904: "&eid": invalid identifier" It executes successfully. The WHERE clause can't have substitution variables. The query prompts for a value to be entered for the variable &eid and executes successfully taking a valid value of employee_id. Answer: B, D. 65. Choose the statements which hold true about the query given below. SELECT first_name, last_name, &&prompt_col FROM employees ORDER BY &&promp_col; It throws an error as the use of the substitution variable prompt_col is not allowed. It executes successfully but the result set is not sorted. It executes successfully but the variable value entered in the SELECT statement is ignored. It executes successfully and the value of the substitution variable is maintained throughout the session. It throws an error as the use of the substitution variable prompt_col is not allowed. It executes successfully but the result set is not sorted. It executes successfully but the variable value entered in the SELECT statement is ignored. It executes successfully and the value of the substitution variable is maintained throughout the session. Answer: D. A substitution variable can be used in all the clauses of SQL query. 66. Which of the following commands is used to create and assign a value to a substitution variable in SQL* Plus? &var &&var SET DEFINE &var &&var SET DEFINE Answer: D. Use DEFINE command in SQL* Plus to declare a substitution variable in a session. 67. What will be the outcome of the below activity in SQL* Plus? DEFINE eid = 117 SELECT first_name, last_name, employee_id, salary FROM employees WHERE employee_id = &eid; The SELECT query throws error as substitution variables cannot be defined in the session. It prompts the user to enter the value for the variable &eid. It executes successfully with the employee ID substituted as 117. It ignores the DEFINE command because the substitution variable is declared without ampersand (&) sign. The SELECT query throws error as substitution variables cannot be defined in the session. It prompts the user to enter the value for the variable &eid. It executes successfully with the employee ID substituted as 117. It ignores the DEFINE command because the substitution variable is declared without ampersand (&) sign. Answer: C. 68. What is the command to remove the value of the substitution variable set by the command DEFINE? UNDEFINE SET OFF DELETE CLEAR UNDEFINE SET OFF DELETE CLEAR Answer: A. Use UNDEFINE command to delete a substitution variable from the session 69. Which of the following commands is used to check the substitution variables values before and after execution of an SQL query? DEFINE UNDEFINE SHOW VARIABLE VERIFY DEFINE UNDEFINE SHOW VARIABLE VERIFY Answer: D.Use VERIFY command in SQL*Plus and SQL Developer to check the substitution of values using substitution variables. 70. Which of the following are valid operators for the WHERE clause? >= IS NULL != IS LIKE >= IS NULL != IS LIKE Answer: A, B, C. 71. Evaluate the following query: SELECT ename || q'{'s salary is }' || sal AS "Salary" FROM emp; Gives an error because braces cannot be used with [q] operator Gives error due to data type mismatch Executes successfully and adds an apostrophe ('s) at the end of each employee's name Executes successfully and appends the employee name with the literal " {'s start date was } " Gives an error because braces cannot be used with [q] operator Gives error due to data type mismatch Executes successfully and adds an apostrophe ('s) at the end of each employee's name Executes successfully and appends the employee name with the literal " {'s start date was } " Answer: C. 72. Which of the below WHERE clause predicates will correctly list the employees from department 20? WHERE deptno IS 20 WHERE deptno 20 WHERE deptno=20 WHERE 20=deptno WHERE deptno IS 20 WHERE deptno 20 WHERE deptno=20 WHERE 20=deptno Answer: C, D. The equality operator (=) is used to compare the operands in the condition for equality. 73. Write a SELECT query to list the employees whose salary is greater than 1000. SELECT ename, sal FROM emp WHERE sal GREATER THAN 1000 SELECT ename, sal FROm emp WHERE sal > 1000 SELECT ename, sal FROM emp WHERE sal >= 1000 SELECT ename, sal FROM emp WHERE sal MORE THAN 1000 SELECT ename, sal FROM emp WHERE sal GREATER THAN 1000 SELECT ename, sal FROM emp WHERE sal GREATER THAN 1000 SELECT ename, sal FROm emp WHERE sal > 1000 SELECT ename, sal FROm emp WHERE sal > 1000 SELECT ename, sal FROM emp WHERE sal >= 1000 SELECT ename, sal FROM emp WHERE sal >= 1000 SELECT ename, sal FROM emp WHERE sal MORE THAN 1000 SELECT ename, sal FROM emp WHERE sal MORE THAN 1000 Answer: B. The greater than operator (>) is used to compare the operands in the condition. 74. What would happen when the below query is executed in SQL* Plus? SELECT ename, sal, deptno FROM emp WHERE sal/10 > deptno*10; Executes successfully and lists the employees whose 10th part of salary is greater than 10 times his department number Raises error because expressions must be enclosed with parentheses Raises error because WHERE clause cannot evaluate expressions Raises error because WHERE clause cannot use literals Executes successfully and lists the employees whose 10th part of salary is greater than 10 times his department number Raises error because expressions must be enclosed with parentheses Raises error because WHERE clause cannot evaluate expressions Raises error because WHERE clause cannot use literals Answer: A. The WHERE clause can contain expressions. 75. Determine the error in the below SELECT statement SELECT ename, deptno, sal FROM emp WHERE job=CLERK; WHERE clause cannot refer the column JOB since it doesn't appears in the SELECT column list Character literal CLERK must be enclosed within single quotes Character literal CLERK must be enclosed within parentheses No error in the query WHERE clause cannot refer the column JOB since it doesn't appears in the SELECT column list Character literal CLERK must be enclosed within single quotes Character literal CLERK must be enclosed within parentheses No error in the query Answer: B. Character literals must be enclosed within single quotes 76. Interpret the output of the below SQL query SELECT ename, deptno, sal FROM emp WHERE sysdate-hiredate > 100; The query lists the employees whose hiredate is atleast 100 days earlier than the current date The query lists the employees who have worked more than 100 days in the company The query lists the employees whose hiredate is after 100 days in that year The query lists the employees who have spent less than 100 days in the company The query lists the employees whose hiredate is atleast 100 days earlier than the current date The query lists the employees who have worked more than 100 days in the company The query lists the employees whose hiredate is after 100 days in that year The query lists the employees who have spent less than 100 days in the company Answer: A, B. Dates expressions can be used in WHERE clause 77. Which of the following query will display the employees which are hired after 31st Decemeber, 1982? SELECT ename, deptno FROM emp WHERE hiredate > '31-DEC-1982'; SELECT ename, deptno FROM emp WHERE hiredate > to_date('31-DEC-1982','DD-MM-YYYY'); SELECT ename, deptno FROM emp WHERE hiredate > to_char('31-DEC-1982','DD-MM-YYYY'); SELECT ename, deptno FROM emp WHERE hiredate > 31-DEC-1982; SELECT ename, deptno FROM emp WHERE hiredate > '31-DEC-1982'; SELECT ename, deptno FROM emp WHERE hiredate > '31-DEC-1982'; SELECT ename, deptno FROM emp WHERE hiredate > to_date('31-DEC-1982','DD-MM-YYYY'); SELECT ename, deptno FROM emp WHERE hiredate > to_date('31-DEC-1982','DD-MM-YYYY'); SELECT ename, deptno FROM emp WHERE hiredate > to_char('31-DEC-1982','DD-MM-YYYY'); SELECT ename, deptno FROM emp WHERE hiredate > to_char('31-DEC-1982','DD-MM-YYYY'); SELECT ename, deptno FROM emp WHERE hiredate > 31-DEC-1982; SELECT ename, deptno FROM emp WHERE hiredate > 31-DEC-1982; Answer: A, B. Date literals must be enclosed within single quotes. 78. Which of the following WHERE conditions will list employees who were hired on current date? WHERE sysdate-hiredate=0 WHERE sysdate=hiredate WHERE sysdate-hiredate<1 WHERE to_date (sysdate,'DD-MON-YYYY') = to_date (hiredate='DD-MON-YYYY') WHERE sysdate-hiredate=0 WHERE sysdate=hiredate WHERE sysdate-hiredate<1 WHERE to_date (sysdate,'DD-MON-YYYY') = to_date (hiredate='DD-MON-YYYY') Answer: C, D. The condition SYSDATE=HIREDATE will not work because SYSDATE contains dynamic timestamp component while hiredate is a static value in the database. 79. What of the following are the valid formats of date literals which can be used in WHERE clause? 24/Mar/95 02-12-1983 19-JUN-2001 31.04.2010 24/Mar/95 02-12-1983 19-JUN-2001 31.04.2010 Answer: A, C. Default format for date literals is DD-MON-RR. 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2563, "s": 2463, "text": "1. Which of the following clause is used to limit the number of rows retrieved from a SELECT query?" }, { "code": null, "e": 2586, "s": 2563, "text": "\nLIMIT\nWHERE\nAND\nFROM\n" }, { "code": null, "e": 2592, "s": 2586, "text": "LIMIT" }, { "code": null, "e": 2598, "s": 2592, "text": "WHERE" }, { "code": null, "e": 2602, "s": 2598, "text": "AND" }, { "code": null, "e": 2607, "s": 2602, "text": "FROM" }, { "code": null, "e": 2704, "s": 2607, "text": "Answer: B. The WHERE clause is used to restrict the number of rows returned from a SELECT query." }, { "code": null, "e": 2802, "s": 2704, "text": "2. Choose the database elements whose values can be compared in a WHERE clause of a SELECT query." }, { "code": null, "e": 2838, "s": 2802, "text": "\nColumn\nSequence\nProcedure\nLiteral\n" }, { "code": null, "e": 2845, "s": 2838, "text": "Column" }, { "code": null, "e": 2854, "s": 2845, "text": "Sequence" }, { "code": null, "e": 2864, "s": 2854, "text": "Procedure" }, { "code": null, "e": 2872, "s": 2864, "text": "Literal" }, { "code": null, "e": 2998, "s": 2872, "text": "Answer: A, D. The WHERE clause can be used to compare the values from columns, literals, arithmetic functions and functions. " }, { "code": null, "e": 3088, "s": 2998, "text": "3. What are the elements NOT contained in the WHERE clause predicate of the SELECT query?" }, { "code": null, "e": 3154, "s": 3088, "text": "\nComparison operator\nComparison condition\nColumn Name\nTable Name\n" }, { "code": null, "e": 3174, "s": 3154, "text": "Comparison operator" }, { "code": null, "e": 3195, "s": 3174, "text": "Comparison condition" }, { "code": null, "e": 3207, "s": 3195, "text": "Column Name" }, { "code": null, "e": 3218, "s": 3207, "text": "Table Name" }, { "code": null, "e": 3287, "s": 3218, "text": "Answer: D. Table Name is not required in the WHERE clause predicate." }, { "code": null, "e": 3384, "s": 3287, "text": "4. Which of the following values can NOT be returned after evaluation of WHERE clause condition?" }, { "code": null, "e": 3410, "s": 3384, "text": "\nUNKNOWN\nTRUE\nFALSE\nNULL\n" }, { "code": null, "e": 3418, "s": 3410, "text": "UNKNOWN" }, { "code": null, "e": 3423, "s": 3418, "text": "TRUE" }, { "code": null, "e": 3429, "s": 3423, "text": "FALSE" }, { "code": null, "e": 3434, "s": 3429, "text": "NULL" }, { "code": null, "e": 3582, "s": 3434, "text": "Answer: A. If the result of the condition in WHERE clause is not known, NULL is returned. In all other scenarios, either TRUE or FALSE is returned." }, { "code": null, "e": 3669, "s": 3582, "text": "5. What is the minimum number of WHERE clauses that must be present in a SELECT query?" }, { "code": null, "e": 3679, "s": 3669, "text": "\n1\n2\n0\n3\n" }, { "code": null, "e": 3681, "s": 3679, "text": "1" }, { "code": null, "e": 3683, "s": 3681, "text": "2" }, { "code": null, "e": 3685, "s": 3683, "text": "0" }, { "code": null, "e": 3687, "s": 3685, "text": "3" }, { "code": null, "e": 3808, "s": 3687, "text": "Answer: C. The WHERE clause is an optional clause in the SELECT query which is only used to restrict the number of rows." }, { "code": null, "e": 3895, "s": 3808, "text": "6. What is the maximum number of WHERE clauses that can be included in a SELECT query?" }, { "code": null, "e": 3905, "s": 3895, "text": "\n1\n2\n0\n3\n" }, { "code": null, "e": 3907, "s": 3905, "text": "1" }, { "code": null, "e": 3909, "s": 3907, "text": "2" }, { "code": null, "e": 3911, "s": 3909, "text": "0" }, { "code": null, "e": 3913, "s": 3911, "text": "3" }, { "code": null, "e": 4045, "s": 3913, "text": "Answer: A. The WHERE clause is an optional clause in the SELECT query which can be used only once to restrict the number of rows. " }, { "code": null, "e": 4118, "s": 4045, "text": "7. Which of the following statements are correct about the WHERE clause?" }, { "code": null, "e": 4355, "s": 4118, "text": "\nColumn Alias can be used in WHERE clause to refer a column\nComparison operator is an optional element in WHERE clause condition\nFunctions can be used as operands in the WHERE clause\nThere can be multiple WHERE clause in a SELECT query\n" }, { "code": null, "e": 4414, "s": 4355, "text": "Column Alias can be used in WHERE clause to refer a column" }, { "code": null, "e": 4483, "s": 4414, "text": "Comparison operator is an optional element in WHERE clause condition" }, { "code": null, "e": 4537, "s": 4483, "text": "Functions can be used as operands in the WHERE clause" }, { "code": null, "e": 4590, "s": 4537, "text": "There can be multiple WHERE clause in a SELECT query" }, { "code": null, "e": 4770, "s": 4590, "text": "Answer: C. The WHERE clause must have comparison operator to evaluate the condition. It can use function as one of the operand. Only one WHERE clause is allowed in a SELECT query." }, { "code": null, "e": 4842, "s": 4770, "text": "8. Write a SELECT query to list down unique departments from EMP table?" }, { "code": null, "e": 4976, "s": 4842, "text": "\nSELECT deptno FROM emp;\nSELECT DISTINCT deptno FROM emp;\nSELECT DISTINCT (deptno) FROM emp;\nSELECT empno, DISTINCT deptno FROM emp;\n" }, { "code": null, "e": 5000, "s": 4976, "text": "SELECT deptno FROM emp;" }, { "code": null, "e": 5024, "s": 5000, "text": "SELECT deptno FROM emp;" }, { "code": null, "e": 5057, "s": 5024, "text": "SELECT DISTINCT deptno FROM emp;" }, { "code": null, "e": 5090, "s": 5057, "text": "SELECT DISTINCT deptno FROM emp;" }, { "code": null, "e": 5125, "s": 5090, "text": "SELECT DISTINCT (deptno) FROM emp;" }, { "code": null, "e": 5160, "s": 5125, "text": "SELECT DISTINCT (deptno) FROM emp;" }, { "code": null, "e": 5200, "s": 5160, "text": "SELECT empno, DISTINCT deptno FROM emp;" }, { "code": null, "e": 5240, "s": 5200, "text": "SELECT empno, DISTINCT deptno FROM emp;" }, { "code": null, "e": 5340, "s": 5240, "text": "Answer: B & C. The keyword DISTINCT is used to filter out the duplicate rows from the SELECT query." }, { "code": null, "e": 5423, "s": 5340, "text": "9. Which of the following operations are permitted for date and timestamp columns?" }, { "code": null, "e": 5469, "s": 5423, "text": "\nDivision\nAddition\nSubtraction\nConcatenation\n" }, { "code": null, "e": 5478, "s": 5469, "text": "Division" }, { "code": null, "e": 5487, "s": 5478, "text": "Addition" }, { "code": null, "e": 5499, "s": 5487, "text": "Subtraction" }, { "code": null, "e": 5513, "s": 5499, "text": "Concatenation" }, { "code": null, "e": 5635, "s": 5513, "text": "Answer: B, C, and D. Addition, subtraction and Concatenation are the operations permitted for date and timestamp columns." }, { "code": null, "e": 5719, "s": 5635, "text": "10. From the below operators, which one of them holds the highest precedence level?" }, { "code": null, "e": 5781, "s": 5719, "text": "\nDivision (/)\nMultiplication (*)\nBrackets ( () )\nSubtraction\n" }, { "code": null, "e": 5794, "s": 5781, "text": "Division (/)" }, { "code": null, "e": 5813, "s": 5794, "text": "Multiplication (*)" }, { "code": null, "e": 5829, "s": 5813, "text": "Brackets ( () )" }, { "code": null, "e": 5841, "s": 5829, "text": "Subtraction" }, { "code": null, "e": 5919, "s": 5841, "text": "Answer: C. Expressions within the brackets hold the highest precedence level." }, { "code": null, "e": 5979, "s": 5919, "text": "11. Interpret the output returned by the below SELECT query" }, { "code": null, "e": 6024, "s": 5979, "text": "SELECT ename, (sysdate - hiredate)\nFROM emp;" }, { "code": null, "e": 6254, "s": 6024, "text": "\nNumber of days in the current year\nNumber of days in the year when an employee was hired\nNumber of days spent by employee with the company\nThe query raises exception \"ORA-00932: inconsistent datatypes: expected NUMBER got DATE\"\n" }, { "code": null, "e": 6289, "s": 6254, "text": "Number of days in the current year" }, { "code": null, "e": 6343, "s": 6289, "text": "Number of days in the year when an employee was hired" }, { "code": null, "e": 6393, "s": 6343, "text": "Number of days spent by employee with the company" }, { "code": null, "e": 6482, "s": 6393, "text": "The query raises exception \"ORA-00932: inconsistent datatypes: expected NUMBER got DATE\"" }, { "code": null, "e": 6599, "s": 6482, "text": "Answer: C. The expression (sysdate-hiredate) returns the number of employment days of an employee with the company. " }, { "code": null, "e": 6679, "s": 6599, "text": "12. Which of the below statements correctly describle the DUAL table in Oracle?" }, { "code": null, "e": 6910, "s": 6679, "text": "\nDUAL table is a temporary table in Oracle database\nDUAL table contains only one character type column known as DUMMY\nDUAL table owned by SYS cannot be dropped\nA table with the name DUAL can be created by a user in its own schema\n" }, { "code": null, "e": 6961, "s": 6910, "text": "DUAL table is a temporary table in Oracle database" }, { "code": null, "e": 7027, "s": 6961, "text": "DUAL table contains only one character type column known as DUMMY" }, { "code": null, "e": 7069, "s": 7027, "text": "DUAL table owned by SYS cannot be dropped" }, { "code": null, "e": 7139, "s": 7069, "text": "A table with the name DUAL can be created by a user in its own schema" }, { "code": null, "e": 7248, "s": 7139, "text": "Answer: B, C, D. The DUAL table in Oracle is owned by SYS and contains one column DUMMY of type VARCHAR2(1)." }, { "code": null, "e": 7309, "s": 7248, "text": "13. Determine the type of output returned by the below query" }, { "code": null, "e": 7362, "s": 7309, "text": "SELECT sysdate - hiredate\nFROM emp\nWHERE empno=7369;" }, { "code": null, "e": 7502, "s": 7362, "text": "\nDATE data type\nNUMBER data type\nVARCHAR2 data type\nThe query raises error since arithmetic operations cannot be performed on date columns\n" }, { "code": null, "e": 7517, "s": 7502, "text": "DATE data type" }, { "code": null, "e": 7534, "s": 7517, "text": "NUMBER data type" }, { "code": null, "e": 7553, "s": 7534, "text": "VARCHAR2 data type" }, { "code": null, "e": 7640, "s": 7553, "text": "The query raises error since arithmetic operations cannot be performed on date columns" }, { "code": null, "e": 7741, "s": 7640, "text": "Answer: B. Subtraction between two dates results in numeric difference of days between the two dates" }, { "code": null, "e": 7790, "s": 7741, "text": "14. Which expressions do NOT return NULL values?" }, { "code": null, "e": 7962, "s": 7790, "text": "\nSELECT ((10 + 20) * 50) + null from dual;\nSELECT 'this is a '||null||'test with nulls' from dual;\nSELECT null/0 from dual;\nSELECT null||'test'||null as “Test” from dual;\n" }, { "code": null, "e": 8004, "s": 7962, "text": "SELECT ((10 + 20) * 50) + null from dual;" }, { "code": null, "e": 8046, "s": 8004, "text": "SELECT ((10 + 20) * 50) + null from dual;" }, { "code": null, "e": 8102, "s": 8046, "text": "SELECT 'this is a '||null||'test with nulls' from dual;" }, { "code": null, "e": 8158, "s": 8102, "text": "SELECT 'this is a '||null||'test with nulls' from dual;" }, { "code": null, "e": 8183, "s": 8158, "text": "SELECT null/0 from dual;" }, { "code": null, "e": 8208, "s": 8183, "text": "SELECT null/0 from dual;" }, { "code": null, "e": 8255, "s": 8208, "text": "SELECT null||'test'||null as “Test” from dual;" }, { "code": null, "e": 8302, "s": 8255, "text": "SELECT null||'test'||null as “Test” from dual;" }, { "code": null, "e": 8368, "s": 8302, "text": "Answer: B, D. Any arithmetic operation with NULL results in NULL." }, { "code": null, "e": 8412, "s": 8368, "text": "15. Determine the output of the below query" }, { "code": null, "e": 8479, "s": 8412, "text": "SELECT 'Tutorial''s Point compiles technical tutorials' FROM DUAL;" }, { "code": null, "e": 8691, "s": 8479, "text": "\nTutorial''s Point compiles technical tutorials\nTutorial's Point compiles technical tutorials\n'Tutorial''s Point compiles technical tutorials'\nRaises exception \"ORA-01756: quoted string not properly terminated\"\n" }, { "code": null, "e": 8738, "s": 8691, "text": "Tutorial''s Point compiles technical tutorials" }, { "code": null, "e": 8784, "s": 8738, "text": "Tutorial's Point compiles technical tutorials" }, { "code": null, "e": 8833, "s": 8784, "text": "'Tutorial''s Point compiles technical tutorials'" }, { "code": null, "e": 8901, "s": 8833, "text": "Raises exception \"ORA-01756: quoted string not properly terminated\"" }, { "code": null, "e": 8913, "s": 8901, "text": "Answer: B. " }, { "code": null, "e": 8960, "s": 8913, "text": "16. Examine the TRAINING table as given below:" }, { "code": null, "e": 9324, "s": 8960, "text": " Name Null? Type\n ----------------------------------------- -------- -------------\n\n TRAINING_ID NOT NULL NUMBER(5)\n TRAINING_LOCATION NUMBER(7,2)\n START_DATE DATE\n END_DATE DATE" }, { "code": null, "e": 9611, "s": 9324, "text": "\nSELECT NVL (ADD_MONTHS (END_DATE,1),SYSDATE) FROM training;\nSELECT TO_DATE (NVL(SYSDATE-END_DATE,SYSDATE)) FROM training;\nSELECT NVL(MONTHS_BETWEEN(START_DATE,END_DATE),’In Progress’) FROM training;\nSELECT NVL(TO_CHAR(MONTHS_BETWEEN(START_DATE,END_DATE)),’In Progress’) FROM training;\n" }, { "code": null, "e": 9671, "s": 9611, "text": "SELECT NVL (ADD_MONTHS (END_DATE,1),SYSDATE) FROM training;" }, { "code": null, "e": 9731, "s": 9671, "text": "SELECT NVL (ADD_MONTHS (END_DATE,1),SYSDATE) FROM training;" }, { "code": null, "e": 9793, "s": 9731, "text": "SELECT TO_DATE (NVL(SYSDATE-END_DATE,SYSDATE)) FROM training;" }, { "code": null, "e": 9855, "s": 9793, "text": "SELECT TO_DATE (NVL(SYSDATE-END_DATE,SYSDATE)) FROM training;" }, { "code": null, "e": 9932, "s": 9855, "text": "SELECT NVL(MONTHS_BETWEEN(START_DATE,END_DATE),’In Progress’) FROM training;" }, { "code": null, "e": 10009, "s": 9932, "text": "SELECT NVL(MONTHS_BETWEEN(START_DATE,END_DATE),’In Progress’) FROM training;" }, { "code": null, "e": 10095, "s": 10009, "text": "SELECT NVL(TO_CHAR(MONTHS_BETWEEN(START_DATE,END_DATE)),’In Progress’) FROM training;" }, { "code": null, "e": 10181, "s": 10095, "text": "SELECT NVL(TO_CHAR(MONTHS_BETWEEN(START_DATE,END_DATE)),’In Progress’) FROM training;" }, { "code": null, "e": 10265, "s": 10181, "text": "Answer: A, D. Use NVL function to provide an alternate value to a column when NULL." }, { "code": null, "e": 10336, "s": 10265, "text": "17. What does the selection of columns in a SELECT statement known as?" }, { "code": null, "e": 10378, "s": 10336, "text": "\nRetrieval\nSelection\nProjection\nLimiting\n" }, { "code": null, "e": 10388, "s": 10378, "text": "Retrieval" }, { "code": null, "e": 10398, "s": 10388, "text": "Selection" }, { "code": null, "e": 10409, "s": 10398, "text": "Projection" }, { "code": null, "e": 10418, "s": 10409, "text": "Limiting" }, { "code": null, "e": 10512, "s": 10418, "text": "Answer: C. Projection is the ability to select only the required columns in SELECT statement." }, { "code": null, "e": 10590, "s": 10512, "text": "18. What does the restriction of rows returned by a SELECT statement known as" }, { "code": null, "e": 10635, "s": 10590, "text": "\nRetrieval\nProjection\nRestricting\nSelection\n" }, { "code": null, "e": 10645, "s": 10635, "text": "Retrieval" }, { "code": null, "e": 10656, "s": 10645, "text": "Projection" }, { "code": null, "e": 10668, "s": 10656, "text": "Restricting" }, { "code": null, "e": 10678, "s": 10668, "text": "Selection" }, { "code": null, "e": 10775, "s": 10678, "text": "Answer: C. Restricting is the ability to limit the number of rows by putting certain conditions." }, { "code": null, "e": 10839, "s": 10775, "text": "19. Which of the following is true about the query given below?" }, { "code": null, "e": 10883, "s": 10839, "text": "SELECT col1, col2 \nFROM tab1\nORDER BY col1;" }, { "code": null, "e": 11206, "s": 10883, "text": "\nAll the rows for the column COL1 will be sorted in the Descending order.\nAll the rows for the column COL1 will be sorted in the Ascending order.\nThe query will give an error as there is no WHERE clause in the query.\nThe query will give an error as the ORDER BY clause should include all the columns in the SELECT clause.\n" }, { "code": null, "e": 11279, "s": 11206, "text": "All the rows for the column COL1 will be sorted in the Descending order." }, { "code": null, "e": 11351, "s": 11279, "text": "All the rows for the column COL1 will be sorted in the Ascending order." }, { "code": null, "e": 11422, "s": 11351, "text": "The query will give an error as there is no WHERE clause in the query." }, { "code": null, "e": 11527, "s": 11422, "text": "The query will give an error as the ORDER BY clause should include all the columns in the SELECT clause." }, { "code": null, "e": 11607, "s": 11527, "text": "Answer: B. By default, the ORDER BY clause sorts the values in ascending order." }, { "code": null, "e": 11677, "s": 11609, "text": "20. Which of the following is true about the SQL query given below?" }, { "code": null, "e": 11747, "s": 11677, "text": "SELECT col1,col2\nFROM tab1\nWHERE col1 = 'A'\nORDER BY col2 DESC, col1;" }, { "code": null, "e": 12384, "s": 11747, "text": "\nIt will display the row which has the col1 value as 'A' ordered by the col1 in the descending order and then col2 in the descending order.\nThe ORDER BY clause will not work as the keyword DESC should be always written in the end of the ORDER BY clause and not in between as given in the query.\nThe above query will be sorted in descending order on the basis of col2 only and the use of col1 in the ORDER BY clause will be discarded.\nIt will display the row which has the col1 value as 'A' ordered by the col1 and then followed by col2 as the execution of the ORDER BY clause happens from the order of columns in the \nSELECT statement.\n" }, { "code": null, "e": 12523, "s": 12384, "text": "It will display the row which has the col1 value as 'A' ordered by the col1 in the descending order and then col2 in the descending order." }, { "code": null, "e": 12678, "s": 12523, "text": "The ORDER BY clause will not work as the keyword DESC should be always written in the end of the ORDER BY clause and not in between as given in the query." }, { "code": null, "e": 12817, "s": 12678, "text": "The above query will be sorted in descending order on the basis of col2 only and the use of col1 in the ORDER BY clause will be discarded." }, { "code": null, "e": 13019, "s": 12817, "text": "It will display the row which has the col1 value as 'A' ordered by the col1 and then followed by col2 as the execution of the ORDER BY clause happens from the order of columns in the \nSELECT statement." }, { "code": null, "e": 13154, "s": 13019, "text": "Answer: C. Since the COL1 is already filtered and fixed in the query as a scalar value, no sorting will happen on the basis of COL1. " }, { "code": null, "e": 13204, "s": 13154, "text": "21. What is true regarding the query given below?" }, { "code": null, "e": 13270, "s": 13204, "text": "SELECT col1, col2\nFROM tab1\nORDER BY col1,col2\nWHERE col2 = 'B';" }, { "code": null, "e": 13633, "s": 13270, "text": "\nIt executes successfully\nIt gives the required result with the COL2 value as 'B' but no ordering by the columns COL1 and COL2 because ORDER BY clause appears before the WHERE clause.\nIt will display the row which has the COL2 value as 'B' ordered by the COL1, COL2.\nIt throws an error as the ORDER BY clause cannot be written before the WHERE clause in Oracle.\n" }, { "code": null, "e": 13658, "s": 13633, "text": "It executes successfully" }, { "code": null, "e": 13816, "s": 13658, "text": "It gives the required result with the COL2 value as 'B' but no ordering by the columns COL1 and COL2 because ORDER BY clause appears before the WHERE clause." }, { "code": null, "e": 13899, "s": 13816, "text": "It will display the row which has the COL2 value as 'B' ordered by the COL1, COL2." }, { "code": null, "e": 13994, "s": 13899, "text": "It throws an error as the ORDER BY clause cannot be written before the WHERE clause in Oracle." }, { "code": null, "e": 14084, "s": 13994, "text": "Answer: D. The ORDER BY clause must appear after the WHERE clause in the SELECT statement" }, { "code": null, "e": 14174, "s": 14084, "text": "22. Which two clauses of the SELECT statement are necessary for Selection and Projection?" }, { "code": null, "e": 14236, "s": 14174, "text": "\nSELECT, FROM\nORDER BY, WHERE\nSELECT, WHERE\nSELECT, ORDER BY\n" }, { "code": null, "e": 14249, "s": 14236, "text": "SELECT, FROM" }, { "code": null, "e": 14265, "s": 14249, "text": "ORDER BY, WHERE" }, { "code": null, "e": 14279, "s": 14265, "text": "SELECT, WHERE" }, { "code": null, "e": 14296, "s": 14279, "text": "SELECT, ORDER BY" }, { "code": null, "e": 14307, "s": 14296, "text": "Answer: C." }, { "code": null, "e": 14388, "s": 14307, "text": "23. Which of the following WHERE clauses will NOT fit in the below SELECT query?" }, { "code": null, "e": 14425, "s": 14388, "text": "SELECT ename, deptno, sal \nFROM emp;" }, { "code": null, "e": 14559, "s": 14425, "text": "\nWHERE HIREDATE IN ('02-JUN-2004');\nWHERE SAL IN ('1000','4000','2000');\nWHERE JOB IN (SALES,CLERK);\nWHERE COMM BETWEEN 0.1 AND 0.5;\n" }, { "code": null, "e": 14594, "s": 14559, "text": "WHERE HIREDATE IN ('02-JUN-2004');" }, { "code": null, "e": 14631, "s": 14594, "text": "WHERE SAL IN ('1000','4000','2000');" }, { "code": null, "e": 14659, "s": 14631, "text": "WHERE JOB IN (SALES,CLERK);" }, { "code": null, "e": 14691, "s": 14659, "text": "WHERE COMM BETWEEN 0.1 AND 0.5;" }, { "code": null, "e": 14760, "s": 14691, "text": "Answer: C. Character literals must be enclosed within single quotes " }, { "code": null, "e": 14878, "s": 14760, "text": "24. Choose the WHERE clause that extracts the DNAME values containing the character literal “er” from the DEPT table." }, { "code": null, "e": 14991, "s": 14878, "text": "\nWHERE DNAME IN ('%e%r');\nWHERE DNAME LIKE '%er%';\nWHERE DNAME BETWEEN 'e' AND 'r';\nWHERE DNAME CONTAINS 'e%r';\n" }, { "code": null, "e": 15016, "s": 14991, "text": "WHERE DNAME IN ('%e%r');" }, { "code": null, "e": 15041, "s": 15016, "text": "WHERE DNAME LIKE '%er%';" }, { "code": null, "e": 15074, "s": 15041, "text": "WHERE DNAME BETWEEN 'e' AND 'r';" }, { "code": null, "e": 15102, "s": 15074, "text": "WHERE DNAME CONTAINS 'e%r';" }, { "code": null, "e": 15183, "s": 15102, "text": "Answer: B. The LIKE operator is used to perform wild card search in SQL queries." }, { "code": null, "e": 15255, "s": 15183, "text": "25. Which two of the following conditions are equivalent to each other?" }, { "code": null, "e": 15343, "s": 15255, "text": "\nWHERE comm IS NULL\nWHERE comm = NULL\nWHERE comm IN (NULL)\nWHERE NOT(comm IS NOT NULL)\n" }, { "code": null, "e": 15362, "s": 15343, "text": "WHERE comm IS NULL" }, { "code": null, "e": 15380, "s": 15362, "text": "WHERE comm = NULL" }, { "code": null, "e": 15401, "s": 15380, "text": "WHERE comm IN (NULL)" }, { "code": null, "e": 15429, "s": 15401, "text": "WHERE NOT(comm IS NOT NULL)" }, { "code": null, "e": 15578, "s": 15429, "text": "Answer: A, D. The NOT operator can be used to negate the effect of its operand. Therefore (COMM IS NULL) is equivalent to (NOT (COMM IS NOT NULL))." }, { "code": null, "e": 15644, "s": 15578, "text": "26. Which of the following clauses are mandatory in an SQL query?" }, { "code": null, "e": 15712, "s": 15644, "text": "\nSELECT, FROM\nSELECT,FROM,WHERE\nSELECT,WHERE\nSELECT,WHERE,ORDER BY\n" }, { "code": null, "e": 15725, "s": 15712, "text": "SELECT, FROM" }, { "code": null, "e": 15743, "s": 15725, "text": "SELECT,FROM,WHERE" }, { "code": null, "e": 15756, "s": 15743, "text": "SELECT,WHERE" }, { "code": null, "e": 15778, "s": 15756, "text": "SELECT,WHERE,ORDER BY" }, { "code": null, "e": 15851, "s": 15778, "text": "Answer: A. SELECT and FROM are the mandatory clauses in a SELECT query. " }, { "code": null, "e": 15938, "s": 15851, "text": "27. Which three of the following WHERE clause conditions are equivalent to each other?" }, { "code": null, "e": 16071, "s": 15938, "text": "\nWHERE SAL <=5000 AND SAL >=2000\nWHERE SAL IN (2000,3000,4000,5000)\nWHERE SAL BETWEEN 2000 AND 5000\nWHERE SAL > 1999 AND SAL < 5001\n" }, { "code": null, "e": 16103, "s": 16071, "text": "WHERE SAL <=5000 AND SAL >=2000" }, { "code": null, "e": 16138, "s": 16103, "text": "WHERE SAL IN (2000,3000,4000,5000)" }, { "code": null, "e": 16170, "s": 16138, "text": "WHERE SAL BETWEEN 2000 AND 5000" }, { "code": null, "e": 16202, "s": 16170, "text": "WHERE SAL > 1999 AND SAL < 5001" }, { "code": null, "e": 16311, "s": 16202, "text": "Answer: A, C, D. The conditions can be made equivalent with the use of IN, BETWEEN and relational operators " }, { "code": null, "e": 16379, "s": 16311, "text": "28. Which of the following is true with respect to the below query?" }, { "code": null, "e": 16439, "s": 16379, "text": "SELECT empno, ename, job\nFROM emp\nWHERE ename like '_ith%';" }, { "code": null, "e": 16907, "s": 16439, "text": "\nIt fetches the employee id, name and job of those employees who have 'ith' appearing anywhere in their name. \nIt fetches the employee id, name and job of those employees whose name starts with 'ith'.\nThe query throws an error as two expressions for string matching cannot be written together.\nIt fetches the employee id, name and job of those employees whose name starts with any alphanumeric character followed by 'ith' and any alphanumeric characters after 'ith'.\n" }, { "code": null, "e": 17017, "s": 16907, "text": "It fetches the employee id, name and job of those employees who have 'ith' appearing anywhere in their name. " }, { "code": null, "e": 17107, "s": 17017, "text": "It fetches the employee id, name and job of those employees whose name starts with 'ith'." }, { "code": null, "e": 17200, "s": 17107, "text": "The query throws an error as two expressions for string matching cannot be written together." }, { "code": null, "e": 17373, "s": 17200, "text": "It fetches the employee id, name and job of those employees whose name starts with any alphanumeric character followed by 'ith' and any alphanumeric characters after 'ith'." }, { "code": null, "e": 17385, "s": 17373, "text": "Answer: D. " }, { "code": null, "e": 17440, "s": 17385, "text": "29. Which of the following is used to end a SQL query?" }, { "code": null, "e": 17450, "s": 17440, "text": "\n:\n;\n.\n/\n" }, { "code": null, "e": 17452, "s": 17450, "text": ":" }, { "code": null, "e": 17454, "s": 17452, "text": ";" }, { "code": null, "e": 17456, "s": 17454, "text": "." }, { "code": null, "e": 17458, "s": 17456, "text": "/" }, { "code": null, "e": 17566, "s": 17458, "text": "Answer: B, D. A semicolon (;) or backslash (/) is used to terminate a query in SQL* Plus and SQL Developer." }, { "code": null, "e": 17722, "s": 17566, "text": "30. The employees JAMES and MILLER want to know their department id by querying the database. Which of the following queries will give the required result?" }, { "code": null, "e": 17935, "s": 17722, "text": "\nSELECT ename, deptno FROM emp WHERE ename = 'JAMES';\nSELECT ename, deptno FROM emp WHERE ename = 'MILLER';\nSELECT ename, deptno FROM dept\nSELECT ename, deptno FROM emp WHERE ename = 'JAMES' OR ename = 'MILLER' \n" }, { "code": null, "e": 17988, "s": 17935, "text": "SELECT ename, deptno FROM emp WHERE ename = 'JAMES';" }, { "code": null, "e": 18041, "s": 17988, "text": "SELECT ename, deptno FROM emp WHERE ename = 'JAMES';" }, { "code": null, "e": 18095, "s": 18041, "text": "SELECT ename, deptno FROM emp WHERE ename = 'MILLER';" }, { "code": null, "e": 18149, "s": 18095, "text": "SELECT ename, deptno FROM emp WHERE ename = 'MILLER';" }, { "code": null, "e": 18180, "s": 18149, "text": "SELECT ename, deptno FROM dept" }, { "code": null, "e": 18211, "s": 18180, "text": "SELECT ename, deptno FROM dept" }, { "code": null, "e": 18284, "s": 18211, "text": "SELECT ename, deptno FROM emp WHERE ename = 'JAMES' OR ename = 'MILLER' " }, { "code": null, "e": 18357, "s": 18284, "text": "SELECT ename, deptno FROM emp WHERE ename = 'JAMES' OR ename = 'MILLER' " }, { "code": null, "e": 18479, "s": 18357, "text": "Answer: D. Multiple conditions can be joined using OR clause. Query execution is successful if either of the two is true." }, { "code": null, "e": 18543, "s": 18479, "text": "31. Which of the following is false regarding the WHERE clause?" }, { "code": null, "e": 18781, "s": 18543, "text": "\nThe WHERE can compare values in columns, literal, arithmetic expressions, or functions.\nThe WHERE clause contains column name\nColumn aliases can be used in the WHERE clause. \nThe WHERE clause cannot contain list of values or constants.\n" }, { "code": null, "e": 18869, "s": 18781, "text": "The WHERE can compare values in columns, literal, arithmetic expressions, or functions." }, { "code": null, "e": 18907, "s": 18869, "text": "The WHERE clause contains column name" }, { "code": null, "e": 18956, "s": 18907, "text": "Column aliases can be used in the WHERE clause. " }, { "code": null, "e": 19017, "s": 18956, "text": "The WHERE clause cannot contain list of values or constants." }, { "code": null, "e": 19031, "s": 19017, "text": "Answer: C, D." }, { "code": null, "e": 19078, "s": 19031, "text": "32. What is the default date format in Oracle?" }, { "code": null, "e": 19121, "s": 19078, "text": "\nDD-MON-YY\nDD-MON-YYYY\nDD-MM-RR\nDD-MON-RR\n" }, { "code": null, "e": 19131, "s": 19121, "text": "DD-MON-YY" }, { "code": null, "e": 19143, "s": 19131, "text": "DD-MON-YYYY" }, { "code": null, "e": 19152, "s": 19143, "text": "DD-MM-RR" }, { "code": null, "e": 19162, "s": 19152, "text": "DD-MON-RR" }, { "code": null, "e": 19222, "s": 19162, "text": "Answer: D. DD-MON-RR is the default date format in Oracle." }, { "code": null, "e": 19269, "s": 19222, "text": "33. Predict the output of the below SQL query." }, { "code": null, "e": 19358, "s": 19269, "text": "SELECT ename, deptno, sal, comm\nFROM emp\nWHERE job = 'SALES'\nAND hiredate = ”01-JAN-97”;" }, { "code": null, "e": 19610, "s": 19358, "text": "\nIt fetches the employee data for all SALES employees\nIt throws an error \"ORA-00904: \"01-JAN-13\": invalid identifier\"\nQuery executes successfully but no results are returned\nIt fetches the data for all SALES employees who were hired on 01st Jan, 1997\n" }, { "code": null, "e": 19663, "s": 19610, "text": "It fetches the employee data for all SALES employees" }, { "code": null, "e": 19727, "s": 19663, "text": "It throws an error \"ORA-00904: \"01-JAN-13\": invalid identifier\"" }, { "code": null, "e": 19783, "s": 19727, "text": "Query executes successfully but no results are returned" }, { "code": null, "e": 19860, "s": 19783, "text": "It fetches the data for all SALES employees who were hired on 01st Jan, 1997" }, { "code": null, "e": 19924, "s": 19860, "text": "Answer: B. Date literals must be enclosed within single quotes." }, { "code": null, "e": 20099, "s": 19924, "text": "34. You need to display the names of all the employees having the first name as \"GARRY\" from the EMPLOYEES table. Which of the following queries will fulfill the requirement?" }, { "code": null, "e": 20361, "s": 20099, "text": "\nSELECT first_name FROM employees WHERE first_name LIKE 'GARRY%';\nSELECT first_name FROM employees WHERE first_name LIKE '%GARRY%';\nSELECT first_name FROM employees WHERE first_name LIKE 'GARRY';\nSELECT first_name FROM employees WHERE first_name LIKE '_ARRY%';\n" }, { "code": null, "e": 20426, "s": 20361, "text": "SELECT first_name FROM employees WHERE first_name LIKE 'GARRY%';" }, { "code": null, "e": 20491, "s": 20426, "text": "SELECT first_name FROM employees WHERE first_name LIKE 'GARRY%';" }, { "code": null, "e": 20557, "s": 20491, "text": "SELECT first_name FROM employees WHERE first_name LIKE '%GARRY%';" }, { "code": null, "e": 20623, "s": 20557, "text": "SELECT first_name FROM employees WHERE first_name LIKE '%GARRY%';" }, { "code": null, "e": 20687, "s": 20623, "text": "SELECT first_name FROM employees WHERE first_name LIKE 'GARRY';" }, { "code": null, "e": 20751, "s": 20687, "text": "SELECT first_name FROM employees WHERE first_name LIKE 'GARRY';" }, { "code": null, "e": 20816, "s": 20751, "text": "SELECT first_name FROM employees WHERE first_name LIKE '_ARRY%';" }, { "code": null, "e": 20881, "s": 20816, "text": "SELECT first_name FROM employees WHERE first_name LIKE '_ARRY%';" }, { "code": null, "e": 20971, "s": 20881, "text": "Answer: C. Wild Cards can be used if certain characters of the search string are unknown." }, { "code": null, "e": 21185, "s": 20971, "text": "35. You need to display the employee ID of all the employees who contain a letter 's' in their last name at second position and department ID as 100. Which of the following queries will fetch the required results?" }, { "code": null, "e": 21488, "s": 21185, "text": "\nSELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '%s%';\nSELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '%s_';\nSELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '_s_%';\nSELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '_s%';\n" }, { "code": null, "e": 21563, "s": 21488, "text": "SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '%s%';" }, { "code": null, "e": 21638, "s": 21563, "text": "SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '%s%';" }, { "code": null, "e": 21713, "s": 21638, "text": "SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '%s_';" }, { "code": null, "e": 21788, "s": 21713, "text": "SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '%s_';" }, { "code": null, "e": 21864, "s": 21788, "text": "SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '_s_%';" }, { "code": null, "e": 21940, "s": 21864, "text": "SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '_s_%';" }, { "code": null, "e": 22015, "s": 21940, "text": "SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '_s%';" }, { "code": null, "e": 22090, "s": 22015, "text": "SELECT emp_id FROM employees WHERE dept_id = 100 AND last_name LIKE '_s%';" }, { "code": null, "e": 22181, "s": 22090, "text": "Answer: D. The wildcard character underscore (_) is used to substitute a single character." }, { "code": null, "e": 22230, "s": 22181, "text": "36. What will be the outcome of the below query?" }, { "code": null, "e": 22312, "s": 22230, "text": "SELECT first_name, last_name, dept_id \nFROM employees\nWHERE hire_date LIKE '%98';" }, { "code": null, "e": 22748, "s": 22312, "text": "\nThe first name, last name and the department ID for all the employees who joined in the year 1998 will be displayed. \nThe first name, last name and the department ID for all the employees who joined in the year 2098 will be displayed. \nNo results will be returned. \nThe first name, last name and the department ID for all the employees who joined in the year 1998 between 1st January, 1998 and 31st December, 1998 will be displayed. \n" }, { "code": null, "e": 22866, "s": 22748, "text": "The first name, last name and the department ID for all the employees who joined in the year 1998 will be displayed. " }, { "code": null, "e": 22984, "s": 22866, "text": "The first name, last name and the department ID for all the employees who joined in the year 2098 will be displayed. " }, { "code": null, "e": 23014, "s": 22984, "text": "No results will be returned. " }, { "code": null, "e": 23182, "s": 23014, "text": "The first name, last name and the department ID for all the employees who joined in the year 1998 between 1st January, 1998 and 31st December, 1998 will be displayed. " }, { "code": null, "e": 23279, "s": 23182, "text": "Answer: D. The LIKE operator is used to perform wild card search on character and date literals." }, { "code": null, "e": 23354, "s": 23279, "text": "37. Which of the following is used to get rows based on a range of values?" }, { "code": null, "e": 23382, "s": 23354, "text": "\nUNION ALL\nIN\nBETWEEN\nLIKE\n" }, { "code": null, "e": 23392, "s": 23382, "text": "UNION ALL" }, { "code": null, "e": 23395, "s": 23392, "text": "IN" }, { "code": null, "e": 23403, "s": 23395, "text": "BETWEEN" }, { "code": null, "e": 23408, "s": 23403, "text": "LIKE" }, { "code": null, "e": 23491, "s": 23408, "text": "Answer: C. The BETWEEN operator is used to retrieve rows based on range of values." }, { "code": null, "e": 23685, "s": 23491, "text": "38. You need to display the employee IDs of the employees who have their salaries between 20000 (inclusive) and 50000(inclusive). Which of the following queries will fetch the required results?" }, { "code": null, "e": 23953, "s": 23685, "text": "\nSELECT emp_id FROM employees WHERE salary >=20000 AND salary <=50000;\nSELECT emp_id FROM employees WHERE salary IN (20000, 50000);\nSELECT emp_id FROM employees WHERE salary >20000 AND salary <50000;\nSELECT emp_id FROM employees WHERE salary between 20000 AND 50000;\n" }, { "code": null, "e": 24023, "s": 23953, "text": "SELECT emp_id FROM employees WHERE salary >=20000 AND salary <=50000;" }, { "code": null, "e": 24093, "s": 24023, "text": "SELECT emp_id FROM employees WHERE salary >=20000 AND salary <=50000;" }, { "code": null, "e": 24154, "s": 24093, "text": "SELECT emp_id FROM employees WHERE salary IN (20000, 50000);" }, { "code": null, "e": 24215, "s": 24154, "text": "SELECT emp_id FROM employees WHERE salary IN (20000, 50000);" }, { "code": null, "e": 24283, "s": 24215, "text": "SELECT emp_id FROM employees WHERE salary >20000 AND salary <50000;" }, { "code": null, "e": 24351, "s": 24283, "text": "SELECT emp_id FROM employees WHERE salary >20000 AND salary <50000;" }, { "code": null, "e": 24418, "s": 24351, "text": "SELECT emp_id FROM employees WHERE salary between 20000 AND 50000;" }, { "code": null, "e": 24485, "s": 24418, "text": "SELECT emp_id FROM employees WHERE salary between 20000 AND 50000;" }, { "code": null, "e": 24651, "s": 24485, "text": "Answer: A, D. For larger ranges of values, BETWEEN and relational operators are best suited in the queries. IN operator is not recommended for large range of values." }, { "code": null, "e": 24701, "s": 24651, "text": "39. What is true with respect to the below query?" }, { "code": null, "e": 24786, "s": 24701, "text": "SELECT first_name, last_name \nFROM employees \nWHERE last_name BETWEEN 'B%' AND 'E%';" }, { "code": null, "e": 25239, "s": 24786, "text": "\nIt will display all the employees having last names starting with the alphabets 'B' till 'E' inclusive of B and exclusive of E. \nIt will throw an error as BETWEEN can only be used for Numbers and not strings. \nIt will display all the employees having last names starting from 'B' and ending with 'E'. \nIt will display all the employees having last names in the range of starting alphabets as 'B' and 'E' excluding the names starting with 'B' and 'E'.\n" }, { "code": null, "e": 25368, "s": 25239, "text": "It will display all the employees having last names starting with the alphabets 'B' till 'E' inclusive of B and exclusive of E. " }, { "code": null, "e": 25449, "s": 25368, "text": "It will throw an error as BETWEEN can only be used for Numbers and not strings. " }, { "code": null, "e": 25541, "s": 25449, "text": "It will display all the employees having last names starting from 'B' and ending with 'E'. " }, { "code": null, "e": 25690, "s": 25541, "text": "It will display all the employees having last names in the range of starting alphabets as 'B' and 'E' excluding the names starting with 'B' and 'E'." }, { "code": null, "e": 25769, "s": 25690, "text": "Answer: A. The BETWEEN operator works with the range of character values also." }, { "code": null, "e": 25828, "s": 25769, "text": "40. What will be the outcome of the query mentioned below?" }, { "code": null, "e": 25942, "s": 25828, "text": "SELECT employee_id, last_name, first_name, salary, manager_id \nFROM employees \nWHERE manager_id IN (200,100,300);" }, { "code": null, "e": 26317, "s": 25942, "text": "\nIt will show all the employees who are under the managers having IDs in the range starting from 100 to 300. \nIt will show all the employees who are under the managers having IDs 100, 200 or 300. \nIt will throw an error as the manager IDs should be put in quotes. \nIt will throw an error as the sorting of manager_id in the WHERE clause conflicts with the ORDER BY clause. \n" }, { "code": null, "e": 26426, "s": 26317, "text": "It will show all the employees who are under the managers having IDs in the range starting from 100 to 300. " }, { "code": null, "e": 26513, "s": 26426, "text": "It will show all the employees who are under the managers having IDs 100, 200 or 300. " }, { "code": null, "e": 26581, "s": 26513, "text": "It will throw an error as the manager IDs should be put in quotes. " }, { "code": null, "e": 26690, "s": 26581, "text": "It will throw an error as the sorting of manager_id in the WHERE clause conflicts with the ORDER BY clause. " }, { "code": null, "e": 26775, "s": 26690, "text": "Answer: B. The IN operator can be used to provide small and limited number of range." }, { "code": null, "e": 26843, "s": 26777, "text": "41. Which of the following clause defines a Membership condition?" }, { "code": null, "e": 26878, "s": 26843, "text": "\nBETWEEN\nLIKE\nIS NULL\nIN (NOT IN)\n" }, { "code": null, "e": 26886, "s": 26878, "text": "BETWEEN" }, { "code": null, "e": 26891, "s": 26886, "text": "LIKE" }, { "code": null, "e": 26899, "s": 26891, "text": "IS NULL" }, { "code": null, "e": 26911, "s": 26899, "text": "IN (NOT IN)" }, { "code": null, "e": 27017, "s": 26911, "text": "Answer: D. The IN operator defines a Membership condition which may use a range of values or a subquery." }, { "code": null, "e": 27087, "s": 27017, "text": "42. Which of the following data types can be used within IN operator?" }, { "code": null, "e": 27114, "s": 27087, "text": "\nVARCHAR2\nNUMBER\nDATE\nALL\n" }, { "code": null, "e": 27123, "s": 27114, "text": "VARCHAR2" }, { "code": null, "e": 27130, "s": 27123, "text": "NUMBER" }, { "code": null, "e": 27135, "s": 27130, "text": "DATE" }, { "code": null, "e": 27139, "s": 27135, "text": "ALL" }, { "code": null, "e": 27198, "s": 27139, "text": "Answer: D. The IN operator works with all types of values." }, { "code": null, "e": 27362, "s": 27198, "text": "43. You need to display the list of all the employees whose first name starts with “Bryan” or “Jason”. Which of the following queries will fulfill the requirement?" }, { "code": null, "e": 27771, "s": 27362, "text": "\nSELECT emp_id, last_name, first_name FROM employees WHERE first_name LIKE 'Bryan%' OR first_name LIKE 'Jason%';\nSELECT emp_id, last_name, first_name FROM employees WHERE first_name BETWEEN 'Bryan' and 'Jason' ;\nSELECT emp_id, last_name, first_name FROM employees WHERE first_name IN ('Bryan', 'Jason'); \nSELECT emp_id, last_name, first_name FROM employees WHERE first_name = 'Bryan' OR first_name = 'Jason'\n" }, { "code": null, "e": 27883, "s": 27771, "text": "SELECT emp_id, last_name, first_name FROM employees WHERE first_name LIKE 'Bryan%' OR first_name LIKE 'Jason%';" }, { "code": null, "e": 27995, "s": 27883, "text": "SELECT emp_id, last_name, first_name FROM employees WHERE first_name LIKE 'Bryan%' OR first_name LIKE 'Jason%';" }, { "code": null, "e": 28094, "s": 27995, "text": "SELECT emp_id, last_name, first_name FROM employees WHERE first_name BETWEEN 'Bryan' and 'Jason' ;" }, { "code": null, "e": 28193, "s": 28094, "text": "SELECT emp_id, last_name, first_name FROM employees WHERE first_name BETWEEN 'Bryan' and 'Jason' ;" }, { "code": null, "e": 28286, "s": 28193, "text": "SELECT emp_id, last_name, first_name FROM employees WHERE first_name IN ('Bryan', 'Jason'); " }, { "code": null, "e": 28378, "s": 28286, "text": "SELECT emp_id, last_name, first_name FROM employees WHERE first_name IN ('Bryan', 'Jason');" }, { "code": null, "e": 28481, "s": 28378, "text": "SELECT emp_id, last_name, first_name FROM employees WHERE first_name = 'Bryan' OR first_name = 'Jason'" }, { "code": null, "e": 28584, "s": 28481, "text": "SELECT emp_id, last_name, first_name FROM employees WHERE first_name = 'Bryan' OR first_name = 'Jason'" }, { "code": null, "e": 28669, "s": 28584, "text": "Answer: C, D. The IN operator checks for ANY values defined as membership condition." }, { "code": null, "e": 28860, "s": 28669, "text": "44. You need to extract details of those departments whose name contains the string '_DXX'. Which of the below WHERE clauses could be used in the SELECT statement to get the required output?" }, { "code": null, "e": 29024, "s": 28860, "text": "\nWHERE dept_id LIKE '%_DXX%' ESCAPE '_'\nWHERE dept_id LIKE '%\\_DXX%' ESCAPE '\\'\nWHERE dept_id LIKE '%_D123%' ESCAPE '%_'\nWHERE dept_id LIKE '%\\_D123%' ESCAPE '\\_'\n" }, { "code": null, "e": 29063, "s": 29024, "text": "WHERE dept_id LIKE '%_DXX%' ESCAPE '_'" }, { "code": null, "e": 29103, "s": 29063, "text": "WHERE dept_id LIKE '%\\_DXX%' ESCAPE '\\'" }, { "code": null, "e": 29144, "s": 29103, "text": "WHERE dept_id LIKE '%_D123%' ESCAPE '%_'" }, { "code": null, "e": 29186, "s": 29144, "text": "WHERE dept_id LIKE '%\\_D123%' ESCAPE '\\_'" }, { "code": null, "e": 29197, "s": 29186, "text": "Answer: B." }, { "code": null, "e": 29280, "s": 29197, "text": "45. Which statement is true regarding the default behavior of the ORDER BY clause?" }, { "code": null, "e": 29587, "s": 29280, "text": "\nIn a character sort, the values are case-sensitive.\nNULL values are not considered at all by the sort operation.\nOnly those columns that are specified in the SELECT list can be used in the ORDER BY clause.\nNumeric values are displayed from the maximum to the minimum value if they have decimal positions.\n" }, { "code": null, "e": 29639, "s": 29587, "text": "In a character sort, the values are case-sensitive." }, { "code": null, "e": 29700, "s": 29639, "text": "NULL values are not considered at all by the sort operation." }, { "code": null, "e": 29793, "s": 29700, "text": "Only those columns that are specified in the SELECT list can be used in the ORDER BY clause." }, { "code": null, "e": 29892, "s": 29793, "text": "Numeric values are displayed from the maximum to the minimum value if they have decimal positions." }, { "code": null, "e": 29976, "s": 29892, "text": "Answer: A. The ORDER BY clause does a case sensitive sorting with character values." }, { "code": null, "e": 30314, "s": 29976, "text": "46. You need to generate a report of all employees from the EMPLOYEES table based on the following conditions:\n1. The Employee first name should not begin with 'T' or 'N'.\n2. The Employee's salary should be more than 20000.\n3. The Employee should have been hired after 1st January 2010.\nWhich WHERE clause would give the required result?" }, { "code": null, "e": 30742, "s": 30314, "text": "\nWHERE first_name NOT LIKE 'T%' OR first_name NOT LIKE 'N%' AND salary > 20000 AND hire_date > '1-JAN-10'\nWHERE (first_name NOT LIKE 'T%' AND first_name NOT LIKE 'N%')OR salary > 20000 OR hire_date > '1-JAN-10'\nWHERE first_name NOT LIKE 'T%' AND first_name NOT LIKE 'N%' AND salary > 20000 AND hire_date > '1-JAN-10'\nWHERE (first_name NOT LIKE '%T%' OR first_name NOT LIKE '%N%') AND(salary > 20000 AND hire_date > '1-JAN-10')\n" }, { "code": null, "e": 30847, "s": 30742, "text": "WHERE first_name NOT LIKE 'T%' OR first_name NOT LIKE 'N%' AND salary > 20000 AND hire_date > '1-JAN-10'" }, { "code": null, "e": 30952, "s": 30847, "text": "WHERE (first_name NOT LIKE 'T%' AND first_name NOT LIKE 'N%')OR salary > 20000 OR hire_date > '1-JAN-10'" }, { "code": null, "e": 31058, "s": 30952, "text": "WHERE first_name NOT LIKE 'T%' AND first_name NOT LIKE 'N%' AND salary > 20000 AND hire_date > '1-JAN-10'" }, { "code": null, "e": 31168, "s": 31058, "text": "WHERE (first_name NOT LIKE '%T%' OR first_name NOT LIKE '%N%') AND(salary > 20000 AND hire_date > '1-JAN-10')" }, { "code": null, "e": 31180, "s": 31168, "text": "Answer: C. " }, { "code": null, "e": 31384, "s": 31180, "text": "47. Using the EMPLOYEES table, you need to display the names of all employees hired after January 1, 2013, starting with the freshers. Which query would give the required result? (Choose all that apply.)" }, { "code": null, "e": 31783, "s": 31384, "text": "\nSELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY 2 DESC;\nSELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY first_name DESC;\nSELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY 1 DESC;\nSELECT first_name, hire_date \"START DATE\" FROM employees WHERE hire_date > '01-JAN-13' ORDER BY \"START DATE\" DESC;\n" }, { "code": null, "e": 31874, "s": 31783, "text": "SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY 2 DESC;" }, { "code": null, "e": 31965, "s": 31874, "text": "SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY 2 DESC;" }, { "code": null, "e": 32065, "s": 31965, "text": "SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY first_name DESC;" }, { "code": null, "e": 32165, "s": 32065, "text": "SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY first_name DESC;" }, { "code": null, "e": 32256, "s": 32165, "text": "SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY 1 DESC;" }, { "code": null, "e": 32347, "s": 32256, "text": "SELECT first_name, hire_date FROM employees WHERE hire_date > '01-JAN-13' ORDER BY 1 DESC;" }, { "code": null, "e": 32462, "s": 32347, "text": "SELECT first_name, hire_date \"START DATE\" FROM employees WHERE hire_date > '01-JAN-13' ORDER BY \"START DATE\" DESC;" }, { "code": null, "e": 32577, "s": 32462, "text": "SELECT first_name, hire_date \"START DATE\" FROM employees WHERE hire_date > '01-JAN-13' ORDER BY \"START DATE\" DESC;" }, { "code": null, "e": 32591, "s": 32577, "text": "Answer: A, D." }, { "code": null, "e": 32841, "s": 32591, "text": "48. Using the EMPLOYEES table, you need to find out the names and salaries of all the employees hired in departments 100 and 101 in the time interval 15th March '12 to 15th October '13. Which two queries would give the required result? (Choose two.)" }, { "code": null, "e": 33356, "s": 32841, "text": "\nSELECT first_name, salary FROM employees WHERE dept_id IN (100,101) AND hire_date BETWEEN '15-MAR-12' AND '15-OCT-12';\nSELECT first_name, salary FROM employees WHERE dept_id = 100 OR dept_id =101 AND hire_date >='15-MAR-12' OR hire_date <='15-OCT-12';\nSELECT first_name, salary FROM employees WHERE (dept_id BETWEEN 100 AND 101) AND (hire_date IN ('15-MAR-12','15-OCT-12'));\nSELECT first_name, salary FROM employees WHERE (dept_id = 100 OR dept_id =101) AND (hire_date >='15-MAR-12' AND hire_date <='15-OCT-12');\n" }, { "code": null, "e": 33475, "s": 33356, "text": "SELECT first_name, salary FROM employees WHERE dept_id IN (100,101) AND hire_date BETWEEN '15-MAR-12' AND '15-OCT-12';" }, { "code": null, "e": 33594, "s": 33475, "text": "SELECT first_name, salary FROM employees WHERE dept_id IN (100,101) AND hire_date BETWEEN '15-MAR-12' AND '15-OCT-12';" }, { "code": null, "e": 33727, "s": 33594, "text": "SELECT first_name, salary FROM employees WHERE dept_id = 100 OR dept_id =101 AND hire_date >='15-MAR-12' OR hire_date <='15-OCT-12';" }, { "code": null, "e": 33860, "s": 33727, "text": "SELECT first_name, salary FROM employees WHERE dept_id = 100 OR dept_id =101 AND hire_date >='15-MAR-12' OR hire_date <='15-OCT-12';" }, { "code": null, "e": 33983, "s": 33860, "text": "SELECT first_name, salary FROM employees WHERE (dept_id BETWEEN 100 AND 101) AND (hire_date IN ('15-MAR-12','15-OCT-12'));" }, { "code": null, "e": 34106, "s": 33983, "text": "SELECT first_name, salary FROM employees WHERE (dept_id BETWEEN 100 AND 101) AND (hire_date IN ('15-MAR-12','15-OCT-12'));" }, { "code": null, "e": 34244, "s": 34106, "text": "SELECT first_name, salary FROM employees WHERE (dept_id = 100 OR dept_id =101) AND (hire_date >='15-MAR-12' AND hire_date <='15-OCT-12');" }, { "code": null, "e": 34382, "s": 34244, "text": "SELECT first_name, salary FROM employees WHERE (dept_id = 100 OR dept_id =101) AND (hire_date >='15-MAR-12' AND hire_date <='15-OCT-12');" }, { "code": null, "e": 34397, "s": 34382, "text": "Answer: A, D. " }, { "code": null, "e": 34614, "s": 34397, "text": "49. Using the EMPLOYEES table, you issue the following query to generate the names, current salary and the salary increased after an appraisal by 25%. The increased salary for all the employees should be above 30000." }, { "code": null, "e": 34730, "s": 34614, "text": "SELECT first_name, salary,\nsalary + (salary *0.25) \"INCREASED_SALARY\"\nFROM employees\nWHERE increased_salary >30000;" }, { "code": null, "e": 34801, "s": 34730, "text": "The query throws an error ORA-00904. What is the reason for the error?" }, { "code": null, "e": 35057, "s": 34801, "text": "\nThe parenthesis is missing in the expression used in SELECT statement.\nSingle quotes must be used to define a column alias.\nColumn alias cannot be used in the WHERE clause.\nColumn alias in the WHERE clause must be enclosed within double quotation marks.\n" }, { "code": null, "e": 35128, "s": 35057, "text": "The parenthesis is missing in the expression used in SELECT statement." }, { "code": null, "e": 35181, "s": 35128, "text": "Single quotes must be used to define a column alias." }, { "code": null, "e": 35230, "s": 35181, "text": "Column alias cannot be used in the WHERE clause." }, { "code": null, "e": 35311, "s": 35230, "text": "Column alias in the WHERE clause must be enclosed within double quotation marks." }, { "code": null, "e": 35436, "s": 35311, "text": "Answer: C. A column alias cannot be used in WHERE clause conditions but can be used in SELECT statement and ORDER BY clause." }, { "code": null, "e": 35626, "s": 35436, "text": "50. You need to display employee names from the EMPLOYEES table that belong to the Department id 100 with minimum salary as either 2000 or 4000 and no job_id. You issue the following query." }, { "code": null, "e": 35752, "s": 35626, "text": "SELECT first_name, dept_id, salary\nFROM employees\nWHERE dept_id = 100 AND (salary = 2000 OR salary = 4000) \nAND job_id <> '';" }, { "code": null, "e": 35803, "s": 35752, "text": "Which statement is true regarding the above query?" }, { "code": null, "e": 36080, "s": 35803, "text": "\nIt executes successfully but returns no result.\nIt executes successfully and returns the required result.\nIt generates an error because the condition specified for job_id is not valid.\nIt generates an error because the condition specified for the salary column is not valid.\n" }, { "code": null, "e": 36128, "s": 36080, "text": "It executes successfully but returns no result." }, { "code": null, "e": 36186, "s": 36128, "text": "It executes successfully and returns the required result." }, { "code": null, "e": 36265, "s": 36186, "text": "It generates an error because the condition specified for job_id is not valid." }, { "code": null, "e": 36355, "s": 36265, "text": "It generates an error because the condition specified for the salary column is not valid." }, { "code": null, "e": 36491, "s": 36355, "text": "Answer: A. The condition (salary = 2000 OR salary = 4000) results in FALSE because an employee cannot held multiple salaries at a time." }, { "code": null, "e": 36594, "s": 36491, "text": "51. Which three tasks can be performed using SQL functions built into Oracle Database? (Choose three.)" }, { "code": null, "e": 36847, "s": 36594, "text": "\nDisplaying a date in a non-default format\nFinding the number of characters in an expression\nSubstituting a character string in a text expression with a specified string\nCombining more than two columns or expressions into a single column in the output\n" }, { "code": null, "e": 36889, "s": 36847, "text": "Displaying a date in a non-default format" }, { "code": null, "e": 36939, "s": 36889, "text": "Finding the number of characters in an expression" }, { "code": null, "e": 37016, "s": 36939, "text": "Substituting a character string in a text expression with a specified string" }, { "code": null, "e": 37098, "s": 37016, "text": "Combining more than two columns or expressions into a single column in the output" }, { "code": null, "e": 37229, "s": 37098, "text": "Answer: A, B, C. Use formatting functions (TO_CHAR, TO_DATE), and character functions (LENGTH, REPLACE) to achieve the objectives." }, { "code": null, "e": 37484, "s": 37229, "text": "52. You need to generate a report that displays the IDs of all employees in the EMPLOYEES table whose salary is at least 25% more than the value 20000. The details should be displayed in the descending order of the salary. You issue the following query." }, { "code": null, "e": 37566, "s": 37484, "text": "SELECT emp_id\nFROM employees\nWHERE salary>=20000*0.25 \nORDER BY salary*0.25 DESC;" }, { "code": null, "e": 37617, "s": 37566, "text": "Which statement is true regarding the above query?" }, { "code": null, "e": 37964, "s": 37617, "text": "\nIt executes and produces the required result.\nIt produces an error because an expression cannot be used in the ORDER BY clause.\nIt produces an error because the DESC option cannot be used with an expression in the ORDER BY clause.\nIt produces an error because the expression in the ORDER BY clause should also be specified in the SELECT clause.\n" }, { "code": null, "e": 38010, "s": 37964, "text": "It executes and produces the required result." }, { "code": null, "e": 38092, "s": 38010, "text": "It produces an error because an expression cannot be used in the ORDER BY clause." }, { "code": null, "e": 38195, "s": 38092, "text": "It produces an error because the DESC option cannot be used with an expression in the ORDER BY clause." }, { "code": null, "e": 38309, "s": 38195, "text": "It produces an error because the expression in the ORDER BY clause should also be specified in the SELECT clause." }, { "code": null, "e": 38372, "s": 38309, "text": "Answer: A. The ORDER BY clause can contain column expressions." }, { "code": null, "e": 38431, "s": 38372, "text": "53. Examine the structure and data of the TRAININGS table:" }, { "code": null, "e": 38795, "s": 38431, "text": " Name Null? Type\n ----------------------------------------- -------- -------------\n\n TRAINING_ID NOT NULL NUMBER(5)\n TRAINING_LOCATION NUMBER(7,2)\n START_DATE DATE\n END_DATE DATE" }, { "code": null, "e": 39021, "s": 38795, "text": "TRAINING_ID START_DATE TRAINING_COST\n------ ---------------- -------------------------------------------------\n11 \t 01-JAN-10 \t\t\t1000\n22 \t\t 01-FEB-10 \t\t\t2000\n33 \t\t 01-MAR-10 \t\t\t3000" }, { "code": null, "e": 39170, "s": 39021, "text": "Dates are stored in the default date format dd-mon-rr in the TRAININGS table. Which three SQL statements would execute successfully? (Choose three.)" }, { "code": null, "e": 39389, "s": 39170, "text": "\nSELECT start_date + '10' FROM trainings;\nSELECT * FROM trainings WHERE start_date = '01-01-10';\nSELECT training_cost FROM trainings WHERE training_id > '11';\nSELECT * FROM trainings WHERE start_date ='01-JANUARY-10';\n" }, { "code": null, "e": 39430, "s": 39389, "text": "SELECT start_date + '10' FROM trainings;" }, { "code": null, "e": 39471, "s": 39430, "text": "SELECT start_date + '10' FROM trainings;" }, { "code": null, "e": 39526, "s": 39471, "text": "SELECT * FROM trainings WHERE start_date = '01-01-10';" }, { "code": null, "e": 39581, "s": 39526, "text": "SELECT * FROM trainings WHERE start_date = '01-01-10';" }, { "code": null, "e": 39643, "s": 39581, "text": "SELECT training_cost FROM trainings WHERE training_id > '11';" }, { "code": null, "e": 39705, "s": 39643, "text": "SELECT training_cost FROM trainings WHERE training_id > '11';" }, { "code": null, "e": 39764, "s": 39705, "text": "SELECT * FROM trainings WHERE start_date ='01-JANUARY-10';" }, { "code": null, "e": 39823, "s": 39764, "text": "SELECT * FROM trainings WHERE start_date ='01-JANUARY-10';" }, { "code": null, "e": 39840, "s": 39823, "text": "Answer: A, C, D." }, { "code": null, "e": 39923, "s": 39840, "text": "54. Which of the following statements is/are true with respect to the below query?" }, { "code": null, "e": 39983, "s": 39923, "text": "SELECT emp_id, first_name \nFROM employees\nORDER BY dept_id;" }, { "code": null, "e": 40283, "s": 39983, "text": "\nORDER BY clause should contain only those columns which are in the SELECT statement. \nThe above query will sort the result set in descending order. \nORDER BY clause can contain any column in the related table, not necessarily the columns in the SELECT statement. \nIt throws an error on execution. \n" }, { "code": null, "e": 40369, "s": 40283, "text": "ORDER BY clause should contain only those columns which are in the SELECT statement. " }, { "code": null, "e": 40432, "s": 40369, "text": "The above query will sort the result set in descending order. " }, { "code": null, "e": 40547, "s": 40432, "text": "ORDER BY clause can contain any column in the related table, not necessarily the columns in the SELECT statement. " }, { "code": null, "e": 40581, "s": 40547, "text": "It throws an error on execution. " }, { "code": null, "e": 40738, "s": 40581, "text": "Answer: C. The ORDER BY clause can use a column to sort the data which is not selected in the column list but is contained in the table used in FROM clause." }, { "code": null, "e": 40811, "s": 40738, "text": "55. Which feature of ORDER BY clause is demonstrated in the below query?" }, { "code": null, "e": 40882, "s": 40811, "text": "SELECT emp_id, first_name “EmpName”\nFROM employees\nORDER BY \"EmpName\";" }, { "code": null, "e": 41206, "s": 40882, "text": "\nORDER BY clause should contain only those columns which are in the SELECT statement. \nThe above query will sort the result set in descending order of first names of employees.\nORDER BY clause works with column aliases. \nThe SELECT query throws an error on execution because column alias cannot be used in ORDER BY clause.\n" }, { "code": null, "e": 41292, "s": 41206, "text": "ORDER BY clause should contain only those columns which are in the SELECT statement. " }, { "code": null, "e": 41382, "s": 41292, "text": "The above query will sort the result set in descending order of first names of employees." }, { "code": null, "e": 41426, "s": 41382, "text": "ORDER BY clause works with column aliases. " }, { "code": null, "e": 41528, "s": 41426, "text": "The SELECT query throws an error on execution because column alias cannot be used in ORDER BY clause." }, { "code": null, "e": 41622, "s": 41528, "text": "Answer: C. The ORDER BY clauses works fine with the column aliases used in SELECT statement. " }, { "code": null, "e": 41668, "s": 41622, "text": "56. What is true about the query given below?" }, { "code": null, "e": 41747, "s": 41668, "text": "SELECT last_name, job_id, department_id, hire_date \nFROM employees\nORDER BY 2;" }, { "code": null, "e": 42028, "s": 41747, "text": "\nIt executes successfully sorting the query results based on the JOB_ID. \nThe ORDER BY clause cannot contain a numeric. \nThe ORDER BY clause will not function as none of the columns in the SELECT statement are used in the ORDER BY clause.\nThe query throws an error on execution. \n" }, { "code": null, "e": 42101, "s": 42028, "text": "It executes successfully sorting the query results based on the JOB_ID. " }, { "code": null, "e": 42148, "s": 42101, "text": "The ORDER BY clause cannot contain a numeric. " }, { "code": null, "e": 42266, "s": 42148, "text": "The ORDER BY clause will not function as none of the columns in the SELECT statement are used in the ORDER BY clause." }, { "code": null, "e": 42307, "s": 42266, "text": "The query throws an error on execution. " }, { "code": null, "e": 42385, "s": 42307, "text": "Answer: A. Numeric position of the column can be used in the ORDER BY clause." }, { "code": null, "e": 42471, "s": 42385, "text": "57. You need to list the employees details for different jobs but only one at a time." }, { "code": null, "e": 42541, "s": 42471, "text": "SELECT emp_id, first_name, last_name FROM employees WHERE job_id....;" }, { "code": null, "e": 42615, "s": 42541, "text": "Which of the following is an easier way to achieve the same in SQL* Plus?" }, { "code": null, "e": 42823, "s": 42615, "text": "\nSubstitute each Job Id at a time\nUse * to list details of all employees\nUse &JOB to prompt for user input every time the query is executed\nDeclare session variables to substitute Job Id values in the query\n" }, { "code": null, "e": 42856, "s": 42823, "text": "Substitute each Job Id at a time" }, { "code": null, "e": 42895, "s": 42856, "text": "Use * to list details of all employees" }, { "code": null, "e": 42962, "s": 42895, "text": "Use &JOB to prompt for user input every time the query is executed" }, { "code": null, "e": 43029, "s": 42962, "text": "Declare session variables to substitute Job Id values in the query" }, { "code": null, "e": 43145, "s": 43029, "text": "Answer: C. The &X notation haults the query execution and prompts for user input every time the query is executed. " }, { "code": null, "e": 43232, "s": 43145, "text": "58. Which of the following statements is true regarding substitution variables in SQL?" }, { "code": null, "e": 43592, "s": 43232, "text": "\nThe same query can be executed for different values using the substitution variables. \nUsing the substitution variables, one needs to alter the WHERE clause every time. \nSubstitution variables are not supported in Oracle. \nThere is a limitation that a value is supposed to be entered in the substitution variables every time during the execution of a query.\n" }, { "code": null, "e": 43679, "s": 43592, "text": "The same query can be executed for different values using the substitution variables. " }, { "code": null, "e": 43762, "s": 43679, "text": "Using the substitution variables, one needs to alter the WHERE clause every time. " }, { "code": null, "e": 43815, "s": 43762, "text": "Substitution variables are not supported in Oracle. " }, { "code": null, "e": 43950, "s": 43815, "text": "There is a limitation that a value is supposed to be entered in the substitution variables every time during the execution of a query." }, { "code": null, "e": 43962, "s": 43950, "text": "Answer: A. " }, { "code": null, "e": 44038, "s": 43962, "text": "59. Which of the following data type is assigned to Substitution variables?" }, { "code": null, "e": 44074, "s": 44038, "text": "\nVARCHAR2\nDATE\nNO DATA TYPE\nNUMBER\n" }, { "code": null, "e": 44083, "s": 44074, "text": "VARCHAR2" }, { "code": null, "e": 44088, "s": 44083, "text": "DATE" }, { "code": null, "e": 44101, "s": 44088, "text": "NO DATA TYPE" }, { "code": null, "e": 44108, "s": 44101, "text": "NUMBER" }, { "code": null, "e": 44247, "s": 44108, "text": "Answer: C. Substitution variables do not have the data type of their own but comply with the column's data type with whom they are used. " }, { "code": null, "e": 44315, "s": 44247, "text": "60. Which among the following is true about substitution variables?" }, { "code": null, "e": 44706, "s": 44315, "text": "\nThe value entered in the variables remains constant and the user cannot change the values after the execution of the query for the first time. \nThe value is stored in the variables after the query executes once. \nThe substitution variables only support NUMBERS.\nThe value stored in the substitution variables (using a single ampersand) is used for the first execution and gets discarded. \n" }, { "code": null, "e": 44850, "s": 44706, "text": "The value entered in the variables remains constant and the user cannot change the values after the execution of the query for the first time. " }, { "code": null, "e": 44919, "s": 44850, "text": "The value is stored in the variables after the query executes once. " }, { "code": null, "e": 44968, "s": 44919, "text": "The substitution variables only support NUMBERS." }, { "code": null, "e": 45095, "s": 44968, "text": "The value stored in the substitution variables (using a single ampersand) is used for the first execution and gets discarded. " }, { "code": null, "e": 45107, "s": 45095, "text": "Answer: D. " }, { "code": null, "e": 45195, "s": 45107, "text": "61. Which of the following is a correct syntax for Substitution variables in SQL* Plus?" }, { "code": null, "e": 45218, "s": 45195, "text": "\n:var\n$var\n&var\n&&var\n" }, { "code": null, "e": 45223, "s": 45218, "text": ":var" }, { "code": null, "e": 45228, "s": 45223, "text": "$var" }, { "code": null, "e": 45233, "s": 45228, "text": "&var" }, { "code": null, "e": 45239, "s": 45233, "text": "&&var" }, { "code": null, "e": 45253, "s": 45239, "text": "Answer: C, D." }, { "code": null, "e": 45383, "s": 45253, "text": "62. Which of the following Substitution variables will take the entered value once and then keeps it for the rest of the session?" }, { "code": null, "e": 45407, "s": 45383, "text": "\n&&var\n&var\n:var\n::var\n" }, { "code": null, "e": 45413, "s": 45407, "text": "&&var" }, { "code": null, "e": 45418, "s": 45413, "text": "&var" }, { "code": null, "e": 45423, "s": 45418, "text": ":var" }, { "code": null, "e": 45429, "s": 45423, "text": "::var" }, { "code": null, "e": 45540, "s": 45429, "text": "Answer: A. A substitution variable with double ampersand repeatedly uses the value once provided by the user. " }, { "code": null, "e": 45605, "s": 45540, "text": "63. Which of the following is true about substitution variables?" }, { "code": null, "e": 45771, "s": 45605, "text": "\nOnly NUMBERS can be entered as values. \nOnly Character strings can be entered as values. \nBoth Numbers and Characters can be entered as values.\nNone of the above. \n" }, { "code": null, "e": 45811, "s": 45771, "text": "Only NUMBERS can be entered as values. " }, { "code": null, "e": 45861, "s": 45811, "text": "Only Character strings can be entered as values. " }, { "code": null, "e": 45915, "s": 45861, "text": "Both Numbers and Characters can be entered as values." }, { "code": null, "e": 45935, "s": 45915, "text": "None of the above. " }, { "code": null, "e": 45947, "s": 45935, "text": "Answer: C. " }, { "code": null, "e": 45993, "s": 45947, "text": "64. What is true about the query given below?" }, { "code": null, "e": 46086, "s": 45993, "text": "SELECT first_name, last_name, employee_id, salary \nFROM employees \nWHERE employee_id = &eid;" }, { "code": null, "e": 46357, "s": 46086, "text": "\nIt throws an error \"ORA-00904: \"&eid\": invalid identifier\"\nIt executes successfully. \nThe WHERE clause can't have substitution variables. \nThe query prompts for a value to be entered for the variable &eid and executes successfully taking a valid value of employee_id. \n" }, { "code": null, "e": 46416, "s": 46357, "text": "It throws an error \"ORA-00904: \"&eid\": invalid identifier\"" }, { "code": null, "e": 46443, "s": 46416, "text": "It executes successfully. " }, { "code": null, "e": 46496, "s": 46443, "text": "The WHERE clause can't have substitution variables. " }, { "code": null, "e": 46626, "s": 46496, "text": "The query prompts for a value to be entered for the variable &eid and executes successfully taking a valid value of employee_id. " }, { "code": null, "e": 46641, "s": 46626, "text": "Answer: B, D. " }, { "code": null, "e": 46712, "s": 46641, "text": "65. Choose the statements which hold true about the query given below." }, { "code": null, "e": 46793, "s": 46712, "text": "SELECT first_name, last_name, &&prompt_col \nFROM employees\nORDER BY &&promp_col;" }, { "code": null, "e": 47141, "s": 46793, "text": "\nIt throws an error as the use of the substitution variable prompt_col is not allowed. \nIt executes successfully but the result set is not sorted. \nIt executes successfully but the variable value entered in the SELECT statement is ignored. \nIt executes successfully and the value of the substitution variable is maintained throughout the session.\n" }, { "code": null, "e": 47228, "s": 47141, "text": "It throws an error as the use of the substitution variable prompt_col is not allowed. " }, { "code": null, "e": 47288, "s": 47228, "text": "It executes successfully but the result set is not sorted. " }, { "code": null, "e": 47381, "s": 47288, "text": "It executes successfully but the variable value entered in the SELECT statement is ignored. " }, { "code": null, "e": 47487, "s": 47381, "text": "It executes successfully and the value of the substitution variable is maintained throughout the session." }, { "code": null, "e": 47567, "s": 47487, "text": "Answer: D. A substitution variable can be used in all the clauses of SQL query." }, { "code": null, "e": 47681, "s": 47567, "text": "66. Which of the following commands is used to create and assign a value to a substitution variable in SQL* Plus?" }, { "code": null, "e": 47705, "s": 47681, "text": "\n&var\n&&var\nSET\nDEFINE\n" }, { "code": null, "e": 47710, "s": 47705, "text": "&var" }, { "code": null, "e": 47716, "s": 47710, "text": "&&var" }, { "code": null, "e": 47720, "s": 47716, "text": "SET" }, { "code": null, "e": 47727, "s": 47720, "text": "DEFINE" }, { "code": null, "e": 47819, "s": 47727, "text": "Answer: D. Use DEFINE command in SQL* Plus to declare a substitution variable in a session." }, { "code": null, "e": 47884, "s": 47819, "text": "67. What will be the outcome of the below activity in SQL* Plus?" }, { "code": null, "e": 47996, "s": 47884, "text": "DEFINE eid = 117 \n\nSELECT first_name, last_name, employee_id, salary \nFROM employees \nWHERE employee_id = &eid;" }, { "code": null, "e": 48322, "s": 47996, "text": "\nThe SELECT query throws error as substitution variables cannot be defined in the session. \nIt prompts the user to enter the value for the variable &eid.\nIt executes successfully with the employee ID substituted as 117. \nIt ignores the DEFINE command because the substitution variable is declared without ampersand (&) sign.\n" }, { "code": null, "e": 48413, "s": 48322, "text": "The SELECT query throws error as substitution variables cannot be defined in the session. " }, { "code": null, "e": 48475, "s": 48413, "text": "It prompts the user to enter the value for the variable &eid." }, { "code": null, "e": 48542, "s": 48475, "text": "It executes successfully with the employee ID substituted as 117. " }, { "code": null, "e": 48646, "s": 48542, "text": "It ignores the DEFINE command because the substitution variable is declared without ampersand (&) sign." }, { "code": null, "e": 48658, "s": 48646, "text": "Answer: C. " }, { "code": null, "e": 48758, "s": 48658, "text": "68. What is the command to remove the value of the substitution variable set by the command DEFINE?" }, { "code": null, "e": 48790, "s": 48758, "text": "\nUNDEFINE\nSET OFF\nDELETE\nCLEAR\n" }, { "code": null, "e": 48799, "s": 48790, "text": "UNDEFINE" }, { "code": null, "e": 48807, "s": 48799, "text": "SET OFF" }, { "code": null, "e": 48814, "s": 48807, "text": "DELETE" }, { "code": null, "e": 48820, "s": 48814, "text": "CLEAR" }, { "code": null, "e": 48903, "s": 48820, "text": "Answer: A. Use UNDEFINE command to delete a substitution variable from the session" }, { "code": null, "e": 49034, "s": 48903, "text": "69. Which of the following commands is used to check the substitution variables values before and after execution of an SQL query?" }, { "code": null, "e": 49073, "s": 49034, "text": "\nDEFINE\nUNDEFINE\nSHOW VARIABLE\nVERIFY\n" }, { "code": null, "e": 49080, "s": 49073, "text": "DEFINE" }, { "code": null, "e": 49089, "s": 49080, "text": "UNDEFINE" }, { "code": null, "e": 49103, "s": 49089, "text": "SHOW VARIABLE" }, { "code": null, "e": 49110, "s": 49103, "text": "VERIFY" }, { "code": null, "e": 49236, "s": 49110, "text": "Answer: D.Use VERIFY command in SQL*Plus and SQL Developer to check the substitution of values using substitution variables. " }, { "code": null, "e": 49305, "s": 49236, "text": "70. Which of the following are valid operators for the WHERE clause?" }, { "code": null, "e": 49329, "s": 49305, "text": "\n>=\nIS NULL\n!=\nIS LIKE\n" }, { "code": null, "e": 49332, "s": 49329, "text": ">=" }, { "code": null, "e": 49340, "s": 49332, "text": "IS NULL" }, { "code": null, "e": 49343, "s": 49340, "text": "!=" }, { "code": null, "e": 49351, "s": 49343, "text": "IS LIKE" }, { "code": null, "e": 49369, "s": 49351, "text": "Answer: A, B, C. " }, { "code": null, "e": 49403, "s": 49369, "text": "71. Evaluate the following query:" }, { "code": null, "e": 49467, "s": 49403, "text": "SELECT ename || q'{'s salary is }' || sal\nAS \"Salary\"\nFROM emp;" }, { "code": null, "e": 49750, "s": 49467, "text": "\nGives an error because braces cannot be used with [q] operator\nGives error due to data type mismatch\nExecutes successfully and adds an apostrophe ('s) at the end of each employee's name\nExecutes successfully and appends the employee name with the literal \" {'s start date was } \" \n" }, { "code": null, "e": 49813, "s": 49750, "text": "Gives an error because braces cannot be used with [q] operator" }, { "code": null, "e": 49851, "s": 49813, "text": "Gives error due to data type mismatch" }, { "code": null, "e": 49936, "s": 49851, "text": "Executes successfully and adds an apostrophe ('s) at the end of each employee's name" }, { "code": null, "e": 50031, "s": 49936, "text": "Executes successfully and appends the employee name with the literal \" {'s start date was } \" " }, { "code": null, "e": 50042, "s": 50031, "text": "Answer: C." }, { "code": null, "e": 50143, "s": 50042, "text": "72. Which of the below WHERE clause predicates will correctly list the employees from department 20?" }, { "code": null, "e": 50212, "s": 50143, "text": "\nWHERE deptno IS 20\nWHERE deptno 20\nWHERE deptno=20\nWHERE 20=deptno\n" }, { "code": null, "e": 50231, "s": 50212, "text": "WHERE deptno IS 20" }, { "code": null, "e": 50247, "s": 50231, "text": "WHERE deptno 20" }, { "code": null, "e": 50263, "s": 50247, "text": "WHERE deptno=20" }, { "code": null, "e": 50279, "s": 50263, "text": "WHERE 20=deptno" }, { "code": null, "e": 50382, "s": 50279, "text": "Answer: C, D. The equality operator (=) is used to compare the operands in the condition for equality." }, { "code": null, "e": 50464, "s": 50382, "text": "73. Write a SELECT query to list the employees whose salary is greater than 1000." }, { "code": null, "e": 50663, "s": 50464, "text": "\nSELECT ename, sal FROM emp WHERE sal GREATER THAN 1000 \nSELECT ename, sal FROm emp WHERE sal > 1000\nSELECT ename, sal FROM emp WHERE sal >= 1000\nSELECT ename, sal FROM emp WHERE sal MORE THAN 1000\n" }, { "code": null, "e": 50719, "s": 50663, "text": "SELECT ename, sal FROM emp WHERE sal GREATER THAN 1000 " }, { "code": null, "e": 50775, "s": 50719, "text": "SELECT ename, sal FROM emp WHERE sal GREATER THAN 1000 " }, { "code": null, "e": 50819, "s": 50775, "text": "SELECT ename, sal FROm emp WHERE sal > 1000" }, { "code": null, "e": 50863, "s": 50819, "text": "SELECT ename, sal FROm emp WHERE sal > 1000" }, { "code": null, "e": 50908, "s": 50863, "text": "SELECT ename, sal FROM emp WHERE sal >= 1000" }, { "code": null, "e": 50953, "s": 50908, "text": "SELECT ename, sal FROM emp WHERE sal >= 1000" }, { "code": null, "e": 51005, "s": 50953, "text": "SELECT ename, sal FROM emp WHERE sal MORE THAN 1000" }, { "code": null, "e": 51057, "s": 51005, "text": "SELECT ename, sal FROM emp WHERE sal MORE THAN 1000" }, { "code": null, "e": 51148, "s": 51057, "text": "Answer: B. The greater than operator (>) is used to compare the operands in the condition." }, { "code": null, "e": 51217, "s": 51148, "text": "74. What would happen when the below query is executed in SQL* Plus?" }, { "code": null, "e": 51278, "s": 51217, "text": "SELECT ename, sal, deptno\nFROM emp\nWHERE sal/10 > deptno*10;" }, { "code": null, "e": 51582, "s": 51278, "text": "\nExecutes successfully and lists the employees whose 10th part of salary is greater than 10 times his department number\nRaises error because expressions must be enclosed with parentheses\nRaises error because WHERE clause cannot evaluate expressions\nRaises error because WHERE clause cannot use literals\n" }, { "code": null, "e": 51701, "s": 51582, "text": "Executes successfully and lists the employees whose 10th part of salary is greater than 10 times his department number" }, { "code": null, "e": 51768, "s": 51701, "text": "Raises error because expressions must be enclosed with parentheses" }, { "code": null, "e": 51830, "s": 51768, "text": "Raises error because WHERE clause cannot evaluate expressions" }, { "code": null, "e": 51884, "s": 51830, "text": "Raises error because WHERE clause cannot use literals" }, { "code": null, "e": 51937, "s": 51884, "text": "Answer: A. The WHERE clause can contain expressions." }, { "code": null, "e": 51991, "s": 51937, "text": "75. Determine the error in the below SELECT statement" }, { "code": null, "e": 52043, "s": 51991, "text": "SELECT ename, deptno, sal\nFROM emp\nWHERE job=CLERK;" }, { "code": null, "e": 52281, "s": 52043, "text": "\nWHERE clause cannot refer the column JOB since it doesn't appears in the SELECT column list\nCharacter literal CLERK must be enclosed within single quotes\nCharacter literal CLERK must be enclosed within parentheses\nNo error in the query\n" }, { "code": null, "e": 52373, "s": 52281, "text": "WHERE clause cannot refer the column JOB since it doesn't appears in the SELECT column list" }, { "code": null, "e": 52435, "s": 52373, "text": "Character literal CLERK must be enclosed within single quotes" }, { "code": null, "e": 52495, "s": 52435, "text": "Character literal CLERK must be enclosed within parentheses" }, { "code": null, "e": 52517, "s": 52495, "text": "No error in the query" }, { "code": null, "e": 52585, "s": 52517, "text": "Answer: B. Character literals must be enclosed within single quotes" }, { "code": null, "e": 52633, "s": 52585, "text": "76. Interpret the output of the below SQL query" }, { "code": null, "e": 52698, "s": 52633, "text": "SELECT ename, deptno, sal\nFROM emp\nWHERE sysdate-hiredate > 100;" }, { "code": null, "e": 53030, "s": 52698, "text": "\nThe query lists the employees whose hiredate is atleast 100 days earlier than the current date\nThe query lists the employees who have worked more than 100 days in the company\nThe query lists the employees whose hiredate is after 100 days in that year\nThe query lists the employees who have spent less than 100 days in the company\n" }, { "code": null, "e": 53125, "s": 53030, "text": "The query lists the employees whose hiredate is atleast 100 days earlier than the current date" }, { "code": null, "e": 53205, "s": 53125, "text": "The query lists the employees who have worked more than 100 days in the company" }, { "code": null, "e": 53281, "s": 53205, "text": "The query lists the employees whose hiredate is after 100 days in that year" }, { "code": null, "e": 53360, "s": 53281, "text": "The query lists the employees who have spent less than 100 days in the company" }, { "code": null, "e": 53420, "s": 53360, "text": "Answer: A, B. Dates expressions can be used in WHERE clause" }, { "code": null, "e": 53524, "s": 53420, "text": "77. Which of the following query will display the employees which are hired after 31st Decemeber, 1982?" }, { "code": null, "e": 53816, "s": 53524, "text": "\nSELECT ename, deptno FROM emp WHERE hiredate > '31-DEC-1982';\nSELECT ename, deptno FROM emp WHERE hiredate > to_date('31-DEC-1982','DD-MM-YYYY');\nSELECT ename, deptno FROM emp WHERE hiredate > to_char('31-DEC-1982','DD-MM-YYYY');\nSELECT ename, deptno FROM emp WHERE hiredate > 31-DEC-1982;\n" }, { "code": null, "e": 53878, "s": 53816, "text": "SELECT ename, deptno FROM emp WHERE hiredate > '31-DEC-1982';" }, { "code": null, "e": 53940, "s": 53878, "text": "SELECT ename, deptno FROM emp WHERE hiredate > '31-DEC-1982';" }, { "code": null, "e": 54024, "s": 53940, "text": "SELECT ename, deptno FROM emp WHERE hiredate > to_date('31-DEC-1982','DD-MM-YYYY');" }, { "code": null, "e": 54108, "s": 54024, "text": "SELECT ename, deptno FROM emp WHERE hiredate > to_date('31-DEC-1982','DD-MM-YYYY');" }, { "code": null, "e": 54192, "s": 54108, "text": "SELECT ename, deptno FROM emp WHERE hiredate > to_char('31-DEC-1982','DD-MM-YYYY');" }, { "code": null, "e": 54276, "s": 54192, "text": "SELECT ename, deptno FROM emp WHERE hiredate > to_char('31-DEC-1982','DD-MM-YYYY');" }, { "code": null, "e": 54336, "s": 54276, "text": "SELECT ename, deptno FROM emp WHERE hiredate > 31-DEC-1982;" }, { "code": null, "e": 54396, "s": 54336, "text": "SELECT ename, deptno FROM emp WHERE hiredate > 31-DEC-1982;" }, { "code": null, "e": 54463, "s": 54396, "text": "Answer: A, B. Date literals must be enclosed within single quotes." }, { "code": null, "e": 54559, "s": 54463, "text": "78. Which of the following WHERE conditions will list employees who were hired on current date?" }, { "code": null, "e": 54707, "s": 54559, "text": "\nWHERE sysdate-hiredate=0\nWHERE sysdate=hiredate\nWHERE sysdate-hiredate<1\nWHERE to_date (sysdate,'DD-MON-YYYY') = to_date (hiredate='DD-MON-YYYY')\n" }, { "code": null, "e": 54732, "s": 54707, "text": "WHERE sysdate-hiredate=0" }, { "code": null, "e": 54755, "s": 54732, "text": "WHERE sysdate=hiredate" }, { "code": null, "e": 54780, "s": 54755, "text": "WHERE sysdate-hiredate<1" }, { "code": null, "e": 54853, "s": 54780, "text": "WHERE to_date (sysdate,'DD-MON-YYYY') = to_date (hiredate='DD-MON-YYYY')" }, { "code": null, "e": 55015, "s": 54853, "text": "Answer: C, D. The condition SYSDATE=HIREDATE will not work because SYSDATE contains dynamic timestamp component while hiredate is a static value in the database." }, { "code": null, "e": 55115, "s": 55015, "text": "79. What of the following are the valid formats of date literals which can be used in WHERE clause?" }, { "code": null, "e": 55161, "s": 55115, "text": "\n24/Mar/95\n02-12-1983\n19-JUN-2001\n31.04.2010\n" }, { "code": null, "e": 55171, "s": 55161, "text": "24/Mar/95" }, { "code": null, "e": 55182, "s": 55171, "text": "02-12-1983" }, { "code": null, "e": 55194, "s": 55182, "text": "19-JUN-2001" }, { "code": null, "e": 55205, "s": 55194, "text": "31.04.2010" }, { "code": null, "e": 55266, "s": 55205, "text": "Answer: A, C. Default format for date literals is DD-MON-RR." }, { "code": null, "e": 55299, "s": 55266, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 55313, "s": 55299, "text": " Anadi Sharma" }, { "code": null, "e": 55346, "s": 55313, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 55360, "s": 55346, "text": " Anadi Sharma" }, { "code": null, "e": 55395, "s": 55360, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 55409, "s": 55395, "text": " Anadi Sharma" }, { "code": null, "e": 55442, "s": 55409, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 55464, "s": 55442, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 55499, "s": 55464, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 55553, "s": 55499, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 55586, "s": 55553, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 55614, "s": 55586, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 55621, "s": 55614, "text": " Print" }, { "code": null, "e": 55632, "s": 55621, "text": " Add Notes" } ]
How to build a simple song recommender system | by Eric Le | Towards Data Science
This blog post is inspired by Siraj Raval’s Deep Learning Foundation Nanodegree at Udacity. Then repo of this exercise can be found here. Building a recommendation system is a common task that is faced by Amazon, Netflix, Spotify and Google. The underlying goal of the recommendation system is to personalize content and identify relevant data for our audiences. These contents can be articles, movies, games, etc There are 3 types of recommendation system: content-based, collaborative and popularity. In this exercise, we will learn how to build a music recommendation system using real data. Our Million Songs Dataset contains of two files: triplet_file and metadata_file. The triplet_file contains user_id, song_id and listen time. The metadat_file contains song_id, title, release_by and artist_name. Million Songs Dataset is a mixture of song from various website with the rating that users gave after listening to the song. A few examples are Last.fm, thisismyjam, musixmatch, etc Our first job is to integrate our dataset, which is very important every time we want to build a data processing pipeline.To integrate both triplet_file and metadata_file, we are going to use a popular Python library called pandas We first define the two files we are going to work with: triplets_file = 'https://static.turi.com/datasets/millionsong/10000.txt'songs_metadata_file = 'https://static.turi.com/datasets/millionsong/song_data.csv' We then read the table of triplet_file using pandas and define the 3 columns as user_id, song_id and listen_count ( df here means dataframe) song_df_1 = pandas.read_table(triplets_file,header=None)song_df_1.columns = ['user_id', 'song_id', 'listen_count'] We also read the metadat_file and going to combine the metadata_file with triplets_file. Whenever you combine 2 or more datasets, there will be duplicate columns. Here we drop the duplicates between 2 datasets using song_id song_df_2 = pandas.read_csv(songs_metadata_file)song_df = pandas.merge(song_df_1, song_df_2.drop_duplicates(['song_id']), on="song_id", how="left") Using command song_df.head()allows us to visualize the combined data set: Here we have the song index, user_id, song_id, listen_count, title, release and artist_name. Running len(song_df) returns the the total length of this dataset indexed by song are 2,000,000. The second step of this exercise is data transformation, where we’re going to select a subset of this data (the first 10,000 songs). We then merge the song and artist_name into one column, aggregated by number of time a particular song is listened too in general by all users. The first line in the code below group the song_df by number of listen_count ascending. The second line calculate the group_sum by summing the listen_count of each song. The third line add a new column called percentage, and calculate this percentage by dividing the listen_count by the sum of listen_count of all songs and then multiply by 100. The last line list the song in the ascending order of popularity for a given song song_grouped = song_df.groupby(['song']).agg({'listen_count': 'count'}).reset_index()grouped_sum = song_grouped['listen_count'].sum()song_grouped['percentage'] = song_grouped['listen_count'].div(grouped_sum)*100song_grouped.sort_values(['listen_count', 'song'], ascending = [0,1]) Below are the example of our dataset after transformation step: Doing data transformation allows us to further simplify our dataset and make it easy and simple to understand. Next step, we’re going to follow a naive approach when building a recommendation system. We’re going to count the number of unique users and songs in our subset of data users = song_df['user_id'].unique()len(users) ## return 365 unique userssongs = song_df['song'].unique()len(songs) ## return 5151 unique songs We then create a song recommender by splitting our dataset into training and testing data. We use the train_test_split function of scikit-learnlibrary. It’s important to note that whenever we build a machine learning system, before we train our model, we always want to split our data into training and testing dataset train_data, test_data = train_test_split(song_df, test_size = 0.20, random_state=0) We arbitrarily pick 20% as our testing size. We then used a popularity based recommender class as a blackbox to train our model. We create an instance of popularity based recommender class and feed it with our training data. The code below achieves the following goal: based on the popularity of each song, create a recommender that accept a user_id as input and out a list of recommended song of that user pm = Recommenders.popularity_recommender_py()pm.create(train_data, 'user_id', 'song')#user the popularity model to make some predictionuser_id = users[5]pm.recommend(user_id) The code for the Recommender Systems model is below. This system is a naive approach and not personalized. It first get a unique count of user_id (ie the number of time that song was listened to in general by all user) for each song and tag it as a recommendation score. The recommend function then accept a user_id and output the top ten recommended song for any given user. Keeping in my that since this is the naive approach, the recommendation is not personalized and will be the same for all users. #Class for Popularity based Recommender System modelclass popularity_recommender_py(): def __init__(self): self.train_data = None self.user_id = None self.item_id = None self.popularity_recommendations = None #Create the popularity based recommender system model def create(self, train_data, user_id, item_id): self.train_data = train_data self.user_id = user_id self.item_id = item_id #Get a count of user_ids for each unique song as recommendation score train_data_grouped = train_data.groupby([self.item_id]).agg({self.user_id: 'count'}).reset_index() train_data_grouped.rename(columns = {'user_id': 'score'},inplace=True) #Sort the songs based upon recommendation score train_data_sort = train_data_grouped.sort_values(['score', self.item_id], ascending = [0,1]) #Generate a recommendation rank based upon score train_data_sort['Rank'] = train_data_sort['score'].rank(ascending=0, method='first') #Get the top 10 recommendations self.popularity_recommendations = train_data_sort.head(10) #Use the popularity based recommender system model to #make recommendations def recommend(self, user_id): user_recommendations = self.popularity_recommendations #Add user_id column for which the recommendations are being generated user_recommendations['user_id'] = user_id #Bring user_id column to the front cols = user_recommendations.columns.tolist() cols = cols[-1:] + cols[:-1] user_recommendations = user_recommendations[cols] return user_recommendations The second part of this exercise is to create a ML personalized song recommender system by leveraging the item similarity based collaborative filtering model. Recall that recommender system is divided into 2 types: content based and collaborative based. Content based system predicts what a user like based on what that user like in the past. Collaborative based system predict what a particular user like based on what other similar users like. Most companies like Netflix and Hulu use the hybrid approach, which provide recommendation based on the combination of what content a user like in the past as well as what other similar user like. According to Agnes Jóhannsdóttir (Twitter: @agnesjohanns) at Cambridge Coding Academy, Memory-based collaborative filtering can be divided into two main approaches: user-item filtering and item-item filtering. Item-item filtering approach involves defining a co-occurrence matrix based on a song a user likes. We are seeking to answer a question, for each song, what a number of time a user, who have listened to that song, will also listen to another set of other songs. To further simplify this, based on what you like in the past, what other similar song that you will like based on what other similar user have liked. Let’s apply this to our code. First we create an instance item similarity based recommender class and feed it with our training data. is_model = Recommenders.item_similarity_recommender_py()is_model.create(train_data, 'user_id', 'song') Notice that inside the recommender system’s source code, the generate_top_recommendations function calculated a weighted average of the scores in cooccurence matrix for all user song. This cooccurence matrix will tend to be sparse matrix because it’s not possible to predict if a user like a particular song, whether or not he/she will like a million other song. The possibility is so vast. Using our model, we will be able to predict the list of song that a user will like #Print the songs for the user in training datauser_id = users[5]user_items = is_model.get_user_items(user_id)#print("------------------------------------------------------------------------------------")print("Training data songs for the user userid: %s:" % user_id)print("------------------------------------------------------------------------------------")for user_item in user_items: print(user_item)print("----------------------------------------------------------------------")print("Recommendation process going on:")print("----------------------------------------------------------------------")#Recommend songs for the user using personalized modelis_model.recommend(user_id) output: ------------------------------------------------------------------------------------Training data songs for the user userid: 4bd88bfb25263a75bbdd467e74018f4ae570e5df:------------------------------------------------------------------------------------Just Lose It - EminemWithout Me - Eminem16 Candles - The CrestsSpeechless - Lady GaGaPush It - Salt-N-PepaGhosts 'n' Stuff (Original Instrumental Mix) - Deadmau5Say My Name - Destiny's ChildMy Dad's Gone Crazy - Eminem / Hailie JadeThe Real Slim Shady - EminemSomebody To Love - Justin BieberForgive Me - Leona LewisMissing You - John WaiteYa Nada Queda - Kudai----------------------------------------------------------------------Recommendation process going on:----------------------------------------------------------------------No. of unique songs for the user: 13no. of unique songs in the training set: 4483Non zero values in cooccurence_matrix :2097 We can also use our item similarity based collaborative filtering model to find similar songs to any songs in our dataset: is_model.get_similar_items(['U Smile - Justin Bieber']) this output no. of unique songs in the training set: 4483Non zero values in cooccurence_matrix :271 It’s worth to note that this method is not Deep Learning but purely based on linear algebra. To recap, in this exercise we discussed 2 models. The first model is popularity based recommender, meaning it is not personalized toward any user and will output the same list of recommended songs. The second model is personalized recommender leveraging the item similarity based collaborative filtering model (ie the cooccurence matrix) to find a personalized list of song that a user might like based on what other similar user have liked. Next we will discuss how to measure the performance of these two models using a precision recall curve to quantitatively compare the popularity based model and personalized collaborative filtering model. To quantitatively measure the performance of recommender system, we use three different metrics: Precision , Recall and F-1 Score According to Marcel Caraciolo, Precision is “the proportion of top results that are relevant, considering some definition of relevant for your problem domain”. In our case, the definition of relevant for our problem domain is the length that a song is listened to, a number of user have all liked the song. Recall would “measure the proportion of all relevant results included in the top results”.In our case, it means precision seeks to measure the relevancy of songs in relation to the top ten results of recommended song, whereas recall seeks to measure the relevancy of songs in relation to all the songs Observing the precision recall curve of both our popularity based model and personalized item similarity model, item similarity model perform better (ie having higher number of recall and precision) up to certain point in precision-recall curve. The last type of recommender system is Matrix Factorization based Recommender System. This type of recommender system uses what is called a Singular Value Decomposition (SVD) factorized matrix of the original similarity matrix to build recommender system. To compute SVD and recommendations, we use the following code: #constants defining the dimensions of our User Rating Matrix (URM) MAX_PID = 4 MAX_UID = 5 #Compute SVD of the user ratings matrix def computeSVD(urm, K): U, s, Vt = sparsesvd(urm, K) dim = (len(s), len(s)) S = np.zeros(dim, dtype=np.float32) for i in range(0, len(s)): S[i,i] = mt.sqrt(s[i]) U = csc_matrix(np.transpose(U), dtype=np.float32) S = csc_matrix(S, dtype=np.float32) Vt = csc_matrix(Vt, dtype=np.float32) return U, S, Vt In this code, U represents user vector, S represents the item vector.Vt represent the joint of these two vectors as collection of points (ie vector) in 2 dimensional spaces. We’re going to use these vectors to measure the distance from one user’s preferences to another user’s preferences. In another word, we are vectorizing matrices in order to compute the distance between matrices. To further clarify this, we’re going to talk through an example. Assume we have a user song matrix below: Song0 Song1 Song2 Song3 User0 3 1 2 3User1 4 3 4 3User2 3 2 1 5User3 1 6 5 2User4 0 0 5 0 Once we perform SVD, the output is going to be vectors and measuring distance between vectors gives us recommendation #Compute estimated rating for the test userdef computeEstimatedRatings(urm, U, S, Vt, uTest, K, test): rightTerm = S*Vt estimatedRatings = np.zeros(shape=(MAX_UID, MAX_PID), dtype=np.float16) for userTest in uTest: prod = U[userTest, :]*rightTerm #we convert the vector to dense format in order to get the #indices #of the movies with the best estimated ratings estimatedRatings[userTest, :] = prod.todense() recom = (-estimatedRatings[userTest, :]).argsort()[:250] return recom#Used in SVD calculation (number of latent factors)K=2#Initialize a sample user rating matrixurm = np.array([[3, 1, 2, 3],[4, 3, 4, 3],[3, 2, 1, 5], [1, 6, 5, 2], [5, 0,0 , 0]])urm = csc_matrix(urm, dtype=np.float32)#Compute SVD of the input user ratings matrixU, S, Vt = computeSVD(urm, K)#Test user set as user_id 4 with ratings [0, 0, 5, 0]uTest = [4]print("User id for whom recommendations are needed: %d" % uTest[0])#Get estimated rating for test userprint("Predictied ratings:")uTest_recommended_items = computeEstimatedRatings(urm, U, S, Vt, uTest, K, True)print(uTest_recommended_items) will output: User id for whom recommendations are needed: 4Predictied ratings:[0 3 2 1] Next, we discuss the real world example of how Hulu applying Deep Learning to Collaborative Filtering to build its industry leading recommendation system. At Hulu, features like Personalized Masthead, Watchlist and Top Picks are all powered by collaborative filtering. The method Hulu used is CF-NADE. Let’s take an example. Suppose we have 4 movies: “Transformers”, “SpongeBob”, “Teenage Mutant Ninja Turtles” and “Interstellar”, with scores 4,2,3 and 5. In CF-NADE, the joint probability of vector (4,2,3,5) is factorized as a product of conditionals by chain rule, which are the following: 1/ The probability that the user gives “Transformers” 4-star conditioned on nothing;2/ The probability that the user gives “SpongeBob” 2-star conditioned on giving “Transformers” 4-star;3/ The probability that the user gives “Teenage Mutant Ninja Turtles” a 3-star conditioned on giving 4-star and 2-star to “Transformers” and “SpongeBob”, respectively;4/ The probability that the user gives “Interstellar” a 5-star conditioned on giving 4-star, 2-star and 3-star to “Transformers”, “SpongeBob” and “Teenage Mutant Ninja Turtles”, respectively; To summarize, this is the chain of probability based on what previously have occurred. Each conditional is modeled by its own neural network and the parameter for all of these neural networks are shared amongst all models. Source: 1/Siraj Raval’s Deep Learning Foundation Nanodegree (https://www.udacity.com/course/deep-learning-nanodegree-foundation--nd101) 2/https://www.youtube.com/watch?v=18adykNGhHU 3/https://github.com/llSourcell/recommender_live 4/Applying Deep Learning to Collaborative Filtering: How Hulu builds its industry leading(http://tech.hulu.com/blog/2016/08/01/cfnade.html) 5/Implementing your own recommender systems in Python(http://online-dev.cambridgecoding.com/notebooks/eWReNYcAfB/implementing-your-own-recommender-systems-in-python-2)
[ { "code": null, "e": 310, "s": 172, "text": "This blog post is inspired by Siraj Raval’s Deep Learning Foundation Nanodegree at Udacity. Then repo of this exercise can be found here." }, { "code": null, "e": 586, "s": 310, "text": "Building a recommendation system is a common task that is faced by Amazon, Netflix, Spotify and Google. The underlying goal of the recommendation system is to personalize content and identify relevant data for our audiences. These contents can be articles, movies, games, etc" }, { "code": null, "e": 675, "s": 586, "text": "There are 3 types of recommendation system: content-based, collaborative and popularity." }, { "code": null, "e": 1160, "s": 675, "text": "In this exercise, we will learn how to build a music recommendation system using real data. Our Million Songs Dataset contains of two files: triplet_file and metadata_file. The triplet_file contains user_id, song_id and listen time. The metadat_file contains song_id, title, release_by and artist_name. Million Songs Dataset is a mixture of song from various website with the rating that users gave after listening to the song. A few examples are Last.fm, thisismyjam, musixmatch, etc" }, { "code": null, "e": 1391, "s": 1160, "text": "Our first job is to integrate our dataset, which is very important every time we want to build a data processing pipeline.To integrate both triplet_file and metadata_file, we are going to use a popular Python library called pandas" }, { "code": null, "e": 1448, "s": 1391, "text": "We first define the two files we are going to work with:" }, { "code": null, "e": 1603, "s": 1448, "text": "triplets_file = 'https://static.turi.com/datasets/millionsong/10000.txt'songs_metadata_file = 'https://static.turi.com/datasets/millionsong/song_data.csv'" }, { "code": null, "e": 1744, "s": 1603, "text": "We then read the table of triplet_file using pandas and define the 3 columns as user_id, song_id and listen_count ( df here means dataframe)" }, { "code": null, "e": 1859, "s": 1744, "text": "song_df_1 = pandas.read_table(triplets_file,header=None)song_df_1.columns = ['user_id', 'song_id', 'listen_count']" }, { "code": null, "e": 2083, "s": 1859, "text": "We also read the metadat_file and going to combine the metadata_file with triplets_file. Whenever you combine 2 or more datasets, there will be duplicate columns. Here we drop the duplicates between 2 datasets using song_id" }, { "code": null, "e": 2232, "s": 2083, "text": "song_df_2 = pandas.read_csv(songs_metadata_file)song_df = pandas.merge(song_df_1, song_df_2.drop_duplicates(['song_id']), on=\"song_id\", how=\"left\")" }, { "code": null, "e": 2306, "s": 2232, "text": "Using command song_df.head()allows us to visualize the combined data set:" }, { "code": null, "e": 2496, "s": 2306, "text": "Here we have the song index, user_id, song_id, listen_count, title, release and artist_name. Running len(song_df) returns the the total length of this dataset indexed by song are 2,000,000." }, { "code": null, "e": 3201, "s": 2496, "text": "The second step of this exercise is data transformation, where we’re going to select a subset of this data (the first 10,000 songs). We then merge the song and artist_name into one column, aggregated by number of time a particular song is listened too in general by all users. The first line in the code below group the song_df by number of listen_count ascending. The second line calculate the group_sum by summing the listen_count of each song. The third line add a new column called percentage, and calculate this percentage by dividing the listen_count by the sum of listen_count of all songs and then multiply by 100. The last line list the song in the ascending order of popularity for a given song" }, { "code": null, "e": 3483, "s": 3201, "text": "song_grouped = song_df.groupby(['song']).agg({'listen_count': 'count'}).reset_index()grouped_sum = song_grouped['listen_count'].sum()song_grouped['percentage'] = song_grouped['listen_count'].div(grouped_sum)*100song_grouped.sort_values(['listen_count', 'song'], ascending = [0,1])" }, { "code": null, "e": 3547, "s": 3483, "text": "Below are the example of our dataset after transformation step:" }, { "code": null, "e": 3658, "s": 3547, "text": "Doing data transformation allows us to further simplify our dataset and make it easy and simple to understand." }, { "code": null, "e": 3827, "s": 3658, "text": "Next step, we’re going to follow a naive approach when building a recommendation system. We’re going to count the number of unique users and songs in our subset of data" }, { "code": null, "e": 3970, "s": 3827, "text": "users = song_df['user_id'].unique()len(users) ## return 365 unique userssongs = song_df['song'].unique()len(songs) ## return 5151 unique songs" }, { "code": null, "e": 4289, "s": 3970, "text": "We then create a song recommender by splitting our dataset into training and testing data. We use the train_test_split function of scikit-learnlibrary. It’s important to note that whenever we build a machine learning system, before we train our model, we always want to split our data into training and testing dataset" }, { "code": null, "e": 4373, "s": 4289, "text": "train_data, test_data = train_test_split(song_df, test_size = 0.20, random_state=0)" }, { "code": null, "e": 4780, "s": 4373, "text": "We arbitrarily pick 20% as our testing size. We then used a popularity based recommender class as a blackbox to train our model. We create an instance of popularity based recommender class and feed it with our training data. The code below achieves the following goal: based on the popularity of each song, create a recommender that accept a user_id as input and out a list of recommended song of that user" }, { "code": null, "e": 4955, "s": 4780, "text": "pm = Recommenders.popularity_recommender_py()pm.create(train_data, 'user_id', 'song')#user the popularity model to make some predictionuser_id = users[5]pm.recommend(user_id)" }, { "code": null, "e": 5459, "s": 4955, "text": "The code for the Recommender Systems model is below. This system is a naive approach and not personalized. It first get a unique count of user_id (ie the number of time that song was listened to in general by all user) for each song and tag it as a recommendation score. The recommend function then accept a user_id and output the top ten recommended song for any given user. Keeping in my that since this is the naive approach, the recommendation is not personalized and will be the same for all users." }, { "code": null, "e": 7287, "s": 5459, "text": "#Class for Popularity based Recommender System modelclass popularity_recommender_py(): def __init__(self): self.train_data = None self.user_id = None self.item_id = None self.popularity_recommendations = None #Create the popularity based recommender system model def create(self, train_data, user_id, item_id): self.train_data = train_data self.user_id = user_id self.item_id = item_id #Get a count of user_ids for each unique song as recommendation score train_data_grouped = train_data.groupby([self.item_id]).agg({self.user_id: 'count'}).reset_index() train_data_grouped.rename(columns = {'user_id': 'score'},inplace=True) #Sort the songs based upon recommendation score train_data_sort = train_data_grouped.sort_values(['score', self.item_id], ascending = [0,1]) #Generate a recommendation rank based upon score train_data_sort['Rank'] = train_data_sort['score'].rank(ascending=0, method='first') #Get the top 10 recommendations self.popularity_recommendations = train_data_sort.head(10) #Use the popularity based recommender system model to #make recommendations def recommend(self, user_id): user_recommendations = self.popularity_recommendations #Add user_id column for which the recommendations are being generated user_recommendations['user_id'] = user_id #Bring user_id column to the front cols = user_recommendations.columns.tolist() cols = cols[-1:] + cols[:-1] user_recommendations = user_recommendations[cols] return user_recommendations" }, { "code": null, "e": 7930, "s": 7287, "text": "The second part of this exercise is to create a ML personalized song recommender system by leveraging the item similarity based collaborative filtering model. Recall that recommender system is divided into 2 types: content based and collaborative based. Content based system predicts what a user like based on what that user like in the past. Collaborative based system predict what a particular user like based on what other similar users like. Most companies like Netflix and Hulu use the hybrid approach, which provide recommendation based on the combination of what content a user like in the past as well as what other similar user like." }, { "code": null, "e": 8142, "s": 7930, "text": "According to Agnes Jóhannsdóttir (Twitter: @agnesjohanns) at Cambridge Coding Academy, Memory-based collaborative filtering can be divided into two main approaches: user-item filtering and item-item filtering." }, { "code": null, "e": 8688, "s": 8142, "text": "Item-item filtering approach involves defining a co-occurrence matrix based on a song a user likes. We are seeking to answer a question, for each song, what a number of time a user, who have listened to that song, will also listen to another set of other songs. To further simplify this, based on what you like in the past, what other similar song that you will like based on what other similar user have liked. Let’s apply this to our code. First we create an instance item similarity based recommender class and feed it with our training data." }, { "code": null, "e": 8791, "s": 8688, "text": "is_model = Recommenders.item_similarity_recommender_py()is_model.create(train_data, 'user_id', 'song')" }, { "code": null, "e": 9265, "s": 8791, "text": "Notice that inside the recommender system’s source code, the generate_top_recommendations function calculated a weighted average of the scores in cooccurence matrix for all user song. This cooccurence matrix will tend to be sparse matrix because it’s not possible to predict if a user like a particular song, whether or not he/she will like a million other song. The possibility is so vast. Using our model, we will be able to predict the list of song that a user will like" }, { "code": null, "e": 9953, "s": 9265, "text": "#Print the songs for the user in training datauser_id = users[5]user_items = is_model.get_user_items(user_id)#print(\"------------------------------------------------------------------------------------\")print(\"Training data songs for the user userid: %s:\" % user_id)print(\"------------------------------------------------------------------------------------\")for user_item in user_items: print(user_item)print(\"----------------------------------------------------------------------\")print(\"Recommendation process going on:\")print(\"----------------------------------------------------------------------\")#Recommend songs for the user using personalized modelis_model.recommend(user_id)" }, { "code": null, "e": 9961, "s": 9953, "text": "output:" }, { "code": null, "e": 10869, "s": 9961, "text": "------------------------------------------------------------------------------------Training data songs for the user userid: 4bd88bfb25263a75bbdd467e74018f4ae570e5df:------------------------------------------------------------------------------------Just Lose It - EminemWithout Me - Eminem16 Candles - The CrestsSpeechless - Lady GaGaPush It - Salt-N-PepaGhosts 'n' Stuff (Original Instrumental Mix) - Deadmau5Say My Name - Destiny's ChildMy Dad's Gone Crazy - Eminem / Hailie JadeThe Real Slim Shady - EminemSomebody To Love - Justin BieberForgive Me - Leona LewisMissing You - John WaiteYa Nada Queda - Kudai----------------------------------------------------------------------Recommendation process going on:----------------------------------------------------------------------No. of unique songs for the user: 13no. of unique songs in the training set: 4483Non zero values in cooccurence_matrix :2097" }, { "code": null, "e": 10992, "s": 10869, "text": "We can also use our item similarity based collaborative filtering model to find similar songs to any songs in our dataset:" }, { "code": null, "e": 11048, "s": 10992, "text": "is_model.get_similar_items(['U Smile - Justin Bieber'])" }, { "code": null, "e": 11060, "s": 11048, "text": "this output" }, { "code": null, "e": 11148, "s": 11060, "text": "no. of unique songs in the training set: 4483Non zero values in cooccurence_matrix :271" }, { "code": null, "e": 11241, "s": 11148, "text": "It’s worth to note that this method is not Deep Learning but purely based on linear algebra." }, { "code": null, "e": 11683, "s": 11241, "text": "To recap, in this exercise we discussed 2 models. The first model is popularity based recommender, meaning it is not personalized toward any user and will output the same list of recommended songs. The second model is personalized recommender leveraging the item similarity based collaborative filtering model (ie the cooccurence matrix) to find a personalized list of song that a user might like based on what other similar user have liked." }, { "code": null, "e": 11887, "s": 11683, "text": "Next we will discuss how to measure the performance of these two models using a precision recall curve to quantitatively compare the popularity based model and personalized collaborative filtering model." }, { "code": null, "e": 12017, "s": 11887, "text": "To quantitatively measure the performance of recommender system, we use three different metrics: Precision , Recall and F-1 Score" }, { "code": null, "e": 12626, "s": 12017, "text": "According to Marcel Caraciolo, Precision is “the proportion of top results that are relevant, considering some definition of relevant for your problem domain”. In our case, the definition of relevant for our problem domain is the length that a song is listened to, a number of user have all liked the song. Recall would “measure the proportion of all relevant results included in the top results”.In our case, it means precision seeks to measure the relevancy of songs in relation to the top ten results of recommended song, whereas recall seeks to measure the relevancy of songs in relation to all the songs" }, { "code": null, "e": 12872, "s": 12626, "text": "Observing the precision recall curve of both our popularity based model and personalized item similarity model, item similarity model perform better (ie having higher number of recall and precision) up to certain point in precision-recall curve." }, { "code": null, "e": 13128, "s": 12872, "text": "The last type of recommender system is Matrix Factorization based Recommender System. This type of recommender system uses what is called a Singular Value Decomposition (SVD) factorized matrix of the original similarity matrix to build recommender system." }, { "code": null, "e": 13191, "s": 13128, "text": "To compute SVD and recommendations, we use the following code:" }, { "code": null, "e": 13728, "s": 13191, "text": "#constants defining the dimensions of our User Rating Matrix (URM) MAX_PID = 4 MAX_UID = 5 #Compute SVD of the user ratings matrix def computeSVD(urm, K): U, s, Vt = sparsesvd(urm, K) dim = (len(s), len(s)) S = np.zeros(dim, dtype=np.float32) for i in range(0, len(s)): S[i,i] = mt.sqrt(s[i]) U = csc_matrix(np.transpose(U), dtype=np.float32) S = csc_matrix(S, dtype=np.float32) Vt = csc_matrix(Vt, dtype=np.float32) return U, S, Vt" }, { "code": null, "e": 14018, "s": 13728, "text": "In this code, U represents user vector, S represents the item vector.Vt represent the joint of these two vectors as collection of points (ie vector) in 2 dimensional spaces. We’re going to use these vectors to measure the distance from one user’s preferences to another user’s preferences." }, { "code": null, "e": 14220, "s": 14018, "text": "In another word, we are vectorizing matrices in order to compute the distance between matrices. To further clarify this, we’re going to talk through an example. Assume we have a user song matrix below:" }, { "code": null, "e": 14424, "s": 14220, "text": " Song0 Song1 Song2 Song3 User0 3 1 2 3User1 4 3 4 3User2 3 2 1 5User3 1 6 5 2User4 0 0 5 0" }, { "code": null, "e": 14542, "s": 14424, "text": "Once we perform SVD, the output is going to be vectors and measuring distance between vectors gives us recommendation" }, { "code": null, "e": 15667, "s": 14542, "text": "#Compute estimated rating for the test userdef computeEstimatedRatings(urm, U, S, Vt, uTest, K, test): rightTerm = S*Vt estimatedRatings = np.zeros(shape=(MAX_UID, MAX_PID), dtype=np.float16) for userTest in uTest: prod = U[userTest, :]*rightTerm #we convert the vector to dense format in order to get the #indices #of the movies with the best estimated ratings estimatedRatings[userTest, :] = prod.todense() recom = (-estimatedRatings[userTest, :]).argsort()[:250] return recom#Used in SVD calculation (number of latent factors)K=2#Initialize a sample user rating matrixurm = np.array([[3, 1, 2, 3],[4, 3, 4, 3],[3, 2, 1, 5], [1, 6, 5, 2], [5, 0,0 , 0]])urm = csc_matrix(urm, dtype=np.float32)#Compute SVD of the input user ratings matrixU, S, Vt = computeSVD(urm, K)#Test user set as user_id 4 with ratings [0, 0, 5, 0]uTest = [4]print(\"User id for whom recommendations are needed: %d\" % uTest[0])#Get estimated rating for test userprint(\"Predictied ratings:\")uTest_recommended_items = computeEstimatedRatings(urm, U, S, Vt, uTest, K, True)print(uTest_recommended_items)" }, { "code": null, "e": 15680, "s": 15667, "text": "will output:" }, { "code": null, "e": 15755, "s": 15680, "text": "User id for whom recommendations are needed: 4Predictied ratings:[0 3 2 1]" }, { "code": null, "e": 16024, "s": 15755, "text": "Next, we discuss the real world example of how Hulu applying Deep Learning to Collaborative Filtering to build its industry leading recommendation system. At Hulu, features like Personalized Masthead, Watchlist and Top Picks are all powered by collaborative filtering." }, { "code": null, "e": 16348, "s": 16024, "text": "The method Hulu used is CF-NADE. Let’s take an example. Suppose we have 4 movies: “Transformers”, “SpongeBob”, “Teenage Mutant Ninja Turtles” and “Interstellar”, with scores 4,2,3 and 5. In CF-NADE, the joint probability of vector (4,2,3,5) is factorized as a product of conditionals by chain rule, which are the following:" }, { "code": null, "e": 16893, "s": 16348, "text": "1/ The probability that the user gives “Transformers” 4-star conditioned on nothing;2/ The probability that the user gives “SpongeBob” 2-star conditioned on giving “Transformers” 4-star;3/ The probability that the user gives “Teenage Mutant Ninja Turtles” a 3-star conditioned on giving 4-star and 2-star to “Transformers” and “SpongeBob”, respectively;4/ The probability that the user gives “Interstellar” a 5-star conditioned on giving 4-star, 2-star and 3-star to “Transformers”, “SpongeBob” and “Teenage Mutant Ninja Turtles”, respectively;" }, { "code": null, "e": 17116, "s": 16893, "text": "To summarize, this is the chain of probability based on what previously have occurred. Each conditional is modeled by its own neural network and the parameter for all of these neural networks are shared amongst all models." }, { "code": null, "e": 17124, "s": 17116, "text": "Source:" }, { "code": null, "e": 17252, "s": 17124, "text": "1/Siraj Raval’s Deep Learning Foundation Nanodegree (https://www.udacity.com/course/deep-learning-nanodegree-foundation--nd101)" }, { "code": null, "e": 17298, "s": 17252, "text": "2/https://www.youtube.com/watch?v=18adykNGhHU" }, { "code": null, "e": 17347, "s": 17298, "text": "3/https://github.com/llSourcell/recommender_live" }, { "code": null, "e": 17487, "s": 17347, "text": "4/Applying Deep Learning to Collaborative Filtering: How Hulu builds its industry leading(http://tech.hulu.com/blog/2016/08/01/cfnade.html)" } ]
Overlay an image segmentation with Numpy and Matplotlib
To overlay an image segmentation with numpy, we can take the following Steps − Make a masked array of 10×10 dimension. Make a masked array of 10×10 dimension. Update the masked array with 1 for some region. Update the masked array with 1 for some region. Make image data using numpy. Make image data using numpy. Mask an array where a condition is met, to get the masked data. Mask an array where a condition is met, to get the masked data. Create a new figure or activate an existing figure using figure() mrthod. Create a new figure or activate an existing figure using figure() mrthod. Use imshow() method to display data as an image, i.e., on a 2D regular raster. Use imshow() method to display data as an image, i.e., on a 2D regular raster. To display the figure, use show() method. To display the figure, use show() method. from matplotlib import pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True mask = np.zeros((10, 10)) mask[3:-3, 3:-3] = 1 im = mask + np.random.randn(10, 10) * 0.01 masked = np.ma.masked_where(mask == 0, mask) plt.figure() plt.subplot(1, 2, 1) plt.imshow(im, 'gray', interpolation='none') plt.subplot(1, 2, 2) plt.imshow(im, 'gray', interpolation='none') plt.imshow(masked, 'jet', interpolation='none', alpha=0.7) plt.show()
[ { "code": null, "e": 1141, "s": 1062, "text": "To overlay an image segmentation with numpy, we can take the following Steps −" }, { "code": null, "e": 1181, "s": 1141, "text": "Make a masked array of 10×10 dimension." }, { "code": null, "e": 1221, "s": 1181, "text": "Make a masked array of 10×10 dimension." }, { "code": null, "e": 1269, "s": 1221, "text": "Update the masked array with 1 for some region." }, { "code": null, "e": 1317, "s": 1269, "text": "Update the masked array with 1 for some region." }, { "code": null, "e": 1346, "s": 1317, "text": "Make image data using numpy." }, { "code": null, "e": 1375, "s": 1346, "text": "Make image data using numpy." }, { "code": null, "e": 1439, "s": 1375, "text": "Mask an array where a condition is met, to get the masked data." }, { "code": null, "e": 1503, "s": 1439, "text": "Mask an array where a condition is met, to get the masked data." }, { "code": null, "e": 1577, "s": 1503, "text": "Create a new figure or activate an existing figure using figure() mrthod." }, { "code": null, "e": 1651, "s": 1577, "text": "Create a new figure or activate an existing figure using figure() mrthod." }, { "code": null, "e": 1730, "s": 1651, "text": "Use imshow() method to display data as an image, i.e., on a 2D regular raster." }, { "code": null, "e": 1809, "s": 1730, "text": "Use imshow() method to display data as an image, i.e., on a 2D regular raster." }, { "code": null, "e": 1851, "s": 1809, "text": "To display the figure, use show() method." }, { "code": null, "e": 1893, "s": 1851, "text": "To display the figure, use show() method." }, { "code": null, "e": 2386, "s": 1893, "text": "from matplotlib import pyplot as plt\nimport numpy as np\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nmask = np.zeros((10, 10))\nmask[3:-3, 3:-3] = 1\nim = mask + np.random.randn(10, 10) * 0.01\nmasked = np.ma.masked_where(mask == 0, mask)\nplt.figure()\nplt.subplot(1, 2, 1)\nplt.imshow(im, 'gray', interpolation='none')\nplt.subplot(1, 2, 2)\nplt.imshow(im, 'gray', interpolation='none')\nplt.imshow(masked, 'jet', interpolation='none', alpha=0.7)\nplt.show()" } ]
How to Create a Reminder Notification in Android?
This example demonstrate about How to Create a Reminder Notification 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" android:padding = "16dp" tools:context = ".MainActivity"> <Button android:onClick= "createNotification" android:text= "create notification" android:layout_centerInParent= "true" android:layout_width= "match_parent" android:layout_height= "wrap_content" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity. package app.tutorialspoint.com.notifyme ; import android.app.AlarmManager ; import android.app.PendingIntent ; import android.content.Intent ; import android.os.Bundle ; import android.support.v7.app.AppCompatActivity ; import android.view.View ; import java.util.Calendar ; public class MainActivity extends AppCompatActivity { @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; } public void createNotification (View view) { Intent myIntent = new Intent(getApplicationContext() , NotifyService. class ) ; AlarmManager alarmManager = (AlarmManager) getSystemService( ALARM_SERVICE ) ; PendingIntent pendingIntent = PendingIntent. getService ( this, 0 , myIntent , 0 ) ; Calendar calendar = Calendar. getInstance () ; calendar.set(Calendar. SECOND , 0 ) ; calendar.set(Calendar. MINUTE , 0 ) ; calendar.set(Calendar. HOUR , 0 ) ; calendar.set(Calendar. AM_PM , Calendar. AM ) ; calendar.add(Calendar. DAY_OF_MONTH , 1 ) ; alarmManager.setRepeating(AlarmManager. RTC_WAKEUP , calendar.getTimeInMillis() , 1000 * 60 * 60 * 24 , pendingIntent) ; } } Step 4 − Add the following code to src/NotifyService package app.tutorialspoint.com.notifyme ; import android.app.NotificationChannel ; import android.app.NotificationManager ; import android.app.PendingIntent ; import android.app.Service ; import android.content.Intent ; import android.os.IBinder ; import android.support.v4.app.NotificationCompat ; public class NotifyService extends Service { public static final String NOTIFICATION_CHANNEL_ID = "10001" ; private final static String default_notification_channel_id = "default" ; public NotifyService () { } @Override public IBinder onBind (Intent intent) { Intent notificationIntent = new Intent(getApplicationContext() , MainActivity. class ) ; notificationIntent.putExtra( "fromNotification" , true ) ; notificationIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_SINGLE_TOP ) ; PendingIntent pendingIntent = PendingIntent. getActivity ( this, 0 , notificationIntent , 0 ) ; NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext() , default_notification_channel_id ) ; mBuilder.setContentTitle( "My Notification" ) ; mBuilder.setContentIntent(pendingIntent) ; mBuilder.setContentText( "Notification Listener Service Example" ) ; mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ; mBuilder.setAutoCancel( true ) ; if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) { int importance = NotificationManager. IMPORTANCE_HIGH ; NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ; mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ; assert mNotificationManager != null; mNotificationManager.createNotificationChannel(notificationChannel) ; } assert mNotificationManager != null; mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ; throw new UnsupportedOperationException( "Not yet implemented" ) ; } } 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.tutorialspoint.com.notifyme" > <uses-permission android :name = "android.permission.VIBRATE" /> <uses-permission android :name = "android.permission.RECEIVE_BOOT_COMPLETED" /> <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" > <service android :name = ".NotifyService" android :enabled = "true" android :exported = "true" > </service> <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": 1142, "s": 1062, "text": "This example demonstrate about How to Create a Reminder Notification in Android" }, { "code": null, "e": 1271, "s": 1142, "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": 1336, "s": 1271, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1905, "s": 1336, "text": "<? xml version = \"1.0\" encoding= \"utf-8\" ?>\n<RelativeLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:padding = \"16dp\"\n tools:context = \".MainActivity\">\n <Button\n android:onClick= \"createNotification\"\n android:text= \"create notification\"\n android:layout_centerInParent= \"true\"\n android:layout_width= \"match_parent\"\n android:layout_height= \"wrap_content\" />\n</RelativeLayout>" }, { "code": null, "e": 1958, "s": 1905, "text": "Step 3 − Add the following code to src/MainActivity." }, { "code": null, "e": 3186, "s": 1958, "text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.AlarmManager ;\nimport android.app.PendingIntent ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\nimport java.util.Calendar ;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n public void createNotification (View view) {\n Intent myIntent = new Intent(getApplicationContext() , NotifyService. class ) ;\n AlarmManager alarmManager = (AlarmManager) getSystemService( ALARM_SERVICE ) ;\n PendingIntent pendingIntent = PendingIntent. getService ( this, 0 , myIntent , 0 ) ;\n Calendar calendar = Calendar. getInstance () ;\n calendar.set(Calendar. SECOND , 0 ) ;\n calendar.set(Calendar. MINUTE , 0 ) ;\n calendar.set(Calendar. HOUR , 0 ) ;\n calendar.set(Calendar. AM_PM , Calendar. AM ) ;\n calendar.add(Calendar. DAY_OF_MONTH , 1 ) ;\n alarmManager.setRepeating(AlarmManager. RTC_WAKEUP , calendar.getTimeInMillis() , 1000 * 60 * 60 * 24 , pendingIntent) ;\n }\n}" }, { "code": null, "e": 3239, "s": 3186, "text": "Step 4 − Add the following code to src/NotifyService" }, { "code": null, "e": 5433, "s": 3239, "text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.app.PendingIntent ;\nimport android.app.Service ;\nimport android.content.Intent ;\nimport android.os.IBinder ;\nimport android.support.v4.app.NotificationCompat ;\npublic class NotifyService extends Service {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n public NotifyService () {\n }\n @Override\n public IBinder onBind (Intent intent) {\n Intent notificationIntent = new Intent(getApplicationContext() , MainActivity. class ) ;\n notificationIntent.putExtra( \"fromNotification\" , true ) ;\n notificationIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_SINGLE_TOP ) ;\n PendingIntent pendingIntent = PendingIntent. getActivity ( this, 0 , notificationIntent , 0 ) ;\n NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext() , default_notification_channel_id ) ;\n mBuilder.setContentTitle( \"My Notification\" ) ;\n mBuilder.setContentIntent(pendingIntent) ;\n mBuilder.setContentText( \"Notification Listener Service Example\" ) ;\n mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n mBuilder.setAutoCancel( true ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new\n NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;\n throw new UnsupportedOperationException( \"Not yet implemented\" ) ;\n }\n}" }, { "code": null, "e": 5488, "s": 5433, "text": "Step 5 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 6515, "s": 5488, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\n <uses-permission android :name = \"android.permission.RECEIVE_BOOT_COMPLETED\" />\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 <service\n android :name = \".NotifyService\"\n android :enabled = \"true\"\n android :exported = \"true\" >\n </service>\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": 6861, "s": 6515, "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": 6903, "s": 6861, "text": "Click here to download the project code" } ]
How to draw images in the Tkinter window?
To process images with Tkinter and other Python packages, we generally refer to use Pillow Package or PIL in Python. It provides a way to load and process the images in the program wherever we need. Initially, we convert the image to an instance of PhotoImage object that allows images to be further used in many use cases. Further, the Canvas widget in Tkinter helps to draw the images in a Tkinter application, we can use the create_image(x,y, image_file) method to display the image in a particular application. #Import the required Libraries from tkinter import * from PIL import Image,ImageTk #Create an instance of tkinter frame win = Tk() #Set the geometry of tkinter frame win.geometry("750x270") #Create a canvas canvas= Canvas(win, width= 600, height= 400) canvas.pack() #Load an image in the script img= ImageTk.PhotoImage(Image.open("download.png")) #Add image to the Canvas Items canvas.create_image(10,10,anchor=NW,image=img) win.mainloop() Running the above code will display a window that will display an image in the Canvas Widget. In order to replace or change the Image file in the given output just import the image in Image.Open(file name) method.
[ { "code": null, "e": 1577, "s": 1062, "text": "To process images with Tkinter and other Python packages, we generally refer to use Pillow Package or PIL in Python. It provides a way to load and process the images in the program wherever we need. Initially, we convert the image to an instance of PhotoImage object that allows images to be further used in many use cases. Further, the Canvas widget in Tkinter helps to draw the images in a Tkinter application, we can use the create_image(x,y, image_file) method to display the image in a particular application." }, { "code": null, "e": 2017, "s": 1577, "text": "#Import the required Libraries\nfrom tkinter import *\nfrom PIL import Image,ImageTk\n#Create an instance of tkinter frame\nwin = Tk()\n#Set the geometry of tkinter frame\nwin.geometry(\"750x270\")\n#Create a canvas\ncanvas= Canvas(win, width= 600, height= 400)\ncanvas.pack()\n#Load an image in the script\nimg= ImageTk.PhotoImage(Image.open(\"download.png\"))\n#Add image to the Canvas Items\ncanvas.create_image(10,10,anchor=NW,image=img)\nwin.mainloop()" }, { "code": null, "e": 2111, "s": 2017, "text": "Running the above code will display a window that will display an image in the Canvas Widget." }, { "code": null, "e": 2231, "s": 2111, "text": "In order to replace or change the Image file in the given output just import the image in Image.Open(file name) method." } ]
Longest Common Subsequence
The longest common subsequence is a type of subsequence which is present in both of the given sequences or arrays. We can see that there are many subproblems, which are computed again and again to solve this problem. By using the Overlapping Substructure Property of Dynamic programming, we can overcome the computational efforts. Once the result of subproblems is calculated and stored in the table, we can simply calculate the next results by use of the previous results. Input: Two strings with different letters or symbols. string 1: AGGTAB string 2: GXTXAYB Output: The length of the longest common subsequence. Here it is 4. AGGTAB and GXTXAYB. The underlined letters are present in both strings and in correct sequence. longestComSubSeq(str1, str2) Input − Two strings to find the length of Longest Common Subsequence. Output − The length of LCS. Begin m := length of str1 n := length of str2 define longSubSeq matrix of order (m+1) x (n+1) for i := 0 to m, do for j := 0 to n, do if i = 0 or j = 0, then longSubSeq[i,j] := 0 else if str1[i-1] = str2[j-1], then longSubSeq[i,j] := longSubSeq[i-1,j-1] + 1 else longSubSeq[i,j] := maximum of longSubSeq[i-1, j] and longSubSeq[i, j-1] done done longSubSeq[m, n] End #include<iostream> using namespace std; int max(int a, int b) { return (a > b)? a : b; } int longestComSs( string str1, string str2) { int m = str1.size(); int n = str2.size(); int longSubSeq[m+1][n+1]; //longSubSeq[i,j] will hold the LCS of str1 (0 to i-1) and str2 (0 to j-1) for (int i=0; i<=m; i++) { for (int j=0; j<=n; j++) { if (i == 0 || j == 0) longSubSeq[i][j] = 0; else if (str1[i-1] == str2[j-1]) longSubSeq[i][j] = longSubSeq[i-1][j-1] + 1; else longSubSeq[i][j] = max(longSubSeq[i-1][j], longSubSeq[i][j-1]); } } return longSubSeq[m][n]; } int main() { string str1 = "AGGTAB"; string str2 = "GXTXAYB"; cout << "Length of Longest Common Subsequence is: " << longestComSs( str1, str2); } Length of Longest Common Subsequence is: 4
[ { "code": null, "e": 1177, "s": 1062, "text": "The longest common subsequence is a type of subsequence which is present in both of the given sequences or arrays." }, { "code": null, "e": 1536, "s": 1177, "text": "We can see that there are many subproblems, which are computed again and again to solve this problem. By using the Overlapping Substructure Property of Dynamic programming, we can overcome the computational efforts. Once the result of subproblems is calculated and stored in the table, we can simply calculate the next results by use of the previous results." }, { "code": null, "e": 1789, "s": 1536, "text": "Input:\nTwo strings with different letters or symbols.\nstring 1: AGGTAB\nstring 2: GXTXAYB\nOutput:\nThe length of the longest common subsequence. Here it is 4.\nAGGTAB and GXTXAYB. The underlined letters are present in both strings and in correct sequence." }, { "code": null, "e": 1818, "s": 1789, "text": "longestComSubSeq(str1, str2)" }, { "code": null, "e": 1888, "s": 1818, "text": "Input − Two strings to find the length of Longest Common Subsequence." }, { "code": null, "e": 1916, "s": 1888, "text": "Output − The length of LCS." }, { "code": null, "e": 2388, "s": 1916, "text": "Begin\n m := length of str1\n n := length of str2\n define longSubSeq matrix of order (m+1) x (n+1)\n\n for i := 0 to m, do\n for j := 0 to n, do\n if i = 0 or j = 0, then\n longSubSeq[i,j] := 0\n else if str1[i-1] = str2[j-1], then\n longSubSeq[i,j] := longSubSeq[i-1,j-1] + 1\n else\n longSubSeq[i,j] := maximum of longSubSeq[i-1, j] and\n longSubSeq[i, j-1]\n done\n done\n\n longSubSeq[m, n]\nEnd" }, { "code": null, "e": 3209, "s": 2388, "text": "#include<iostream>\nusing namespace std;\n\nint max(int a, int b) {\n return (a > b)? a : b;\n}\n\nint longestComSs( string str1, string str2) {\n int m = str1.size();\n int n = str2.size();\n \n int longSubSeq[m+1][n+1];\n \n //longSubSeq[i,j] will hold the LCS of str1 (0 to i-1) and str2 (0 to j-1)\n for (int i=0; i<=m; i++) {\n for (int j=0; j<=n; j++) {\n if (i == 0 || j == 0)\n longSubSeq[i][j] = 0;\n else if (str1[i-1] == str2[j-1])\n longSubSeq[i][j] = longSubSeq[i-1][j-1] + 1;\n else\n longSubSeq[i][j] = max(longSubSeq[i-1][j], longSubSeq[i][j-1]);\n }\n }\n return longSubSeq[m][n];\n}\n\nint main() {\n string str1 = \"AGGTAB\";\n string str2 = \"GXTXAYB\";\n\n cout << \"Length of Longest Common Subsequence is: \" << longestComSs( str1, str2);\n}" }, { "code": null, "e": 3252, "s": 3209, "text": "Length of Longest Common Subsequence is: 4" } ]
Apache Derby - Environment Setup
Following chapter explains how to download and install Apache Derby. Visit the home page of Apache Derby home page https://db.apache.org/derby/. Click the Download tab. Select and click on the link of the latest version of Apache Derby. On clicking the selected link, you will be redirected to the Distributions page of apache derby. If you observe here, derby provides distributions namely, db-derby-bin, db-derbylib.zip, db-derby-lib-debug.zip, and db-derby-src.zip. Download the db-derby-bin folder. Copy its contents to a separate folder where you wanted to install Apache Derby. (for example, say C:\Derby) Now, to work with Derby, Make sure that you already have set the JAVA_HOME variable by passing the location of bin folder of Java Installation folder, and include the JAVA_HOME/bin in the PATH variable. Make sure that you already have set the JAVA_HOME variable by passing the location of bin folder of Java Installation folder, and include the JAVA_HOME/bin in the PATH variable. Create a new environment variable, DERBY_HOME with value C:\Derby. Create a new environment variable, DERBY_HOME with value C:\Derby. The bin folder of db-derby-bin distributions (we changed it as C:\Derby\bin) contains all the required jar files. The bin folder of db-derby-bin distributions (we changed it as C:\Derby\bin) contains all the required jar files. As discussed, Apache Derby can be installed/deployed in two ways as follows − Embedded mode − In this, you need to access the database using Embedded Derby JDBC driver. You can start and stop derby through Java application. Both Database engine and your application will run on the same JVM. Embedded mode − In this, you need to access the database using Embedded Derby JDBC driver. You can start and stop derby through Java application. Both Database engine and your application will run on the same JVM. Network Server mode − In this mode, you can access Derby in a typical clientserver fashion, where Derby is embedded in the server system. Then, the client machines running in different JVM’s (that of the Server) will send requests to the server, and the server responds to those requests. Network Server mode − In this mode, you can access Derby in a typical clientserver fashion, where Derby is embedded in the server system. Then, the client machines running in different JVM’s (that of the Server) will send requests to the server, and the server responds to those requests. The client can be another JVM in the same system machine of the server or a Java application from a remote system. To install Apache Derby in embedded mode, include the jar file derby.jar in your CLASSPATH. Or, you can set the classpath for required jar files by running the setEmbeddedCP command. Browse through the bin directory of Apache Derby and run this file as shown below − C:\Users\MYUSER>cd %DERBY_HOME%/bin C:\Derby\bin>setEmbeddedCP.bat C:\Derby\bin>SET DERBY_HOME=C:\Derby C:\Derby\bin>set CLASSPATH=C:\Derby\lib\derby.jar;C:\Derby\lib\derbytools.jar;C:\Derby/lib/derby optionaltools.jar;C:\Users\Tutorialspoint\Google Drive\Office\Derby\derby_zip\New folder\db-derby-10.12.1.1- bin\lib;C:\EXAMPLES_\Task\jars\*;C:\EXAMPLES\jars\mysql-connector-java-5.1.40- bin.jar;C:\Users\Tutorialspoint\Google Drive\Office\37.Junit Update\jars;C:\Program Files\Apache Software Foundation\Tomcat 8.5\lib\*;C:\Derby\lib\*; After setting up Apache Derby, to access it, run Java programs using the embedded driver. You can verify the setup using the ij tool as shown below − C:\Derby\bin>ij ij version 10.14 ij> connect 'jdbc:derby:SampleDB;create=true'; ij> To install Apache Derby in network server mode, you need to include derbynet.jar and derbytools.jar files to the CLASSPATH. Or, you can set the class path for required jar files by running the setNetworkServerCP command. Browse through the bin directory of Apache Derby and run this file as shown below − C:\Users\MYUSER>cd %DERBY_HOME%/bin C:\Derby\bin>setNetworkServerCP.bat C:\Derby\bin>SET DERBY_INSTALL=C:\Derby C:\Derby\bin>set CLASSPATH=C:\Derby\lib\derbynet.jar;C:\Derby\lib\derbytools.jar;C:\Derby/lib/de rbyoptionaltools.jar;C:\Users\Tutorialspoint\Google Drive\Office\Derby\derby_zip\New folder\db-derby-10.12.1.1- bin\lib;C:\EXAMPLES_\Task\jars\*;C:\EXAMPLES\jars\mysql-connector-java-5.1.40- bin.jar;C:\Users\Tutorialspoint\Google Drive\Office\37.Junit Update\jars;C:\Program Files\Apache Software Foundation\Tomcat 8.5\lib\*;C:\Derby\lib\*; You can start Network Server by running the command startNetworkServer. Browse through the bin directory of Apache Derby and run this command as shown below − C:\Derby\bin>startNetworkServer Fri Jan 04 11:20:30 IST 2019 : Security manager installed using the Basic server security policy. Fri Jan 04 11:20:30 IST 2019 : Apache Derby Network Server - 10.14.2.0 - (1828579) started and ready to accept connections on port 1527 Or, you can start the server using derbyrun.jar as shown below − C:\Users\MYUSER>cd %DERBY_HOME%/lib C:\Derby\lib>java -jar derbyrun.jar server start Fri Jan 04 11:27:20 IST 2019: Security manager installed using the Basic server security policy. Fri Jan 04 11:27:21 IST 2019: Apache Derby Network Server - 10.14.2.0 - (1828579) started and ready to accept connections on port 1527 In client, add the jar files derbyclient.jar and derbytools.jar to the CLASSPATH. Or, run the setNetworkClientCP command as shown below − C:\Users\MYUSER>cd %DERBY_HOME%/bin C:\Derby\bin>setNetworkClientCP C:\Derby\bin>SET DERBY_HOME=C:\Derby C:\Derby\bin>set CLASSPATH=C:\Derby\lib\derbyclient.jar;C:\Derby\lib\derbytools.jar;C:\Derby/lib /derbyoptionaltools.jar;C:\Derby\lib\derby.jar;C:\Derby\lib\derbytools.jar;C:\D erby/lib/derbyoptionaltools.jar;C:\Users\Tutorialspoint\Google Drive\Office\Derby\derby_zip\New folder\db-derby-10.12.1.1- bin\lib;C:\EXAMPLES_\Task\jars\*;C:\EXAMPLES\jars\mysql-connector-java-5.1.40- bin.jar;C:\Users\Tutorialspoint\Google Drive\Office\37.Junit Update\jars;C:\Program Files\Apache Software Foundation\Tomcat 8.5\lib\*;C:\Derby\lib\*; Then from this client, you can send requests to the server. You can verify the setup using the ij tool as shown below − C:\Derby\bin>ij ij version 10.14 ij> connect 'jdbc:derby://localhost:1527/SampleDB;create=true'; ij> While working with Eclipse, you need to set the build path for all the required jar files. Open eclipse and create a sample project. Right click on the project and select the option Build Path -> Configure Build Path as shown below − In the Java Build Path frame in the Libraries tab, click on Add External JARs. And select the required jar files in the lib folder of the Derby installation folder and click on Apply and Close. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2249, "s": 2180, "text": "Following chapter explains how to download and install Apache Derby." }, { "code": null, "e": 2349, "s": 2249, "text": "Visit the home page of Apache Derby home page https://db.apache.org/derby/. Click the Download tab." }, { "code": null, "e": 2417, "s": 2349, "text": "Select and click on the link of the latest version of Apache Derby." }, { "code": null, "e": 2649, "s": 2417, "text": "On clicking the selected link, you will be redirected to the Distributions page of apache derby. If you observe here, derby provides distributions namely, db-derby-bin, db-derbylib.zip, db-derby-lib-debug.zip, and db-derby-src.zip." }, { "code": null, "e": 2792, "s": 2649, "text": "Download the db-derby-bin folder. Copy its contents to a separate folder where you wanted to install Apache Derby. (for example, say C:\\Derby)" }, { "code": null, "e": 2817, "s": 2792, "text": "Now, to work with Derby," }, { "code": null, "e": 2995, "s": 2817, "text": "Make sure that you already have set the JAVA_HOME variable by passing the location of bin folder of Java Installation folder, and include the JAVA_HOME/bin in the PATH variable." }, { "code": null, "e": 3173, "s": 2995, "text": "Make sure that you already have set the JAVA_HOME variable by passing the location of bin folder of Java Installation folder, and include the JAVA_HOME/bin in the PATH variable." }, { "code": null, "e": 3240, "s": 3173, "text": "Create a new environment variable, DERBY_HOME with value C:\\Derby." }, { "code": null, "e": 3307, "s": 3240, "text": "Create a new environment variable, DERBY_HOME with value C:\\Derby." }, { "code": null, "e": 3421, "s": 3307, "text": "The bin folder of db-derby-bin distributions (we changed it as C:\\Derby\\bin) contains all the required jar files." }, { "code": null, "e": 3535, "s": 3421, "text": "The bin folder of db-derby-bin distributions (we changed it as C:\\Derby\\bin) contains all the required jar files." }, { "code": null, "e": 3613, "s": 3535, "text": "As discussed, Apache Derby can be installed/deployed in two ways as follows −" }, { "code": null, "e": 3827, "s": 3613, "text": "Embedded mode − In this, you need to access the database using Embedded Derby JDBC driver. You can start and stop derby through Java application. Both Database engine and your application will run on the same JVM." }, { "code": null, "e": 4041, "s": 3827, "text": "Embedded mode − In this, you need to access the database using Embedded Derby JDBC driver. You can start and stop derby through Java application. Both Database engine and your application will run on the same JVM." }, { "code": null, "e": 4330, "s": 4041, "text": "Network Server mode − In this mode, you can access Derby in a typical clientserver fashion, where Derby is embedded in the server system. Then, the client machines running in different JVM’s (that of the Server) will send requests to the server, and the server responds to those requests." }, { "code": null, "e": 4619, "s": 4330, "text": "Network Server mode − In this mode, you can access Derby in a typical clientserver fashion, where Derby is embedded in the server system. Then, the client machines running in different JVM’s (that of the Server) will send requests to the server, and the server responds to those requests." }, { "code": null, "e": 4734, "s": 4619, "text": "The client can be another JVM in the same system machine of the server or a Java application from a remote system." }, { "code": null, "e": 4826, "s": 4734, "text": "To install Apache Derby in embedded mode, include the jar file derby.jar in your CLASSPATH." }, { "code": null, "e": 5001, "s": 4826, "text": "Or, you can set the classpath for required jar files by running the setEmbeddedCP\ncommand. Browse through the bin directory of Apache Derby and run this file as shown\nbelow −" }, { "code": null, "e": 5541, "s": 5001, "text": "C:\\Users\\MYUSER>cd %DERBY_HOME%/bin\nC:\\Derby\\bin>setEmbeddedCP.bat\nC:\\Derby\\bin>SET DERBY_HOME=C:\\Derby\nC:\\Derby\\bin>set\nCLASSPATH=C:\\Derby\\lib\\derby.jar;C:\\Derby\\lib\\derbytools.jar;C:\\Derby/lib/derby\noptionaltools.jar;C:\\Users\\Tutorialspoint\\Google\nDrive\\Office\\Derby\\derby_zip\\New folder\\db-derby-10.12.1.1-\nbin\\lib;C:\\EXAMPLES_\\Task\\jars\\*;C:\\EXAMPLES\\jars\\mysql-connector-java-5.1.40-\nbin.jar;C:\\Users\\Tutorialspoint\\Google Drive\\Office\\37.Junit\nUpdate\\jars;C:\\Program Files\\Apache Software Foundation\\Tomcat\n8.5\\lib\\*;C:\\Derby\\lib\\*;\n" }, { "code": null, "e": 5631, "s": 5541, "text": "After setting up Apache Derby, to access it, run Java programs using the embedded driver." }, { "code": null, "e": 5691, "s": 5631, "text": "You can verify the setup using the ij tool as shown below −" }, { "code": null, "e": 5776, "s": 5691, "text": "C:\\Derby\\bin>ij\nij version 10.14\nij> connect 'jdbc:derby:SampleDB;create=true';\nij>\n" }, { "code": null, "e": 5900, "s": 5776, "text": "To install Apache Derby in network server mode, you need to include derbynet.jar and derbytools.jar files to the CLASSPATH." }, { "code": null, "e": 6081, "s": 5900, "text": "Or, you can set the class path for required jar files by running the setNetworkServerCP\ncommand. Browse through the bin directory of Apache Derby and run this file as shown below −" }, { "code": null, "e": 6632, "s": 6081, "text": "C:\\Users\\MYUSER>cd %DERBY_HOME%/bin\nC:\\Derby\\bin>setNetworkServerCP.bat\nC:\\Derby\\bin>SET DERBY_INSTALL=C:\\Derby\nC:\\Derby\\bin>set\nCLASSPATH=C:\\Derby\\lib\\derbynet.jar;C:\\Derby\\lib\\derbytools.jar;C:\\Derby/lib/de\nrbyoptionaltools.jar;C:\\Users\\Tutorialspoint\\Google\nDrive\\Office\\Derby\\derby_zip\\New folder\\db-derby-10.12.1.1-\nbin\\lib;C:\\EXAMPLES_\\Task\\jars\\*;C:\\EXAMPLES\\jars\\mysql-connector-java-5.1.40-\nbin.jar;C:\\Users\\Tutorialspoint\\Google Drive\\Office\\37.Junit\nUpdate\\jars;C:\\Program Files\\Apache Software Foundation\\Tomcat\n8.5\\lib\\*;C:\\Derby\\lib\\*;\n" }, { "code": null, "e": 6791, "s": 6632, "text": "You can start Network Server by running the command startNetworkServer. Browse through the bin directory of Apache Derby and run this command as shown below −" }, { "code": null, "e": 7058, "s": 6791, "text": "C:\\Derby\\bin>startNetworkServer\nFri Jan 04 11:20:30 IST 2019 : Security manager installed using the Basic\nserver security policy.\nFri Jan 04 11:20:30 IST 2019 : Apache Derby Network Server - 10.14.2.0 -\n(1828579) started and ready to accept connections on port 1527\n" }, { "code": null, "e": 7123, "s": 7058, "text": "Or, you can start the server using derbyrun.jar as shown below −" }, { "code": null, "e": 7441, "s": 7123, "text": "C:\\Users\\MYUSER>cd %DERBY_HOME%/lib\nC:\\Derby\\lib>java -jar derbyrun.jar server start\nFri Jan 04 11:27:20 IST 2019: Security manager installed using the Basic server\nsecurity policy.\nFri Jan 04 11:27:21 IST 2019: Apache Derby Network Server - 10.14.2.0 -\n(1828579) started and ready to accept connections on port 1527\n" }, { "code": null, "e": 7579, "s": 7441, "text": "In client, add the jar files derbyclient.jar and derbytools.jar to the CLASSPATH. Or, run the setNetworkClientCP command as shown below −" }, { "code": null, "e": 8214, "s": 7579, "text": "C:\\Users\\MYUSER>cd %DERBY_HOME%/bin\nC:\\Derby\\bin>setNetworkClientCP\nC:\\Derby\\bin>SET DERBY_HOME=C:\\Derby\nC:\\Derby\\bin>set\nCLASSPATH=C:\\Derby\\lib\\derbyclient.jar;C:\\Derby\\lib\\derbytools.jar;C:\\Derby/lib\n/derbyoptionaltools.jar;C:\\Derby\\lib\\derby.jar;C:\\Derby\\lib\\derbytools.jar;C:\\D\nerby/lib/derbyoptionaltools.jar;C:\\Users\\Tutorialspoint\\Google\nDrive\\Office\\Derby\\derby_zip\\New folder\\db-derby-10.12.1.1-\nbin\\lib;C:\\EXAMPLES_\\Task\\jars\\*;C:\\EXAMPLES\\jars\\mysql-connector-java-5.1.40-\nbin.jar;C:\\Users\\Tutorialspoint\\Google Drive\\Office\\37.Junit\nUpdate\\jars;C:\\Program Files\\Apache Software Foundation\\Tomcat\n8.5\\lib\\*;C:\\Derby\\lib\\*;\n" }, { "code": null, "e": 8274, "s": 8214, "text": "Then from this client, you can send requests to the server." }, { "code": null, "e": 8334, "s": 8274, "text": "You can verify the setup using the ij tool as shown below −" }, { "code": null, "e": 8436, "s": 8334, "text": "C:\\Derby\\bin>ij\nij version 10.14\nij> connect 'jdbc:derby://localhost:1527/SampleDB;create=true';\nij>\n" }, { "code": null, "e": 8527, "s": 8436, "text": "While working with Eclipse, you need to set the build path for all the required jar files." }, { "code": null, "e": 8670, "s": 8527, "text": "Open eclipse and create a sample project. Right click on the project and select the option\nBuild Path -> Configure Build Path as shown below −" }, { "code": null, "e": 8749, "s": 8670, "text": "In the Java Build Path frame in the Libraries tab, click on Add External JARs." }, { "code": null, "e": 8865, "s": 8749, "text": "And select the required jar files in the lib folder of the Derby installation folder and click on Apply and Close." }, { "code": null, "e": 8900, "s": 8865, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8919, "s": 8900, "text": " Arnab Chakraborty" }, { "code": null, "e": 8954, "s": 8919, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8975, "s": 8954, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 9008, "s": 8975, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 9021, "s": 9008, "text": " Nilay Mehta" }, { "code": null, "e": 9056, "s": 9021, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9074, "s": 9056, "text": " Bigdata Engineer" }, { "code": null, "e": 9107, "s": 9074, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 9125, "s": 9107, "text": " Bigdata Engineer" }, { "code": null, "e": 9158, "s": 9125, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 9176, "s": 9158, "text": " Bigdata Engineer" }, { "code": null, "e": 9183, "s": 9176, "text": " Print" }, { "code": null, "e": 9194, "s": 9183, "text": " Add Notes" } ]
How to use Volley Library to parse JSON in Android Kotlin App?
This example demonstrates how to use Volley Library to parse JSON in Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16sp" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="Tutorials Point" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="32sp" android:textStyle="bold" /> <TextView android:id="@+id/textViewResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textColor="@android:color/black" android:textSize="20sp" /> <Button android:id="@+id/btnParse" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerInParent="true" android:layout_marginBottom="20sp" android:text="Parse JSON" /> </RelativeLayout> Step 3 − Add the following dependency to the build.gradle file− implementation 'com.android.volley:volley:1.1.0' Step 4 − Add the following code to MainActivity.kt import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.Volley import org.json.JSONException class MainActivity : AppCompatActivity() { private lateinit var textView: TextView private var requestQueue: RequestQueue? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" textView = findViewById(R.id.textViewResult) val button: Button = findViewById(R.id.btnParse) requestQueue = Volley.newRequestQueue(this) button.setOnClickListener { jsonParse() } } private fun jsonParse() { val url = "https://api.myjson.com/bins/xbspb" val request = JsonObjectRequest(Request.Method.GET, url, null, Response.Listener { response ->try { val jsonArray = response.getJSONArray("employees") for (i in 0 until jsonArray.length()) { val employee = jsonArray.getJSONObject(i) val firstName = employee.getString("firstname") val age = employee.getInt("age") val mail = employee.getString("mail") textView.append("$firstName, $age, $mail\n\n") } } catch (e: JSONException) { e.printStackTrace() } }, Response.ErrorListener { error -> error.printStackTrace() }) requestQueue?.add(request) } } 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.kotlipapp"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1139, "s": 1062, "text": "This example demonstrates how to use Volley Library to parse JSON in Kotlin." }, { "code": null, "e": 1268, "s": 1139, "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": 1333, "s": 1268, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2584, "s": 1333, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"16sp\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/textViewResult\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textColor=\"@android:color/black\"\n android:textSize=\"20sp\" />\n <Button\n android:id=\"@+id/btnParse\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentBottom=\"true\"\n android:layout_centerInParent=\"true\"\n android:layout_marginBottom=\"20sp\"\n android:text=\"Parse JSON\" />\n</RelativeLayout>" }, { "code": null, "e": 2648, "s": 2584, "text": "Step 3 − Add the following dependency to the build.gradle file−" }, { "code": null, "e": 2697, "s": 2648, "text": "implementation 'com.android.volley:volley:1.1.0'" }, { "code": null, "e": 2748, "s": 2697, "text": "Step 4 − Add the following code to MainActivity.kt" }, { "code": null, "e": 4440, "s": 2748, "text": "import android.os.Bundle\nimport android.widget.Button\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nimport com.android.volley.Request\nimport com.android.volley.RequestQueue\nimport com.android.volley.Response\nimport com.android.volley.toolbox.JsonObjectRequest\nimport com.android.volley.toolbox.Volley\nimport org.json.JSONException\nclass MainActivity : AppCompatActivity() {\n private lateinit var textView: TextView\n private var requestQueue: RequestQueue? = null\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.textViewResult)\n val button: Button = findViewById(R.id.btnParse)\n requestQueue = Volley.newRequestQueue(this)\n button.setOnClickListener {\n jsonParse()\n }\n }\n private fun jsonParse() {\n val url = \"https://api.myjson.com/bins/xbspb\"\n val request = JsonObjectRequest(Request.Method.GET, url, null, Response.Listener {\n response ->try {\n val jsonArray = response.getJSONArray(\"employees\")\n for (i in 0 until jsonArray.length()) {\n val employee = jsonArray.getJSONObject(i)\n val firstName = employee.getString(\"firstname\")\n val age = employee.getInt(\"age\")\n val mail = employee.getString(\"mail\")\n textView.append(\"$firstName, $age, $mail\\n\\n\")\n }\n } catch (e: JSONException) {\n e.printStackTrace()\n }\n }, Response.ErrorListener { error -> error.printStackTrace() })\n requestQueue?.add(request)\n }\n}" }, { "code": null, "e": 4495, "s": 4440, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5234, "s": 4495, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.kotlipapp\">\n<uses-permission android:name=\"android.permission.INTERNET\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5585, "s": 5234, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 5626, "s": 5585, "text": "Click here to download the project code." } ]
Algorithms | Analysis of Algorithms (Recurrences) | Question 6 - GeeksforGeeks
28 Jun, 2021 The running time of an algorithm is represented by the following recurrence relation: if n <= 3 then T(n) = n else T(n) = T(n/3) + cn Which one of the following represents the time complexity of the algorithm?(A) (n)(B) (n log n)(C) (n^2)(D) (n^2log n)(A) A(B) B(C) C(D) DAnswer: (A)Explanation: T(n) = cn + T(n/3) = cn + cn/3 + T(n/9) = cn + cn/3 + cn/9 + T(n/27) Taking the sum of infinite GP series. The value of T(n) will be less than this sum. T(n) <= cn(1/(1-1/3)) <= 3cn/2 or we can say cn <= T(n) <= 3cn/2 Therefore T(n) = (n) This can also be solved using Master Theorem for solving recurrences. The given expression lies in Case 3 of the theorem.Quiz of this Question Algorithms-Analysis of Algorithms (Recurrences) Analysis of Algorithms (Recurrences) Algorithms Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithms | Dynamic Programming | Question 2 Algorithms | Dynamic Programming | Question 3 Algorithms | Analysis of Algorithms | Question 17 Algorithms | Greedy Algorithms | Question 1 Algorithms | Recursion | Question 9 Algorithms Quiz | Dynamic Programming | Question 8 Algorithms | Divide and Conquer | Question 6 Algorithms | Graph Traversals | Question 12 Algorithms | Sorting | Question 23 Algorithms | NP Complete | Question 4
[ { "code": null, "e": 25012, "s": 24984, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25098, "s": 25012, "text": "The running time of an algorithm is represented by the following recurrence relation:" }, { "code": null, "e": 25159, "s": 25098, "text": " if n <= 3 then T(n) = n\n else T(n) = T(n/3) + cn\n" }, { "code": null, "e": 25321, "s": 25159, "text": "Which one of the following represents the time complexity of the algorithm?(A) (n)(B) (n log n)(C) (n^2)(D) (n^2log n)(A) A(B) B(C) C(D) DAnswer: (A)Explanation:" }, { "code": null, "e": 25578, "s": 25321, "text": "T(n) = cn + T(n/3)\n = cn + cn/3 + T(n/9)\n = cn + cn/3 + cn/9 + T(n/27)\nTaking the sum of infinite GP series. The value of T(n) will\nbe less than this sum.\nT(n) <= cn(1/(1-1/3))\n <= 3cn/2\n\nor we can say \ncn <= T(n) <= 3cn/2\nTherefore T(n) = (n)\n" }, { "code": null, "e": 25721, "s": 25578, "text": "This can also be solved using Master Theorem for solving recurrences. The given expression lies in Case 3 of the theorem.Quiz of this Question" }, { "code": null, "e": 25769, "s": 25721, "text": "Algorithms-Analysis of Algorithms (Recurrences)" }, { "code": null, "e": 25806, "s": 25769, "text": "Analysis of Algorithms (Recurrences)" }, { "code": null, "e": 25822, "s": 25806, "text": "Algorithms Quiz" }, { "code": null, "e": 25920, "s": 25822, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25966, "s": 25920, "text": "Algorithms | Dynamic Programming | Question 2" }, { "code": null, "e": 26012, "s": 25966, "text": "Algorithms | Dynamic Programming | Question 3" }, { "code": null, "e": 26062, "s": 26012, "text": "Algorithms | Analysis of Algorithms | Question 17" }, { "code": null, "e": 26106, "s": 26062, "text": "Algorithms | Greedy Algorithms | Question 1" }, { "code": null, "e": 26142, "s": 26106, "text": "Algorithms | Recursion | Question 9" }, { "code": null, "e": 26193, "s": 26142, "text": "Algorithms Quiz | Dynamic Programming | Question 8" }, { "code": null, "e": 26238, "s": 26193, "text": "Algorithms | Divide and Conquer | Question 6" }, { "code": null, "e": 26282, "s": 26238, "text": "Algorithms | Graph Traversals | Question 12" }, { "code": null, "e": 26317, "s": 26282, "text": "Algorithms | Sorting | Question 23" } ]
How do you remove an array element by its index in MongoDB
To remove array element by its index in MongoDB, you can use unsetandpull operator. There are two steps to remove array elements from an array.The syntax for the same is as follows: db.yourCollectionName.update({},{$unset:{"yourArrayListName.yourPosition":yourPositionValue}}; db.yourCollectionName.update({},{$pull:{"yourArrayListName":null}}); To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows: >db.removeArrayElements.insertOne({"StudentName":"Larry","StudentAge":23,"TechnicalSub ject":["C","C++","Java","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ea4879c4643706aef56d2") } Display all documents from a collection with the help of find() method. The query is as follows: > db.removeArrayElements.find().pretty(); The following is the output: { "_id" : ObjectId("5c6ea4879c4643706aef56d2"), "StudentName" : "Larry", "StudentAge" : 23, "TechnicalSubject" : [ "C", "C++", "Java", "MongoDB" ] } Here is the query to remove array element by its index: > db.removeArrayElements.update({},{$unset:{"TechnicalSubject.3":1}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.removeArrayElements.update({},{$pull:{"TechnicalSubject":null}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Above, we have removed array element “MongoDB”, which is at index 3. Let us display documents from a collection. The query is as follows: > db.removeArrayElements.find().pretty(); The following is the output: { "_id" : ObjectId("5c6ea4879c4643706aef56d2"), "StudentName" : "Larry", "StudentAge" : 23, "TechnicalSubject" : [ "C", "C++", "Java" ] } Look at the above sample output, the index 3 i.e. position 4 has been removed from the array i.e. the element “MongoDB”.
[ { "code": null, "e": 1244, "s": 1062, "text": "To remove array element by its index in MongoDB, you can use unsetandpull operator. There are two steps to remove array elements from an array.The syntax for the same is as follows:" }, { "code": null, "e": 1408, "s": 1244, "text": "db.yourCollectionName.update({},{$unset:{\"yourArrayListName.yourPosition\":yourPositionValue}};\ndb.yourCollectionName.update({},{$pull:{\"yourArrayListName\":null}});" }, { "code": null, "e": 1544, "s": 1408, "text": "To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:" }, { "code": null, "e": 1754, "s": 1544, "text": ">db.removeArrayElements.insertOne({\"StudentName\":\"Larry\",\"StudentAge\":23,\"TechnicalSub\nject\":[\"C\",\"C++\",\"Java\",\"MongoDB\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ea4879c4643706aef56d2\")\n}" }, { "code": null, "e": 1851, "s": 1754, "text": "Display all documents from a collection with the help of find() method. The query is as follows:" }, { "code": null, "e": 1893, "s": 1851, "text": "> db.removeArrayElements.find().pretty();" }, { "code": null, "e": 1922, "s": 1893, "text": "The following is the output:" }, { "code": null, "e": 2110, "s": 1922, "text": "{\n \"_id\" : ObjectId(\"5c6ea4879c4643706aef56d2\"),\n \"StudentName\" : \"Larry\",\n \"StudentAge\" : 23,\n \"TechnicalSubject\" : [\n \"C\",\n \"C++\",\n \"Java\",\n \"MongoDB\"\n ]\n}" }, { "code": null, "e": 2166, "s": 2110, "text": "Here is the query to remove array element by its index:" }, { "code": null, "e": 2441, "s": 2166, "text": "> db.removeArrayElements.update({},{$unset:{\"TechnicalSubject.3\":1}});\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })\n\n> db.removeArrayElements.update({},{$pull:{\"TechnicalSubject\":null}});\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })" }, { "code": null, "e": 2579, "s": 2441, "text": "Above, we have removed array element “MongoDB”, which is at index 3. Let us display documents from a collection. The query is as follows:" }, { "code": null, "e": 2621, "s": 2579, "text": "> db.removeArrayElements.find().pretty();" }, { "code": null, "e": 2650, "s": 2621, "text": "The following is the output:" }, { "code": null, "e": 2821, "s": 2650, "text": "{\n \"_id\" : ObjectId(\"5c6ea4879c4643706aef56d2\"),\n \"StudentName\" : \"Larry\",\n \"StudentAge\" : 23,\n \"TechnicalSubject\" : [\n \"C\",\n \"C++\",\n \"Java\"\n ]\n}" }, { "code": null, "e": 2942, "s": 2821, "text": "Look at the above sample output, the index 3 i.e. position 4 has been removed from the array i.e. the element “MongoDB”." } ]
Data Cleaning — How to Handle Missing Values with Pandas | by Indhumathy Chelliah | Towards Data Science
Data Cleaning is one of the important steps in EDA. Data cleaning can be done in many ways. One of them is handling missing values. Let’s learn about how to handle missing values in a dataset. Identify Missing ValuesReplace Missing ValuesFill missing valuesDrop missing values Identify Missing Values Replace Missing Values Fill missing values Drop missing values Different types of missing values: Standard Missing Values Non-standard Missing Values Unexpected Missing Values Blank cells, NaN, n/a → These will be treated by default as null values in Pandas. Standard missing values only can be detected by pandas. Example: I have created a simple dataset having different types of null values Let’s import the dataset df=pd.read_csv(“student.csv”)df.head(10) 2. df.isnull().sum() → It will return the count of null values in each column.It will count only the standard null values. df.isnull().sum() Only 3 standard missing values are counted. [Blank cells, NaN, n/a] 3. df[“Math”].isnull() → It will return a boolean array. True -means null values. df["Math"].isnull() Sometimes missing values will be entered like .., __, — , missing, na, @,??,***, etc. Now let’s check all the unique values in the “Math” and “English” columns. By checking this, we can identify all the non-standard missing values in the dataset. df[“Math”].unique() df[“English”].unique() It will return all the unique values in that particular column. We can identify what are the other values, which are to be treated as “missing values”. From the two columns unique values, we can identify some missing values like na and ?? These are non-standard missing values. Unexpected missing values are identified based on the context of the dataset. Here marks range from 0 to 100 only. So 999999 and X also identified as missing values. df.replace(old_value, new_value) → old_value will be replaced by new_value df.replace(old_value, new_value) → old_value will be replaced by new_value missing_values=['??','na','X','999999']df=df.replace(missing_values,np.NaN)df Now all the missing values are replaced with NaN. Now it’s easy to treat all the null values. We can either drop all null values or fill those by mean/median. Mean/Median, Modebfill,ffillinterpolatereplace Mean/Median, Mode bfill,ffill interpolate replace Numerical Data →Mean/Median Categorical Data →Mode In columns having numerical data, we can fill the missing values by mean/median. Mean — When the data has no outliers. Mean is the average value. Mean will be affected by outliers. [Example. If we are calculating, mean salary of the employees in a room and if the company CEO walks in, the mean will tend to be higher. It can’t be the representative amount. In that scenario, we can choose median] Median — When the data has more outliers, it's best to replace them with the median value. Median is the middle value (50%) In columns having categorical data, we can fill the missing values by mode Mode — Most common value. Let’s fill the missing values by mean First, we have to check the data type of the column. First, we have to check the data type of the column. df.dtypes “Math” and “English” are in “object” datatype. We have to convert to “float” datatype to calculate mean. 2. Changing the datatype of the column and calculating mean df["Math"]=df["Math"].astype("float64")m=round(df["Math"].mean(),2)m Output: 75.83 3. Now filling the missing values in the “Math” column by mean -75.83 df["Math"].fillna(m,inplace=True)df If we want to replace missing values in categorical data, we can replace them with mode(most common value) Let’s replace the null value in the “Role” column Let’s replace the null value in the “Role” column df=pd.read_csv("employee.csv")m=df["Role"].mode()m#Output0 Developerdtype: object 2. It returns a series object, containing the most common value. We have to select the particular value in the series. m=df["Role"].mode()[0]m#Output:'Developer' 3. Fill in the value df["Role"].fillna(m,inplace=True)df bfill — backward fill — It will propagate the first observed non-null value backward.ffill — forward fill — it propagates the last observed non-null value forward. If we have temperature recorded for consecutive days in our dataset, we can fill the missing values by bfill or ffill. It will be more accurate when compared to the mean/median for this type of dataset. bfill bfill df1=pd.read_csv("weather.csv")df1.bfill(inplace=True)df1 2. ffill df1.ffill(inplace=True)df1 interpolate() is one of the methods to fill the missing values. We have missing values for three consecutive days. Instead of filling all three rows with the same value, we can use interpolate method. bfill/ffill will fill the same value for consequent missing values. df2=pd.read_csv("weather1.csv")df2=df2.interpolate()df2 Let’s visualize the dataset after filling consecutive missing values with interpolate method vs bfill import seaborn as snssns.pointplot(x="Day",y="Temp",data=df3,color='darkorange') From the plot, we could see how the missing values are filled by interpolate method [ by default linear method is used] Sometimes we can replace the specific missing values by using replace method. Like we can get data from an external source and replace it. Removing all the null values in the dataset Removing all the null values in the dataset df.dropna() 2. Removing the null values in a specific column df.dropna(subset=["Math"]) Data cleaning involves many steps. I have covered only how to handle missing values in the dataset. There are many more like fixing invalid values, splitting columns, merging columns, filtering subset, standardizing data, scaling data. Thanks for reading! Watch this space for more articles on Python and DataScience. If you like to read more of my tutorials, follow me on Medium, LinkedIn, Twitter. Become a Medium Member by Clicking here: https://indhumathychelliah.medium.com/membership
[ { "code": null, "e": 179, "s": 47, "text": "Data Cleaning is one of the important steps in EDA. Data cleaning can be done in many ways. One of them is handling missing values." }, { "code": null, "e": 240, "s": 179, "text": "Let’s learn about how to handle missing values in a dataset." }, { "code": null, "e": 324, "s": 240, "text": "Identify Missing ValuesReplace Missing ValuesFill missing valuesDrop missing values" }, { "code": null, "e": 348, "s": 324, "text": "Identify Missing Values" }, { "code": null, "e": 371, "s": 348, "text": "Replace Missing Values" }, { "code": null, "e": 391, "s": 371, "text": "Fill missing values" }, { "code": null, "e": 411, "s": 391, "text": "Drop missing values" }, { "code": null, "e": 446, "s": 411, "text": "Different types of missing values:" }, { "code": null, "e": 470, "s": 446, "text": "Standard Missing Values" }, { "code": null, "e": 498, "s": 470, "text": "Non-standard Missing Values" }, { "code": null, "e": 524, "s": 498, "text": "Unexpected Missing Values" }, { "code": null, "e": 607, "s": 524, "text": "Blank cells, NaN, n/a → These will be treated by default as null values in Pandas." }, { "code": null, "e": 663, "s": 607, "text": "Standard missing values only can be detected by pandas." }, { "code": null, "e": 742, "s": 663, "text": "Example: I have created a simple dataset having different types of null values" }, { "code": null, "e": 767, "s": 742, "text": "Let’s import the dataset" }, { "code": null, "e": 808, "s": 767, "text": "df=pd.read_csv(“student.csv”)df.head(10)" }, { "code": null, "e": 931, "s": 808, "text": "2. df.isnull().sum() → It will return the count of null values in each column.It will count only the standard null values." }, { "code": null, "e": 949, "s": 931, "text": "df.isnull().sum()" }, { "code": null, "e": 1017, "s": 949, "text": "Only 3 standard missing values are counted. [Blank cells, NaN, n/a]" }, { "code": null, "e": 1099, "s": 1017, "text": "3. df[“Math”].isnull() → It will return a boolean array. True -means null values." }, { "code": null, "e": 1119, "s": 1099, "text": "df[\"Math\"].isnull()" }, { "code": null, "e": 1205, "s": 1119, "text": "Sometimes missing values will be entered like .., __, — , missing, na, @,??,***, etc." }, { "code": null, "e": 1366, "s": 1205, "text": "Now let’s check all the unique values in the “Math” and “English” columns. By checking this, we can identify all the non-standard missing values in the dataset." }, { "code": null, "e": 1386, "s": 1366, "text": "df[“Math”].unique()" }, { "code": null, "e": 1409, "s": 1386, "text": "df[“English”].unique()" }, { "code": null, "e": 1561, "s": 1409, "text": "It will return all the unique values in that particular column. We can identify what are the other values, which are to be treated as “missing values”." }, { "code": null, "e": 1648, "s": 1561, "text": "From the two columns unique values, we can identify some missing values like na and ??" }, { "code": null, "e": 1687, "s": 1648, "text": "These are non-standard missing values." }, { "code": null, "e": 1853, "s": 1687, "text": "Unexpected missing values are identified based on the context of the dataset. Here marks range from 0 to 100 only. So 999999 and X also identified as missing values." }, { "code": null, "e": 1928, "s": 1853, "text": "df.replace(old_value, new_value) → old_value will be replaced by new_value" }, { "code": null, "e": 2003, "s": 1928, "text": "df.replace(old_value, new_value) → old_value will be replaced by new_value" }, { "code": null, "e": 2081, "s": 2003, "text": "missing_values=['??','na','X','999999']df=df.replace(missing_values,np.NaN)df" }, { "code": null, "e": 2240, "s": 2081, "text": "Now all the missing values are replaced with NaN. Now it’s easy to treat all the null values. We can either drop all null values or fill those by mean/median." }, { "code": null, "e": 2287, "s": 2240, "text": "Mean/Median, Modebfill,ffillinterpolatereplace" }, { "code": null, "e": 2305, "s": 2287, "text": "Mean/Median, Mode" }, { "code": null, "e": 2317, "s": 2305, "text": "bfill,ffill" }, { "code": null, "e": 2329, "s": 2317, "text": "interpolate" }, { "code": null, "e": 2337, "s": 2329, "text": "replace" }, { "code": null, "e": 2365, "s": 2337, "text": "Numerical Data →Mean/Median" }, { "code": null, "e": 2388, "s": 2365, "text": "Categorical Data →Mode" }, { "code": null, "e": 2469, "s": 2388, "text": "In columns having numerical data, we can fill the missing values by mean/median." }, { "code": null, "e": 2569, "s": 2469, "text": "Mean — When the data has no outliers. Mean is the average value. Mean will be affected by outliers." }, { "code": null, "e": 2786, "s": 2569, "text": "[Example. If we are calculating, mean salary of the employees in a room and if the company CEO walks in, the mean will tend to be higher. It can’t be the representative amount. In that scenario, we can choose median]" }, { "code": null, "e": 2910, "s": 2786, "text": "Median — When the data has more outliers, it's best to replace them with the median value. Median is the middle value (50%)" }, { "code": null, "e": 2985, "s": 2910, "text": "In columns having categorical data, we can fill the missing values by mode" }, { "code": null, "e": 3011, "s": 2985, "text": "Mode — Most common value." }, { "code": null, "e": 3049, "s": 3011, "text": "Let’s fill the missing values by mean" }, { "code": null, "e": 3102, "s": 3049, "text": "First, we have to check the data type of the column." }, { "code": null, "e": 3155, "s": 3102, "text": "First, we have to check the data type of the column." }, { "code": null, "e": 3165, "s": 3155, "text": "df.dtypes" }, { "code": null, "e": 3270, "s": 3165, "text": "“Math” and “English” are in “object” datatype. We have to convert to “float” datatype to calculate mean." }, { "code": null, "e": 3330, "s": 3270, "text": "2. Changing the datatype of the column and calculating mean" }, { "code": null, "e": 3399, "s": 3330, "text": "df[\"Math\"]=df[\"Math\"].astype(\"float64\")m=round(df[\"Math\"].mean(),2)m" }, { "code": null, "e": 3413, "s": 3399, "text": "Output: 75.83" }, { "code": null, "e": 3483, "s": 3413, "text": "3. Now filling the missing values in the “Math” column by mean -75.83" }, { "code": null, "e": 3519, "s": 3483, "text": "df[\"Math\"].fillna(m,inplace=True)df" }, { "code": null, "e": 3626, "s": 3519, "text": "If we want to replace missing values in categorical data, we can replace them with mode(most common value)" }, { "code": null, "e": 3676, "s": 3626, "text": "Let’s replace the null value in the “Role” column" }, { "code": null, "e": 3726, "s": 3676, "text": "Let’s replace the null value in the “Role” column" }, { "code": null, "e": 3811, "s": 3726, "text": "df=pd.read_csv(\"employee.csv\")m=df[\"Role\"].mode()m#Output0 Developerdtype: object" }, { "code": null, "e": 3930, "s": 3811, "text": "2. It returns a series object, containing the most common value. We have to select the particular value in the series." }, { "code": null, "e": 3973, "s": 3930, "text": "m=df[\"Role\"].mode()[0]m#Output:'Developer'" }, { "code": null, "e": 3994, "s": 3973, "text": "3. Fill in the value" }, { "code": null, "e": 4030, "s": 3994, "text": "df[\"Role\"].fillna(m,inplace=True)df" }, { "code": null, "e": 4194, "s": 4030, "text": "bfill — backward fill — It will propagate the first observed non-null value backward.ffill — forward fill — it propagates the last observed non-null value forward." }, { "code": null, "e": 4397, "s": 4194, "text": "If we have temperature recorded for consecutive days in our dataset, we can fill the missing values by bfill or ffill. It will be more accurate when compared to the mean/median for this type of dataset." }, { "code": null, "e": 4403, "s": 4397, "text": "bfill" }, { "code": null, "e": 4409, "s": 4403, "text": "bfill" }, { "code": null, "e": 4466, "s": 4409, "text": "df1=pd.read_csv(\"weather.csv\")df1.bfill(inplace=True)df1" }, { "code": null, "e": 4475, "s": 4466, "text": "2. ffill" }, { "code": null, "e": 4502, "s": 4475, "text": "df1.ffill(inplace=True)df1" }, { "code": null, "e": 4566, "s": 4502, "text": "interpolate() is one of the methods to fill the missing values." }, { "code": null, "e": 4703, "s": 4566, "text": "We have missing values for three consecutive days. Instead of filling all three rows with the same value, we can use interpolate method." }, { "code": null, "e": 4771, "s": 4703, "text": "bfill/ffill will fill the same value for consequent missing values." }, { "code": null, "e": 4827, "s": 4771, "text": "df2=pd.read_csv(\"weather1.csv\")df2=df2.interpolate()df2" }, { "code": null, "e": 4929, "s": 4827, "text": "Let’s visualize the dataset after filling consecutive missing values with interpolate method vs bfill" }, { "code": null, "e": 5010, "s": 4929, "text": "import seaborn as snssns.pointplot(x=\"Day\",y=\"Temp\",data=df3,color='darkorange')" }, { "code": null, "e": 5130, "s": 5010, "text": "From the plot, we could see how the missing values are filled by interpolate method [ by default linear method is used]" }, { "code": null, "e": 5208, "s": 5130, "text": "Sometimes we can replace the specific missing values by using replace method." }, { "code": null, "e": 5269, "s": 5208, "text": "Like we can get data from an external source and replace it." }, { "code": null, "e": 5313, "s": 5269, "text": "Removing all the null values in the dataset" }, { "code": null, "e": 5357, "s": 5313, "text": "Removing all the null values in the dataset" }, { "code": null, "e": 5369, "s": 5357, "text": "df.dropna()" }, { "code": null, "e": 5418, "s": 5369, "text": "2. Removing the null values in a specific column" }, { "code": null, "e": 5445, "s": 5418, "text": "df.dropna(subset=[\"Math\"])" }, { "code": null, "e": 5681, "s": 5445, "text": "Data cleaning involves many steps. I have covered only how to handle missing values in the dataset. There are many more like fixing invalid values, splitting columns, merging columns, filtering subset, standardizing data, scaling data." }, { "code": null, "e": 5701, "s": 5681, "text": "Thanks for reading!" }, { "code": null, "e": 5845, "s": 5701, "text": "Watch this space for more articles on Python and DataScience. If you like to read more of my tutorials, follow me on Medium, LinkedIn, Twitter." } ]
“register” keyword in C
Register variables tell the compiler to store the variable in CPU register instead of memory. Frequently used variables are kept in registers and they have faster accessibility. We can never get the addresses of these variables. “register” keyword is used to declare the register variables. Scope − They are local to the function. Default value − Default initialized value is the garbage value. Lifetime − Till the end of the execution of the block in which it is defined. Here is an example of register variable in C language, Live Demo #include <stdio.h> int main() { register char x = 'S'; register int a = 10; auto int b = 8; printf("The value of register variable b : %c\n",x); printf("The sum of auto and register variable : %d",(a+b)); return 0; } The value of register variable b : S The sum of auto and register variable : 18 Register keyword can be used with pointer also. It can have address of memory location. It will not create any error. Here is an example of register keyword in C language Live Demo #include<stdio.h> int main() { int i = 10; register int *a = &i; printf("The value of pointer : %d", *a); getchar(); return 0; } The value of pointer : 10
[ { "code": null, "e": 1353, "s": 1062, "text": "Register variables tell the compiler to store the variable in CPU register instead of memory. Frequently used variables are kept in registers and they have faster accessibility. We can never get the addresses of these variables. “register” keyword is used to declare the register variables." }, { "code": null, "e": 1393, "s": 1353, "text": "Scope − They are local to the function." }, { "code": null, "e": 1457, "s": 1393, "text": "Default value − Default initialized value is the garbage value." }, { "code": null, "e": 1535, "s": 1457, "text": "Lifetime − Till the end of the execution of the block in which it is defined." }, { "code": null, "e": 1590, "s": 1535, "text": "Here is an example of register variable in C language," }, { "code": null, "e": 1601, "s": 1590, "text": " Live Demo" }, { "code": null, "e": 1836, "s": 1601, "text": "#include <stdio.h>\nint main() {\n register char x = 'S';\n register int a = 10;\n auto int b = 8;\n printf(\"The value of register variable b : %c\\n\",x);\n printf(\"The sum of auto and register variable : %d\",(a+b));\n return 0;\n}" }, { "code": null, "e": 1916, "s": 1836, "text": "The value of register variable b : S\nThe sum of auto and register variable : 18" }, { "code": null, "e": 2034, "s": 1916, "text": "Register keyword can be used with pointer also. It can have address of memory location. It will not create any error." }, { "code": null, "e": 2087, "s": 2034, "text": "Here is an example of register keyword in C language" }, { "code": null, "e": 2098, "s": 2087, "text": " Live Demo" }, { "code": null, "e": 2242, "s": 2098, "text": "#include<stdio.h>\nint main() {\n int i = 10;\n register int *a = &i;\n printf(\"The value of pointer : %d\", *a);\n getchar();\n return 0;\n}" }, { "code": null, "e": 2268, "s": 2242, "text": "The value of pointer : 10" } ]
Tryit Editor v3.7
Tryit: HTML text color
[]
Byte Streams in Java
These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using these you can store characters, videos, audios, images etc. The InputStream and OutputStream classes (abstract) are the super classes of all the input/output stream classes: classes that are used to read/write a stream of bytes. Following are the byte array stream classes provided by Java − Following Java program reads data from a particular file using FileInputStream and writes it to another, using FileOutputStream. import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class IOStreamsExample { public static void main(String args[]) throws IOException { //Creating FileInputStream object File file = new File("D:/myFile.txt"); FileInputStream fis = new FileInputStream(file); byte bytes[] = new byte[(int) file.length()]; //Reading data from the file fis.read(bytes); //Writing data to another file File out = new File("D:/CopyOfmyFile.txt"); FileOutputStream outputStream = new FileOutputStream(out); //Writing data to the file outputStream.write(bytes); outputStream.flush(); System.out.println("Data successfully written in the specified file"); } } Data successfully written in the specified file
[ { "code": null, "e": 1221, "s": 1062, "text": "These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using these you can store characters, videos, audios, images etc." }, { "code": null, "e": 1453, "s": 1221, "text": "The InputStream and OutputStream classes (abstract) are the super classes of all the input/output stream classes: classes that are used to read/write a stream of bytes. Following are the byte array stream classes provided by Java −" }, { "code": null, "e": 1582, "s": 1453, "text": "Following Java program reads data from a particular file using FileInputStream and writes it to another, using FileOutputStream." }, { "code": null, "e": 2371, "s": 1582, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\npublic class IOStreamsExample {\n public static void main(String args[]) throws IOException {\n //Creating FileInputStream object\n File file = new File(\"D:/myFile.txt\");\n FileInputStream fis = new FileInputStream(file);\n byte bytes[] = new byte[(int) file.length()];\n //Reading data from the file\n fis.read(bytes);\n //Writing data to another file\n File out = new File(\"D:/CopyOfmyFile.txt\");\n FileOutputStream outputStream = new FileOutputStream(out);\n //Writing data to the file\n outputStream.write(bytes);\n outputStream.flush();\n System.out.println(\"Data successfully written in the specified file\");\n }\n}" }, { "code": null, "e": 2419, "s": 2371, "text": "Data successfully written in the specified file" } ]
Documenting Flask Endpoint using Flask-Autodoc - GeeksforGeeks
04 Jul, 2021 Documentation of endpoints is an essential task in web development and being able to apply it in different frameworks is always a utility. This article discusses how endpoints in Flask can be decorated to generate good documentation of them using the Flask-Autodoc module. This module provides the following features – Helps to document endpoints of application based upon routes, function arguments, and docstrings. Renders on the terminal as well as on HTML templates. Customed grouping and templating provided. To install this module type the below command in the terminal. pip install flask-autodoc After installation, Autodoc class needs to imported and initialized with the application context. And routes need to be defined. doc() : All the routes with this wrapper only will be documented. html() : Generates documentation in HTML format. generate() : Generates documentation in Non-HTML format. Note: The possible error that can occur while using the flask-autodoc is that – ModuleNotFoundError: No module named 'flask.ext' To remove this error open the __init__.py file of the flask_autodoc module and change the from flask.ext.autodoc.autodoc import Autodoc to from flask_autodoc.autodoc import Autodoc Generating documentation in HTML format Python3 from flask import Flask, render_template app = Flask(__name__)from flask_autodoc.autodoc import Autodoc auto = Autodoc(app) # GET [email protected]('/')def index(): return render_template('index.html') # POST [email protected]()@app.route('/add', methods = ['POST'])def post_data(): return render_template('form.html') # GET API with path [email protected]('/gfg/<int:page>')@auto.doc()def gfg(page): return render_template('gfg.html', page=page) # This route generates HTML of [email protected]('/documentation')def documentation(): return auto.html() if __name__ == '__main__': app.run() After running the server, route to /documentation, exact documentation of routes with wrapper .doc() will be displayed.Output : Example 2 : Printing documentation on stdout. This can be achieved using generate() Python3 from flask import Flask, render_template app = Flask(__name__)from flask_autodoc.autodoc import Autodoc auto = Autodoc(app) # GET [email protected]('/')def index(): return render_template('index.html') # POST [email protected]()@app.route('/add', methods = ['POST'])def post_data(): return render_template('form.html') # GET API with path [email protected]('/gfg/<int:page>')@auto.doc()def gfg(page): return render_template('gfg.html', page=page) # This route generates documentation in list # of [email protected]('/documentation')def documentation(): return str(auto.generate()) Output : Explanation: List of rules, with certain parameters. methods : Method allowed (ie [‘GET’, ‘POST’]) rule : Relative Url Structure (ie ‘/gfg/int:page’) endpoint: Function name (ie ‘gfg’) doc : Docstring of the function if provided args : Function arguments if provided ( e.g page ) defaults : Defaults values for the arguments. Example 3 : Working with Custom Templating Apart from the generic template, a custom template with a custom template and other jinja compatible tags can be passed onto HTML for documenting better by passing in auto.html() function. Python3 from flask import Flask, render_template app = Flask(__name__)from flask_autodoc.autodoc import Autodoc auto = Autodoc(app) # GET [email protected]('/')@auto.doc()def index(): return render_template('index.html') # GET API with path [email protected]('/gfg/<int:page>')@auto.doc()def gfg(page): return render_template('gfg.html', page=page) # This route generates documentation in list of rules# in custom [email protected]('/documentation')def documentation(): return auto.html(template='custom_autodoc.html', title='Custom Gfg Flask AutoDoc', author='Manjeet Singh',) if __name__ == '__main__': app.run() Output : Example 4: Working with groups Separate documentation sets can be constructed to keep logics/endpoints abstracted from certain sets according to use cases, or depending upon product requirements of groupings. Each route can be part of 1 or more groups by passing “groups” as list. Python3 from flask import Flask, render_template app = Flask(__name__)from flask_autodoc.autodoc import Autodoc auto = Autodoc(app) @app.route('/')@auto.doc(groups=['red'])def index(): return render_template('index.html') @app.route('/gfg/<int:page>')@auto.doc(groups=['green'])def gfg(page): return render_template('gfg.html', page=page) @app.route('/gfg-red-green')@auto.doc(groups=['green', 'red'])def gfg_all(page): return render_template('gfg-all.html', page=page) @app.route('/gfg-blue-hidden')@auto.doc(groups=['blue'])def gfg_blue(page): return render_template('gfg-blue.html', page=page) # generating red grouped [email protected]('/red')def red(): return auto.html(groups='red') # generating blue grouped [email protected]('/blue')def blue(): return auto.html(groups='blue') # generating green grouped [email protected]('/green')def green(): return auto.html(groups='green') if __name__ == '__main__': app.run() Output : Python Flask Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24316, "s": 24288, "text": "\n04 Jul, 2021" }, { "code": null, "e": 24636, "s": 24316, "text": "Documentation of endpoints is an essential task in web development and being able to apply it in different frameworks is always a utility. This article discusses how endpoints in Flask can be decorated to generate good documentation of them using the Flask-Autodoc module. This module provides the following features – " }, { "code": null, "e": 24734, "s": 24636, "text": "Helps to document endpoints of application based upon routes, function arguments, and docstrings." }, { "code": null, "e": 24788, "s": 24734, "text": "Renders on the terminal as well as on HTML templates." }, { "code": null, "e": 24831, "s": 24788, "text": "Customed grouping and templating provided." }, { "code": null, "e": 24894, "s": 24831, "text": "To install this module type the below command in the terminal." }, { "code": null, "e": 24920, "s": 24894, "text": "pip install flask-autodoc" }, { "code": null, "e": 25050, "s": 24920, "text": "After installation, Autodoc class needs to imported and initialized with the application context. And routes need to be defined. " }, { "code": null, "e": 25116, "s": 25050, "text": "doc() : All the routes with this wrapper only will be documented." }, { "code": null, "e": 25165, "s": 25116, "text": "html() : Generates documentation in HTML format." }, { "code": null, "e": 25222, "s": 25165, "text": "generate() : Generates documentation in Non-HTML format." }, { "code": null, "e": 25228, "s": 25222, "text": "Note:" }, { "code": null, "e": 25303, "s": 25228, "text": "The possible error that can occur while using the flask-autodoc is that – " }, { "code": null, "e": 25352, "s": 25303, "text": "ModuleNotFoundError: No module named 'flask.ext'" }, { "code": null, "e": 25443, "s": 25352, "text": "To remove this error open the __init__.py file of the flask_autodoc module and change the " }, { "code": null, "e": 25534, "s": 25443, "text": "from flask.ext.autodoc.autodoc import Autodoc\nto\nfrom flask_autodoc.autodoc import Autodoc" }, { "code": null, "e": 25575, "s": 25534, "text": "Generating documentation in HTML format " }, { "code": null, "e": 25583, "s": 25575, "text": "Python3" }, { "code": "from flask import Flask, render_template app = Flask(__name__)from flask_autodoc.autodoc import Autodoc auto = Autodoc(app) # GET [email protected]('/')def index(): return render_template('index.html') # POST [email protected]()@app.route('/add', methods = ['POST'])def post_data(): return render_template('form.html') # GET API with path [email protected]('/gfg/<int:page>')@auto.doc()def gfg(page): return render_template('gfg.html', page=page) # This route generates HTML of [email protected]('/documentation')def documentation(): return auto.html() if __name__ == '__main__': app.run()", "e": 26194, "s": 25583, "text": null }, { "code": null, "e": 26322, "s": 26194, "text": "After running the server, route to /documentation, exact documentation of routes with wrapper .doc() will be displayed.Output :" }, { "code": null, "e": 26369, "s": 26322, "text": "Example 2 : Printing documentation on stdout. " }, { "code": null, "e": 26407, "s": 26369, "text": "This can be achieved using generate()" }, { "code": null, "e": 26415, "s": 26407, "text": "Python3" }, { "code": "from flask import Flask, render_template app = Flask(__name__)from flask_autodoc.autodoc import Autodoc auto = Autodoc(app) # GET [email protected]('/')def index(): return render_template('index.html') # POST [email protected]()@app.route('/add', methods = ['POST'])def post_data(): return render_template('form.html') # GET API with path [email protected]('/gfg/<int:page>')@auto.doc()def gfg(page): return render_template('gfg.html', page=page) # This route generates documentation in list # of [email protected]('/documentation')def documentation(): return str(auto.generate())", "e": 27001, "s": 26415, "text": null }, { "code": null, "e": 27011, "s": 27001, "text": "Output : " }, { "code": null, "e": 27065, "s": 27011, "text": "Explanation: List of rules, with certain parameters. " }, { "code": null, "e": 27111, "s": 27065, "text": "methods : Method allowed (ie [‘GET’, ‘POST’])" }, { "code": null, "e": 27162, "s": 27111, "text": "rule : Relative Url Structure (ie ‘/gfg/int:page’)" }, { "code": null, "e": 27197, "s": 27162, "text": "endpoint: Function name (ie ‘gfg’)" }, { "code": null, "e": 27241, "s": 27197, "text": "doc : Docstring of the function if provided" }, { "code": null, "e": 27292, "s": 27241, "text": "args : Function arguments if provided ( e.g page )" }, { "code": null, "e": 27338, "s": 27292, "text": "defaults : Defaults values for the arguments." }, { "code": null, "e": 27381, "s": 27338, "text": "Example 3 : Working with Custom Templating" }, { "code": null, "e": 27570, "s": 27381, "text": "Apart from the generic template, a custom template with a custom template and other jinja compatible tags can be passed onto HTML for documenting better by passing in auto.html() function." }, { "code": null, "e": 27578, "s": 27570, "text": "Python3" }, { "code": "from flask import Flask, render_template app = Flask(__name__)from flask_autodoc.autodoc import Autodoc auto = Autodoc(app) # GET [email protected]('/')@auto.doc()def index(): return render_template('index.html') # GET API with path [email protected]('/gfg/<int:page>')@auto.doc()def gfg(page): return render_template('gfg.html', page=page) # This route generates documentation in list of rules# in custom [email protected]('/documentation')def documentation(): return auto.html(template='custom_autodoc.html', title='Custom Gfg Flask AutoDoc', author='Manjeet Singh',) if __name__ == '__main__': app.run()", "e": 28239, "s": 27578, "text": null }, { "code": null, "e": 28249, "s": 28239, "text": "Output : " }, { "code": null, "e": 28280, "s": 28249, "text": "Example 4: Working with groups" }, { "code": null, "e": 28530, "s": 28280, "text": "Separate documentation sets can be constructed to keep logics/endpoints abstracted from certain sets according to use cases, or depending upon product requirements of groupings. Each route can be part of 1 or more groups by passing “groups” as list." }, { "code": null, "e": 28538, "s": 28530, "text": "Python3" }, { "code": "from flask import Flask, render_template app = Flask(__name__)from flask_autodoc.autodoc import Autodoc auto = Autodoc(app) @app.route('/')@auto.doc(groups=['red'])def index(): return render_template('index.html') @app.route('/gfg/<int:page>')@auto.doc(groups=['green'])def gfg(page): return render_template('gfg.html', page=page) @app.route('/gfg-red-green')@auto.doc(groups=['green', 'red'])def gfg_all(page): return render_template('gfg-all.html', page=page) @app.route('/gfg-blue-hidden')@auto.doc(groups=['blue'])def gfg_blue(page): return render_template('gfg-blue.html', page=page) # generating red grouped [email protected]('/red')def red(): return auto.html(groups='red') # generating blue grouped [email protected]('/blue')def blue(): return auto.html(groups='blue') # generating green grouped [email protected]('/green')def green(): return auto.html(groups='green') if __name__ == '__main__': app.run()", "e": 29493, "s": 28538, "text": null }, { "code": null, "e": 29503, "s": 29493, "text": "Output : " }, { "code": null, "e": 29516, "s": 29503, "text": "Python Flask" }, { "code": null, "e": 29523, "s": 29516, "text": "Python" }, { "code": null, "e": 29621, "s": 29523, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29653, "s": 29621, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29695, "s": 29653, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29751, "s": 29695, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29793, "s": 29751, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29848, "s": 29793, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 29879, "s": 29848, "text": "Python | os.path.join() method" }, { "code": null, "e": 29901, "s": 29879, "text": "Defaultdict in Python" }, { "code": null, "e": 29930, "s": 29901, "text": "Create a directory in Python" }, { "code": null, "e": 29969, "s": 29930, "text": "Python | Get unique values from a list" } ]
What is the difference between JavaScript and C++?
The following are the differences between JavaScript and C++. JavaScript is a lightweight, interpreted programming language. It is designed for creating network-centric applications. It is complementary to and integrated with Java. JavaScript is very easy to implement because it is integrated with HTML. It is open and cross-platform. C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. JavaScript is a scripting whereas C++ is a programming language. C++ program is to be compiled and executed, whereas a script in JavaScript is interpreted. JavaScript is dynamically typed whereas C++ is statically typed. In Java, you have to declare the type of the variable with the variable, for example, int a; float f; In JavaScript, you need to only write the variable name, without adding the type. After that, you can assign the value like 5 for int, “amit” for string, etc. var a; var f JavaScript supports Java virtual machine implementation, whereas C++ does not support Java virtual machine implementation. C++ support procedural and generic programming. JavaScript support reflective programming
[ { "code": null, "e": 1124, "s": 1062, "text": "The following are the differences between JavaScript and C++." }, { "code": null, "e": 1398, "s": 1124, "text": "JavaScript is a lightweight, interpreted programming language. It is designed for creating network-centric applications. It is complementary to and integrated with Java. JavaScript is very easy to implement because it is integrated with HTML. It is open and cross-platform." }, { "code": null, "e": 1597, "s": 1398, "text": "C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX." }, { "code": null, "e": 1662, "s": 1597, "text": "JavaScript is a scripting whereas C++ is a programming language." }, { "code": null, "e": 1753, "s": 1662, "text": "C++ program is to be compiled and executed, whereas a script in JavaScript is interpreted." }, { "code": null, "e": 1818, "s": 1753, "text": "JavaScript is dynamically typed whereas C++ is statically typed." }, { "code": null, "e": 1904, "s": 1818, "text": "In Java, you have to declare the type of the variable with the variable, for example," }, { "code": null, "e": 1920, "s": 1904, "text": "int a;\nfloat f;" }, { "code": null, "e": 2079, "s": 1920, "text": "In JavaScript, you need to only write the variable name, without adding the type. After that, you can assign the value like 5 for int, “amit” for string, etc." }, { "code": null, "e": 2092, "s": 2079, "text": "var a; var f" }, { "code": null, "e": 2215, "s": 2092, "text": "JavaScript supports Java virtual machine implementation, whereas C++ does not support Java virtual machine implementation." }, { "code": null, "e": 2305, "s": 2215, "text": "C++ support procedural and generic programming. JavaScript support reflective programming" } ]
Check if all digits of a number divide it in Python
Suppose we have a number n. We have to check whether all digits of it can divide n or not. So, if the input is like n = 135, then the output will be True, because (135 / 1 = 135), (135 / 3 = 45) and (135 / 5 = 27). To solve this, we will follow these steps − val := n while val > 0, dod := val mod 10if n is not divisible by d, thenreturn Falseval := quotient of (val / 10) d := val mod 10 if n is not divisible by d, thenreturn False return False val := quotient of (val / 10) return True Let us see the following implementation to get better understanding − Live Demo def is_divisible(n, d) : return d != 0 and n % d == 0 def solve(n) : val = n while (val > 0) : d = val % 10 if not is_divisible(n, d): return False val = val // 10 return True n = 135 print(solve(n)) 135 True
[ { "code": null, "e": 1153, "s": 1062, "text": "Suppose we have a number n. We have to check whether all digits of it can divide n or not." }, { "code": null, "e": 1277, "s": 1153, "text": "So, if the input is like n = 135, then the output will be True, because (135 / 1 = 135), (135 / 3 = 45) and (135 / 5 = 27)." }, { "code": null, "e": 1321, "s": 1277, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1330, "s": 1321, "text": "val := n" }, { "code": null, "e": 1436, "s": 1330, "text": "while val > 0, dod := val mod 10if n is not divisible by d, thenreturn Falseval := quotient of (val / 10)" }, { "code": null, "e": 1452, "s": 1436, "text": "d := val mod 10" }, { "code": null, "e": 1497, "s": 1452, "text": "if n is not divisible by d, thenreturn False" }, { "code": null, "e": 1510, "s": 1497, "text": "return False" }, { "code": null, "e": 1540, "s": 1510, "text": "val := quotient of (val / 10)" }, { "code": null, "e": 1552, "s": 1540, "text": "return True" }, { "code": null, "e": 1622, "s": 1552, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1633, "s": 1622, "text": " Live Demo" }, { "code": null, "e": 1866, "s": 1633, "text": "def is_divisible(n, d) :\n return d != 0 and n % d == 0\ndef solve(n) :\n val = n\n while (val > 0) :\n d = val % 10\n if not is_divisible(n, d):\n return False\n val = val // 10\n return True\nn = 135\nprint(solve(n))" }, { "code": null, "e": 1870, "s": 1866, "text": "135" }, { "code": null, "e": 1875, "s": 1870, "text": "True" } ]
How to create a separator using JavaFX?
A separator is a horizontal or, the vertical line separating the UI elements of an application. In JavaFX the javafx.scene.control.Separator class represents a separator, to create a separator you need to instantiate this class. This class has three properties namely − halignment − This property specifies the horizontal alignment of a vertical separator. You can set value to this, using the setHalignment() method halignment − This property specifies the horizontal alignment of a vertical separator. You can set value to this, using the setHalignment() method orientation − This property specifies the orientation of the current separator i.e. horizontal or vertical. You can set value to this property using the setOrientation() method. orientation − This property specifies the orientation of the current separator i.e. horizontal or vertical. You can set value to this property using the setOrientation() method. valignment − This property specifies the vertical alignment of a horizontal separator. You can set value to this, using the setValignment() method valignment − This property specifies the vertical alignment of a horizontal separator. You can set value to this, using the setValignment() method By default the separator class creates a horizontal separator, to create a vertical separator you need to change its orientation using the setOrientation() method. import javafx.application.Application; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.Separator; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.stage.Stage; public class SeparatorExample extends Application { public void start(Stage stage) { //Creating the check boxes CheckBox checkBox1 = new CheckBox("Hindi"); CheckBox checkBox2 = new CheckBox("Gujarathi"); CheckBox checkBox3 = new CheckBox("Punjabi"); CheckBox checkBox4 = new CheckBox("Telugu"); CheckBox checkBox5 = new CheckBox("Tamil"); CheckBox checkBox6= new CheckBox("Malayalam"); //Creating a label Label label = new Label("Select known languages:"); Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12); label.setFont(font); //Creating a separator Separator sep = new Separator(); sep.setMaxWidth(80); sep.setHalignment(HPos.CENTER); //Adding the check boxes and separator to the pane VBox vBox = new VBox(5); vBox.setPadding(new Insets(5, 5, 5, 50)); vBox.getChildren().addAll(label, checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6); //Adding the separator after the 3rd check box vBox.getChildren().add(4, sep); //Setting the stage Scene scene = new Scene(vBox, 595, 200, Color.BEIGE); stage.setTitle("Seperator Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1158, "s": 1062, "text": "A separator is a horizontal or, the vertical line separating the UI elements of an application." }, { "code": null, "e": 1332, "s": 1158, "text": "In JavaFX the javafx.scene.control.Separator class represents a separator, to create a separator you need to instantiate this class. This class has three properties namely −" }, { "code": null, "e": 1479, "s": 1332, "text": "halignment − This property specifies the horizontal alignment of a vertical separator. You can set value to this, using the setHalignment() method" }, { "code": null, "e": 1626, "s": 1479, "text": "halignment − This property specifies the horizontal alignment of a vertical separator. You can set value to this, using the setHalignment() method" }, { "code": null, "e": 1804, "s": 1626, "text": "orientation − This property specifies the orientation of the current separator i.e. horizontal or vertical. You can set value to this property using the setOrientation() method." }, { "code": null, "e": 1982, "s": 1804, "text": "orientation − This property specifies the orientation of the current separator i.e. horizontal or vertical. You can set value to this property using the setOrientation() method." }, { "code": null, "e": 2129, "s": 1982, "text": "valignment − This property specifies the vertical alignment of a horizontal separator. You can set value to this, using the setValignment() method" }, { "code": null, "e": 2276, "s": 2129, "text": "valignment − This property specifies the vertical alignment of a horizontal separator. You can set value to this, using the setValignment() method" }, { "code": null, "e": 2440, "s": 2276, "text": "By default the separator class creates a horizontal separator, to create a vertical separator you need to change its orientation using the setOrientation() method." }, { "code": null, "e": 4225, "s": 2440, "text": "import javafx.application.Application;\nimport javafx.geometry.HPos;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.control.CheckBox;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.Separator;\nimport javafx.scene.layout.VBox;\nimport javafx.scene.paint.Color;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.FontPosture;\nimport javafx.scene.text.FontWeight;\nimport javafx.stage.Stage;\npublic class SeparatorExample extends Application {\n public void start(Stage stage) {\n //Creating the check boxes\n CheckBox checkBox1 = new CheckBox(\"Hindi\");\n CheckBox checkBox2 = new CheckBox(\"Gujarathi\");\n CheckBox checkBox3 = new CheckBox(\"Punjabi\");\n CheckBox checkBox4 = new CheckBox(\"Telugu\");\n CheckBox checkBox5 = new CheckBox(\"Tamil\");\n CheckBox checkBox6= new CheckBox(\"Malayalam\");\n //Creating a label\n Label label = new Label(\"Select known languages:\");\n Font font = Font.font(\"verdana\", FontWeight.BOLD, FontPosture.REGULAR, 12);\n label.setFont(font);\n //Creating a separator\n Separator sep = new Separator();\n sep.setMaxWidth(80);\n sep.setHalignment(HPos.CENTER);\n //Adding the check boxes and separator to the pane\n VBox vBox = new VBox(5);\n vBox.setPadding(new Insets(5, 5, 5, 50));\n vBox.getChildren().addAll(label, checkBox1, checkBox2, checkBox3,\n checkBox4, checkBox5, checkBox6);\n //Adding the separator after the 3rd check box\n vBox.getChildren().add(4, sep);\n //Setting the stage\n Scene scene = new Scene(vBox, 595, 200, Color.BEIGE);\n stage.setTitle(\"Seperator Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
How to call multiple JavaScript functions in onclick event?
To call multiple JavaScript functions in on click event, use a semicolon as shown below − onclick="Display1();Display2()" Live Demo <html> <head> <script> function Display1() { document.write ("Hello there!"); } function Display2() { document.write ("Hello World!"); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type = "button" onclick = "Display1(); Display2()" value = "Result"> </form> </body> </html>
[ { "code": null, "e": 1152, "s": 1062, "text": "To call multiple JavaScript functions in on click event, use a semicolon as shown below −" }, { "code": null, "e": 1184, "s": 1152, "text": "onclick=\"Display1();Display2()\"" }, { "code": null, "e": 1194, "s": 1184, "text": "Live Demo" }, { "code": null, "e": 1629, "s": 1194, "text": "<html>\n <head>\n <script>\n function Display1() {\n document.write (\"Hello there!\");\n }\n function Display2() {\n document.write (\"Hello World!\");\n }\n </script>\n </head>\n <body>\n <p>Click the following button to call the function</p>\n <form>\n <input type = \"button\" onclick = \"Display1(); Display2()\" value = \"Result\">\n </form>\n </body>\n</html>" } ]
numpy.zeros_like() in Python - GeeksforGeeks
28 Mar, 2022 This numpy method returns an array of given shape and type as given array, with zeros. Syntax: numpy.zeros_like(array, dtype = None, order = 'K', subok = True) Parameters : array : array_like input subok : [optional, boolean]If true, then newly created array will be sub-class of array; otherwise, a base-class array order : C_contiguous or F_contiguous C-contiguous order in memory(last index varies the fastest) C order means that operating row-rise on the array will be slightly quicker FORTRAN-contiguous order in memory (first index varies the fastest). F order means that column-wise operations will be faster. dtype : [optional, float(byDefault)] Data type of returned array. Returns : ndarray of zeros having given shape, order and datatype. Code 1 : Python # Python Programming illustrating# numpy.zeros_like method import numpy as geek array = geek.arange(10).reshape(5, 2)print("Original array : \n", array) b = geek.zeros_like(array, float)print("\nMatrix b : \n", b) array = geek.arange(8)c = geek.zeros_like(array)print("\nMatrix c : \n", c) Output: Original array : [[0 1] [2 3] [4 5] [6 7] [8 9]] Matrix b : [[ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.]] Matrix c : [0 0 0 0 0 0 0 0] Code 2 : Python # Python Programming illustrating# numpy.zeros_like method import numpy as geek array = geek.arange(10).reshape(5, 2)print("Original array : \n", array) array = geek.arange(4).reshape(2, 2)c = geek.zeros_like(array, dtype = 'float')print("\nMatrix : \n", c) array = geek.arange(8)c = geek.zeros_like(array, dtype = 'float', order ='C')print("\nMatrix : \n", c) Output : Original array : [[0 1] [2 3] [4 5] [6 7] [8 9]] Matrix : [[ 0. 0.] [ 0. 0.]] Matrix : [ 0. 0. 0. 0. 0. 0. 0. 0.] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.zeros_like.html#numpy.zeros_like Note : Also, these codes won’t run on online IDE’s. Please run them on your systems to explore the workingThis article is contributed by Mohit Gupta_OMG . 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. Akanksha_Rai kapoorsagar226 avtarkumar719 kothavvsaakash Pyhton numpy-arrayCreation 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 ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n28 Mar, 2022" }, { "code": null, "e": 24381, "s": 24292, "text": "This numpy method returns an array of given shape and type as given array, with zeros. " }, { "code": null, "e": 24454, "s": 24381, "text": "Syntax: numpy.zeros_like(array, dtype = None, order = 'K', subok = True)" }, { "code": null, "e": 24468, "s": 24454, "text": "Parameters : " }, { "code": null, "e": 25038, "s": 24468, "text": "array : array_like input\nsubok : [optional, boolean]If true, then newly created array will be sub-class of array; \n otherwise, a base-class array\norder : C_contiguous or F_contiguous\n C-contiguous order in memory(last index varies the fastest)\n C order means that operating row-rise on the array will be slightly quicker\n FORTRAN-contiguous order in memory (first index varies the fastest).\n F order means that column-wise operations will be faster. \ndtype : [optional, float(byDefault)] Data type of returned array. " }, { "code": null, "e": 25049, "s": 25038, "text": "Returns : " }, { "code": null, "e": 25106, "s": 25049, "text": "ndarray of zeros having given shape, order and datatype." }, { "code": null, "e": 25117, "s": 25106, "text": "Code 1 : " }, { "code": null, "e": 25124, "s": 25117, "text": "Python" }, { "code": "# Python Programming illustrating# numpy.zeros_like method import numpy as geek array = geek.arange(10).reshape(5, 2)print(\"Original array : \\n\", array) b = geek.zeros_like(array, float)print(\"\\nMatrix b : \\n\", b) array = geek.arange(8)c = geek.zeros_like(array)print(\"\\nMatrix c : \\n\", c)", "e": 25415, "s": 25124, "text": null }, { "code": null, "e": 25424, "s": 25415, "text": "Output: " }, { "code": null, "e": 25581, "s": 25424, "text": "Original array : \n [[0 1]\n [2 3]\n [4 5]\n [6 7]\n [8 9]]\n\nMatrix b : \n [[ 0. 0.]\n [ 0. 0.]\n [ 0. 0.]\n [ 0. 0.]\n [ 0. 0.]]\n\nMatrix c : \n [0 0 0 0 0 0 0 0]" }, { "code": null, "e": 25591, "s": 25581, "text": "Code 2 : " }, { "code": null, "e": 25598, "s": 25591, "text": "Python" }, { "code": "# Python Programming illustrating# numpy.zeros_like method import numpy as geek array = geek.arange(10).reshape(5, 2)print(\"Original array : \\n\", array) array = geek.arange(4).reshape(2, 2)c = geek.zeros_like(array, dtype = 'float')print(\"\\nMatrix : \\n\", c) array = geek.arange(8)c = geek.zeros_like(array, dtype = 'float', order ='C')print(\"\\nMatrix : \\n\", c)", "e": 25961, "s": 25598, "text": null }, { "code": null, "e": 25971, "s": 25961, "text": "Output : " }, { "code": null, "e": 26109, "s": 25971, "text": "Original array : \n [[0 1]\n [2 3]\n [4 5]\n [6 7]\n [8 9]]\n\nMatrix : \n [[ 0. 0.]\n [ 0. 0.]]\n\nMatrix : \n [ 0. 0. 0. 0. 0. 0. 0. 0.]" }, { "code": null, "e": 26748, "s": 26109, "text": "References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.zeros_like.html#numpy.zeros_like Note : Also, these codes won’t run on online IDE’s. Please run them on your systems to explore the workingThis article is contributed by Mohit Gupta_OMG . 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": 26761, "s": 26748, "text": "Akanksha_Rai" }, { "code": null, "e": 26776, "s": 26761, "text": "kapoorsagar226" }, { "code": null, "e": 26790, "s": 26776, "text": "avtarkumar719" }, { "code": null, "e": 26805, "s": 26790, "text": "kothavvsaakash" }, { "code": null, "e": 26832, "s": 26805, "text": "Pyhton numpy-arrayCreation" }, { "code": null, "e": 26845, "s": 26832, "text": "Python-numpy" }, { "code": null, "e": 26852, "s": 26845, "text": "Python" }, { "code": null, "e": 26950, "s": 26852, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26982, "s": 26950, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27038, "s": 26982, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27080, "s": 27038, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27122, "s": 27080, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27144, "s": 27122, "text": "Defaultdict in Python" }, { "code": null, "e": 27183, "s": 27144, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27214, "s": 27183, "text": "Python | os.path.join() method" }, { "code": null, "e": 27269, "s": 27214, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27298, "s": 27269, "text": "Create a directory in Python" } ]
Python | Pandas Period.qyear - GeeksforGeeks
06 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Period.qyear attribute return the fiscal year the Period lies in according to its starting-quarter. The year and the qyear of the period will be the same if the fiscal and calendar years are the same. When they are not, the fiscal year can be different from the calendar year of the period. Syntax : Period.qyear Parameters : None Return : fiscal year Example #1: Use Period.qyear attribute to find the fiscal year the period lies in for the given Period object. # importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='S', year = 2000, month = 2, day = 21, hour = 8, minute = 21) # Print the Period objectprint(prd) Output : Now we will use the Period.qyear attribute to find the fiscal year # return the fiscal yearprd.qyear Output : As we can see in the output, the Period.qyear attribute has returned 2000 indicating that the given period lies in the year of 2000. Example #2: Use Period.qyear attribute to find the fiscal year the period lies in for the given Period object. # importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='T', year = 2006, month = 10, hour = 15, minute = 49) # Print the Period objectprint(prd) Output : Now we will use the Period.qyear attribute to find the fiscal year # return the fiscal yearprd.qyear Output : As we can see in the output, the Period.qyear attribute has returned 2006 indicating that the given period lies in the year of 2006. Pandas scalar-period Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n06 Jan, 2019" }, { "code": null, "e": 24506, "s": 24292, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 24804, "s": 24506, "text": "Pandas Period.qyear attribute return the fiscal year the Period lies in according to its starting-quarter. The year and the qyear of the period will be the same if the fiscal and calendar years are the same. When they are not, the fiscal year can be different from the calendar year of the period." }, { "code": null, "e": 24826, "s": 24804, "text": "Syntax : Period.qyear" }, { "code": null, "e": 24844, "s": 24826, "text": "Parameters : None" }, { "code": null, "e": 24865, "s": 24844, "text": "Return : fiscal year" }, { "code": null, "e": 24976, "s": 24865, "text": "Example #1: Use Period.qyear attribute to find the fiscal year the period lies in for the given Period object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='S', year = 2000, month = 2, day = 21, hour = 8, minute = 21) # Print the Period objectprint(prd)", "e": 25185, "s": 24976, "text": null }, { "code": null, "e": 25194, "s": 25185, "text": "Output :" }, { "code": null, "e": 25261, "s": 25194, "text": "Now we will use the Period.qyear attribute to find the fiscal year" }, { "code": "# return the fiscal yearprd.qyear", "e": 25295, "s": 25261, "text": null }, { "code": null, "e": 25304, "s": 25295, "text": "Output :" }, { "code": null, "e": 25437, "s": 25304, "text": "As we can see in the output, the Period.qyear attribute has returned 2000 indicating that the given period lies in the year of 2000." }, { "code": null, "e": 25548, "s": 25437, "text": "Example #2: Use Period.qyear attribute to find the fiscal year the period lies in for the given Period object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='T', year = 2006, month = 10, hour = 15, minute = 49) # Print the Period objectprint(prd)", "e": 25759, "s": 25548, "text": null }, { "code": null, "e": 25768, "s": 25759, "text": "Output :" }, { "code": null, "e": 25835, "s": 25768, "text": "Now we will use the Period.qyear attribute to find the fiscal year" }, { "code": "# return the fiscal yearprd.qyear", "e": 25869, "s": 25835, "text": null }, { "code": null, "e": 25878, "s": 25869, "text": "Output :" }, { "code": null, "e": 26011, "s": 25878, "text": "As we can see in the output, the Period.qyear attribute has returned 2006 indicating that the given period lies in the year of 2006." }, { "code": null, "e": 26032, "s": 26011, "text": "Pandas scalar-period" }, { "code": null, "e": 26046, "s": 26032, "text": "Python-pandas" }, { "code": null, "e": 26053, "s": 26046, "text": "Python" }, { "code": null, "e": 26151, "s": 26053, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26183, "s": 26151, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26225, "s": 26183, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26281, "s": 26225, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26323, "s": 26281, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26354, "s": 26323, "text": "Python | os.path.join() method" }, { "code": null, "e": 26409, "s": 26354, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26431, "s": 26409, "text": "Defaultdict in Python" }, { "code": null, "e": 26470, "s": 26431, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26499, "s": 26470, "text": "Create a directory in Python" } ]
Add elements to LinkedHashMap collection in Java
Use the put() method to add elements to LinkedHashMap collection. First, let us create a LinkedHashMap − LinkedHashMap<String, String> l = new LinkedHashMap<String, String>(); Now, add elements − l.put("1", "Jack"); l.put("2", "Tom"); l.put("3", "Jimmy"); l.put("4", "Morgan"); l.put("5", "Tim"); l.put("6", "Brad"); The following is an example to add elements to LinkedHashMap collection − Live Demo import java.util.LinkedHashMap; public class Demo { public static void main(String[] args) { LinkedHashMap<String, String> l = new LinkedHashMap<String, String>(); l.put("1", "Jack"); l.put("2", "Tom"); l.put("3", "Jimmy"); l.put("4", "Morgan"); l.put("5", "Tim"); l.put("6", "Brad"); System.out.println("LinkedHashMap elements\n"+l); } } LinkedHashMap elements {1=Jack, 2=Tom, 3=Jimmy, 4=Morgan, 5=Tim, 6=Brad}
[ { "code": null, "e": 1128, "s": 1062, "text": "Use the put() method to add elements to LinkedHashMap collection." }, { "code": null, "e": 1167, "s": 1128, "text": "First, let us create a LinkedHashMap −" }, { "code": null, "e": 1238, "s": 1167, "text": "LinkedHashMap<String, String> l = new LinkedHashMap<String, String>();" }, { "code": null, "e": 1258, "s": 1238, "text": "Now, add elements −" }, { "code": null, "e": 1379, "s": 1258, "text": "l.put(\"1\", \"Jack\");\nl.put(\"2\", \"Tom\");\nl.put(\"3\", \"Jimmy\");\nl.put(\"4\", \"Morgan\");\nl.put(\"5\", \"Tim\");\nl.put(\"6\", \"Brad\");" }, { "code": null, "e": 1453, "s": 1379, "text": "The following is an example to add elements to LinkedHashMap collection −" }, { "code": null, "e": 1464, "s": 1453, "text": " Live Demo" }, { "code": null, "e": 1857, "s": 1464, "text": "import java.util.LinkedHashMap;\npublic class Demo {\n public static void main(String[] args) {\n LinkedHashMap<String, String> l = new LinkedHashMap<String, String>();\n l.put(\"1\", \"Jack\");\n l.put(\"2\", \"Tom\");\n l.put(\"3\", \"Jimmy\");\n l.put(\"4\", \"Morgan\");\n l.put(\"5\", \"Tim\");\n l.put(\"6\", \"Brad\");\n System.out.println(\"LinkedHashMap elements\\n\"+l);\n }\n}" }, { "code": null, "e": 1930, "s": 1857, "text": "LinkedHashMap elements\n{1=Jack, 2=Tom, 3=Jimmy, 4=Morgan, 5=Tim, 6=Brad}" } ]
Python Number uniform() Method
Python number method uniform() returns a random float r, such that x is less than or equal to r and r is less than y. Following is the syntax for uniform() method − uniform(x, y) Note − This function is not accessible directly, so we need to import uniform module and then we need to call this function using random static object. x − Sets the lower limit of the random float. x − Sets the lower limit of the random float. y − Sets the upper limit of the random float. y − Sets the upper limit of the random float. This method returns a floating point number. The following example shows the usage of uniform() method. #!/usr/bin/python import random print "Random Float uniform(5, 10) : ", random.uniform(5, 10) print "Random Float uniform(7, 14) : ", random.uniform(7, 14) Let us run the above program, this will produce the following result − Random Float uniform(5, 10) : 5.52615217015 Random Float uniform(7, 14) : 12.5326369199 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": 2362, "s": 2244, "text": "Python number method uniform() returns a random float r, such that x is less than or equal to r and r is less than y." }, { "code": null, "e": 2409, "s": 2362, "text": "Following is the syntax for uniform() method −" }, { "code": null, "e": 2424, "s": 2409, "text": "uniform(x, y)\n" }, { "code": null, "e": 2576, "s": 2424, "text": "Note − This function is not accessible directly, so we need to import uniform module and then we need to call this function using random static object." }, { "code": null, "e": 2622, "s": 2576, "text": "x − Sets the lower limit of the random float." }, { "code": null, "e": 2668, "s": 2622, "text": "x − Sets the lower limit of the random float." }, { "code": null, "e": 2714, "s": 2668, "text": "y − Sets the upper limit of the random float." }, { "code": null, "e": 2760, "s": 2714, "text": "y − Sets the upper limit of the random float." }, { "code": null, "e": 2805, "s": 2760, "text": "This method returns a floating point number." }, { "code": null, "e": 2864, "s": 2805, "text": "The following example shows the usage of uniform() method." }, { "code": null, "e": 3023, "s": 2864, "text": "#!/usr/bin/python\nimport random\n\nprint \"Random Float uniform(5, 10) : \", random.uniform(5, 10)\nprint \"Random Float uniform(7, 14) : \", random.uniform(7, 14)" }, { "code": null, "e": 3094, "s": 3023, "text": "Let us run the above program, this will produce the following result −" }, { "code": null, "e": 3185, "s": 3094, "text": "Random Float uniform(5, 10) : 5.52615217015\nRandom Float uniform(7, 14) : 12.5326369199\n" }, { "code": null, "e": 3222, "s": 3185, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3238, "s": 3222, "text": " Malhar Lathkar" }, { "code": null, "e": 3271, "s": 3238, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3290, "s": 3271, "text": " Arnab Chakraborty" }, { "code": null, "e": 3325, "s": 3290, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3347, "s": 3325, "text": " In28Minutes Official" }, { "code": null, "e": 3381, "s": 3347, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3409, "s": 3381, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3444, "s": 3409, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3458, "s": 3444, "text": " Lets Kode It" }, { "code": null, "e": 3491, "s": 3458, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3508, "s": 3491, "text": " Abhilash Nelson" }, { "code": null, "e": 3515, "s": 3508, "text": " Print" }, { "code": null, "e": 3526, "s": 3515, "text": " Add Notes" } ]
How to add radio button list in alert dialog?
This example demonstrate about how to add radio button list in alert dialog Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent"> <TextView android:id = "@+id/click" android:layout_width = "wrap_content" android:textSize = "30sp" android:layout_height = "wrap_content" android:text = "Click"/> </LinearLayout> In the above code, we have taken text view. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.annotation.TargetApi; import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { TextView text; @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = findViewById(R.id.click); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showAlertDialog(); } }); } private void showAlertDialog() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); alertDialog.setTitle("AlertDialog"); String[] items = {"java","android","Data Structures","HTML","CSS"}; int checkedItem = 1; alertDialog.setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: Toast.makeText(MainActivity.this, "Clicked on java", Toast.LENGTH_LONG).show(); break; case 1: Toast.makeText(MainActivity.this, "Clicked on android", Toast.LENGTH_LONG).show(); break; case 2: Toast.makeText(MainActivity.this, "Clicked on Data Structures", Toast.LENGTH_LONG).show(); break; case 3: Toast.makeText(MainActivity.this, "Clicked on HTML", Toast.LENGTH_LONG).show(); break; case 4: Toast.makeText(MainActivity.this, "Clicked on CSS", Toast.LENGTH_LONG).show(); break; } } }); AlertDialog alert = alertDialog.create(); alert.setCanceledOnTouchOutside(false); alert.show(); } } 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 – Now click on textview to open Alert Dialog.
[ { "code": null, "e": 1138, "s": 1062, "text": "This example demonstrate about how to add radio button list in alert dialog" }, { "code": null, "e": 1267, "s": 1138, "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": 1332, "s": 1267, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1777, "s": 1332, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\">\n <TextView\n android:id = \"@+id/click\"\n android:layout_width = \"wrap_content\"\n android:textSize = \"30sp\"\n android:layout_height = \"wrap_content\"\n android:text = \"Click\"/>\n</LinearLayout>" }, { "code": null, "e": 1821, "s": 1777, "text": "In the above code, we have taken text view." }, { "code": null, "e": 1878, "s": 1821, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4095, "s": 1878, "text": "package com.example.myapplication;\nimport android.annotation.TargetApi;\nimport android.content.DialogInterface;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.v7.app.AlertDialog;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Switch;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class MainActivity extends AppCompatActivity {\n TextView text;\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n text = findViewById(R.id.click);\n text.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n showAlertDialog();\n }\n });\n }\n private void showAlertDialog() {\n AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);\n alertDialog.setTitle(\"AlertDialog\");\n String[] items = {\"java\",\"android\",\"Data Structures\",\"HTML\",\"CSS\"};\n int checkedItem = 1;\n alertDialog.setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n switch (which) {\n case 0:\n Toast.makeText(MainActivity.this, \"Clicked on java\", Toast.LENGTH_LONG).show();\n break;\n case 1:\n Toast.makeText(MainActivity.this, \"Clicked on android\", Toast.LENGTH_LONG).show();\n break;\n case 2:\n Toast.makeText(MainActivity.this, \"Clicked on Data Structures\", Toast.LENGTH_LONG).show();\n break;\n case 3:\n Toast.makeText(MainActivity.this, \"Clicked on HTML\", Toast.LENGTH_LONG).show();\n break;\n case 4:\n Toast.makeText(MainActivity.this, \"Clicked on CSS\", Toast.LENGTH_LONG).show();\n break;\n }\n }\n });\n AlertDialog alert = alertDialog.create();\n alert.setCanceledOnTouchOutside(false);\n alert.show();\n }\n}" }, { "code": null, "e": 4442, "s": 4095, "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": 4486, "s": 4442, "text": "Now click on textview to open Alert Dialog." } ]
AUC and its implementation in CatBoost | by Anna Volodkevich | Towards Data Science
The ROC curve shows the model’s ability to distinguishing between classes. The model which randomly assigns a class to object is a ‘bad’ classifier and has a diagonal ROC curve. The better is the classifier, the higher is the ROC curve. The ROC curve is plotted with TPR, True Positive Rate, on the y-axis against the FPR, False Positive Rate, on the x-axis. The curve also could be interpreted in terms of Sensitivity and Specificity of the model with Sensitivity on the y-axis and (1-Specificity) on the x-axis. Building and visualizing the ROC curve could be used to measure classification algorithm performance with different probability boundaries and select the probability boundary required to achieve the specified false-positive or false-negative rate. AUC is the Area Under the ROC Curve. The best AUC = 1 for a model that ranks all the objects right (all objects with class 1 are assigned higher probabilities then objects of class 0). AUC for the ‘bad’ classifier which is working as random guessing is equal to 0.5. AUC is used for binary classification, multiclass classification, and ranking problems. AUC measures the proportion of correctly ordered objects and the capability of the model to distinguish between the classes. The AUC has an important statistical property: the AUC of a classifier is equivalent to the probability that the classifier will rank a randomly chosen positive instance higher than a randomly chosen negative instance. There are implementations of AUC in CatBoost for binary classification, multiclassification and ranking problems. You can calculate AUC during training for overfitting detection and automated best model selection, evaluate the model on new data with model.eval_metric and use AUC as a metric for predictions evaluation and comparison with utils.eval_metric. See examples of models fitting and AUC calculation with CatBoost in the section How to use AUC in Catboost on real datasets? Read more about ROC on Wikipedia. To get an understanding of the ROC curve building from scratch see the article. To get an understanding of AUCμ for multiclass classification see the article. AUC for binary classification is calculated according to the following formula: where ai,aj — predictions (probabilities) of objects to belong to the class 1 given by the algorithm. The sum is calculated on all pairs of objects i, j such that: ti=0, tj=1 where t is the true class label. I is an indicator function equal to 1 if objects i, j are ordered correctly: A user could assign weights for each object to specify the importance of each object in metric calculation. Let’s look at a simple example of ROC curve building and AUC calculation: We have a sample of 10 objects, 4 from class 1 and 6 from class 0 (‘class’ column). All objects are equally important (weights = 1). Assume we predicted probabilities of objects to come from class 1 (‘prediction’ column). The denominator is equal to the number of pairs of objects i, j such that true class ti=0,tj=1. As there are 4 objects from class 1 and 6 objects from class 0, the denominator is equal to 24. For each object from class 1 count the number of objects from class 0, which are below (has less probability) in the sorted dataset. We add +1 of objects ordered correctly (e.g. objects with IDs 0 and 4) and +0.5 if probabilities are equal (e.g. objects with IDs 1 and 7). For example, the object with ID = 1 adds +4.5 to AUC numerator as correctly ordered with objects with IDs: 8, 3, 6, 9 and has equal prediction with object 7: denominator = sum(toy_example['class'] == 1) * sum(toy_example['class'] == 0)numerator = (6 + 5 + 4.5 + 2)manually_calculated_auc = numerator / denominatormanually_calculated_auc = 0.7292 Let’s calculate the same metric with Catboost and ensure everything is right: catboost_auc = eval_metric(toy_example['class'], toy_example['prediction'], 'AUC')[0] To build a ROC curve put the number of objects of class 1 (n1) in the square with side 1 along the y-axis, and the number of objects of class 0 (n0) along the x-axis. Going by the list of target labels dorted by model predictions in descending order will add 1/n1 along the y-axis encountering an object of class 1 and 1/n0 along the x-axis encountering an object of class 0. Going from top to bottom by the ‘class’ column we go up on the plot if the class is 1 or right if the class is 0. When meet objects with equal prediction add the number of 1 along y and the number of 0 along x and go by the diagonal of the rectangle. CatBoost allows us to assign a weight to each object in the dataset for AUC calculation according to the formula above. If no weights assigned, all weights are equal to 1 and thus AUC is proportional to the number of correctly ordered pairs. If weights assigned this property is changed. Weights are useful for unbalanced datasets. If there is a class or a group of objects with a small number of samples in the train dataset it could be reasonable to increase the weights for corresponding objects. For example, if we assign weight 10 to one object it can be understood as adding 9 of the same objects to the dataset. Let’s calculate AUC for an example of the wrong and right classification of one important object with weight = 10. roc_auc = catboost.utils.eval_metric(toy_example[‘class’], toy_example[‘prediction’], ‘AUC’, weight=toy_example[‘weight’])[0] AUC = 0.9167. An important object is correctly ordered, AUC increases roc_auc = catboost.utils.eval_metric(toy_example['class'], toy_example['prediction'], 'AUC', weight=toy_example['weight'])[0] AUC = 0.4417. An important object is incorrectly ordered, AUC decreases There are two AUC metrics implemented for multiclass classification in Catboost. The first is OneVsAll. AUC value is calculated separately for each class according to the binary classification calculation principles. The second is AUCμ, which is designed to meet the following properties: Property 1. If a model gives the correct label the highest probability on every example, then AUC = 1 Property 2. Random guessing on examples yields AUC = 0.5 Property 3. AUC is insensitive to class skew AUCμ could be interpreted as an average of pairwise AUCs between the classes. Details could be found in the article. OneVsAll AUC in Catboost returns n AUC values for n-class classification. The value is calculated separately for each class k numbered from 0 to K–1 according to the binary classification calculation rules. The objects of class k are considered positive, while all others are considered negative. It works almost the same way as the binary classification, so I skip calculation details here (they are present in the iPython notebook). OneVsAll AUC measures the ability of the classifier to distinguish objects of one class from another. An advantage of OneVsAll is the ability to monitor performance on different classes separately. AUCμ could be used as an evaluation metric to prevent overfitting, while OneVsAll AUC could be used only for information as contains k values (k is the number of classes). Let’s have a look at the AUCμ formula: K is a number of classes, i < j ≤ K are the classes’ numbers. S(i, j) is a separability measure between classes i and j defined as: where I is indicator function applied to results of O, which returns 1 if O returns a positive value, 0 if O returns a negative value, and 0.5 if O returns 0. O is an orientation function indicating if the two instances are ordered correctly, incorrectly, or tied. O returns a positive value if the predictions are ranked correctly, a negative value if they are ranked incorrectly, and 0 if their rank is tied. a, b are objects from classes i, j respectively, p(a), p(b) are vectors of predicted probabilities of the object to belong to the classes, y(a), y(b) are true labels of objects a, b (one-hot vectors), vi j is a two-class decision hyperplane normal vector. O is calculated as follows: Vectors v_i,j come from misclassification cost matrix A, which is defined manually following the learning task. vi j=A i.−A j. A i j is the cost of classifying an instance as class i when its true class is j. Then A defines a partition on the (K−1)−simplex and induces decision boundaries between the K classes. Default misclassification cost matrix values are 1 everywhere, except the diagonal where they are 0. It is called the argmax partition matrix as it assigns a class with maximal probability. Here is a partition for a 3-class classification problem with the argmax partition matrix A. For a used-defined partition matrix the boundaries (marked by arrows) are shifted. Follow the article for more details. CatBoost allows us to set the misclassification cost matrix A and objects’ weights to calculate AUCμ. Let’s calculate AUCμ for a very small example with 3 classes and 4 objects: Let’s compute S(i,j) for each ordered classes’ pair: Let’s calculate the same metric with Catboost AUCμ and ensure everything is right: As we can see AUCμ is pretty high, but actually, algorithm performance is bad, accuracy is 0.25. Thus it is reasonable to evaluate the other important metrics during the training. AUCμ is a good generalizing metric to estimate algorithm ability to separate classes in multiclassification problems. See more about different approaches to multiclass AUC calculation and their properties in section 4.3 of the article. AUCμ could be interpreted as an average of pairwise AUCs between the classes. AUCμ is a single value unlike OneVsAll AUC and thus it could be used as an evaluation metric during training for overfitting detection and trees pruning. There are two variants of AUC for Ranking in CatBoost. is used for models with Logloss and CrossEntropy loss functions. It has the same formula as AUC for binary classification: ai, aj — predicted rank of objects i, j. The sum is calculated on all pairs of objects i, j such that: ti=0, tj=1 where t is relevance. The formula above suits for simple tasks with target values equal to 1 and 0. What if we have more target values? If the target type is not binary, then every object i with target value t and weight w is replaced with two objects for the metric calculation: σ1 with weight wt and target value 1 σ2 with weight w(1−t) and target value 0. Target values must be in the range [0; 1]. Let’s calculate Classic AUC for Ranking for a small example. Assume we have 2 documents, 2 requests, corresponding relevances in the range [1, 5] and predicted relevance in the range [0, 1]: After data preprocessing (see the notebook for details) we get: Let’s calculate AUC: Ranking AUC is used for ranking loss functions. ai, aj are predicted rank of objects i, j. The sum is calculated on all pairs of objects i, j such that: ti<tj where t is relevance. Ranking AUC is directly measuring the quantity of correctly ranked pairs. The problem is the metric is calculated regardless of groups. In our example, we have groups (requests) and we may want to measure quality inside the groups, but currently, AUC is calculated over the dataset and AUC penalizes us if, for example, top-one document for one request is ranked lower than top-one for another document while true ranks are opposite (but still top-one for each document). One more problem of AUC for Ranking is that it does not distinguish the top object from the others. If we have a lot of irrelevant documents, which are ranked irrelevant by the model, but bad ranking in top-10, AUC could still be high because of that “tail” of irrelevant objects, ranked lower than relevant. AUC is a widely used metric to measure the ability of a model to distinguish classes and correctly order objects from different classes / with different relevance. AUC is not differentiable and thus cannot be used as a loss function, but it is pretty informative and useful as a metric. We have examined the following AUC types: AUC for binary classification. It is a classical metric, which measures the model quality. ROC curve allows selecting the probability threshold to meet required False Positive or False Negative Rates. AUC for multiclass classification: OneVsAll and AUCμ. OneVsAll AUC helps to control algorithm performance for each class, but can not be used as a metric to prevent overfitting. On the contrary, AUCμ is good as a generalizing metric, but will not detect a problem with one class. AUC for ranking: Classic AUC and Ranking AUC. AUC suits for ranking tasks because it is designed to measure how the algorithm distinguishes between classes and it is simply transferring to distinguishing between relevant and irrelevant objects. But AUC does not take into account that in ranking problems the first n positions are very important and treats each correctly ordered pair of documents equally. To have a closer look at the data processing, calculation details, and examples of using AUC in CatBoost see the iPython notebook with code in CatBoost tutorials.
[ { "code": null, "e": 247, "s": 172, "text": "The ROC curve shows the model’s ability to distinguishing between classes." }, { "code": null, "e": 686, "s": 247, "text": "The model which randomly assigns a class to object is a ‘bad’ classifier and has a diagonal ROC curve. The better is the classifier, the higher is the ROC curve. The ROC curve is plotted with TPR, True Positive Rate, on the y-axis against the FPR, False Positive Rate, on the x-axis. The curve also could be interpreted in terms of Sensitivity and Specificity of the model with Sensitivity on the y-axis and (1-Specificity) on the x-axis." }, { "code": null, "e": 934, "s": 686, "text": "Building and visualizing the ROC curve could be used to measure classification algorithm performance with different probability boundaries and select the probability boundary required to achieve the specified false-positive or false-negative rate." }, { "code": null, "e": 1201, "s": 934, "text": "AUC is the Area Under the ROC Curve. The best AUC = 1 for a model that ranks all the objects right (all objects with class 1 are assigned higher probabilities then objects of class 0). AUC for the ‘bad’ classifier which is working as random guessing is equal to 0.5." }, { "code": null, "e": 1414, "s": 1201, "text": "AUC is used for binary classification, multiclass classification, and ranking problems. AUC measures the proportion of correctly ordered objects and the capability of the model to distinguish between the classes." }, { "code": null, "e": 1633, "s": 1414, "text": "The AUC has an important statistical property: the AUC of a classifier is equivalent to the probability that the classifier will rank a randomly chosen positive instance higher than a randomly chosen negative instance." }, { "code": null, "e": 2116, "s": 1633, "text": "There are implementations of AUC in CatBoost for binary classification, multiclassification and ranking problems. You can calculate AUC during training for overfitting detection and automated best model selection, evaluate the model on new data with model.eval_metric and use AUC as a metric for predictions evaluation and comparison with utils.eval_metric. See examples of models fitting and AUC calculation with CatBoost in the section How to use AUC in Catboost on real datasets?" }, { "code": null, "e": 2150, "s": 2116, "text": "Read more about ROC on Wikipedia." }, { "code": null, "e": 2230, "s": 2150, "text": "To get an understanding of the ROC curve building from scratch see the article." }, { "code": null, "e": 2309, "s": 2230, "text": "To get an understanding of AUCμ for multiclass classification see the article." }, { "code": null, "e": 2389, "s": 2309, "text": "AUC for binary classification is calculated according to the following formula:" }, { "code": null, "e": 2491, "s": 2389, "text": "where ai,aj — predictions (probabilities) of objects to belong to the class 1 given by the algorithm." }, { "code": null, "e": 2597, "s": 2491, "text": "The sum is calculated on all pairs of objects i, j such that: ti=0, tj=1 where t is the true class label." }, { "code": null, "e": 2674, "s": 2597, "text": "I is an indicator function equal to 1 if objects i, j are ordered correctly:" }, { "code": null, "e": 2782, "s": 2674, "text": "A user could assign weights for each object to specify the importance of each object in metric calculation." }, { "code": null, "e": 2856, "s": 2782, "text": "Let’s look at a simple example of ROC curve building and AUC calculation:" }, { "code": null, "e": 3078, "s": 2856, "text": "We have a sample of 10 objects, 4 from class 1 and 6 from class 0 (‘class’ column). All objects are equally important (weights = 1). Assume we predicted probabilities of objects to come from class 1 (‘prediction’ column)." }, { "code": null, "e": 3270, "s": 3078, "text": "The denominator is equal to the number of pairs of objects i, j such that true class ti=0,tj=1. As there are 4 objects from class 1 and 6 objects from class 0, the denominator is equal to 24." }, { "code": null, "e": 3403, "s": 3270, "text": "For each object from class 1 count the number of objects from class 0, which are below (has less probability) in the sorted dataset." }, { "code": null, "e": 3543, "s": 3403, "text": "We add +1 of objects ordered correctly (e.g. objects with IDs 0 and 4) and +0.5 if probabilities are equal (e.g. objects with IDs 1 and 7)." }, { "code": null, "e": 3701, "s": 3543, "text": "For example, the object with ID = 1 adds +4.5 to AUC numerator as correctly ordered with objects with IDs: 8, 3, 6, 9 and has equal prediction with object 7:" }, { "code": null, "e": 3889, "s": 3701, "text": "denominator = sum(toy_example['class'] == 1) * sum(toy_example['class'] == 0)numerator = (6 + 5 + 4.5 + 2)manually_calculated_auc = numerator / denominatormanually_calculated_auc = 0.7292" }, { "code": null, "e": 3967, "s": 3889, "text": "Let’s calculate the same metric with Catboost and ensure everything is right:" }, { "code": null, "e": 4053, "s": 3967, "text": "catboost_auc = eval_metric(toy_example['class'], toy_example['prediction'], 'AUC')[0]" }, { "code": null, "e": 4220, "s": 4053, "text": "To build a ROC curve put the number of objects of class 1 (n1) in the square with side 1 along the y-axis, and the number of objects of class 0 (n0) along the x-axis." }, { "code": null, "e": 4429, "s": 4220, "text": "Going by the list of target labels dorted by model predictions in descending order will add 1/n1 along the y-axis encountering an object of class 1 and 1/n0 along the x-axis encountering an object of class 0." }, { "code": null, "e": 4680, "s": 4429, "text": "Going from top to bottom by the ‘class’ column we go up on the plot if the class is 1 or right if the class is 0. When meet objects with equal prediction add the number of 1 along y and the number of 0 along x and go by the diagonal of the rectangle." }, { "code": null, "e": 4968, "s": 4680, "text": "CatBoost allows us to assign a weight to each object in the dataset for AUC calculation according to the formula above. If no weights assigned, all weights are equal to 1 and thus AUC is proportional to the number of correctly ordered pairs. If weights assigned this property is changed." }, { "code": null, "e": 5180, "s": 4968, "text": "Weights are useful for unbalanced datasets. If there is a class or a group of objects with a small number of samples in the train dataset it could be reasonable to increase the weights for corresponding objects." }, { "code": null, "e": 5299, "s": 5180, "text": "For example, if we assign weight 10 to one object it can be understood as adding 9 of the same objects to the dataset." }, { "code": null, "e": 5414, "s": 5299, "text": "Let’s calculate AUC for an example of the wrong and right classification of one important object with weight = 10." }, { "code": null, "e": 5540, "s": 5414, "text": "roc_auc = catboost.utils.eval_metric(toy_example[‘class’], toy_example[‘prediction’], ‘AUC’, weight=toy_example[‘weight’])[0]" }, { "code": null, "e": 5610, "s": 5540, "text": "AUC = 0.9167. An important object is correctly ordered, AUC increases" }, { "code": null, "e": 5736, "s": 5610, "text": "roc_auc = catboost.utils.eval_metric(toy_example['class'], toy_example['prediction'], 'AUC', weight=toy_example['weight'])[0]" }, { "code": null, "e": 5808, "s": 5736, "text": "AUC = 0.4417. An important object is incorrectly ordered, AUC decreases" }, { "code": null, "e": 5889, "s": 5808, "text": "There are two AUC metrics implemented for multiclass classification in Catboost." }, { "code": null, "e": 6025, "s": 5889, "text": "The first is OneVsAll. AUC value is calculated separately for each class according to the binary classification calculation principles." }, { "code": null, "e": 6097, "s": 6025, "text": "The second is AUCμ, which is designed to meet the following properties:" }, { "code": null, "e": 6199, "s": 6097, "text": "Property 1. If a model gives the correct label the highest probability on every example, then AUC = 1" }, { "code": null, "e": 6256, "s": 6199, "text": "Property 2. Random guessing on examples yields AUC = 0.5" }, { "code": null, "e": 6301, "s": 6256, "text": "Property 3. AUC is insensitive to class skew" }, { "code": null, "e": 6418, "s": 6301, "text": "AUCμ could be interpreted as an average of pairwise AUCs between the classes. Details could be found in the article." }, { "code": null, "e": 6715, "s": 6418, "text": "OneVsAll AUC in Catboost returns n AUC values for n-class classification. The value is calculated separately for each class k numbered from 0 to K–1 according to the binary classification calculation rules. The objects of class k are considered positive, while all others are considered negative." }, { "code": null, "e": 6853, "s": 6715, "text": "It works almost the same way as the binary classification, so I skip calculation details here (they are present in the iPython notebook)." }, { "code": null, "e": 6955, "s": 6853, "text": "OneVsAll AUC measures the ability of the classifier to distinguish objects of one class from another." }, { "code": null, "e": 7051, "s": 6955, "text": "An advantage of OneVsAll is the ability to monitor performance on different classes separately." }, { "code": null, "e": 7223, "s": 7051, "text": "AUCμ could be used as an evaluation metric to prevent overfitting, while OneVsAll AUC could be used only for information as contains k values (k is the number of classes)." }, { "code": null, "e": 7262, "s": 7223, "text": "Let’s have a look at the AUCμ formula:" }, { "code": null, "e": 7324, "s": 7262, "text": "K is a number of classes, i < j ≤ K are the classes’ numbers." }, { "code": null, "e": 7394, "s": 7324, "text": "S(i, j) is a separability measure between classes i and j defined as:" }, { "code": null, "e": 7400, "s": 7394, "text": "where" }, { "code": null, "e": 7553, "s": 7400, "text": "I is indicator function applied to results of O, which returns 1 if O returns a positive value, 0 if O returns a negative value, and 0.5 if O returns 0." }, { "code": null, "e": 7805, "s": 7553, "text": "O is an orientation function indicating if the two instances are ordered correctly, incorrectly, or tied. O returns a positive value if the predictions are ranked correctly, a negative value if they are ranked incorrectly, and 0 if their rank is tied." }, { "code": null, "e": 7854, "s": 7805, "text": "a, b are objects from classes i, j respectively," }, { "code": null, "e": 7944, "s": 7854, "text": "p(a), p(b) are vectors of predicted probabilities of the object to belong to the classes," }, { "code": null, "e": 8006, "s": 7944, "text": "y(a), y(b) are true labels of objects a, b (one-hot vectors)," }, { "code": null, "e": 8061, "s": 8006, "text": "vi j is a two-class decision hyperplane normal vector." }, { "code": null, "e": 8089, "s": 8061, "text": "O is calculated as follows:" }, { "code": null, "e": 8201, "s": 8089, "text": "Vectors v_i,j come from misclassification cost matrix A, which is defined manually following the learning task." }, { "code": null, "e": 8216, "s": 8201, "text": "vi j=A i.−A j." }, { "code": null, "e": 8401, "s": 8216, "text": "A i j is the cost of classifying an instance as class i when its true class is j. Then A defines a partition on the (K−1)−simplex and induces decision boundaries between the K classes." }, { "code": null, "e": 8591, "s": 8401, "text": "Default misclassification cost matrix values are 1 everywhere, except the diagonal where they are 0. It is called the argmax partition matrix as it assigns a class with maximal probability." }, { "code": null, "e": 8767, "s": 8591, "text": "Here is a partition for a 3-class classification problem with the argmax partition matrix A. For a used-defined partition matrix the boundaries (marked by arrows) are shifted." }, { "code": null, "e": 8804, "s": 8767, "text": "Follow the article for more details." }, { "code": null, "e": 8906, "s": 8804, "text": "CatBoost allows us to set the misclassification cost matrix A and objects’ weights to calculate AUCμ." }, { "code": null, "e": 8982, "s": 8906, "text": "Let’s calculate AUCμ for a very small example with 3 classes and 4 objects:" }, { "code": null, "e": 9035, "s": 8982, "text": "Let’s compute S(i,j) for each ordered classes’ pair:" }, { "code": null, "e": 9118, "s": 9035, "text": "Let’s calculate the same metric with Catboost AUCμ and ensure everything is right:" }, { "code": null, "e": 9298, "s": 9118, "text": "As we can see AUCμ is pretty high, but actually, algorithm performance is bad, accuracy is 0.25. Thus it is reasonable to evaluate the other important metrics during the training." }, { "code": null, "e": 9534, "s": 9298, "text": "AUCμ is a good generalizing metric to estimate algorithm ability to separate classes in multiclassification problems. See more about different approaches to multiclass AUC calculation and their properties in section 4.3 of the article." }, { "code": null, "e": 9766, "s": 9534, "text": "AUCμ could be interpreted as an average of pairwise AUCs between the classes. AUCμ is a single value unlike OneVsAll AUC and thus it could be used as an evaluation metric during training for overfitting detection and trees pruning." }, { "code": null, "e": 9821, "s": 9766, "text": "There are two variants of AUC for Ranking in CatBoost." }, { "code": null, "e": 9944, "s": 9821, "text": "is used for models with Logloss and CrossEntropy loss functions. It has the same formula as AUC for binary classification:" }, { "code": null, "e": 9985, "s": 9944, "text": "ai, aj — predicted rank of objects i, j." }, { "code": null, "e": 10080, "s": 9985, "text": "The sum is calculated on all pairs of objects i, j such that: ti=0, tj=1 where t is relevance." }, { "code": null, "e": 10194, "s": 10080, "text": "The formula above suits for simple tasks with target values equal to 1 and 0. What if we have more target values?" }, { "code": null, "e": 10338, "s": 10194, "text": "If the target type is not binary, then every object i with target value t and weight w is replaced with two objects for the metric calculation:" }, { "code": null, "e": 10375, "s": 10338, "text": "σ1 with weight wt and target value 1" }, { "code": null, "e": 10417, "s": 10375, "text": "σ2 with weight w(1−t) and target value 0." }, { "code": null, "e": 10460, "s": 10417, "text": "Target values must be in the range [0; 1]." }, { "code": null, "e": 10651, "s": 10460, "text": "Let’s calculate Classic AUC for Ranking for a small example. Assume we have 2 documents, 2 requests, corresponding relevances in the range [1, 5] and predicted relevance in the range [0, 1]:" }, { "code": null, "e": 10715, "s": 10651, "text": "After data preprocessing (see the notebook for details) we get:" }, { "code": null, "e": 10736, "s": 10715, "text": "Let’s calculate AUC:" }, { "code": null, "e": 10784, "s": 10736, "text": "Ranking AUC is used for ranking loss functions." }, { "code": null, "e": 10827, "s": 10784, "text": "ai, aj are predicted rank of objects i, j." }, { "code": null, "e": 10917, "s": 10827, "text": "The sum is calculated on all pairs of objects i, j such that: ti<tj where t is relevance." }, { "code": null, "e": 11389, "s": 10917, "text": "Ranking AUC is directly measuring the quantity of correctly ranked pairs. The problem is the metric is calculated regardless of groups. In our example, we have groups (requests) and we may want to measure quality inside the groups, but currently, AUC is calculated over the dataset and AUC penalizes us if, for example, top-one document for one request is ranked lower than top-one for another document while true ranks are opposite (but still top-one for each document)." }, { "code": null, "e": 11698, "s": 11389, "text": "One more problem of AUC for Ranking is that it does not distinguish the top object from the others. If we have a lot of irrelevant documents, which are ranked irrelevant by the model, but bad ranking in top-10, AUC could still be high because of that “tail” of irrelevant objects, ranked lower than relevant." }, { "code": null, "e": 11985, "s": 11698, "text": "AUC is a widely used metric to measure the ability of a model to distinguish classes and correctly order objects from different classes / with different relevance. AUC is not differentiable and thus cannot be used as a loss function, but it is pretty informative and useful as a metric." }, { "code": null, "e": 12027, "s": 11985, "text": "We have examined the following AUC types:" }, { "code": null, "e": 12228, "s": 12027, "text": "AUC for binary classification. It is a classical metric, which measures the model quality. ROC curve allows selecting the probability threshold to meet required False Positive or False Negative Rates." }, { "code": null, "e": 12508, "s": 12228, "text": "AUC for multiclass classification: OneVsAll and AUCμ. OneVsAll AUC helps to control algorithm performance for each class, but can not be used as a metric to prevent overfitting. On the contrary, AUCμ is good as a generalizing metric, but will not detect a problem with one class." }, { "code": null, "e": 12915, "s": 12508, "text": "AUC for ranking: Classic AUC and Ranking AUC. AUC suits for ranking tasks because it is designed to measure how the algorithm distinguishes between classes and it is simply transferring to distinguishing between relevant and irrelevant objects. But AUC does not take into account that in ranking problems the first n positions are very important and treats each correctly ordered pair of documents equally." } ]
Edge Chasing Algorithms - GeeksforGeeks
24 Jun, 2020 Deadlock might be a virtual disadvantage that may get up at some point of a community of cooperating or competitive procedures. A deadlock is that state of affairs where a group of methods are blocked as a result of every technique requiring a fixed process, sources needed for its headaches and anticipating release of ultimate assets held by using others in equal organization for that reason making it impossible for any of methods to proceed. Deadlock involves following elements : 1. Resource :Operating gadget and useful resource manager system can be concerned in deadlock scenarios.Finite numbers of assets are on market inside system.These resources are distributed among a selection of competitive methods. Reusable sources –A reusable aid is one that can be correctly used by using handiest one method at a time and isn’t depleted by means of that use. Processes accumulate aid units that they later unharness for application through different tactics.Examples of reusable sources are embody processors, I/O channels, I/O devices, number one and secondary memory, files, database, semaphores, etc. Expendable sources –The expendable aid is one that can be created and destroyed. There’s no restriction on quantity of expendable assets of a particular kind. Samples of expendable sources are interrupts, indicators messages, and expertise in I/O buffers.A technique ought to request a resource before victimizing it and need to unleash useful resource once victimizing it. The quantity of assets requested won’t exceed complete wide variety of assets on market within gadget. 2. Request :Request may be understood as when any processor asks for use of any resource. If request can’t be granted in real time, then requesting technique must wait till it will accumulate sources. 3. Use :This state arises when resources are allotted to the processor. 4. Release :After performing required operation ,resources are set to free state which may be concerned as release of resources. Distributed Deadlock Detection Algorithms :The algorithmic program will be initiated on every occasion when a way of deadlock is pressured to attend. The algorithmic program could be initiated either by using native web site of method or by using positioning anyplace method waits.Distributed situations will be detected through taking a shot of device and examining it for condition of an impasse. Distributed deadlock detection algorithmic program can be divided into four classes as follows: Path push-in –Path info- dispatched to waiting node to blocking off node. Edge-chasing –Probe message area unit dispatched on graph edge. Diffusion computation –Echo messages location unit dispatched on graph edges. Global nation detection –Sweep-out, sweep-in WFG creation and reduction. Edge Chasing Algorithm : Edge chasing algorithm makes use of a unique message on every occasion, impasse detection is initiated by procedure Pi and it’s miles being sent by means of house web site of manner Pi to house web site of procedure Pk. A probe message travels along rims ofworldwide TWF graph. An impasse is detected if a probe message returns to its initiating process. Note –A Boolean array, dependents, for each technique Pi , is maintained. If Pj is aware that Pi is depending on it, dependent (j) is ready to true. Otherwise, it’s far false. Example: Contemplate a system as given in Fig. If method P1 initiates situation detection , it sends probe (1, 3, 4) to S2. Since P6 is awaiting P8 and P7 is awaiting P10. S2 sends probe ( 1, 6, 8) and (1, 7, 10) to S3 that successively sends probe ( 1, 9, 1) to S1. On receiving probe (1, 9, 1), S1 declares that P1 is obstructed (deadlock). If Pi is locally dependent on itself then declare deadlock Else for all Pj and Pk such that Pi is locally dependent upon Pj, and Pj is waiting on Pk, and Pj and Pk are on totally different sites Send probe(i,j,k) to home site of Pk On receipt of probe(i, j,k), positioning takes subsequent actions. If Pk is blocked, and dependentk(i) is false. and Pk has not replied to any or all requests of Pj then begin dependentk(i)= true; if k = i then declare that Pi is under deadlock else for all Pm and Pn such that Pk is locally dependent upon Pm, and Pm is waiting on Pn and Pm and Pn are on totally different sites, send Prob(I,m,n) to house sites of Pn end Solution of given example using Edge chasing algorithm : P6 at beginning asks P8 for its public label and changes it’s own 2 to 3.P3 asks P4 and changes its public label 1 to 3.P9 asks P1 and finds its own public label 3 then detects situation.P1 → P2 → P3 → P4 → P5 → P6 → P8 → P9 → P1. P6 at beginning asks P8 for its public label and changes it’s own 2 to 3. P3 asks P4 and changes its public label 1 to 3. P9 asks P1 and finds its own public label 3 then detects situation. P1 → P2 → P3 → P4 → P5 → P6 → P8 → P9 → P1. Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Memory Management in Operating System File Allocation Methods Logical and Physical Address in Operating System File Access Methods in Operating System Difference between Internal and External fragmentation Memory Hierarchy Design and its Characteristics File Systems in Operating System Process Table and Process Control Block (PCB) Structures of Directory in Operating System States of a Process in Operating Systems
[ { "code": null, "e": 25871, "s": 25843, "text": "\n24 Jun, 2020" }, { "code": null, "e": 26318, "s": 25871, "text": "Deadlock might be a virtual disadvantage that may get up at some point of a community of cooperating or competitive procedures. A deadlock is that state of affairs where a group of methods are blocked as a result of every technique requiring a fixed process, sources needed for its headaches and anticipating release of ultimate assets held by using others in equal organization for that reason making it impossible for any of methods to proceed." }, { "code": null, "e": 26357, "s": 26318, "text": "Deadlock involves following elements :" }, { "code": null, "e": 26588, "s": 26357, "text": "1. Resource :Operating gadget and useful resource manager system can be concerned in deadlock scenarios.Finite numbers of assets are on market inside system.These resources are distributed among a selection of competitive methods." }, { "code": null, "e": 26980, "s": 26588, "text": "Reusable sources –A reusable aid is one that can be correctly used by using handiest one method at a time and isn’t depleted by means of that use. Processes accumulate aid units that they later unharness for application through different tactics.Examples of reusable sources are embody processors, I/O channels, I/O devices, number one and secondary memory, files, database, semaphores, etc." }, { "code": null, "e": 27457, "s": 26980, "text": "Expendable sources –The expendable aid is one that can be created and destroyed. There’s no restriction on quantity of expendable assets of a particular kind. Samples of expendable sources are interrupts, indicators messages, and expertise in I/O buffers.A technique ought to request a resource before victimizing it and need to unleash useful resource once victimizing it. The quantity of assets requested won’t exceed complete wide variety of assets on market within gadget." }, { "code": null, "e": 27658, "s": 27457, "text": "2. Request :Request may be understood as when any processor asks for use of any resource. If request can’t be granted in real time, then requesting technique must wait till it will accumulate sources." }, { "code": null, "e": 27730, "s": 27658, "text": "3. Use :This state arises when resources are allotted to the processor." }, { "code": null, "e": 27859, "s": 27730, "text": "4. Release :After performing required operation ,resources are set to free state which may be concerned as release of resources." }, { "code": null, "e": 28258, "s": 27859, "text": "Distributed Deadlock Detection Algorithms :The algorithmic program will be initiated on every occasion when a way of deadlock is pressured to attend. The algorithmic program could be initiated either by using native web site of method or by using positioning anyplace method waits.Distributed situations will be detected through taking a shot of device and examining it for condition of an impasse." }, { "code": null, "e": 28354, "s": 28258, "text": "Distributed deadlock detection algorithmic program can be divided into four classes as follows:" }, { "code": null, "e": 28428, "s": 28354, "text": "Path push-in –Path info- dispatched to waiting node to blocking off node." }, { "code": null, "e": 28492, "s": 28428, "text": "Edge-chasing –Probe message area unit dispatched on graph edge." }, { "code": null, "e": 28570, "s": 28492, "text": "Diffusion computation –Echo messages location unit dispatched on graph edges." }, { "code": null, "e": 28643, "s": 28570, "text": "Global nation detection –Sweep-out, sweep-in WFG creation and reduction." }, { "code": null, "e": 28668, "s": 28643, "text": "Edge Chasing Algorithm :" }, { "code": null, "e": 28888, "s": 28668, "text": "Edge chasing algorithm makes use of a unique message on every occasion, impasse detection is initiated by procedure Pi and it’s miles being sent by means of house web site of manner Pi to house web site of procedure Pk." }, { "code": null, "e": 29023, "s": 28888, "text": "A probe message travels along rims ofworldwide TWF graph. An impasse is detected if a probe message returns to its initiating process." }, { "code": null, "e": 29199, "s": 29023, "text": "Note –A Boolean array, dependents, for each technique Pi , is maintained. If Pj is aware that Pi is depending on it, dependent (j) is ready to true. Otherwise, it’s far false." }, { "code": null, "e": 29542, "s": 29199, "text": "Example: Contemplate a system as given in Fig. If method P1 initiates situation detection , it sends probe (1, 3, 4) to S2. Since P6 is awaiting P8 and P7 is awaiting P10. S2 sends probe ( 1, 6, 8) and (1, 7, 10) to S3 that successively sends probe ( 1, 9, 1) to S1. On receiving probe (1, 9, 1), S1 declares that P1 is obstructed (deadlock)." }, { "code": null, "e": 29795, "s": 29542, "text": "If Pi is locally dependent on itself then declare deadlock\nElse for all Pj and Pk such that\n Pi is locally dependent upon Pj, and\n Pj is waiting on Pk, and\n Pj and Pk are on totally different sites\n Send probe(i,j,k) to home site of Pk" }, { "code": null, "e": 29862, "s": 29795, "text": "On receipt of probe(i, j,k), positioning takes subsequent actions." }, { "code": null, "e": 30271, "s": 29862, "text": "If\nPk is blocked, and\ndependentk(i) is false. and\nPk has not replied to any or all requests of Pj\nthen\n begin\n dependentk(i)= true;\n if k = i then declare that Pi is under deadlock\n else for all Pm and Pn such that\n Pk is locally dependent upon Pm, and\n Pm is waiting on Pn and\n Pm and Pn are on totally different sites,\n send Prob(I,m,n) to house sites of Pn\nend" }, { "code": null, "e": 30328, "s": 30271, "text": "Solution of given example using Edge chasing algorithm :" }, { "code": null, "e": 30559, "s": 30328, "text": "P6 at beginning asks P8 for its public label and changes it’s own 2 to 3.P3 asks P4 and changes its public label 1 to 3.P9 asks P1 and finds its own public label 3 then detects situation.P1 → P2 → P3 → P4 → P5 → P6 → P8 → P9 → P1." }, { "code": null, "e": 30633, "s": 30559, "text": "P6 at beginning asks P8 for its public label and changes it’s own 2 to 3." }, { "code": null, "e": 30681, "s": 30633, "text": "P3 asks P4 and changes its public label 1 to 3." }, { "code": null, "e": 30749, "s": 30681, "text": "P9 asks P1 and finds its own public label 3 then detects situation." }, { "code": null, "e": 30793, "s": 30749, "text": "P1 → P2 → P3 → P4 → P5 → P6 → P8 → P9 → P1." }, { "code": null, "e": 30811, "s": 30793, "text": "Operating Systems" }, { "code": null, "e": 30829, "s": 30811, "text": "Operating Systems" }, { "code": null, "e": 30927, "s": 30829, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30965, "s": 30927, "text": "Memory Management in Operating System" }, { "code": null, "e": 30989, "s": 30965, "text": "File Allocation Methods" }, { "code": null, "e": 31038, "s": 30989, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 31078, "s": 31038, "text": "File Access Methods in Operating System" }, { "code": null, "e": 31133, "s": 31078, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 31181, "s": 31133, "text": "Memory Hierarchy Design and its Characteristics" }, { "code": null, "e": 31214, "s": 31181, "text": "File Systems in Operating System" }, { "code": null, "e": 31260, "s": 31214, "text": "Process Table and Process Control Block (PCB)" }, { "code": null, "e": 31304, "s": 31260, "text": "Structures of Directory in Operating System" } ]
StringBuilder appendCodePoint() method in Java with Examples - GeeksforGeeks
13 Dec, 2021 The appendCodePoint(int codePoint) method of StringBuilder class is the inbuilt method used to append the string representation of the codePoint argument to this sequence. The argument is appended to this StringBuilder content and length of the object is increased by Character.charCount(codePoint). The effect is the same as if the int value in parameter is converted to a char array and the character in that array were then appended to this character sequence. Syntax: public StringBuilder appendCodePoint(int codePoint) Parameters: This method accepts only one parameter codePoint which is int type value refers to a Unicode code point. Return Value: This method returns reference to this object.Below programs illustrate the java.lang.StringBuilder.appendCodePoint() method:Example 1: Java // Java program to illustrate the// appendCodePoint(int codePoint) import java.lang.*; public class Geeks { public static void main(String[] args) { // create StringBuilder object StringBuilder str = new StringBuilder("GeeksforGeeks"); System.out.println("StringBuilder = " + str); // Append 'C'(67) to the String str.appendCodePoint(67); // Print the modified String System.out.println("Modified StringBuilder = " + str); }} StringBuilder = GeeksforGeeks Modified StringBuilder = GeeksforGeeksC Example 2: Java // Java program to illustrate the// appendCodePoint(int codePoint) import java.lang.*; public class Geeks { public static void main(String[] args) { // create StringBuilder object StringBuilder str = new StringBuilder("GeeksforGeeks"); System.out.println("StringBuilder = " + str); // Append ', '(44) to the String str.appendCodePoint(44); // Print the modified String System.out.println("Modified StringBuilder = " + str); }} StringBuilder = GeeksforGeeks Modified StringBuilder = GeeksforGeeks, References: https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#appendCodePoint(int) Akanksha_Rai gabaa406 java-basics Java-Functions Java-StringBuilder Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Exceptions in Java Constructors in Java Different ways of Reading a text file in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples PriorityQueue in Java Introduction to Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 24090, "s": 24062, "text": "\n13 Dec, 2021" }, { "code": null, "e": 24563, "s": 24090, "text": "The appendCodePoint(int codePoint) method of StringBuilder class is the inbuilt method used to append the string representation of the codePoint argument to this sequence. The argument is appended to this StringBuilder content and length of the object is increased by Character.charCount(codePoint). The effect is the same as if the int value in parameter is converted to a char array and the character in that array were then appended to this character sequence. Syntax: " }, { "code": null, "e": 24615, "s": 24563, "text": "public StringBuilder appendCodePoint(int codePoint)" }, { "code": null, "e": 24883, "s": 24615, "text": "Parameters: This method accepts only one parameter codePoint which is int type value refers to a Unicode code point. Return Value: This method returns reference to this object.Below programs illustrate the java.lang.StringBuilder.appendCodePoint() method:Example 1: " }, { "code": null, "e": 24888, "s": 24883, "text": "Java" }, { "code": "// Java program to illustrate the// appendCodePoint(int codePoint) import java.lang.*; public class Geeks { public static void main(String[] args) { // create StringBuilder object StringBuilder str = new StringBuilder(\"GeeksforGeeks\"); System.out.println(\"StringBuilder = \" + str); // Append 'C'(67) to the String str.appendCodePoint(67); // Print the modified String System.out.println(\"Modified StringBuilder = \" + str); }}", "e": 25449, "s": 24888, "text": null }, { "code": null, "e": 25519, "s": 25449, "text": "StringBuilder = GeeksforGeeks\nModified StringBuilder = GeeksforGeeksC" }, { "code": null, "e": 25533, "s": 25521, "text": "Example 2: " }, { "code": null, "e": 25538, "s": 25533, "text": "Java" }, { "code": "// Java program to illustrate the// appendCodePoint(int codePoint) import java.lang.*; public class Geeks { public static void main(String[] args) { // create StringBuilder object StringBuilder str = new StringBuilder(\"GeeksforGeeks\"); System.out.println(\"StringBuilder = \" + str); // Append ', '(44) to the String str.appendCodePoint(44); // Print the modified String System.out.println(\"Modified StringBuilder = \" + str); }}", "e": 26100, "s": 25538, "text": null }, { "code": null, "e": 26170, "s": 26100, "text": "StringBuilder = GeeksforGeeks\nModified StringBuilder = GeeksforGeeks," }, { "code": null, "e": 26277, "s": 26172, "text": "References: https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#appendCodePoint(int) " }, { "code": null, "e": 26290, "s": 26277, "text": "Akanksha_Rai" }, { "code": null, "e": 26299, "s": 26290, "text": "gabaa406" }, { "code": null, "e": 26311, "s": 26299, "text": "java-basics" }, { "code": null, "e": 26326, "s": 26311, "text": "Java-Functions" }, { "code": null, "e": 26345, "s": 26326, "text": "Java-StringBuilder" }, { "code": null, "e": 26350, "s": 26345, "text": "Java" }, { "code": null, "e": 26355, "s": 26350, "text": "Java" }, { "code": null, "e": 26453, "s": 26355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26468, "s": 26453, "text": "Stream In Java" }, { "code": null, "e": 26487, "s": 26468, "text": "Exceptions in Java" }, { "code": null, "e": 26508, "s": 26487, "text": "Constructors in Java" }, { "code": null, "e": 26554, "s": 26508, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26584, "s": 26554, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26601, "s": 26584, "text": "Generics in Java" }, { "code": null, "e": 26644, "s": 26601, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 26666, "s": 26644, "text": "PriorityQueue in Java" }, { "code": null, "e": 26687, "s": 26666, "text": "Introduction to Java" } ]
Bootstrap .nav-justified class
Make tabs or pills of equal widths as of their parent at screens wider than 768px using class .nav-justified along with .nav, .nav-tabs or .nav, .nav-pills respectively. On smaller screens, the nav links are stacked. 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 style = "background: #FADBD8;"> <h2>Subjects</h2> <ul class = "nav nav-tabs nav-justified"> <li class = "active"><a href = "#">Home</a></li> <li><a href = "#">Team</a></li> <li><a href = "#">Authors</a></li> <li><a href = "#">MVPs</a></li> </ul> </body> </html>
[ { "code": null, "e": 1279, "s": 1062, "text": "Make tabs or pills of equal widths as of their parent at screens wider than 768px using class .nav-justified along with .nav, .nav-tabs or .nav, .nav-pills respectively. On smaller screens, the nav links are stacked." }, { "code": null, "e": 1289, "s": 1279, "text": "Live Demo" }, { "code": null, "e": 1910, "s": 1289, "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 style = \"background: #FADBD8;\">\n <h2>Subjects</h2>\n <ul class = \"nav nav-tabs nav-justified\">\n <li class = \"active\"><a href = \"#\">Home</a></li>\n <li><a href = \"#\">Team</a></li>\n <li><a href = \"#\">Authors</a></li>\n <li><a href = \"#\">MVPs</a></li>\n </ul>\n </body>\n</html>" } ]
How to Round Time to the Nearest Quarter Hour using JavaScript ? - GeeksforGeeks
26 Mar, 2020 We have given a time and the task is to round the time to the nearest quarter-hour with the help of JavaScript. There are two approaches that are discussed below: Approach 1: Use getMinutes() and getHours() methods to get the minutes and hours in a variable (Ex. mins, hrs) add the 7.5 to mins, divide it by 15, take the integer value and multiply it by 15, which will give the nearest quarter of minutes. If this value goes beyond 60, then take the mod with 60. For hrs, if mins 52 and if the hrs == 23, set hrs to 0 else increment its value by 1. Example:<!DOCTYPE HTML><html> <head> <title> Round time to the nearest quarter hour in JavaScript </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Click on button to round the time to nearest quarter hour </p> <p id="gfg"></p> <button onClick="GFG_Fun()"> click here </button> <p id="geeks"></p> <script> var up = document.getElementById('gfg'); var down = document.getElementById('geeks'); var date = new Date(); up.innerHTML = "" + date + ""; function GFG_Fun() { // Getting minutes var mins = date.getMinutes(); // Getting hours var hrs = date.getHours(); var m = (parseInt((mins + 7.5) / 15) * 15) % 60; // Converting '09:0' to '09:00' m = m < 10 ? '0' + m : m; var h = mins > 52 ? (hrs === 23 ? 0 : ++hrs) : hrs; // Converting '9:00' to '09:00' h = h < 10 ? '0' + h : h; down.innerHTML = h + ":" + m; } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> Round time to the nearest quarter hour in JavaScript </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Click on button to round the time to nearest quarter hour </p> <p id="gfg"></p> <button onClick="GFG_Fun()"> click here </button> <p id="geeks"></p> <script> var up = document.getElementById('gfg'); var down = document.getElementById('geeks'); var date = new Date(); up.innerHTML = "" + date + ""; function GFG_Fun() { // Getting minutes var mins = date.getMinutes(); // Getting hours var hrs = date.getHours(); var m = (parseInt((mins + 7.5) / 15) * 15) % 60; // Converting '09:0' to '09:00' m = m < 10 ? '0' + m : m; var h = mins > 52 ? (hrs === 23 ? 0 : ++hrs) : hrs; // Converting '9:00' to '09:00' h = h < 10 ? '0' + h : h; down.innerHTML = h + ":" + m; } </script></body> </html> Output: Approach 2: Use getMinutes() and getHours() methods to get the minutes and hours in a variable (Ex. mins, hrs). Divide mins by 15, take the round value by Math.round() and multiply it by 15, which will give the nearest quarter of minutes. If this value goes beyond 60, then take the mod with 60. For hrs, if mins 52 and if the hrs == 23, set hrs to 0 else increment its value by 1. Example:<!DOCTYPE HTML><html> <head> <title> Round time to the nearest quarter hour in JavaScript </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Click on button to round the time to nearest quarter hour </p> <p id="gfg"></p> <button onClick="GFG_Fun()"> click here </button> <p id="geeks"></p> <script> var up = document.getElementById('gfg'); var down = document.getElementById('geeks'); var date = new Date(); up.innerHTML = "" + date + ""; function GFG_Fun() { // Getting minutes var mins = date.getMinutes(); // Getting hours var hrs = date.getHours(); var m = (Math.round(mins/15) * 15) % 60; // Converting '09:0' to '09:00' m = m < 10 ? '0' + m : m; var h = mins > 52 ? (hrs === 23 ? 0 : ++hrs) : hrs; // Converting '9:00' to '09:00' h = h < 10 ? '0' + h : h; down.innerHTML = h + ":" + m; } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> Round time to the nearest quarter hour in JavaScript </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Click on button to round the time to nearest quarter hour </p> <p id="gfg"></p> <button onClick="GFG_Fun()"> click here </button> <p id="geeks"></p> <script> var up = document.getElementById('gfg'); var down = document.getElementById('geeks'); var date = new Date(); up.innerHTML = "" + date + ""; function GFG_Fun() { // Getting minutes var mins = date.getMinutes(); // Getting hours var hrs = date.getHours(); var m = (Math.round(mins/15) * 15) % 60; // Converting '09:0' to '09:00' m = m < 10 ? '0' + m : m; var h = mins > 52 ? (hrs === 23 ? 0 : ++hrs) : hrs; // Converting '9:00' to '09:00' h = h < 10 ? '0' + h : h; down.innerHTML = h + ":" + m; } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to set div width to fit content using CSS ? How to set fixed width for <td> in a table ? How to apply style to parent if it has child with CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? Hide or show elements in HTML using display property REST API (Introduction)
[ { "code": null, "e": 25478, "s": 25450, "text": "\n26 Mar, 2020" }, { "code": null, "e": 25641, "s": 25478, "text": "We have given a time and the task is to round the time to the nearest quarter-hour with the help of JavaScript. There are two approaches that are discussed below:" }, { "code": null, "e": 26027, "s": 25641, "text": "Approach 1: Use getMinutes() and getHours() methods to get the minutes and hours in a variable (Ex. mins, hrs) add the 7.5 to mins, divide it by 15, take the integer value and multiply it by 15, which will give the nearest quarter of minutes. If this value goes beyond 60, then take the mod with 60. For hrs, if mins 52 and if the hrs == 23, set hrs to 0 else increment its value by 1." }, { "code": null, "e": 27247, "s": 26027, "text": "Example:<!DOCTYPE HTML><html> <head> <title> Round time to the nearest quarter hour in JavaScript </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Click on button to round the time to nearest quarter hour </p> <p id=\"gfg\"></p> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"geeks\"></p> <script> var up = document.getElementById('gfg'); var down = document.getElementById('geeks'); var date = new Date(); up.innerHTML = \"\" + date + \"\"; function GFG_Fun() { // Getting minutes var mins = date.getMinutes(); // Getting hours var hrs = date.getHours(); var m = (parseInt((mins + 7.5) / 15) * 15) % 60; // Converting '09:0' to '09:00' m = m < 10 ? '0' + m : m; var h = mins > 52 ? (hrs === 23 ? 0 : ++hrs) : hrs; // Converting '9:00' to '09:00' h = h < 10 ? '0' + h : h; down.innerHTML = h + \":\" + m; } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> Round time to the nearest quarter hour in JavaScript </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Click on button to round the time to nearest quarter hour </p> <p id=\"gfg\"></p> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"geeks\"></p> <script> var up = document.getElementById('gfg'); var down = document.getElementById('geeks'); var date = new Date(); up.innerHTML = \"\" + date + \"\"; function GFG_Fun() { // Getting minutes var mins = date.getMinutes(); // Getting hours var hrs = date.getHours(); var m = (parseInt((mins + 7.5) / 15) * 15) % 60; // Converting '09:0' to '09:00' m = m < 10 ? '0' + m : m; var h = mins > 52 ? (hrs === 23 ? 0 : ++hrs) : hrs; // Converting '9:00' to '09:00' h = h < 10 ? '0' + h : h; down.innerHTML = h + \":\" + m; } </script></body> </html>", "e": 28459, "s": 27247, "text": null }, { "code": null, "e": 28467, "s": 28459, "text": "Output:" }, { "code": null, "e": 28849, "s": 28467, "text": "Approach 2: Use getMinutes() and getHours() methods to get the minutes and hours in a variable (Ex. mins, hrs). Divide mins by 15, take the round value by Math.round() and multiply it by 15, which will give the nearest quarter of minutes. If this value goes beyond 60, then take the mod with 60. For hrs, if mins 52 and if the hrs == 23, set hrs to 0 else increment its value by 1." }, { "code": null, "e": 30061, "s": 28849, "text": "Example:<!DOCTYPE HTML><html> <head> <title> Round time to the nearest quarter hour in JavaScript </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Click on button to round the time to nearest quarter hour </p> <p id=\"gfg\"></p> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"geeks\"></p> <script> var up = document.getElementById('gfg'); var down = document.getElementById('geeks'); var date = new Date(); up.innerHTML = \"\" + date + \"\"; function GFG_Fun() { // Getting minutes var mins = date.getMinutes(); // Getting hours var hrs = date.getHours(); var m = (Math.round(mins/15) * 15) % 60; // Converting '09:0' to '09:00' m = m < 10 ? '0' + m : m; var h = mins > 52 ? (hrs === 23 ? 0 : ++hrs) : hrs; // Converting '9:00' to '09:00' h = h < 10 ? '0' + h : h; down.innerHTML = h + \":\" + m; } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> Round time to the nearest quarter hour in JavaScript </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Click on button to round the time to nearest quarter hour </p> <p id=\"gfg\"></p> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"geeks\"></p> <script> var up = document.getElementById('gfg'); var down = document.getElementById('geeks'); var date = new Date(); up.innerHTML = \"\" + date + \"\"; function GFG_Fun() { // Getting minutes var mins = date.getMinutes(); // Getting hours var hrs = date.getHours(); var m = (Math.round(mins/15) * 15) % 60; // Converting '09:0' to '09:00' m = m < 10 ? '0' + m : m; var h = mins > 52 ? (hrs === 23 ? 0 : ++hrs) : hrs; // Converting '9:00' to '09:00' h = h < 10 ? '0' + h : h; down.innerHTML = h + \":\" + m; } </script></body> </html>", "e": 31265, "s": 30061, "text": null }, { "code": null, "e": 31273, "s": 31265, "text": "Output:" }, { "code": null, "e": 31282, "s": 31273, "text": "CSS-Misc" }, { "code": null, "e": 31292, "s": 31282, "text": "HTML-Misc" }, { "code": null, "e": 31308, "s": 31292, "text": "JavaScript-Misc" }, { "code": null, "e": 31312, "s": 31308, "text": "CSS" }, { "code": null, "e": 31317, "s": 31312, "text": "HTML" }, { "code": null, "e": 31328, "s": 31317, "text": "JavaScript" }, { "code": null, "e": 31345, "s": 31328, "text": "Web Technologies" }, { "code": null, "e": 31372, "s": 31345, "text": "Web technologies Questions" }, { "code": null, "e": 31377, "s": 31372, "text": "HTML" }, { "code": null, "e": 31475, "s": 31377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31484, "s": 31475, "text": "Comments" }, { "code": null, "e": 31497, "s": 31484, "text": "Old Comments" }, { "code": null, "e": 31538, "s": 31497, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 31575, "s": 31538, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31623, "s": 31575, "text": "How to set div width to fit content using CSS ?" }, { "code": null, "e": 31668, "s": 31623, "text": "How to set fixed width for <td> in a table ?" }, { "code": null, "e": 31723, "s": 31668, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 31783, "s": 31723, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31844, "s": 31783, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 31894, "s": 31844, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 31947, "s": 31894, "text": "Hide or show elements in HTML using display property" } ]