title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to Create Engraved Text Effect using HTML and CSS ? - GeeksforGeeks
08 Jun, 2020 The engraved text effect is an effect that you can use in your websites as a heading or a sub-heading to make it look more pleasing and attractive. Approach: The engraved text effect can be easily generated using HTML and CSS. First we will create a basic text using HTML and then by using the CSS text-shadow property we will generate the desired effect. Example 1: <!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Engraved Text Effect</title> <style> body { margin: 0; padding: 0; font-family: serif; justify-content: center; align-items: center; display: flex; background-color: #65E73C; } div { content: ''; font-size: 3em; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: transparent; background: #008000; -webkit-background-clip: text; text-shadow: 2px 5px 5px rgba(255, 255, 255, 0.3); } </style></head> <body> <div> <h2>GeeksforGeeks</h2> </div></body> </html> In the above example, we first create a div tag that contains some text inside of it, then we design text using CSS basic properties. Then we will use the text-shadow property to generate the engraved effect. Output: Example 2: <!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Engraved Text Effect</title> <style> body { margin: 0; padding: 0; font-family: serif; justify-content: center; align-items: center; display: flex; background-color: gray; } div { content: ''; font-size: 3em; position: absolute; top: 50%; left: 50%; transform: translate(-70%, -90%); color: transparent; background: black; -webkit-background-clip: text; text-shadow: 2px 5px 5px rgba(255, 255, 255, 0.3); } </style></head> <body> <div> <h2>GeeksforGeeks</h2> </div></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc 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 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 ? Design a web page using HTML and CSS How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 25913, "s": 25885, "text": "\n08 Jun, 2020" }, { "code": null, "e": 26061, "s": 25913, "text": "The engraved text effect is an effect that you can use in your websites as a heading or a sub-heading to make it look more pleasing and attractive." }, { "code": null, "e": 26269, "s": 26061, "text": "Approach: The engraved text effect can be easily generated using HTML and CSS. First we will create a basic text using HTML and then by using the CSS text-shadow property we will generate the desired effect." }, { "code": null, "e": 26280, "s": 26269, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title>Engraved Text Effect</title> <style> body { margin: 0; padding: 0; font-family: serif; justify-content: center; align-items: center; display: flex; background-color: #65E73C; } div { content: ''; font-size: 3em; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: transparent; background: #008000; -webkit-background-clip: text; text-shadow: 2px 5px 5px rgba(255, 255, 255, 0.3); } </style></head> <body> <div> <h2>GeeksforGeeks</h2> </div></body> </html>", "e": 27106, "s": 26280, "text": null }, { "code": null, "e": 27315, "s": 27106, "text": "In the above example, we first create a div tag that contains some text inside of it, then we design text using CSS basic properties. Then we will use the text-shadow property to generate the engraved effect." }, { "code": null, "e": 27323, "s": 27315, "text": "Output:" }, { "code": null, "e": 27334, "s": 27323, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title>Engraved Text Effect</title> <style> body { margin: 0; padding: 0; font-family: serif; justify-content: center; align-items: center; display: flex; background-color: gray; } div { content: ''; font-size: 3em; position: absolute; top: 50%; left: 50%; transform: translate(-70%, -90%); color: transparent; background: black; -webkit-background-clip: text; text-shadow: 2px 5px 5px rgba(255, 255, 255, 0.3); } </style></head> <body> <div> <h2>GeeksforGeeks</h2> </div></body> </html>", "e": 28155, "s": 27334, "text": null }, { "code": null, "e": 28163, "s": 28155, "text": "Output:" }, { "code": null, "e": 28300, "s": 28163, "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": 28309, "s": 28300, "text": "CSS-Misc" }, { "code": null, "e": 28319, "s": 28309, "text": "HTML-Misc" }, { "code": null, "e": 28323, "s": 28319, "text": "CSS" }, { "code": null, "e": 28328, "s": 28323, "text": "HTML" }, { "code": null, "e": 28345, "s": 28328, "text": "Web Technologies" }, { "code": null, "e": 28372, "s": 28345, "text": "Web technologies Questions" }, { "code": null, "e": 28377, "s": 28372, "text": "HTML" }, { "code": null, "e": 28475, "s": 28377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28530, "s": 28475, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 28567, "s": 28530, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28631, "s": 28567, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28670, "s": 28631, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28707, "s": 28670, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28767, "s": 28707, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28820, "s": 28767, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28881, "s": 28820, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28905, "s": 28881, "text": "REST API (Introduction)" } ]
DateFormat setLenient() Method in Java with Examples - GeeksforGeeks
01 Apr, 2019 The setLenient(boolean leniency) method in DateFormat class is used to specify whether the interpretation of the date and time of this DateFormat object is to be lenient or not. Syntax: public void setLenient(boolean leniency) Parameters: The method takes one parameter leniency of the boolean type that refers to the mode of the calendar of the DateFormat object. The boolean value true turns on the leniency mode and false turns off the leniency mode. Return Value: The method does not return any value. Below programs illustrate the working of setLenient() Method of Calendar class:Example 1: // Java code to illustrate// setLenient() method import java.text.*;import java.util.*; public class DateFormat_Demo { public static void main(String[] args) { // Initializing the first formatter DateFormat DFormat = DateFormat.getDateTimeInstance(); System.out.println("Object: " + DFormat); // String formatting String str = DFormat.format(new Date()); // Displaying the string time System.out.println(str); System.out.println("Leniency: " + DFormat.isLenient()); // Changing the leniency DFormat.setLenient(false); // Displaying the modified leniency System.out.println("New Leniency: " + DFormat.isLenient()); }} Object: java.text.SimpleDateFormat@7945516e Mar 28, 2019 6:03:48 PM Leniency: true New Leniency: false Example 2: // Java code to illustrate// setLenient() method import java.text.*;import java.util.*; public class DateFormat_Demo { public static void main(String[] args) { // Initializing the first formatter DateFormat DFormat = DateFormat.getDateInstance(); System.out.println("Object: " + DFormat); // String formatting String str = DFormat.format(new Date()); // Displaying the string time System.out.println(str); System.out.println("Leniency: " + DFormat.isLenient()); // Changing the leniency DFormat.setLenient(false); // Displaying the modified leniency System.out.println("New Leniency: " + DFormat.isLenient()); }} Object: java.text.SimpleDateFormat@ce9bf0a5 Mar 28, 2019 Leniency: true New Leniency: false Reference: https://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#setLenient(boolean) Java-DateFormat Java-Functions Java-text package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples 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
[ { "code": null, "e": 25753, "s": 25725, "text": "\n01 Apr, 2019" }, { "code": null, "e": 25931, "s": 25753, "text": "The setLenient(boolean leniency) method in DateFormat class is used to specify whether the interpretation of the date and time of this DateFormat object is to be lenient or not." }, { "code": null, "e": 25939, "s": 25931, "text": "Syntax:" }, { "code": null, "e": 25980, "s": 25939, "text": "public void setLenient(boolean leniency)" }, { "code": null, "e": 26207, "s": 25980, "text": "Parameters: The method takes one parameter leniency of the boolean type that refers to the mode of the calendar of the DateFormat object. The boolean value true turns on the leniency mode and false turns off the leniency mode." }, { "code": null, "e": 26259, "s": 26207, "text": "Return Value: The method does not return any value." }, { "code": null, "e": 26349, "s": 26259, "text": "Below programs illustrate the working of setLenient() Method of Calendar class:Example 1:" }, { "code": "// Java code to illustrate// setLenient() method import java.text.*;import java.util.*; public class DateFormat_Demo { public static void main(String[] args) { // Initializing the first formatter DateFormat DFormat = DateFormat.getDateTimeInstance(); System.out.println(\"Object: \" + DFormat); // String formatting String str = DFormat.format(new Date()); // Displaying the string time System.out.println(str); System.out.println(\"Leniency: \" + DFormat.isLenient()); // Changing the leniency DFormat.setLenient(false); // Displaying the modified leniency System.out.println(\"New Leniency: \" + DFormat.isLenient()); }}", "e": 27134, "s": 26349, "text": null }, { "code": null, "e": 27238, "s": 27134, "text": "Object: java.text.SimpleDateFormat@7945516e\nMar 28, 2019 6:03:48 PM\nLeniency: true\nNew Leniency: false\n" }, { "code": null, "e": 27249, "s": 27238, "text": "Example 2:" }, { "code": "// Java code to illustrate// setLenient() method import java.text.*;import java.util.*; public class DateFormat_Demo { public static void main(String[] args) { // Initializing the first formatter DateFormat DFormat = DateFormat.getDateInstance(); System.out.println(\"Object: \" + DFormat); // String formatting String str = DFormat.format(new Date()); // Displaying the string time System.out.println(str); System.out.println(\"Leniency: \" + DFormat.isLenient()); // Changing the leniency DFormat.setLenient(false); // Displaying the modified leniency System.out.println(\"New Leniency: \" + DFormat.isLenient()); }}", "e": 28032, "s": 27249, "text": null }, { "code": null, "e": 28125, "s": 28032, "text": "Object: java.text.SimpleDateFormat@ce9bf0a5\nMar 28, 2019\nLeniency: true\nNew Leniency: false\n" }, { "code": null, "e": 28224, "s": 28125, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#setLenient(boolean)" }, { "code": null, "e": 28240, "s": 28224, "text": "Java-DateFormat" }, { "code": null, "e": 28255, "s": 28240, "text": "Java-Functions" }, { "code": null, "e": 28273, "s": 28255, "text": "Java-text package" }, { "code": null, "e": 28278, "s": 28273, "text": "Java" }, { "code": null, "e": 28283, "s": 28278, "text": "Java" }, { "code": null, "e": 28381, "s": 28283, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28432, "s": 28381, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28462, "s": 28432, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28481, "s": 28462, "text": "Interfaces in Java" }, { "code": null, "e": 28496, "s": 28481, "text": "Stream In Java" }, { "code": null, "e": 28527, "s": 28496, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28545, "s": 28527, "text": "ArrayList in Java" }, { "code": null, "e": 28577, "s": 28545, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28597, "s": 28577, "text": "Stack Class in Java" }, { "code": null, "e": 28629, "s": 28597, "text": "Multidimensional Arrays in Java" } ]
Python Program for Insertion Sort - GeeksforGeeks
30 Dec, 2020 Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. # Python program for implementation of Insertion Sort # Function to do insertion sortdef insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key # Driver code to test abovearr = [12, 11, 13, 5, 6]insertionSort(arr)print ("Sorted array is:")for i in range(len(arr)): print ("%d" %arr[i]) # This code is contributed by Mohit Kumra Output: Sorted array is: 5 6 11 12 13 Please refer complete article on Insertion Sort for more details! python sorting-exercises Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python | Convert string dictionary to dictionary Iterate over characters of a string in Python Python Program for factorial of a number Python | Convert set into a list Python | Convert a list into a tuple Python | Check if a variable is string Add a key:value pair to dictionary in Python Appending to list in Python dictionary Python program to find sum of elements in list Python program to find largest number in a list
[ { "code": null, "e": 25603, "s": 25575, "text": "\n30 Dec, 2020" }, { "code": null, "e": 25703, "s": 25603, "text": "Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands." }, { "code": "# Python program for implementation of Insertion Sort # Function to do insertion sortdef insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key # Driver code to test abovearr = [12, 11, 13, 5, 6]insertionSort(arr)print (\"Sorted array is:\")for i in range(len(arr)): print (\"%d\" %arr[i]) # This code is contributed by Mohit Kumra", "e": 26360, "s": 25703, "text": null }, { "code": null, "e": 26368, "s": 26360, "text": "Output:" }, { "code": null, "e": 26400, "s": 26368, "text": "Sorted array is:\n5\n6\n11\n12\n13\n\n" }, { "code": null, "e": 26466, "s": 26400, "text": "Please refer complete article on Insertion Sort for more details!" }, { "code": null, "e": 26491, "s": 26466, "text": "python sorting-exercises" }, { "code": null, "e": 26507, "s": 26491, "text": "Python Programs" }, { "code": null, "e": 26605, "s": 26507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26654, "s": 26605, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 26700, "s": 26654, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 26741, "s": 26700, "text": "Python Program for factorial of a number" }, { "code": null, "e": 26774, "s": 26741, "text": "Python | Convert set into a list" }, { "code": null, "e": 26811, "s": 26774, "text": "Python | Convert a list into a tuple" }, { "code": null, "e": 26850, "s": 26811, "text": "Python | Check if a variable is string" }, { "code": null, "e": 26895, "s": 26850, "text": "Add a key:value pair to dictionary in Python" }, { "code": null, "e": 26934, "s": 26895, "text": "Appending to list in Python dictionary" }, { "code": null, "e": 26981, "s": 26934, "text": "Python program to find sum of elements in list" } ]
Python Set | Pairs of complete strings in two sets - GeeksforGeeks
03 Jan, 2018 Two strings are said to be complete if on concatenation, they contain all the 26 English alphabets. For example, “abcdefghi” and “jklmnopqrstuvwxyz” are complete as they together have all characters from ‘a’ to ‘z’.We are given two sets of sizes n and m respectively and we need to find the number of pairs that are complete on concatenating each string from set 1 to each string from set 2. Examples: Input : set1[] = {"abcdefgh", "geeksforgeeks", "lmnopqrst", "abc"} set2[] = {"ijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz", "defghijklmnopqrstuvwxyz"} Output : 7 The total complete pairs that are forming are: "abcdefghijklmnopqrstuvwxyz" "abcdefghabcdefghijklmnopqrstuvwxyz" "abcdefghdefghijklmnopqrstuvwxyz" "geeksforgeeksabcdefghijklmnopqrstuvwxyz" "lmnopqrstabcdefghijklmnopqrstuvwxyz" "abcabcdefghijklmnopqrstuvwxyz" "abcdefghijklmnopqrstuvwxyz" We have existing solution for this problem please refer Pairs of complete strings in two sets of strings link. We can solve this problem quickly in python using Set data structure. Approach is very simple, Consider all pairs of strings, concatenate them one by one and converts it into set.Now one by one add all alphabets in concatenated string into set. Since set contains unique values so if length of set is equal to 26 that means set contains all 26 english alphabets. Consider all pairs of strings, concatenate them one by one and converts it into set. Now one by one add all alphabets in concatenated string into set. Since set contains unique values so if length of set is equal to 26 that means set contains all 26 english alphabets. # Function to find pairs of complete strings# in two sets of strings def completePair(set1,set2): # consider all pairs of string from # set1 and set2 count = 0 for str1 in set1: for str2 in set2: result = str1 + str2 # push all alphabets of concatenated # string into temporary set tmpSet = set([ch for ch in result if (ord(ch)>=ord('a') and ord(ch)<=ord('z'))]) if len(tmpSet)==26: count = count + 1 print (count) # Driver programif __name__ == "__main__": set1 = ['abcdefgh', 'geeksforgeeks','lmnopqrst', 'abc'] set2 = ['ijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz','defghijklmnopqrstuvwxyz'] completePair(set1,set2) Output: 7 python-set python-string Python python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26305, "s": 26277, "text": "\n03 Jan, 2018" }, { "code": null, "e": 26697, "s": 26305, "text": "Two strings are said to be complete if on concatenation, they contain all the 26 English alphabets. For example, “abcdefghi” and “jklmnopqrstuvwxyz” are complete as they together have all characters from ‘a’ to ‘z’.We are given two sets of sizes n and m respectively and we need to find the number of pairs that are complete on concatenating each string from set 1 to each string from set 2." }, { "code": null, "e": 26707, "s": 26697, "text": "Examples:" }, { "code": null, "e": 27225, "s": 26707, "text": "Input : set1[] = {\"abcdefgh\", \"geeksforgeeks\",\n \"lmnopqrst\", \"abc\"}\n set2[] = {\"ijklmnopqrstuvwxyz\", \n \"abcdefghijklmnopqrstuvwxyz\", \n \"defghijklmnopqrstuvwxyz\"} \nOutput : 7\nThe total complete pairs that are forming are:\n\"abcdefghijklmnopqrstuvwxyz\"\n\"abcdefghabcdefghijklmnopqrstuvwxyz\"\n\"abcdefghdefghijklmnopqrstuvwxyz\"\n\"geeksforgeeksabcdefghijklmnopqrstuvwxyz\"\n\"lmnopqrstabcdefghijklmnopqrstuvwxyz\"\n\"abcabcdefghijklmnopqrstuvwxyz\"\n\"abcdefghijklmnopqrstuvwxyz\"\n" }, { "code": null, "e": 27431, "s": 27225, "text": "We have existing solution for this problem please refer Pairs of complete strings in two sets of strings link. We can solve this problem quickly in python using Set data structure. Approach is very simple," }, { "code": null, "e": 27699, "s": 27431, "text": "Consider all pairs of strings, concatenate them one by one and converts it into set.Now one by one add all alphabets in concatenated string into set. Since set contains unique values so if length of set is equal to 26 that means set contains all 26 english alphabets." }, { "code": null, "e": 27784, "s": 27699, "text": "Consider all pairs of strings, concatenate them one by one and converts it into set." }, { "code": null, "e": 27968, "s": 27784, "text": "Now one by one add all alphabets in concatenated string into set. Since set contains unique values so if length of set is equal to 26 that means set contains all 26 english alphabets." }, { "code": "# Function to find pairs of complete strings# in two sets of strings def completePair(set1,set2): # consider all pairs of string from # set1 and set2 count = 0 for str1 in set1: for str2 in set2: result = str1 + str2 # push all alphabets of concatenated # string into temporary set tmpSet = set([ch for ch in result if (ord(ch)>=ord('a') and ord(ch)<=ord('z'))]) if len(tmpSet)==26: count = count + 1 print (count) # Driver programif __name__ == \"__main__\": set1 = ['abcdefgh', 'geeksforgeeks','lmnopqrst', 'abc'] set2 = ['ijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz','defghijklmnopqrstuvwxyz'] completePair(set1,set2)", "e": 28704, "s": 27968, "text": null }, { "code": null, "e": 28712, "s": 28704, "text": "Output:" }, { "code": null, "e": 28715, "s": 28712, "text": "7\n" }, { "code": null, "e": 28726, "s": 28715, "text": "python-set" }, { "code": null, "e": 28740, "s": 28726, "text": "python-string" }, { "code": null, "e": 28747, "s": 28740, "text": "Python" }, { "code": null, "e": 28758, "s": 28747, "text": "python-set" }, { "code": null, "e": 28856, "s": 28758, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28874, "s": 28856, "text": "Python Dictionary" }, { "code": null, "e": 28909, "s": 28874, "text": "Read a file line by line in Python" }, { "code": null, "e": 28941, "s": 28909, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28963, "s": 28941, "text": "Enumerate() in Python" }, { "code": null, "e": 29005, "s": 28963, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29035, "s": 29005, "text": "Iterate over a list in Python" }, { "code": null, "e": 29061, "s": 29035, "text": "Python String | replace()" }, { "code": null, "e": 29090, "s": 29061, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29134, "s": 29090, "text": "Reading and Writing to text files in Python" } ]
Add Common Main Title for Multiple Plots in R - GeeksforGeeks
29 Jun, 2021 In this article, we will be looking at the two different approaches to add a common main title for multiple plots in base R and ggplot2 package in the R programming language. In this approach to add a common main title for multiple plots, the user needs to call the par() and the mtext() function, which is the in-built functions of the R programming language, here the user needs to also use the mfrow argument of the par function and pass the required parameters in both functions, then create a matrix of nrows x ncols plots which will lead to the formation of the multiple plots in the single plots and the mtext() function will add the text is written in one of the four margins of the current figure region which will lead to the addition of the common main title for multiple plots in the R programming language. par() function can be used to set or query graphical parameters. Syntax: par(..., no.readonly = FALSE) Parameter: ...: arguments in tag = value form, or a list of tagged values. no.readonly: logical; if TRUE and there are no other arguments, only parameters are returned which can be set by a subsequent par() call on the same device. mtext() function is used to text written in one of the four margins of the current figure region or one of the outer margins of the device region Syntax: mtext(text, side = 3, line = 0, outer = FALSE, at = NA, adj = NA, padj = NA, cex = NA, col = NA, font = NA, ...) Parameter: text: a character or expression vector specifying the text to be written. Other objects are coerced by as.graphicsAnnot. side: on which side of the plot (1=bottom, 2=left, 3=top, 4=right). line: on which MARgin line, starting at 0 countings outwards. outer: use outer margins if available. at: give the location of each string in user coordinates. adj: adjustment for each string in reading direction. padj: adjustment for each string perpendicular to the reading direction. cex: character expansion factor. NULL and NA are equivalent to 1.0. col: color to use. Can be a vector. NA values (the default) mean use par(“col”). font: font for text. Can be a vector. NA values (the default) mean use par(“font”). ...: Further graphical parameters, including family, las and xpd. Example: Data in use: R gfg_data <- data.frame(x = 1:10,y = 10:1) par(mfrow = c(2, 2)) plot(gfg_data$x, gfg_data$y) plot(density(gfg_data$x), main = "") barplot(gfg_data$x)boxplot(gfg_data) mtext("GFG Multiplot", side = 3, line = - 2, outer = TRUE) Output: In this approach to add a common main title for multiple plots, the user first needs to install and import the ggplot2 and the patchwork package in the R console, and with the help of the ggplot2 package user will be able to plot multiple plots and with the help of the patch package and call the plot_annotation() with the required parameters and the user will be able to add the common main title to the multiple plots created by the ggplot2 package and further, it will lead to the addition of common main title for multiple plots. plot_annotation() function is mainly used to annotate the final patchwork. Syntax: plot_annotation( title = NULL, subtitle = NULL, caption = NULL, tag_levels = NULL, tag_prefix = NULL, tag_suffix = NULL, tag_sep = NULL, theme = NULL) Parameters: title, subtitle, caption: Text strings to use for the various plot annotations. tag_levels: A character vector defining the enumeration format to use at each level. tag_prefix, tag_suffix: Strings that should appear before or after the tag. tag_sep: A separator between different tag levels theme: A ggplot theme specification to use for the plot. Only elements related to the titles as well as plot margin and background is used. Example: Data in use: R library("ggplot2")library("patchwork") gfg_data <- data.frame(x = 1:10,y = 10:1) gfg_plot_1 <- ggplot(gfg_data, aes(x, y)) + geom_point()gfg_plot_2 <- ggplot(gfg_data, aes(x)) + geom_density()gfg_plot_3 <- ggplot(gfg_data, aes(x)) +geom_boxplot() gfg_plot <- (gfg_plot_1 + gfg_plot_2) / (gfg_plot_3 ) + plot_annotation(title = "GFG Multiplot") & theme(plot.title = element_text(hjust = 0.5)) gfg_plot Output: Picked R-Charts R-ggplot R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to import an Excel File into R ? How to filter R DataFrame by values in a column? Time Series Analysis in R R - if statement Logistic Regression in R Programming
[ { "code": null, "e": 26487, "s": 26459, "text": "\n29 Jun, 2021" }, { "code": null, "e": 26662, "s": 26487, "text": "In this article, we will be looking at the two different approaches to add a common main title for multiple plots in base R and ggplot2 package in the R programming language." }, { "code": null, "e": 27307, "s": 26662, "text": "In this approach to add a common main title for multiple plots, the user needs to call the par() and the mtext() function, which is the in-built functions of the R programming language, here the user needs to also use the mfrow argument of the par function and pass the required parameters in both functions, then create a matrix of nrows x ncols plots which will lead to the formation of the multiple plots in the single plots and the mtext() function will add the text is written in one of the four margins of the current figure region which will lead to the addition of the common main title for multiple plots in the R programming language." }, { "code": null, "e": 27372, "s": 27307, "text": "par() function can be used to set or query graphical parameters." }, { "code": null, "e": 27380, "s": 27372, "text": "Syntax:" }, { "code": null, "e": 27410, "s": 27380, "text": "par(..., no.readonly = FALSE)" }, { "code": null, "e": 27421, "s": 27410, "text": "Parameter:" }, { "code": null, "e": 27485, "s": 27421, "text": "...: arguments in tag = value form, or a list of tagged values." }, { "code": null, "e": 27642, "s": 27485, "text": "no.readonly: logical; if TRUE and there are no other arguments, only parameters are returned which can be set by a subsequent par() call on the same device." }, { "code": null, "e": 27788, "s": 27642, "text": "mtext() function is used to text written in one of the four margins of the current figure region or one of the outer margins of the device region" }, { "code": null, "e": 27796, "s": 27788, "text": "Syntax:" }, { "code": null, "e": 27894, "s": 27796, "text": "mtext(text, side = 3, line = 0, outer = FALSE, at = NA, adj = NA, padj = NA, cex = NA, col = NA," }, { "code": null, "e": 27911, "s": 27894, "text": " font = NA, ...)" }, { "code": null, "e": 27922, "s": 27911, "text": "Parameter:" }, { "code": null, "e": 28043, "s": 27922, "text": "text: a character or expression vector specifying the text to be written. Other objects are coerced by as.graphicsAnnot." }, { "code": null, "e": 28111, "s": 28043, "text": "side: on which side of the plot (1=bottom, 2=left, 3=top, 4=right)." }, { "code": null, "e": 28173, "s": 28111, "text": "line: on which MARgin line, starting at 0 countings outwards." }, { "code": null, "e": 28212, "s": 28173, "text": "outer: use outer margins if available." }, { "code": null, "e": 28270, "s": 28212, "text": "at: give the location of each string in user coordinates." }, { "code": null, "e": 28324, "s": 28270, "text": "adj: adjustment for each string in reading direction." }, { "code": null, "e": 28397, "s": 28324, "text": "padj: adjustment for each string perpendicular to the reading direction." }, { "code": null, "e": 28465, "s": 28397, "text": "cex: character expansion factor. NULL and NA are equivalent to 1.0." }, { "code": null, "e": 28546, "s": 28465, "text": "col: color to use. Can be a vector. NA values (the default) mean use par(“col”)." }, { "code": null, "e": 28630, "s": 28546, "text": "font: font for text. Can be a vector. NA values (the default) mean use par(“font”)." }, { "code": null, "e": 28696, "s": 28630, "text": "...: Further graphical parameters, including family, las and xpd." }, { "code": null, "e": 28705, "s": 28696, "text": "Example:" }, { "code": null, "e": 28718, "s": 28705, "text": "Data in use:" }, { "code": null, "e": 28720, "s": 28718, "text": "R" }, { "code": "gfg_data <- data.frame(x = 1:10,y = 10:1) par(mfrow = c(2, 2)) plot(gfg_data$x, gfg_data$y) plot(density(gfg_data$x), main = \"\") barplot(gfg_data$x)boxplot(gfg_data) mtext(\"GFG Multiplot\", side = 3, line = - 2, outer = TRUE)", "e": 28995, "s": 28720, "text": null }, { "code": null, "e": 29003, "s": 28995, "text": "Output:" }, { "code": null, "e": 29538, "s": 29003, "text": "In this approach to add a common main title for multiple plots, the user first needs to install and import the ggplot2 and the patchwork package in the R console, and with the help of the ggplot2 package user will be able to plot multiple plots and with the help of the patch package and call the plot_annotation() with the required parameters and the user will be able to add the common main title to the multiple plots created by the ggplot2 package and further, it will lead to the addition of common main title for multiple plots." }, { "code": null, "e": 29613, "s": 29538, "text": "plot_annotation() function is mainly used to annotate the final patchwork." }, { "code": null, "e": 29621, "s": 29613, "text": "Syntax:" }, { "code": null, "e": 29772, "s": 29621, "text": "plot_annotation( title = NULL, subtitle = NULL, caption = NULL, tag_levels = NULL, tag_prefix = NULL, tag_suffix = NULL, tag_sep = NULL, theme = NULL)" }, { "code": null, "e": 29784, "s": 29772, "text": "Parameters:" }, { "code": null, "e": 29864, "s": 29784, "text": "title, subtitle, caption: Text strings to use for the various plot annotations." }, { "code": null, "e": 29949, "s": 29864, "text": "tag_levels: A character vector defining the enumeration format to use at each level." }, { "code": null, "e": 30025, "s": 29949, "text": "tag_prefix, tag_suffix: Strings that should appear before or after the tag." }, { "code": null, "e": 30075, "s": 30025, "text": "tag_sep: A separator between different tag levels" }, { "code": null, "e": 30215, "s": 30075, "text": "theme: A ggplot theme specification to use for the plot. Only elements related to the titles as well as plot margin and background is used." }, { "code": null, "e": 30224, "s": 30215, "text": "Example:" }, { "code": null, "e": 30237, "s": 30224, "text": "Data in use:" }, { "code": null, "e": 30239, "s": 30237, "text": "R" }, { "code": "library(\"ggplot2\")library(\"patchwork\") gfg_data <- data.frame(x = 1:10,y = 10:1) gfg_plot_1 <- ggplot(gfg_data, aes(x, y)) + geom_point()gfg_plot_2 <- ggplot(gfg_data, aes(x)) + geom_density()gfg_plot_3 <- ggplot(gfg_data, aes(x)) +geom_boxplot() gfg_plot <- (gfg_plot_1 + gfg_plot_2) / (gfg_plot_3 ) + plot_annotation(title = \"GFG Multiplot\") & theme(plot.title = element_text(hjust = 0.5)) gfg_plot", "e": 30646, "s": 30239, "text": null }, { "code": null, "e": 30654, "s": 30646, "text": "Output:" }, { "code": null, "e": 30661, "s": 30654, "text": "Picked" }, { "code": null, "e": 30670, "s": 30661, "text": "R-Charts" }, { "code": null, "e": 30679, "s": 30670, "text": "R-ggplot" }, { "code": null, "e": 30688, "s": 30679, "text": "R-Graphs" }, { "code": null, "e": 30696, "s": 30688, "text": "R-plots" }, { "code": null, "e": 30707, "s": 30696, "text": "R Language" }, { "code": null, "e": 30805, "s": 30707, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30857, "s": 30805, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30892, "s": 30857, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30930, "s": 30892, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30988, "s": 30930, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 31031, "s": 30988, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 31068, "s": 31031, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 31117, "s": 31068, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 31143, "s": 31117, "text": "Time Series Analysis in R" }, { "code": null, "e": 31160, "s": 31143, "text": "R - if statement" } ]
C program to draw a football ground using computer graphics - GeeksforGeeks
04 May, 2021 In this article, we will discuss how to design a 2D football ground using computer graphics. Approach: At first, create a rectangle using the rectangle() function. This will act as the Ground Outline and draw two lines using the line() function. For coloring the middle part of two lines with White using the setfillstyle() and floodfill() functions. Then draw two circles using the circle() function and also color Middle part with White using setfillstyle() & floodfill() functions. Draw a total of four rectangles using the rectangle() function on the left side. Among them, two will act as the outer outline and two will act as the Inner outline. Then color the middle parts of rectangles with white using the setfillstyle() & floodfill() functions. Draw the two half circles using the arc() function and also color it with white color using setfillstyle() & floodfill() functions. Perform all the above operations on the right side also. Below is the implementation of the above approach: C // C program for the above approach #include <conio.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ int gd = DETECT, gm; // Initialize of gdriver with // DETECT macros initgraph(&gd, &gm, "C:\\turboc3\\bgi"); // Ground Outline rectangle(100, 50, 1200, 550); // Coloring Green setfillstyle(SOLID_FILL, GREEN); floodfill(150, 150, 15); // Ground Middle Line line(650, 50, 650, 550); line(656, 50, 656, 550); // Coloring White setfillstyle(SOLID_FILL, WHITE); floodfill(652, 150, 15); // Mid Circles circle(653, 300, 60); circle(653, 300, 65); circle(653, 300, 10); // Outer Rectangle Left rectangle(100, 200, 250, 400); rectangle(100, 205, 245, 395); // Inner Rectangle Left rectangle(100, 230, 200, 370); rectangle(100, 235, 195, 365); // Arc Left Side arc(250, 300, 270, 90, 40); arc(250, 300, 270, 90, 35); // Outer Rectangle Right rectangle(1200, 200, 1050, 400); rectangle(1200, 205, 1055, 395); // Inner Rectangle Right rectangle(1200, 230, 1100, 370); rectangle(1200, 235, 1105, 365); // Arc Right Side arc(1051, 300, 90, 270, 40); arc(1051, 300, 90, 270, 35); // Coloring All White floodfill(714, 300, 15); floodfill(592, 300, 15); floodfill(657, 300, 15); floodfill(645, 300, 15); floodfill(247, 300, 15); floodfill(197, 300, 15); floodfill(287, 300, 15); floodfill(1053, 300, 15); floodfill(1103, 300, 15); floodfill(1013, 300, 15); // Holding Screen For a While getch(); // Close the initialized gdriver closegraph();} Output computer-graphics C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C Exit codes in C/C++ with Examples C program to find the length of a string C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7 Handling multiple clients on server with multithreading using Socket Programming in C/C++ Regular expressions in C Conditional wait and signal in multi-threading Create n-child process from same parent process using fork() in C How to store words in an array in C?
[ { "code": null, "e": 26201, "s": 26173, "text": "\n04 May, 2021" }, { "code": null, "e": 26294, "s": 26201, "text": "In this article, we will discuss how to design a 2D football ground using computer graphics." }, { "code": null, "e": 26304, "s": 26294, "text": "Approach:" }, { "code": null, "e": 26447, "s": 26304, "text": "At first, create a rectangle using the rectangle() function. This will act as the Ground Outline and draw two lines using the line() function." }, { "code": null, "e": 26552, "s": 26447, "text": "For coloring the middle part of two lines with White using the setfillstyle() and floodfill() functions." }, { "code": null, "e": 26686, "s": 26552, "text": "Then draw two circles using the circle() function and also color Middle part with White using setfillstyle() & floodfill() functions." }, { "code": null, "e": 26767, "s": 26686, "text": "Draw a total of four rectangles using the rectangle() function on the left side." }, { "code": null, "e": 26852, "s": 26767, "text": "Among them, two will act as the outer outline and two will act as the Inner outline." }, { "code": null, "e": 26955, "s": 26852, "text": "Then color the middle parts of rectangles with white using the setfillstyle() & floodfill() functions." }, { "code": null, "e": 27087, "s": 26955, "text": "Draw the two half circles using the arc() function and also color it with white color using setfillstyle() & floodfill() functions." }, { "code": null, "e": 27144, "s": 27087, "text": "Perform all the above operations on the right side also." }, { "code": null, "e": 27195, "s": 27144, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27197, "s": 27195, "text": "C" }, { "code": "// C program for the above approach #include <conio.h>#include <graphics.h>#include <stdio.h> // Driver Codevoid main(){ int gd = DETECT, gm; // Initialize of gdriver with // DETECT macros initgraph(&gd, &gm, \"C:\\\\turboc3\\\\bgi\"); // Ground Outline rectangle(100, 50, 1200, 550); // Coloring Green setfillstyle(SOLID_FILL, GREEN); floodfill(150, 150, 15); // Ground Middle Line line(650, 50, 650, 550); line(656, 50, 656, 550); // Coloring White setfillstyle(SOLID_FILL, WHITE); floodfill(652, 150, 15); // Mid Circles circle(653, 300, 60); circle(653, 300, 65); circle(653, 300, 10); // Outer Rectangle Left rectangle(100, 200, 250, 400); rectangle(100, 205, 245, 395); // Inner Rectangle Left rectangle(100, 230, 200, 370); rectangle(100, 235, 195, 365); // Arc Left Side arc(250, 300, 270, 90, 40); arc(250, 300, 270, 90, 35); // Outer Rectangle Right rectangle(1200, 200, 1050, 400); rectangle(1200, 205, 1055, 395); // Inner Rectangle Right rectangle(1200, 230, 1100, 370); rectangle(1200, 235, 1105, 365); // Arc Right Side arc(1051, 300, 90, 270, 40); arc(1051, 300, 90, 270, 35); // Coloring All White floodfill(714, 300, 15); floodfill(592, 300, 15); floodfill(657, 300, 15); floodfill(645, 300, 15); floodfill(247, 300, 15); floodfill(197, 300, 15); floodfill(287, 300, 15); floodfill(1053, 300, 15); floodfill(1103, 300, 15); floodfill(1013, 300, 15); // Holding Screen For a While getch(); // Close the initialized gdriver closegraph();}", "e": 28834, "s": 27197, "text": null }, { "code": null, "e": 28841, "s": 28834, "text": "Output" }, { "code": null, "e": 28859, "s": 28841, "text": "computer-graphics" }, { "code": null, "e": 28870, "s": 28859, "text": "C Programs" }, { "code": null, "e": 28968, "s": 28870, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29009, "s": 28968, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 29040, "s": 29009, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 29074, "s": 29040, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 29115, "s": 29074, "text": "C program to find the length of a string" }, { "code": null, "e": 29186, "s": 29115, "text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 29276, "s": 29186, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 29301, "s": 29276, "text": "Regular expressions in C" }, { "code": null, "e": 29348, "s": 29301, "text": "Conditional wait and signal in multi-threading" }, { "code": null, "e": 29414, "s": 29348, "text": "Create n-child process from same parent process using fork() in C" } ]
Maximum Tip Calculator - GeeksforGeeks
28 Feb, 2022 Rahul and Ankit are the only two waiters in the Royal Restaurant. Today, the restaurant received N orders. The amount of tips may differ when handled by different waiters and given as arrays A[] and B[] such that if Rahul takes the ith Order, he would be tipped A[i] rupees, and if Ankit takes this order, the tip would be B[i] rupees. In order to maximize the total tip value, they decided to distribute the order among themselves. One order will be handled by one person only. Also, due to time constraints, Rahul cannot take more than X orders and Ankit cannot take more than Y orders. It is guaranteed that X + Y is greater than or equal to N, which means that all the orders can be handled by either Rahul or Ankit. The task is to find out the maximum possible amount of total tip money after processing all the orders. Examples: Input: N = 5, X = 3, Y = 3, A[] = {1, 2, 3, 4, 5}, B[] = {5, 4, 3, 2, 1}Output: 21Explanation:Step 1: 5 is included from Ankit’s arrayStep 2: 4 is included from Ankit’s arrayStep 3: As both of them has same value 3 then choose any one of themStep 4: 4 is included from Rahul’s arrayStep 4: 5 is included from Rahul’s arrayTherefore, the maximum possible amount of total tip money sums up to 21. Input: N = 7, X = 3, Y = 4, A[] = {8, 7, 15, 19, 16, 16, 18}, B[] = {1, 7, 15, 11, 12, 31, 9}Output: 110 Naive Approach: The simplest approach is to traverse the given arrays and start traversing both the arrays simultaneously and pick the maximum element among them and reduce the count of X if the element is taken from X else the count of Y. If one of the X or Y becomes 0, traverse other non-zero array and add its value to the maximum profit. As in every step, there is a choice to be made, this is similar to the 0-1 Knapsack Problem, in which decisions are made whether to include or exclude an element. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that finds the maximum tips// from the given arrays as per the// given conditionsint maximumTip(vector<int> &arr1,vector<int> & arr2, int n, int x, int y){ // Base Condition if (n == 0) return 0; // If both have non-zero count then // return max element from both array if (x != 0 and y != 0) return max( arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y), arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1)); // Traverse first array, as y // count has become 0 if (y == 0) return arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y); // Traverse 2nd array, as x // count has become 0 else return arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1);} // Drive Codeint main(){ int N = 5; int X = 3; int Y = 3; vector<int> A = { 1, 2, 3, 4, 5 }; vector<int> B = { 5, 4, 3, 2, 1 }; // Function Call cout << (maximumTip(A, B, N, X, Y));} // This code is contributed by mohit kumar 29 /*package whatever //do not write package name here */import java.io.*; class GFG{ // Function that finds the maximum tips// from the given arrays as per the// given conditionsstatic int maximumTip(int []arr1,int []arr2, int n, int x, int y){ // Base Condition if (n == 0) return 0; // If both have non-zero count then // return max element from both array if (x != 0 && y != 0) return Math.max( arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y), arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1)); // Traverse first array, as y // count has become 0 if (y == 0) return arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y); // Traverse 2nd array, as x // count has become 0 else return arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1);} // Drive Code public static void main (String[] args) { int N = 5; int X = 3; int Y = 3; int A[] = { 1, 2, 3, 4, 5 }; int B[] = { 5, 4, 3, 2, 1 }; // Function Call System.out.println(maximumTip(A, B, N, X, Y)); }} // This code is contributed by Potta Lokesh # Python program for the above approach # Function that finds the maximum tips# from the given arrays as per the# given conditionsdef maximumTip(arr1, arr2, n, x, y): # Base Condition if n == 0: return 0 # If both have non-zero count then # return max element from both array if x != 0 and y != 0: return max( arr1[n-1] + maximumTip(arr1, arr2, n - 1, x-1, y), arr2[n-1] + maximumTip(arr1, arr2, n-1, x, y-1) ) # Traverse first array, as y # count has become 0 if y == 0: return arr1[n-1] + maximumTip(arr1, arr2, n-1, x-1, y) # Traverse 2nd array, as x # count has become 0 else: return arr2[n - 1] + maximumTip(arr1, arr2, n-1, x, y-1) # Drive CodeN = 5X = 3Y = 3A = [1, 2, 3, 4, 5]B = [5, 4, 3, 2, 1] # Function Callprint(maximumTip(A, B, N, X, Y)) /*package whatever //do not write package name here */using System;public class GFG{ // Function that finds the maximum tips // from the given arrays as per the // given conditions static int maximumTip(int []arr1,int []arr2, int n, int x, int y) { // Base Condition if (n == 0) return 0; // If both have non-zero count then // return max element from both array if (x != 0 && y != 0) return Math.Max( arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y), arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1)); // Traverse first array, as y // count has become 0 if (y == 0) return arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y); // Traverse 2nd array, as x // count has become 0 else return arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1); } // Drive Code public static void Main(String[] args) { int N = 5; int X = 3; int Y = 3; int []A = { 1, 2, 3, 4, 5 }; int []B = { 5, 4, 3, 2, 1 }; // Function Call Console.WriteLine(maximumTip(A, B, N, X, Y)); }} // This code is contributed by umadevi9616 <script> // JavaScript Program for the above approach // Function that finds the maximum tips // from the given arrays as per the // given conditions function maximumTip(arr1, arr2, n, x, y) { // Base Condition if (n == 0) return 0; // If both have non-zero count then // return max element from both array if (x != 0 && y != 0) return Math.max( arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y), arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1)); // Traverse first array, as y // count has become 0 if (y == 0) return arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y); // Traverse 2nd array, as x // count has become 0 else return arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1); } // Drive Code let N = 5; let X = 3; let Y = 3; let A = [1, 2, 3, 4, 5]; let B = [5, 4, 3, 2, 1]; // Function Call document.write(maximumTip(A, B, N, X, Y)); // This code is contributed by Potta Lokesh </script> 21 Time Complexity: O(2N)Auxiliary Space: O(1) Efficient Approach: The above approach can be optimized by using Dynamic Programming and Memoization. If execution is traced for the values of N, X, Y, it can be seen that are there are Overlapping Subproblems. These overlapping subproblems can be computed once and stored and used when the same subproblem is called in the recursive call. Below are the steps: Initialize a Map/Dictionary to store the overlapping subproblems result. The keys of the map will be combined values of N, X, and Y. At each recursive call, check if a given key is present in the map then return the value from the map itself. Else, call the function recursively and store the value in the map and return the stored value. If X and Y are non-zero, recursively call function and take the maximum of the value returned when X is used and when Y is used. If X or Y is zero, recursively call for the non-zero array. After the above recursive calls end, then print the maximum possible amount of tip calculated. Below is the implementation of the above approach: C++ Java Python3 Javascript #include <bits/stdc++.h>using namespace std;int dp[1001][101][101];int rec(int level, int x, int y, int arr1[], int arr2[], int n){ if (level == n) return 0; if (x == 0 && y == 0) return 0; if (x == 0) return arr2[level] + rec(level + 1, x, y - 1, arr1, arr2, n); if (y == 0) return arr1[level] + rec(level + 1, x - 1, y, arr1, arr2, n); if (dp[level][x][y] != -1) return dp[level][x][y]; int ans = max(rec(level + 1, x - 1, y, arr1, arr2, n) + arr1[level], rec(level + 1, x, y - 1, arr1, arr2, n) + arr2[level]); return dp[level][x][y] = ans;} void solve(){ int n = 7, x = 3, y = 4; int arr1[] = { 8, 7, 15, 19, 16, 16, 18 }, arr2[] = { 1, 7, 15, 11, 12, 31, 9 }; memset(dp, -1, sizeof(dp)); cout << rec(0, x, y, arr1, arr2, n);}int main(){ solve(); return 0;} // Java program for the above approachimport java.io.*;import java.util.HashMap; class GFG { // Function that finds the maximum tips // from the given arrays as per the // given conditions static int maximumTip(int[] arr1, int[] arr2, int n, int x, int y, HashMap<String, Integer> dd) { // Create key of N, X, Y String key = Integer.toString(n) + "_" + Integer.toString(x) + "_" + Integer.toString(y); // Return if the current state is // already calculated if (dd.get(key) != null) return dd.get(key); // Base Condition if (n == 0) return 0; // If both have non-zero count then store and // return max element from both array if (x != 0 && y != 0) { int temp = Math.max( arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y, dd), arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1, dd)); dd.put(key, temp); // Return the current state result return dd.get(key); } // if y is zero, only x value // can be used if (y == 0) { int temp = arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y, dd); dd.put(key, temp); // Return the current state result return dd.get(key); } // if x is zero, only y value // can be used else { int temp = arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1, dd); dd.put(key, temp); // Return the current state result return dd.get(key); } } // Driver Code public static void main(String[] args) { int N = 5; int X = 3; int Y = 3; int A[] = { 1, 2, 3, 4, 5 }; int B[] = { 5, 4, 3, 2, 1 }; // Stores the results of the // overlapping state HashMap<String, Integer> dd = new HashMap<String, Integer>(); // Function Call System.out.println(maximumTip(A, B, N, X, Y, dd)); }} // This code is contributed by MuskanKalra1 # Python program for the above approach # Function that finds the maximum tips# from the given arrays as per the# given conditionsdef maximumTip(arr1, arr2, n, x, y, dd): # Create key of N, X, Y key = str(n) + '_' + str(x) + '_' + str(y) # Return if the current state is # already calculated if key in dd: return dd[key] # Base Condition if n == 0: return 0 # Store and return if x != 0 and y != 0: dd[key] = max( arr1[n-1] + maximumTip(arr1, arr2, n-1, x-1, y, dd), arr2[n-1] + maximumTip(arr1, arr2, n-1, x, y-1, dd) ) # Return the current state result return dd[key] # If y is zero, only x value # can be used if y == 0: dd[key] = arr1[n-1] + maximumTip(arr1, arr2, n-1, x-1, y, dd) # Return the current state result return dd[key] # If x is zero, only y value # can be used else: dd[key] = arr2[n-1] + maximumTip(arr1, arr2, n-1, x, y-1, dd) # Return the current state result return dd[key] # Drive CodeN = 5X = 3Y = 3A = [1, 2, 3, 4, 5]B = [5, 4, 3, 2, 1] # Stores the results of the# overlapping statedd = {} # Function Callprint(maximumTip(A, B, N, X, Y, dd)) <script> // JavaScript program for the above approach// Function that finds the maximum tips// from the given arrays as per the// given conditions function maximumTip(arr1, arr2, n, x, y, dd) { // Create key of N, X, Y key = `${n}_${x}_${y}`; // Return if the current state is // already calculated for (var key in dd) { return dd[key]; } // Base Condition if (n == 0) { return 0; } // Store and return if (x != 0 && y != 0) { dd[key] = Math.max( arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y, dd), arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1, dd) ); // Return the current state result return dd[key]; } // If y is zero, only x value // can be used if (y == 0) { dd[key] = arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y, dd); // Return the current state result return dd[key]; } // If x is zero, only y value // can be used else { dd[key] = arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1, dd); // Return the current state result return dd[key]; }} // Drive Codelet N = 5;let X = 3;let Y = 3;let A = [1, 2, 3, 4, 5];let B = [5, 4, 3, 2, 1]; // Stores the results of the// overlapping statedd = {}; // Function Calldocument.write(maximumTip(A, B, N, X, Y, dd)); // This code is contributed by rdtank.</script> 21 Time Complexity: O(N*X*Y)Auxiliary Space: O(N*X*Y) mohit kumar 29 lokeshpotta20 MuskanKalra1 priyangid04 rdtank umadevi9616 Amazon Amazon-Question interview-preparation knapsack Arrays Dynamic Programming Hash Recursion Amazon Arrays Hash Dynamic Programming Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26041, "s": 26013, "text": "\n28 Feb, 2022" }, { "code": null, "e": 26377, "s": 26041, "text": "Rahul and Ankit are the only two waiters in the Royal Restaurant. Today, the restaurant received N orders. The amount of tips may differ when handled by different waiters and given as arrays A[] and B[] such that if Rahul takes the ith Order, he would be tipped A[i] rupees, and if Ankit takes this order, the tip would be B[i] rupees." }, { "code": null, "e": 26866, "s": 26377, "text": "In order to maximize the total tip value, they decided to distribute the order among themselves. One order will be handled by one person only. Also, due to time constraints, Rahul cannot take more than X orders and Ankit cannot take more than Y orders. It is guaranteed that X + Y is greater than or equal to N, which means that all the orders can be handled by either Rahul or Ankit. The task is to find out the maximum possible amount of total tip money after processing all the orders." }, { "code": null, "e": 26876, "s": 26866, "text": "Examples:" }, { "code": null, "e": 27271, "s": 26876, "text": "Input: N = 5, X = 3, Y = 3, A[] = {1, 2, 3, 4, 5}, B[] = {5, 4, 3, 2, 1}Output: 21Explanation:Step 1: 5 is included from Ankit’s arrayStep 2: 4 is included from Ankit’s arrayStep 3: As both of them has same value 3 then choose any one of themStep 4: 4 is included from Rahul’s arrayStep 4: 5 is included from Rahul’s arrayTherefore, the maximum possible amount of total tip money sums up to 21." }, { "code": null, "e": 27376, "s": 27271, "text": "Input: N = 7, X = 3, Y = 4, A[] = {8, 7, 15, 19, 16, 16, 18}, B[] = {1, 7, 15, 11, 12, 31, 9}Output: 110" }, { "code": null, "e": 27882, "s": 27376, "text": "Naive Approach: The simplest approach is to traverse the given arrays and start traversing both the arrays simultaneously and pick the maximum element among them and reduce the count of X if the element is taken from X else the count of Y. If one of the X or Y becomes 0, traverse other non-zero array and add its value to the maximum profit. As in every step, there is a choice to be made, this is similar to the 0-1 Knapsack Problem, in which decisions are made whether to include or exclude an element." }, { "code": null, "e": 27933, "s": 27882, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27937, "s": 27933, "text": "C++" }, { "code": null, "e": 27942, "s": 27937, "text": "Java" }, { "code": null, "e": 27950, "s": 27942, "text": "Python3" }, { "code": null, "e": 27953, "s": 27950, "text": "C#" }, { "code": null, "e": 27964, "s": 27953, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that finds the maximum tips// from the given arrays as per the// given conditionsint maximumTip(vector<int> &arr1,vector<int> & arr2, int n, int x, int y){ // Base Condition if (n == 0) return 0; // If both have non-zero count then // return max element from both array if (x != 0 and y != 0) return max( arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y), arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1)); // Traverse first array, as y // count has become 0 if (y == 0) return arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y); // Traverse 2nd array, as x // count has become 0 else return arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1);} // Drive Codeint main(){ int N = 5; int X = 3; int Y = 3; vector<int> A = { 1, 2, 3, 4, 5 }; vector<int> B = { 5, 4, 3, 2, 1 }; // Function Call cout << (maximumTip(A, B, N, X, Y));} // This code is contributed by mohit kumar 29", "e": 29338, "s": 27964, "text": null }, { "code": "/*package whatever //do not write package name here */import java.io.*; class GFG{ // Function that finds the maximum tips// from the given arrays as per the// given conditionsstatic int maximumTip(int []arr1,int []arr2, int n, int x, int y){ // Base Condition if (n == 0) return 0; // If both have non-zero count then // return max element from both array if (x != 0 && y != 0) return Math.max( arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y), arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1)); // Traverse first array, as y // count has become 0 if (y == 0) return arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y); // Traverse 2nd array, as x // count has become 0 else return arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1);} // Drive Code public static void main (String[] args) { int N = 5; int X = 3; int Y = 3; int A[] = { 1, 2, 3, 4, 5 }; int B[] = { 5, 4, 3, 2, 1 }; // Function Call System.out.println(maximumTip(A, B, N, X, Y)); }} // This code is contributed by Potta Lokesh", "e": 30772, "s": 29338, "text": null }, { "code": "# Python program for the above approach # Function that finds the maximum tips# from the given arrays as per the# given conditionsdef maximumTip(arr1, arr2, n, x, y): # Base Condition if n == 0: return 0 # If both have non-zero count then # return max element from both array if x != 0 and y != 0: return max( arr1[n-1] + maximumTip(arr1, arr2, n - 1, x-1, y), arr2[n-1] + maximumTip(arr1, arr2, n-1, x, y-1) ) # Traverse first array, as y # count has become 0 if y == 0: return arr1[n-1] + maximumTip(arr1, arr2, n-1, x-1, y) # Traverse 2nd array, as x # count has become 0 else: return arr2[n - 1] + maximumTip(arr1, arr2, n-1, x, y-1) # Drive CodeN = 5X = 3Y = 3A = [1, 2, 3, 4, 5]B = [5, 4, 3, 2, 1] # Function Callprint(maximumTip(A, B, N, X, Y))", "e": 31623, "s": 30772, "text": null }, { "code": "/*package whatever //do not write package name here */using System;public class GFG{ // Function that finds the maximum tips // from the given arrays as per the // given conditions static int maximumTip(int []arr1,int []arr2, int n, int x, int y) { // Base Condition if (n == 0) return 0; // If both have non-zero count then // return max element from both array if (x != 0 && y != 0) return Math.Max( arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y), arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1)); // Traverse first array, as y // count has become 0 if (y == 0) return arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y); // Traverse 2nd array, as x // count has become 0 else return arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1); } // Drive Code public static void Main(String[] args) { int N = 5; int X = 3; int Y = 3; int []A = { 1, 2, 3, 4, 5 }; int []B = { 5, 4, 3, 2, 1 }; // Function Call Console.WriteLine(maximumTip(A, B, N, X, Y)); }} // This code is contributed by umadevi9616", "e": 32894, "s": 31623, "text": null }, { "code": "<script> // JavaScript Program for the above approach // Function that finds the maximum tips // from the given arrays as per the // given conditions function maximumTip(arr1, arr2, n, x, y) { // Base Condition if (n == 0) return 0; // If both have non-zero count then // return max element from both array if (x != 0 && y != 0) return Math.max( arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y), arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1)); // Traverse first array, as y // count has become 0 if (y == 0) return arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y); // Traverse 2nd array, as x // count has become 0 else return arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1); } // Drive Code let N = 5; let X = 3; let Y = 3; let A = [1, 2, 3, 4, 5]; let B = [5, 4, 3, 2, 1]; // Function Call document.write(maximumTip(A, B, N, X, Y)); // This code is contributed by Potta Lokesh </script>", "e": 34226, "s": 32894, "text": null }, { "code": null, "e": 34229, "s": 34226, "text": "21" }, { "code": null, "e": 34273, "s": 34229, "text": "Time Complexity: O(2N)Auxiliary Space: O(1)" }, { "code": null, "e": 34634, "s": 34273, "text": "Efficient Approach: The above approach can be optimized by using Dynamic Programming and Memoization. If execution is traced for the values of N, X, Y, it can be seen that are there are Overlapping Subproblems. These overlapping subproblems can be computed once and stored and used when the same subproblem is called in the recursive call. Below are the steps:" }, { "code": null, "e": 34767, "s": 34634, "text": "Initialize a Map/Dictionary to store the overlapping subproblems result. The keys of the map will be combined values of N, X, and Y." }, { "code": null, "e": 34877, "s": 34767, "text": "At each recursive call, check if a given key is present in the map then return the value from the map itself." }, { "code": null, "e": 34973, "s": 34877, "text": "Else, call the function recursively and store the value in the map and return the stored value." }, { "code": null, "e": 35102, "s": 34973, "text": "If X and Y are non-zero, recursively call function and take the maximum of the value returned when X is used and when Y is used." }, { "code": null, "e": 35162, "s": 35102, "text": "If X or Y is zero, recursively call for the non-zero array." }, { "code": null, "e": 35257, "s": 35162, "text": "After the above recursive calls end, then print the maximum possible amount of tip calculated." }, { "code": null, "e": 35308, "s": 35257, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 35312, "s": 35308, "text": "C++" }, { "code": null, "e": 35317, "s": 35312, "text": "Java" }, { "code": null, "e": 35325, "s": 35317, "text": "Python3" }, { "code": null, "e": 35336, "s": 35325, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std;int dp[1001][101][101];int rec(int level, int x, int y, int arr1[], int arr2[], int n){ if (level == n) return 0; if (x == 0 && y == 0) return 0; if (x == 0) return arr2[level] + rec(level + 1, x, y - 1, arr1, arr2, n); if (y == 0) return arr1[level] + rec(level + 1, x - 1, y, arr1, arr2, n); if (dp[level][x][y] != -1) return dp[level][x][y]; int ans = max(rec(level + 1, x - 1, y, arr1, arr2, n) + arr1[level], rec(level + 1, x, y - 1, arr1, arr2, n) + arr2[level]); return dp[level][x][y] = ans;} void solve(){ int n = 7, x = 3, y = 4; int arr1[] = { 8, 7, 15, 19, 16, 16, 18 }, arr2[] = { 1, 7, 15, 11, 12, 31, 9 }; memset(dp, -1, sizeof(dp)); cout << rec(0, x, y, arr1, arr2, n);}int main(){ solve(); return 0;}", "e": 36273, "s": 35336, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.util.HashMap; class GFG { // Function that finds the maximum tips // from the given arrays as per the // given conditions static int maximumTip(int[] arr1, int[] arr2, int n, int x, int y, HashMap<String, Integer> dd) { // Create key of N, X, Y String key = Integer.toString(n) + \"_\" + Integer.toString(x) + \"_\" + Integer.toString(y); // Return if the current state is // already calculated if (dd.get(key) != null) return dd.get(key); // Base Condition if (n == 0) return 0; // If both have non-zero count then store and // return max element from both array if (x != 0 && y != 0) { int temp = Math.max( arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y, dd), arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1, dd)); dd.put(key, temp); // Return the current state result return dd.get(key); } // if y is zero, only x value // can be used if (y == 0) { int temp = arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y, dd); dd.put(key, temp); // Return the current state result return dd.get(key); } // if x is zero, only y value // can be used else { int temp = arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1, dd); dd.put(key, temp); // Return the current state result return dd.get(key); } } // Driver Code public static void main(String[] args) { int N = 5; int X = 3; int Y = 3; int A[] = { 1, 2, 3, 4, 5 }; int B[] = { 5, 4, 3, 2, 1 }; // Stores the results of the // overlapping state HashMap<String, Integer> dd = new HashMap<String, Integer>(); // Function Call System.out.println(maximumTip(A, B, N, X, Y, dd)); }} // This code is contributed by MuskanKalra1", "e": 38680, "s": 36273, "text": null }, { "code": "# Python program for the above approach # Function that finds the maximum tips# from the given arrays as per the# given conditionsdef maximumTip(arr1, arr2, n, x, y, dd): # Create key of N, X, Y key = str(n) + '_' + str(x) + '_' + str(y) # Return if the current state is # already calculated if key in dd: return dd[key] # Base Condition if n == 0: return 0 # Store and return if x != 0 and y != 0: dd[key] = max( arr1[n-1] + maximumTip(arr1, arr2, n-1, x-1, y, dd), arr2[n-1] + maximumTip(arr1, arr2, n-1, x, y-1, dd) ) # Return the current state result return dd[key] # If y is zero, only x value # can be used if y == 0: dd[key] = arr1[n-1] + maximumTip(arr1, arr2, n-1, x-1, y, dd) # Return the current state result return dd[key] # If x is zero, only y value # can be used else: dd[key] = arr2[n-1] + maximumTip(arr1, arr2, n-1, x, y-1, dd) # Return the current state result return dd[key] # Drive CodeN = 5X = 3Y = 3A = [1, 2, 3, 4, 5]B = [5, 4, 3, 2, 1] # Stores the results of the# overlapping statedd = {} # Function Callprint(maximumTip(A, B, N, X, Y, dd))", "e": 39910, "s": 38680, "text": null }, { "code": "<script> // JavaScript program for the above approach// Function that finds the maximum tips// from the given arrays as per the// given conditions function maximumTip(arr1, arr2, n, x, y, dd) { // Create key of N, X, Y key = `${n}_${x}_${y}`; // Return if the current state is // already calculated for (var key in dd) { return dd[key]; } // Base Condition if (n == 0) { return 0; } // Store and return if (x != 0 && y != 0) { dd[key] = Math.max( arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y, dd), arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1, dd) ); // Return the current state result return dd[key]; } // If y is zero, only x value // can be used if (y == 0) { dd[key] = arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y, dd); // Return the current state result return dd[key]; } // If x is zero, only y value // can be used else { dd[key] = arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1, dd); // Return the current state result return dd[key]; }} // Drive Codelet N = 5;let X = 3;let Y = 3;let A = [1, 2, 3, 4, 5];let B = [5, 4, 3, 2, 1]; // Stores the results of the// overlapping statedd = {}; // Function Calldocument.write(maximumTip(A, B, N, X, Y, dd)); // This code is contributed by rdtank.</script>", "e": 41225, "s": 39910, "text": null }, { "code": null, "e": 41228, "s": 41225, "text": "21" }, { "code": null, "e": 41279, "s": 41228, "text": "Time Complexity: O(N*X*Y)Auxiliary Space: O(N*X*Y)" }, { "code": null, "e": 41294, "s": 41279, "text": "mohit kumar 29" }, { "code": null, "e": 41308, "s": 41294, "text": "lokeshpotta20" }, { "code": null, "e": 41321, "s": 41308, "text": "MuskanKalra1" }, { "code": null, "e": 41333, "s": 41321, "text": "priyangid04" }, { "code": null, "e": 41340, "s": 41333, "text": "rdtank" }, { "code": null, "e": 41352, "s": 41340, "text": "umadevi9616" }, { "code": null, "e": 41359, "s": 41352, "text": "Amazon" }, { "code": null, "e": 41375, "s": 41359, "text": "Amazon-Question" }, { "code": null, "e": 41397, "s": 41375, "text": "interview-preparation" }, { "code": null, "e": 41406, "s": 41397, "text": "knapsack" }, { "code": null, "e": 41413, "s": 41406, "text": "Arrays" }, { "code": null, "e": 41433, "s": 41413, "text": "Dynamic Programming" }, { "code": null, "e": 41438, "s": 41433, "text": "Hash" }, { "code": null, "e": 41448, "s": 41438, "text": "Recursion" }, { "code": null, "e": 41455, "s": 41448, "text": "Amazon" }, { "code": null, "e": 41462, "s": 41455, "text": "Arrays" }, { "code": null, "e": 41467, "s": 41462, "text": "Hash" }, { "code": null, "e": 41487, "s": 41467, "text": "Dynamic Programming" }, { "code": null, "e": 41497, "s": 41487, "text": "Recursion" }, { "code": null, "e": 41595, "s": 41497, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41626, "s": 41595, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 41653, "s": 41626, "text": "Count pairs with given sum" }, { "code": null, "e": 41678, "s": 41653, "text": "Window Sliding Technique" }, { "code": null, "e": 41716, "s": 41678, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 41737, "s": 41716, "text": "Next Greater Element" }, { "code": null, "e": 41766, "s": 41737, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 41796, "s": 41766, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 41830, "s": 41796, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 41861, "s": 41830, "text": "Bellman–Ford Algorithm | DP-23" } ]
Python | Using for loop in Flask - GeeksforGeeks
11 Oct, 2018 Prerequisite: HTML Basics, Python Basics, Flask It is not possible to write front-end course every time user make changes in his/her profile. We use a template and it generates code according to the content. Flask is one of the web development frameworks written in Python. Through flask, a loop can be run in the HTML code using jinja template and automatically HTML code can be generated using this. The code will be stored in Directories in the format of Flask. So we will be making two directories, static – For static Files like images, css, js templates – For Html templates app.py file which will contain all the Python file will be stored in the main directory and index.html file will be stored in templates. app.pyThe code of app.py is same for both examples. We will print a Python list with Some names of Pokemons first in the format of a listand then a table. # importing modulesfrom flask import Flask, render_template # declaring app nameapp = Flask(__name__) # making list of pokemonsPokemons =["Pikachu", "Charizard", "Squirtle", "Jigglypuff", "Bulbasaur", "Gengar", "Charmander", "Mew", "Lugia", "Gyarados"] # defining home page@app.route('/')def homepage(): # returning index.html and list# and length of list to html page return render_template("index.html", len = len(Pokemons), Pokemons = Pokemons) # if __name__ == '__main__': # running app app.run(use_reloader = True, debug = True) Example #1: Making a ListWe will use the argument Pokemons passed from python file here to automatically print a list instead of Writing it everytime. index.html <!DOCTYPE html> <html><head> <title>For loop in Flask</title></head><body> <ol><!-- For loop logic of jinja template -->{%for i in range(0, len)%} <li>{{Pokemons[i]}}</li>{%endfor%} </ol> </body></html> Output:Without writing any data of list, the list will be automatically generated. You can use the css and js to make these look beautiful. Example #2: Making a Table We will use the argument Pokemons passed from python file here to automatically print a table instead of Writing it our self. Code for app.py for this example is same as the above one. index.html <!DOCTYPE html> <html><head> <title>For loop in Flask</title></head> <!-- Adding some style to table (OPTIONAL) --><style type="text/css"> th:tr{ color: blue; } tr:nth-of-type(2n){ border: 1px solid black; background-color: rgba(150, 150, 150, 0.5); } td{ padding: 8px 8px; border: 1px solid black; }</style> <body> <table style="margin-left: 20px;"><!-- Table headers --> <th> <tr style="color: green; "> <td>Serial Number</td> <td>Pokemon Name</td></tr> </th> <!-- For loop logic of jinja template -->{%for i in range(0, len)%} <!-- table rows --><tr> <td>{{i}}</td> <td>{{Pokemons[i]}}</td> {%endfor%} </tr> </table> </body></html> Output:Without writing any data of list, the table will be automatically generated. Instructions to Run code: Download the files from link provided above or make and store the code in the same format Run the app.py file in root directory Go to the local host ( http://127.0.0.1:5000/ in my case) and there you have the website Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 25687, "s": 25659, "text": "\n11 Oct, 2018" }, { "code": null, "e": 25735, "s": 25687, "text": "Prerequisite: HTML Basics, Python Basics, Flask" }, { "code": null, "e": 25895, "s": 25735, "text": "It is not possible to write front-end course every time user make changes in his/her profile. We use a template and it generates code according to the content." }, { "code": null, "e": 26089, "s": 25895, "text": "Flask is one of the web development frameworks written in Python. Through flask, a loop can be run in the HTML code using jinja template and automatically HTML code can be generated using this." }, { "code": null, "e": 26190, "s": 26089, "text": "The code will be stored in Directories in the format of Flask. So we will be making two directories," }, { "code": null, "e": 26237, "s": 26190, "text": "static – For static Files like images, css, js" }, { "code": null, "e": 26268, "s": 26237, "text": "templates – For Html templates" }, { "code": null, "e": 26405, "s": 26268, "text": "app.py file which will contain all the Python file will be stored in the main directory and index.html file will be stored in templates." }, { "code": null, "e": 26560, "s": 26405, "text": "app.pyThe code of app.py is same for both examples. We will print a Python list with Some names of Pokemons first in the format of a listand then a table." }, { "code": "# importing modulesfrom flask import Flask, render_template # declaring app nameapp = Flask(__name__) # making list of pokemonsPokemons =[\"Pikachu\", \"Charizard\", \"Squirtle\", \"Jigglypuff\", \"Bulbasaur\", \"Gengar\", \"Charmander\", \"Mew\", \"Lugia\", \"Gyarados\"] # defining home page@app.route('/')def homepage(): # returning index.html and list# and length of list to html page return render_template(\"index.html\", len = len(Pokemons), Pokemons = Pokemons) # if __name__ == '__main__': # running app app.run(use_reloader = True, debug = True)", "e": 27125, "s": 26560, "text": null }, { "code": null, "e": 27276, "s": 27125, "text": "Example #1: Making a ListWe will use the argument Pokemons passed from python file here to automatically print a list instead of Writing it everytime." }, { "code": null, "e": 27287, "s": 27276, "text": "index.html" }, { "code": "<!DOCTYPE html> <html><head> <title>For loop in Flask</title></head><body> <ol><!-- For loop logic of jinja template -->{%for i in range(0, len)%} <li>{{Pokemons[i]}}</li>{%endfor%} </ol> </body></html>", "e": 27502, "s": 27287, "text": null }, { "code": null, "e": 27669, "s": 27502, "text": "Output:Without writing any data of list, the list will be automatically generated. You can use the css and js to make these look beautiful. Example #2: Making a Table" }, { "code": null, "e": 27854, "s": 27669, "text": "We will use the argument Pokemons passed from python file here to automatically print a table instead of Writing it our self. Code for app.py for this example is same as the above one." }, { "code": null, "e": 27865, "s": 27854, "text": "index.html" }, { "code": "<!DOCTYPE html> <html><head> <title>For loop in Flask</title></head> <!-- Adding some style to table (OPTIONAL) --><style type=\"text/css\"> th:tr{ color: blue; } tr:nth-of-type(2n){ border: 1px solid black; background-color: rgba(150, 150, 150, 0.5); } td{ padding: 8px 8px; border: 1px solid black; }</style> <body> <table style=\"margin-left: 20px;\"><!-- Table headers --> <th> <tr style=\"color: green; \"> <td>Serial Number</td> <td>Pokemon Name</td></tr> </th> <!-- For loop logic of jinja template -->{%for i in range(0, len)%} <!-- table rows --><tr> <td>{{i}}</td> <td>{{Pokemons[i]}}</td> {%endfor%} </tr> </table> </body></html>", "e": 28621, "s": 27865, "text": null }, { "code": null, "e": 28705, "s": 28621, "text": "Output:Without writing any data of list, the table will be automatically generated." }, { "code": null, "e": 28731, "s": 28705, "text": "Instructions to Run code:" }, { "code": null, "e": 28821, "s": 28731, "text": "Download the files from link provided above or make and store the code in the same format" }, { "code": null, "e": 28859, "s": 28821, "text": "Run the app.py file in root directory" }, { "code": null, "e": 28948, "s": 28859, "text": "Go to the local host ( http://127.0.0.1:5000/ in my case) and there you have the website" }, { "code": null, "e": 28972, "s": 28948, "text": "Technical Scripter 2018" }, { "code": null, "e": 28979, "s": 28972, "text": "Python" }, { "code": null, "e": 28998, "s": 28979, "text": "Technical Scripter" }, { "code": null, "e": 29096, "s": 28998, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29114, "s": 29096, "text": "Python Dictionary" }, { "code": null, "e": 29149, "s": 29114, "text": "Read a file line by line in Python" }, { "code": null, "e": 29181, "s": 29149, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29223, "s": 29181, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29249, "s": 29223, "text": "Python String | replace()" }, { "code": null, "e": 29278, "s": 29249, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29322, "s": 29278, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29359, "s": 29322, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29395, "s": 29359, "text": "Convert integer to string in Python" } ]
Minimum enclosing circle | Set 2 - Welzl's algorithm - GeeksforGeeks
23 Dec, 2021 Prerequisites: Equation of circle when three points on the circle are given, Minimum Enclosing Circle.Given an array arr[][] containing N points in a 2-D plane with integer coordinates. The task is to find the centre and the radius of the minimum enclosing circle(MEC). A minimum enclosing circle is a circle in which all the points lie either inside the circle or on its boundaries.Examples: Input: arr[][] = {{0, 0}, {0, 1}, {1, 0}} Output: Center = {0.5, 0.5}, Radius = 0.7071 Explanation: On plotting the above circle with radius 0.707 and center (0.5, 0.5), it can be observed clearly that all the mentioned points lie either inside or on the circle. Input: arr[][] = {{5, -2}, {-3, -2}, {-2, 5}, {1, 6}, {0, 2}} Output: Center = {1.0, 1.0}, Radius = 5.000 Approach: In the previous article, a naive approach and an optimized approach by getting the convex full of the set of points first and then performing a naive approach has been discussed. Although the optimized solution would work very well for certain inputs, the worst-case time complexity after that optimization was still O(N4). In this article, an optimized approach has been discussed.The idea is to use Welzl’s recursive algorithm. Using this algorithm, the MEC can be found in O(N). The working of the algorithm depends on the observations and conclusions drawn from the previous article. The idea of the algorithm is to randomly remove a point from the given input set to form a circle equation. Once the equation is formed, check if the point which was removed is enclosed by the equation or not. If it doesn’t, then the point must lie on the boundary of the MEC. Therefore, this point is considered as a boundary point and the function is recursively called. The detailed working of the algorithm is as follows:The algorithm takes a set of points P and a set R that’s initially empty and used to represent the points on the boundary of the MEC as the input.The base case of the algorithm is when P becomes empty or the size of the set R is equal to 3: If P is empty, then all the points have been processed. If |R| = 3, then 3 points have already been found that lie on the circle boundary, and since a circle can be uniquely determined using 3 points only, the recursion can be stopped. When the algorithm reaches the base case above, it returns the trivial solution for R, being: If |R| = 1, we return a circle centered at R[0] with radius = 0 If |R| = 2, we return the MEC for R[0] and R[2] If |R| = 3, we return the MEC by trying the 3 pairs (R[0], R[1]), (R[0], R[2]), (R[1], R[2]) If none of these pairs is valid, we return the circle defined by the 3 points in R If none of these pairs is valid, we return the circle defined by the 3 points in R If the base case is not reached yet, we do the following: Pick a random point p from P and remove it from P Call the algorithm on P and R to get circle d If p is enclosed by d, then we return d otherwise, p must lie on the boundary of the MEC Add p to RReturn the output of the algorithm on P and R Add p to R Return the output of the algorithm on P and R Below is the implementation of the above approach: CPP Python3 // C++ program to find the minimum enclosing// circle for N integer points in a 2-D plane#include <algorithm>#include <assert.h>#include <iostream>#include <math.h>#include <vector>using namespace std; // Defining infinityconst double INF = 1e18; // Structure to represent a 2D pointstruct Point { double X, Y;}; // Structure to represent a 2D circlestruct Circle { Point C; double R;}; // Function to return the euclidean distance// between two pointsdouble dist(const Point& a, const Point& b){ return sqrt(pow(a.X - b.X, 2) + pow(a.Y - b.Y, 2));} // Function to check whether a point lies inside// or on the boundaries of the circlebool is_inside(const Circle& c, const Point& p){ return dist(c.C, p) <= c.R;} // The following two functions are used// To find the equation of the circle when// three points are given. // Helper method to get a circle defined by 3 pointsPoint get_circle_center(double bx, double by, double cx, double cy){ double B = bx * bx + by * by; double C = cx * cx + cy * cy; double D = bx * cy - by * cx; return { (cy * B - by * C) / (2 * D), (bx * C - cx * B) / (2 * D) };} // Function to return a unique circle that// intersects three pointsCircle circle_from(const Point& A, const Point& B, const Point& C){ Point I = get_circle_center(B.X - A.X, B.Y - A.Y, C.X - A.X, C.Y - A.Y); I.X += A.X; I.Y += A.Y; return { I, dist(I, A) };} // Function to return the smallest circle// that intersects 2 pointsCircle circle_from(const Point& A, const Point& B){ // Set the center to be the midpoint of A and B Point C = { (A.X + B.X) / 2.0, (A.Y + B.Y) / 2.0 }; // Set the radius to be half the distance AB return { C, dist(A, B) / 2.0 };} // Function to check whether a circle// encloses the given pointsbool is_valid_circle(const Circle& c, const vector<Point>& P){ // Iterating through all the points // to check whether the points // lie inside the circle or not for (const Point& p : P) if (!is_inside(c, p)) return false; return true;} // Function to return the minimum enclosing// circle for N <= 3Circle min_circle_trivial(vector<Point>& P){ assert(P.size() <= 3); if (P.empty()) { return { { 0, 0 }, 0 }; } else if (P.size() == 1) { return { P[0], 0 }; } else if (P.size() == 2) { return circle_from(P[0], P[1]); } // To check if MEC can be determined // by 2 points only for (int i = 0; i < 3; i++) { for (int j = i + 1; j < 3; j++) { Circle c = circle_from(P[i], P[j]); if (is_valid_circle(c, P)) return c; } } return circle_from(P[0], P[1], P[2]);} // Returns the MEC using Welzl's algorithm// Takes a set of input points P and a set R// points on the circle boundary.// n represents the number of points in P// that are not yet processed.Circle welzl_helper(vector<Point>& P, vector<Point> R, int n){ // Base case when all points processed or |R| = 3 if (n == 0 || R.size() == 3) { return min_circle_trivial(R); } // Pick a random point randomly int idx = rand() % n; Point p = P[idx]; // Put the picked point at the end of P // since it's more efficient than // deleting from the middle of the vector swap(P[idx], P[n - 1]); // Get the MEC circle d from the // set of points P - {p} Circle d = welzl_helper(P, R, n - 1); // If d contains p, return d if (is_inside(d, p)) { return d; } // Otherwise, must be on the boundary of the MEC R.push_back(p); // Return the MEC for P - {p} and R U {p} return welzl_helper(P, R, n - 1);} Circle welzl(const vector<Point>& P){ vector<Point> P_copy = P; random_shuffle(P_copy.begin(), P_copy.end()); return welzl_helper(P_copy, {}, P_copy.size());} // Driver codeint main(){ Circle mec = welzl({ { 0, 0 }, { 0, 1 }, { 1, 0 } }); cout << "Center = { " << mec.C.X << ", " << mec.C.Y << " } Radius = " << mec.R << endl; Circle mec2 = welzl({ { 5, -2 }, { -3, -2 }, { -2, 5 }, { 1, 6 }, { 0, 2 } }); cout << "Center = { " << mec2.C.X << ", " << mec2.C.Y << " } Radius = " << mec2.R << endl; return 0;} # Python3 program to find the minimum enclosing# circle for N integer points in a 2-D planefrom math import sqrtfrom random import randint,shuffle # Defining infinityINF = 1e18 # Structure to represent a 2D pointclass Point : def __init__(self,X=0,Y=0) -> None: self.X=X self.Y=Y # Structure to represent a 2D circleclass Circle : def __init__(self,c=Point(),r=0) -> None: self.C=c self.R=r # Function to return the euclidean distance# between two pointsdef dist(a, b): return sqrt(pow(a.X - b.X, 2) + pow(a.Y - b.Y, 2)) # Function to check whether a point lies inside# or on the boundaries of the circledef is_inside(c, p): return dist(c.C, p) <= c.R # The following two functions are used# To find the equation of the circle when# three points are given. # Helper method to get a circle defined by 3 pointsdef get_circle_center(bx, by, cx, cy): B = bx * bx + by * by C = cx * cx + cy * cy D = bx * cy - by * cx return Point((cy * B - by * C) / (2 * D), (bx * C - cx * B) / (2 * D)) # Function to return the smallest circle# that intersects 2 pointsdef circle_from1(A, B): # Set the center to be the midpoint of A and B C = Point((A.X + B.X) / 2.0, (A.Y + B.Y) / 2.0 ) # Set the radius to be half the distance AB return Circle(C, dist(A, B) / 2.0 ) # Function to return a unique circle that# intersects three pointsdef circle_from2(A, B, C): I = get_circle_center(B.X - A.X, B.Y - A.Y, C.X - A.X, C.Y - A.Y) I.X += A.X I.Y += A.Y return Circle(I, dist(I, A)) # Function to check whether a circle# encloses the given pointsdef is_valid_circle(c, P): # Iterating through all the points # to check whether the points # lie inside the circle or not for p in P: if (not is_inside(c, p)): return False return True # Function to return the minimum enclosing# circle for N <= 3def min_circle_trivial(P): assert(len(P) <= 3) if not P : return Circle() elif (len(P) == 1) : return Circle(P[0], 0) elif (len(P) == 2) : return circle_from1(P[0], P[1]) # To check if MEC can be determined # by 2 points only for i in range(3): for j in range(i + 1,3): c = circle_from1(P[i], P[j]) if (is_valid_circle(c, P)): return c return circle_from2(P[0], P[1], P[2]) # Returns the MEC using Welzl's algorithm# Takes a set of input points P and a set R# points on the circle boundary.# n represents the number of points in P# that are not yet processed.def welzl_helper(P, R, n): # Base case when all points processed or |R| = 3 if (n == 0 or len(R) == 3) : return min_circle_trivial(R) # Pick a random point randomly idx = randint(0,n-1) p = P[idx] # Put the picked point at the end of P # since it's more efficient than # deleting from the middle of the vector P[idx], P[n - 1]=P[n-1],P[idx] # Get the MEC circle d from the # set of points P - :p d = welzl_helper(P, R.copy(), n - 1) # If d contains p, return d if (is_inside(d, p)) : return d # Otherwise, must be on the boundary of the MEC R.append(p) # Return the MEC for P - :p and R U :p return welzl_helper(P, R.copy(), n - 1) def welzl(P): P_copy = P.copy() shuffle(P_copy) return welzl_helper(P_copy, [], len(P_copy)) # Driver codeif __name__ == '__main__': mec = welzl([Point(0, 0) , Point(0, 1) , Point(1, 0) ]) print("Center = {",mec.C.X,",", mec.C.Y,"} Radius =",mec.R) mec2 = welzl([Point(5, -2) , Point(-3, -2) , Point(-2, 5) , Point(1, 6), Point(0, 2)] ) print("Center = {",mec2.C.X,",",mec2.C.Y,"} Radius =",mec2.R) Center = { 0.5, 0.5 } Radius = 0.707107 Center = { 1, 1 } Radius = 5 Time Complexity: This algorithm has an expected time and space complexity of O(N) where N is the number of points. The space is due to the fact recursion is being used. To understand why the time complexity is linear, we can observe the number of different states to know how many calls can happen to the recursive function. With every call, the size of P gets reduced by one. Also, the size of R can remain the same or can be increased by one. Since |R| cannot exceed 3, then the number of different states would be 3N. Therefore, this makes the time complexity to be O(N). surindertarika1234 amartyaghoshgfg circle Algorithms Competitive Programming Geometric Mathematical Mathematical Geometric Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to write a Pseudo Code? Understanding Time Complexity with Simple Examples Introduction to Algorithms Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming
[ { "code": null, "e": 26023, "s": 25995, "text": "\n23 Dec, 2021" }, { "code": null, "e": 26418, "s": 26023, "text": "Prerequisites: Equation of circle when three points on the circle are given, Minimum Enclosing Circle.Given an array arr[][] containing N points in a 2-D plane with integer coordinates. The task is to find the centre and the radius of the minimum enclosing circle(MEC). A minimum enclosing circle is a circle in which all the points lie either inside the circle or on its boundaries.Examples: " }, { "code": null, "e": 26683, "s": 26418, "text": "Input: arr[][] = {{0, 0}, {0, 1}, {1, 0}} Output: Center = {0.5, 0.5}, Radius = 0.7071 Explanation: On plotting the above circle with radius 0.707 and center (0.5, 0.5), it can be observed clearly that all the mentioned points lie either inside or on the circle. " }, { "code": null, "e": 26791, "s": 26683, "text": "Input: arr[][] = {{5, -2}, {-3, -2}, {-2, 5}, {1, 6}, {0, 2}} Output: Center = {1.0, 1.0}, Radius = 5.000 " }, { "code": null, "e": 28059, "s": 26793, "text": "Approach: In the previous article, a naive approach and an optimized approach by getting the convex full of the set of points first and then performing a naive approach has been discussed. Although the optimized solution would work very well for certain inputs, the worst-case time complexity after that optimization was still O(N4). In this article, an optimized approach has been discussed.The idea is to use Welzl’s recursive algorithm. Using this algorithm, the MEC can be found in O(N). The working of the algorithm depends on the observations and conclusions drawn from the previous article. The idea of the algorithm is to randomly remove a point from the given input set to form a circle equation. Once the equation is formed, check if the point which was removed is enclosed by the equation or not. If it doesn’t, then the point must lie on the boundary of the MEC. Therefore, this point is considered as a boundary point and the function is recursively called. The detailed working of the algorithm is as follows:The algorithm takes a set of points P and a set R that’s initially empty and used to represent the points on the boundary of the MEC as the input.The base case of the algorithm is when P becomes empty or the size of the set R is equal to 3: " }, { "code": null, "e": 28115, "s": 28059, "text": "If P is empty, then all the points have been processed." }, { "code": null, "e": 28295, "s": 28115, "text": "If |R| = 3, then 3 points have already been found that lie on the circle boundary, and since a circle can be uniquely determined using 3 points only, the recursion can be stopped." }, { "code": null, "e": 28391, "s": 28295, "text": "When the algorithm reaches the base case above, it returns the trivial solution for R, being: " }, { "code": null, "e": 28455, "s": 28391, "text": "If |R| = 1, we return a circle centered at R[0] with radius = 0" }, { "code": null, "e": 28503, "s": 28455, "text": "If |R| = 2, we return the MEC for R[0] and R[2]" }, { "code": null, "e": 28679, "s": 28503, "text": "If |R| = 3, we return the MEC by trying the 3 pairs (R[0], R[1]), (R[0], R[2]), (R[1], R[2]) If none of these pairs is valid, we return the circle defined by the 3 points in R" }, { "code": null, "e": 28762, "s": 28679, "text": "If none of these pairs is valid, we return the circle defined by the 3 points in R" }, { "code": null, "e": 28822, "s": 28762, "text": "If the base case is not reached yet, we do the following: " }, { "code": null, "e": 28872, "s": 28822, "text": "Pick a random point p from P and remove it from P" }, { "code": null, "e": 28918, "s": 28872, "text": "Call the algorithm on P and R to get circle d" }, { "code": null, "e": 28958, "s": 28918, "text": "If p is enclosed by d, then we return d" }, { "code": null, "e": 29063, "s": 28958, "text": "otherwise, p must lie on the boundary of the MEC Add p to RReturn the output of the algorithm on P and R" }, { "code": null, "e": 29074, "s": 29063, "text": "Add p to R" }, { "code": null, "e": 29120, "s": 29074, "text": "Return the output of the algorithm on P and R" }, { "code": null, "e": 29172, "s": 29120, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 29176, "s": 29172, "text": "CPP" }, { "code": null, "e": 29184, "s": 29176, "text": "Python3" }, { "code": "// C++ program to find the minimum enclosing// circle for N integer points in a 2-D plane#include <algorithm>#include <assert.h>#include <iostream>#include <math.h>#include <vector>using namespace std; // Defining infinityconst double INF = 1e18; // Structure to represent a 2D pointstruct Point { double X, Y;}; // Structure to represent a 2D circlestruct Circle { Point C; double R;}; // Function to return the euclidean distance// between two pointsdouble dist(const Point& a, const Point& b){ return sqrt(pow(a.X - b.X, 2) + pow(a.Y - b.Y, 2));} // Function to check whether a point lies inside// or on the boundaries of the circlebool is_inside(const Circle& c, const Point& p){ return dist(c.C, p) <= c.R;} // The following two functions are used// To find the equation of the circle when// three points are given. // Helper method to get a circle defined by 3 pointsPoint get_circle_center(double bx, double by, double cx, double cy){ double B = bx * bx + by * by; double C = cx * cx + cy * cy; double D = bx * cy - by * cx; return { (cy * B - by * C) / (2 * D), (bx * C - cx * B) / (2 * D) };} // Function to return a unique circle that// intersects three pointsCircle circle_from(const Point& A, const Point& B, const Point& C){ Point I = get_circle_center(B.X - A.X, B.Y - A.Y, C.X - A.X, C.Y - A.Y); I.X += A.X; I.Y += A.Y; return { I, dist(I, A) };} // Function to return the smallest circle// that intersects 2 pointsCircle circle_from(const Point& A, const Point& B){ // Set the center to be the midpoint of A and B Point C = { (A.X + B.X) / 2.0, (A.Y + B.Y) / 2.0 }; // Set the radius to be half the distance AB return { C, dist(A, B) / 2.0 };} // Function to check whether a circle// encloses the given pointsbool is_valid_circle(const Circle& c, const vector<Point>& P){ // Iterating through all the points // to check whether the points // lie inside the circle or not for (const Point& p : P) if (!is_inside(c, p)) return false; return true;} // Function to return the minimum enclosing// circle for N <= 3Circle min_circle_trivial(vector<Point>& P){ assert(P.size() <= 3); if (P.empty()) { return { { 0, 0 }, 0 }; } else if (P.size() == 1) { return { P[0], 0 }; } else if (P.size() == 2) { return circle_from(P[0], P[1]); } // To check if MEC can be determined // by 2 points only for (int i = 0; i < 3; i++) { for (int j = i + 1; j < 3; j++) { Circle c = circle_from(P[i], P[j]); if (is_valid_circle(c, P)) return c; } } return circle_from(P[0], P[1], P[2]);} // Returns the MEC using Welzl's algorithm// Takes a set of input points P and a set R// points on the circle boundary.// n represents the number of points in P// that are not yet processed.Circle welzl_helper(vector<Point>& P, vector<Point> R, int n){ // Base case when all points processed or |R| = 3 if (n == 0 || R.size() == 3) { return min_circle_trivial(R); } // Pick a random point randomly int idx = rand() % n; Point p = P[idx]; // Put the picked point at the end of P // since it's more efficient than // deleting from the middle of the vector swap(P[idx], P[n - 1]); // Get the MEC circle d from the // set of points P - {p} Circle d = welzl_helper(P, R, n - 1); // If d contains p, return d if (is_inside(d, p)) { return d; } // Otherwise, must be on the boundary of the MEC R.push_back(p); // Return the MEC for P - {p} and R U {p} return welzl_helper(P, R, n - 1);} Circle welzl(const vector<Point>& P){ vector<Point> P_copy = P; random_shuffle(P_copy.begin(), P_copy.end()); return welzl_helper(P_copy, {}, P_copy.size());} // Driver codeint main(){ Circle mec = welzl({ { 0, 0 }, { 0, 1 }, { 1, 0 } }); cout << \"Center = { \" << mec.C.X << \", \" << mec.C.Y << \" } Radius = \" << mec.R << endl; Circle mec2 = welzl({ { 5, -2 }, { -3, -2 }, { -2, 5 }, { 1, 6 }, { 0, 2 } }); cout << \"Center = { \" << mec2.C.X << \", \" << mec2.C.Y << \" } Radius = \" << mec2.R << endl; return 0;}", "e": 33659, "s": 29184, "text": null }, { "code": "# Python3 program to find the minimum enclosing# circle for N integer points in a 2-D planefrom math import sqrtfrom random import randint,shuffle # Defining infinityINF = 1e18 # Structure to represent a 2D pointclass Point : def __init__(self,X=0,Y=0) -> None: self.X=X self.Y=Y # Structure to represent a 2D circleclass Circle : def __init__(self,c=Point(),r=0) -> None: self.C=c self.R=r # Function to return the euclidean distance# between two pointsdef dist(a, b): return sqrt(pow(a.X - b.X, 2) + pow(a.Y - b.Y, 2)) # Function to check whether a point lies inside# or on the boundaries of the circledef is_inside(c, p): return dist(c.C, p) <= c.R # The following two functions are used# To find the equation of the circle when# three points are given. # Helper method to get a circle defined by 3 pointsdef get_circle_center(bx, by, cx, cy): B = bx * bx + by * by C = cx * cx + cy * cy D = bx * cy - by * cx return Point((cy * B - by * C) / (2 * D), (bx * C - cx * B) / (2 * D)) # Function to return the smallest circle# that intersects 2 pointsdef circle_from1(A, B): # Set the center to be the midpoint of A and B C = Point((A.X + B.X) / 2.0, (A.Y + B.Y) / 2.0 ) # Set the radius to be half the distance AB return Circle(C, dist(A, B) / 2.0 ) # Function to return a unique circle that# intersects three pointsdef circle_from2(A, B, C): I = get_circle_center(B.X - A.X, B.Y - A.Y, C.X - A.X, C.Y - A.Y) I.X += A.X I.Y += A.Y return Circle(I, dist(I, A)) # Function to check whether a circle# encloses the given pointsdef is_valid_circle(c, P): # Iterating through all the points # to check whether the points # lie inside the circle or not for p in P: if (not is_inside(c, p)): return False return True # Function to return the minimum enclosing# circle for N <= 3def min_circle_trivial(P): assert(len(P) <= 3) if not P : return Circle() elif (len(P) == 1) : return Circle(P[0], 0) elif (len(P) == 2) : return circle_from1(P[0], P[1]) # To check if MEC can be determined # by 2 points only for i in range(3): for j in range(i + 1,3): c = circle_from1(P[i], P[j]) if (is_valid_circle(c, P)): return c return circle_from2(P[0], P[1], P[2]) # Returns the MEC using Welzl's algorithm# Takes a set of input points P and a set R# points on the circle boundary.# n represents the number of points in P# that are not yet processed.def welzl_helper(P, R, n): # Base case when all points processed or |R| = 3 if (n == 0 or len(R) == 3) : return min_circle_trivial(R) # Pick a random point randomly idx = randint(0,n-1) p = P[idx] # Put the picked point at the end of P # since it's more efficient than # deleting from the middle of the vector P[idx], P[n - 1]=P[n-1],P[idx] # Get the MEC circle d from the # set of points P - :p d = welzl_helper(P, R.copy(), n - 1) # If d contains p, return d if (is_inside(d, p)) : return d # Otherwise, must be on the boundary of the MEC R.append(p) # Return the MEC for P - :p and R U :p return welzl_helper(P, R.copy(), n - 1) def welzl(P): P_copy = P.copy() shuffle(P_copy) return welzl_helper(P_copy, [], len(P_copy)) # Driver codeif __name__ == '__main__': mec = welzl([Point(0, 0) , Point(0, 1) , Point(1, 0) ]) print(\"Center = {\",mec.C.X,\",\", mec.C.Y,\"} Radius =\",mec.R) mec2 = welzl([Point(5, -2) , Point(-3, -2) , Point(-2, 5) , Point(1, 6), Point(0, 2)] ) print(\"Center = {\",mec2.C.X,\",\",mec2.C.Y,\"} Radius =\",mec2.R)", "e": 37606, "s": 33659, "text": null }, { "code": null, "e": 37675, "s": 37606, "text": "Center = { 0.5, 0.5 } Radius = 0.707107\nCenter = { 1, 1 } Radius = 5" }, { "code": null, "e": 38253, "s": 37677, "text": "Time Complexity: This algorithm has an expected time and space complexity of O(N) where N is the number of points. The space is due to the fact recursion is being used. To understand why the time complexity is linear, we can observe the number of different states to know how many calls can happen to the recursive function. With every call, the size of P gets reduced by one. Also, the size of R can remain the same or can be increased by one. Since |R| cannot exceed 3, then the number of different states would be 3N. Therefore, this makes the time complexity to be O(N). " }, { "code": null, "e": 38272, "s": 38253, "text": "surindertarika1234" }, { "code": null, "e": 38288, "s": 38272, "text": "amartyaghoshgfg" }, { "code": null, "e": 38295, "s": 38288, "text": "circle" }, { "code": null, "e": 38306, "s": 38295, "text": "Algorithms" }, { "code": null, "e": 38330, "s": 38306, "text": "Competitive Programming" }, { "code": null, "e": 38340, "s": 38330, "text": "Geometric" }, { "code": null, "e": 38353, "s": 38340, "text": "Mathematical" }, { "code": null, "e": 38366, "s": 38353, "text": "Mathematical" }, { "code": null, "e": 38376, "s": 38366, "text": "Geometric" }, { "code": null, "e": 38387, "s": 38376, "text": "Algorithms" }, { "code": null, "e": 38485, "s": 38387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38534, "s": 38485, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 38559, "s": 38534, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 38587, "s": 38559, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 38638, "s": 38587, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 38665, "s": 38638, "text": "Introduction to Algorithms" }, { "code": null, "e": 38708, "s": 38665, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 38751, "s": 38708, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 38792, "s": 38751, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 38870, "s": 38792, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
KeyStore getEntry() method in Java with Examples - GeeksforGeeks
28 Nov, 2021 The getEntry() method of java.security.KeyStore class is used to get the keystore entry for this instance with the help of the specified alias and the protection parameter. Syntax: public final KeyStore.Entry getEntry(String alias, KeyStore.ProtectionParameter protParam) throws NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException Parameter: This method accepts following arguments as a parameter. alias: which is name of the Keystore Entry to be fetched. protParam: which contains the password to access keystore. Return Value: This method returns the keystore entry for the requested alias if it exists. Exception: This method throws following exception NullPointerException: for null alias. NoSuchAlgorithmException: if the algorithm is missing. UnrecoverableEntryException: if the specified password is invalid. KeyStoreException: if the keystore has not been initialized (loaded). Note: All the programs in this article won’t run on online IDE as no ‘privatekey’ Keystore exists. You can check this code on Java compiler on your system. To check this code, create a Keystore ‘privatekey’ on your system and set your own Keystore password to access that Keystore. Below are the examples to illustrate the getCertificate() method: Example 1: // Java program to demonstrate getEntry() method import java.security.*;import java.security.cert.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating the object of KeyStore // and getting instance KeyStore sr = KeyStore.getInstance("JKS"); // Keystore password is required // to access Keystore char[] pass = ("123456").toCharArray(); // creating and initializing object of InputStream InputStream is = new FileInputStream( "f:/java/private key.store"); // initializing keystore object sr.load(is, pass); // creating and initializing // KeyStore.ProtectionParameter object KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(pass); // getting KeyStore.PrivateKeyEntry object // using getEntry() method KeyStore.PrivateKeyEntry print = (KeyStore.PrivateKeyEntry)sr .getEntry("ftpkey", entryPassword); // display the result System.out.println("PrivateKey of particular entry: " + print.getPrivateKey()); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } catch (KeyStoreException e) { System.out.println("Exception thrown : " + e); } catch (FileNotFoundException e) { System.out.println("Exception thrown : " + e); } catch (IOException e) { System.out.println("Exception thrown : " + e); } catch (CertificateException e) { System.out.println("Exception thrown : " + e); } catch (UnrecoverableEntryException e) { System.out.println("Exception thrown : " + e); } }} Example 2: For KeyStoreException // Java program to demonstrate getEntry() method import java.security.*;import java.security.cert.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating the object of KeyStore // and getting instance KeyStore sr = KeyStore.getInstance("JKS"); // keystore password is required to access keystore char[] pass = ("123456").toCharArray(); // creating and initializing object of InputStream InputStream is = new FileInputStream( "f:/java/private key.store"); // initializing keystore object // sr.load(is, pass); // creating and initializing // KeyStore.ProtectionParameter object KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(pass); // getting KeyStore.PrivateKeyEntry object // using getEntry() method KeyStore.PrivateKeyEntry print = (KeyStore.PrivateKeyEntry)sr .getEntry("ftpkey", entryPassword); // display the result System.out.println( "PrivateKey of particular entry : " + print.getPrivateKey()); } catch (FileNotFoundException e) { System.out.println("Exception thrown : " + e); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } catch (KeyStoreException e) { System.out.println("\nException thrown : " + e); } catch (UnrecoverableEntryException e) { System.out.println("Exception thrown : " + e); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } }} Reference: https://docs.oracle.com/javase/9/docs/api/java/security/KeyStore.html#getEntry-java.lang.String-java.security.KeyStore.ProtectionParameter- shubham_singh singghakshay Java-Functions Java-KeyStore Java-security package 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 Internal Working of HashMap in Java Introduction to Java Comparator Interface in Java with Examples PriorityQueue in Java
[ { "code": null, "e": 25237, "s": 25209, "text": "\n28 Nov, 2021" }, { "code": null, "e": 25410, "s": 25237, "text": "The getEntry() method of java.security.KeyStore class is used to get the keystore entry for this instance with the help of the specified alias and the protection parameter." }, { "code": null, "e": 25418, "s": 25410, "text": "Syntax:" }, { "code": null, "e": 25631, "s": 25418, "text": "public final KeyStore.Entry\n getEntry(String alias, \n KeyStore.ProtectionParameter protParam)\n throws NoSuchAlgorithmException, \n UnrecoverableEntryException, \n KeyStoreException" }, { "code": null, "e": 25698, "s": 25631, "text": "Parameter: This method accepts following arguments as a parameter." }, { "code": null, "e": 25756, "s": 25698, "text": "alias: which is name of the Keystore Entry to be fetched." }, { "code": null, "e": 25815, "s": 25756, "text": "protParam: which contains the password to access keystore." }, { "code": null, "e": 25906, "s": 25815, "text": "Return Value: This method returns the keystore entry for the requested alias if it exists." }, { "code": null, "e": 25956, "s": 25906, "text": "Exception: This method throws following exception" }, { "code": null, "e": 25994, "s": 25956, "text": "NullPointerException: for null alias." }, { "code": null, "e": 26049, "s": 25994, "text": "NoSuchAlgorithmException: if the algorithm is missing." }, { "code": null, "e": 26116, "s": 26049, "text": "UnrecoverableEntryException: if the specified password is invalid." }, { "code": null, "e": 26186, "s": 26116, "text": "KeyStoreException: if the keystore has not been initialized (loaded)." }, { "code": null, "e": 26468, "s": 26186, "text": "Note: All the programs in this article won’t run on online IDE as no ‘privatekey’ Keystore exists. You can check this code on Java compiler on your system. To check this code, create a Keystore ‘privatekey’ on your system and set your own Keystore password to access that Keystore." }, { "code": null, "e": 26534, "s": 26468, "text": "Below are the examples to illustrate the getCertificate() method:" }, { "code": null, "e": 26545, "s": 26534, "text": "Example 1:" }, { "code": "// Java program to demonstrate getEntry() method import java.security.*;import java.security.cert.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating the object of KeyStore // and getting instance KeyStore sr = KeyStore.getInstance(\"JKS\"); // Keystore password is required // to access Keystore char[] pass = (\"123456\").toCharArray(); // creating and initializing object of InputStream InputStream is = new FileInputStream( \"f:/java/private key.store\"); // initializing keystore object sr.load(is, pass); // creating and initializing // KeyStore.ProtectionParameter object KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(pass); // getting KeyStore.PrivateKeyEntry object // using getEntry() method KeyStore.PrivateKeyEntry print = (KeyStore.PrivateKeyEntry)sr .getEntry(\"ftpkey\", entryPassword); // display the result System.out.println(\"PrivateKey of particular entry: \" + print.getPrivateKey()); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } catch (KeyStoreException e) { System.out.println(\"Exception thrown : \" + e); } catch (FileNotFoundException e) { System.out.println(\"Exception thrown : \" + e); } catch (IOException e) { System.out.println(\"Exception thrown : \" + e); } catch (CertificateException e) { System.out.println(\"Exception thrown : \" + e); } catch (UnrecoverableEntryException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 28657, "s": 26545, "text": null }, { "code": null, "e": 28690, "s": 28657, "text": "Example 2: For KeyStoreException" }, { "code": "// Java program to demonstrate getEntry() method import java.security.*;import java.security.cert.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating the object of KeyStore // and getting instance KeyStore sr = KeyStore.getInstance(\"JKS\"); // keystore password is required to access keystore char[] pass = (\"123456\").toCharArray(); // creating and initializing object of InputStream InputStream is = new FileInputStream( \"f:/java/private key.store\"); // initializing keystore object // sr.load(is, pass); // creating and initializing // KeyStore.ProtectionParameter object KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(pass); // getting KeyStore.PrivateKeyEntry object // using getEntry() method KeyStore.PrivateKeyEntry print = (KeyStore.PrivateKeyEntry)sr .getEntry(\"ftpkey\", entryPassword); // display the result System.out.println( \"PrivateKey of particular entry : \" + print.getPrivateKey()); } catch (FileNotFoundException e) { System.out.println(\"Exception thrown : \" + e); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } catch (KeyStoreException e) { System.out.println(\"\\nException thrown : \" + e); } catch (UnrecoverableEntryException e) { System.out.println(\"Exception thrown : \" + e); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 30586, "s": 28690, "text": null }, { "code": null, "e": 30737, "s": 30586, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/security/KeyStore.html#getEntry-java.lang.String-java.security.KeyStore.ProtectionParameter-" }, { "code": null, "e": 30751, "s": 30737, "text": "shubham_singh" }, { "code": null, "e": 30764, "s": 30751, "text": "singghakshay" }, { "code": null, "e": 30779, "s": 30764, "text": "Java-Functions" }, { "code": null, "e": 30793, "s": 30779, "text": "Java-KeyStore" }, { "code": null, "e": 30815, "s": 30793, "text": "Java-security package" }, { "code": null, "e": 30820, "s": 30815, "text": "Java" }, { "code": null, "e": 30825, "s": 30820, "text": "Java" }, { "code": null, "e": 30923, "s": 30825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30938, "s": 30923, "text": "Stream In Java" }, { "code": null, "e": 30959, "s": 30938, "text": "Constructors in Java" }, { "code": null, "e": 30978, "s": 30959, "text": "Exceptions in Java" }, { "code": null, "e": 31008, "s": 30978, "text": "Functional Interfaces in Java" }, { "code": null, "e": 31054, "s": 31008, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 31071, "s": 31054, "text": "Generics in Java" }, { "code": null, "e": 31107, "s": 31071, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 31128, "s": 31107, "text": "Introduction to Java" }, { "code": null, "e": 31171, "s": 31128, "text": "Comparator Interface in Java with Examples" } ]
malloc() vs new() in C/C++
The function malloc() is used to allocate the requested size of bytes and it returns a pointer to the first byte of allocated memory. It returns null pointer, if fails. Here is the syntax of malloc() in C++ language, pointer_name = (cast-type*) malloc(size); Here, pointer_name − Any name given to the pointer. cast-type − The datatype in which you want to cast the allocated memory by malloc(). size − Size of allocated memory in bytes. Here is an example of malloc() in C language, Live Demo #include <stdio.h> #include <stdlib.h> int main() { int n = 4, i, *p, s = 0; p = (int*) malloc(n * sizeof(int)); if(p == NULL) { printf("\nError! memory not allocated."); exit(0); } printf("\nEnter elements of array : "); for(i = 0; i < n; ++i) { scanf("%d", p + i); s += *(p + i); } printf("\nSum : %d", s); return 0; } Here is the output, Enter elements of array : 32 23 21 8 Sum : 84 In the above program, four variables are declared and one of them is a pointer variable *p which is storing the memory allocated by malloc. We are printing the sum of elements. int n = 4, i, *p, s = 0; p = (int*) malloc(n * sizeof(int)); if(p == NULL) { printf("\nError! memory not allocated."); exit(0); } printf("\nEnter elements of array : "); for(i = 0; i < n; ++i) { scanf("%d", p + i); s += *(p + i); } printf("\nSum : %d", s); The new operator requests for the memory allocation in heap. If the sufficient memory is available, it initializes the memory to the pointer variable and returns its address. Here is the syntax of new operator in C++ language, pointer_variable = new datatype; Here is the syntax to initialize the memory, pointer_variable = new datatype(value); Here is the syntax to allocate a block of memory, pointer_variable = new datatype[size]; Here is an example of new operator in C++ language, Live Demo #include <iostream> using namespace std; int main () { int *ptr1 = NULL; ptr1 = new int; float *ptr2 = new float(223.324); int *ptr3 = new int[28]; *ptr1 = 28; cout << "Value of pointer variable 1 : " << *ptr1 << endl; cout << "Value of pointer variable 2 : " << *ptr2 << endl; if (!ptr3) cout << "Allocation of memory failed\n"; else { for (int i = 10; i < 15; i++) ptr3[i] = i+1; cout << "Value to store in block of memory: "; for (int i = 10; i < 15; i++) cout << ptr3[i] << " "; } return 0; } Value of pointer variable 1 : 28 Value of pointer variable 2 : 223.324 Value to store in block of memory: 11 12 13 14 15 In the above program, three pointer variables are declared as ptr1, ptr2 and ptr3. The pointer variables ptr1 and ptr2 are initialized with the value using new() and ptr3 is storing the allocated block of memory by new() function. ptr1 = new int; float *ptr2 = new float(223.324); int *ptr3 = new int[28]; *ptr1 = 28;
[ { "code": null, "e": 1231, "s": 1062, "text": "The function malloc() is used to allocate the requested size of bytes and it returns a pointer to the first byte of allocated memory. It returns null pointer, if fails." }, { "code": null, "e": 1279, "s": 1231, "text": "Here is the syntax of malloc() in C++ language," }, { "code": null, "e": 1321, "s": 1279, "text": "pointer_name = (cast-type*) malloc(size);" }, { "code": null, "e": 1327, "s": 1321, "text": "Here," }, { "code": null, "e": 1373, "s": 1327, "text": "pointer_name − Any name given to the pointer." }, { "code": null, "e": 1458, "s": 1373, "text": "cast-type − The datatype in which you want to cast the allocated memory by malloc()." }, { "code": null, "e": 1500, "s": 1458, "text": "size − Size of allocated memory in bytes." }, { "code": null, "e": 1546, "s": 1500, "text": "Here is an example of malloc() in C language," }, { "code": null, "e": 1557, "s": 1546, "text": " Live Demo" }, { "code": null, "e": 1929, "s": 1557, "text": "#include <stdio.h>\n#include <stdlib.h>\nint main() {\n int n = 4, i, *p, s = 0;\n p = (int*) malloc(n * sizeof(int));\n if(p == NULL) {\n printf(\"\\nError! memory not allocated.\");\n exit(0);\n }\n printf(\"\\nEnter elements of array : \");\n for(i = 0; i < n; ++i) {\n scanf(\"%d\", p + i);\n s += *(p + i);\n }\n printf(\"\\nSum : %d\", s);\n return 0;\n}" }, { "code": null, "e": 1949, "s": 1929, "text": "Here is the output," }, { "code": null, "e": 1995, "s": 1949, "text": "Enter elements of array : 32 23 21 8\nSum : 84" }, { "code": null, "e": 2172, "s": 1995, "text": "In the above program, four variables are declared and one of them is a pointer variable *p which is storing the memory allocated by malloc. We are printing the sum of elements." }, { "code": null, "e": 2441, "s": 2172, "text": "int n = 4, i, *p, s = 0;\np = (int*) malloc(n * sizeof(int));\nif(p == NULL) {\n printf(\"\\nError! memory not allocated.\");\n exit(0);\n}\nprintf(\"\\nEnter elements of array : \");\nfor(i = 0; i < n; ++i) {\n scanf(\"%d\", p + i);\n s += *(p + i);\n}\nprintf(\"\\nSum : %d\", s);" }, { "code": null, "e": 2616, "s": 2441, "text": "The new operator requests for the memory allocation in heap. If the sufficient memory is available, it initializes the memory to the pointer variable and returns its address." }, { "code": null, "e": 2668, "s": 2616, "text": "Here is the syntax of new operator in C++ language," }, { "code": null, "e": 2701, "s": 2668, "text": "pointer_variable = new datatype;" }, { "code": null, "e": 2746, "s": 2701, "text": "Here is the syntax to initialize the memory," }, { "code": null, "e": 2786, "s": 2746, "text": "pointer_variable = new datatype(value);" }, { "code": null, "e": 2836, "s": 2786, "text": "Here is the syntax to allocate a block of memory," }, { "code": null, "e": 2875, "s": 2836, "text": "pointer_variable = new datatype[size];" }, { "code": null, "e": 2927, "s": 2875, "text": "Here is an example of new operator in C++ language," }, { "code": null, "e": 2938, "s": 2927, "text": " Live Demo" }, { "code": null, "e": 3502, "s": 2938, "text": "#include <iostream>\nusing namespace std;\nint main () {\n int *ptr1 = NULL;\n ptr1 = new int;\n float *ptr2 = new float(223.324);\n int *ptr3 = new int[28];\n *ptr1 = 28;\n cout << \"Value of pointer variable 1 : \" << *ptr1 << endl;\n cout << \"Value of pointer variable 2 : \" << *ptr2 << endl;\n if (!ptr3)\n cout << \"Allocation of memory failed\\n\";\n else {\n for (int i = 10; i < 15; i++)\n ptr3[i] = i+1;\n\n cout << \"Value to store in block of memory: \";\n for (int i = 10; i < 15; i++)\n cout << ptr3[i] << \" \";\n }\n return 0;\n}" }, { "code": null, "e": 3623, "s": 3502, "text": "Value of pointer variable 1 : 28\nValue of pointer variable 2 : 223.324\nValue to store in block of memory: 11 12 13 14 15" }, { "code": null, "e": 3854, "s": 3623, "text": "In the above program, three pointer variables are declared as ptr1, ptr2 and ptr3. The pointer variables ptr1 and ptr2 are initialized with the value using new() and ptr3 is storing the allocated block of memory by new() function." }, { "code": null, "e": 3941, "s": 3854, "text": "ptr1 = new int;\nfloat *ptr2 = new float(223.324);\nint *ptr3 = new int[28];\n*ptr1 = 28;" } ]
Java 8 How to get Common Elements From Two Lists
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 Here we will see how to get common elements from two lists we can even say the intersection of two lists using different ways. Input: a = {"1","2","3","4","5"} b = {"1","2","3"} Result: 1,2,3 retainAll() method from the Collection interface is used to remove the common elements from two different lists. List<Integer> list1 = new ArrayList<>(Arrays.asList(1,2,3,4,5)); List<Integer> list2 = new ArrayList<>(Arrays.asList(1,2,3)); list1.retainAll(list2); System.out.println(list1); Output: [1, 2, 3] We even get the common elements from two lists using java 8 stream API distinct() method. List<Integer> list1 = new ArrayList<>(Arrays.asList(1,2,3,4,5)); List<Integer> list2 = new ArrayList<>(Arrays.asList(1,2,3)); List<Integer> result = list1.stream() .distinct() .filter(list2::contains) .collect(Collectors.toList()); result.forEach(System.out::print); Output: 123 Getting common elements from two different lists using java 8 filter condition. List<Integer> list1 = new ArrayList<>(Arrays.asList(1,2,3,4,5)); List<Integer> list2 = new ArrayList<>(Arrays.asList(1,2,3)); List<Integer> finalList = list1.stream().filter(item-> !list2.contains(item)).collect(Collectors.toList()); finalList.stream().forEach(System.out::print); Output: 123 Done! Java 8 Stream API Happy Learning 🙂 ArrayList in Java Java 8 Stream Filter Example with Objects Java 8 Getting Min and Max values from a Stream Java 8 Stream API and Parallelism How to get Stream count in Java 8 How to Merge Streams in Java 8 Java 8 How to Convert List to String comma separated values Python List Data Structure In Depth 2 ways to Create ArrayList in Java How to calculate Employees Salaries Java 8 summingInt How to Convert Iterable to Stream Java 8 How to add elements to ArrayList in Java How to merge two lists in Python jQuery Add Elements Example Tutorials JQuery Remove Elements Example ArrayList in Java Java 8 Stream Filter Example with Objects Java 8 Getting Min and Max values from a Stream Java 8 Stream API and Parallelism How to get Stream count in Java 8 How to Merge Streams in Java 8 Java 8 How to Convert List to String comma separated values Python List Data Structure In Depth 2 ways to Create ArrayList in Java How to calculate Employees Salaries Java 8 summingInt How to Convert Iterable to Stream Java 8 How to add elements to ArrayList in Java How to merge two lists in Python jQuery Add Elements Example Tutorials JQuery Remove Elements Example Varun March 16, 2022 at 2:32 am - Reply How can I do this for n number of lists? shree Dhar March 19, 2022 at 6:47 am - Reply For Common Elements from two lists using java8 filter: filter is not using properly. Current query – list1.stream().filter(item-> !list2.contains(item)).collect(Collectors.toList()); Correct query – list1.stream().filter(item-> list2.contains(item)).collect(Collectors.toList()); Varun March 16, 2022 at 2:32 am - Reply How can I do this for n number of lists? How can I do this for n number of lists? shree Dhar March 19, 2022 at 6:47 am - Reply For Common Elements from two lists using java8 filter: filter is not using properly. Current query – list1.stream().filter(item-> !list2.contains(item)).collect(Collectors.toList()); Correct query – list1.stream().filter(item-> list2.contains(item)).collect(Collectors.toList()); For Common Elements from two lists using java8 filter: filter is not using properly. Current query – list1.stream().filter(item-> !list2.contains(item)).collect(Collectors.toList()); Correct query – list1.stream().filter(item-> list2.contains(item)).collect(Collectors.toList()); Δ Java8 – Install Windows Java8 – foreach Java8 – forEach with index Java8 – Stream Filter Objects Java8 – Comparator Userdefined Java8 – GroupingBy Java8 – SummingInt Java8 – walk ReadFiles Java8 – JAVA_HOME on Windows Howto – Install Java on Mac OS Howto – Convert Iterable to Stream Howto – Get common elements from two Lists Howto – Convert List to String Howto – Concatenate Arrays using Stream Howto – Remove duplicates from List Howto – Filter null values from Stream Howto – Convert List to Map Howto – Convert Stream to List Howto – Sort a Map Howto – Filter a Map Howto – Get Current UTC Time Howto – Verify an Array contains a specific value Howto – Convert ArrayList to Array Howto – Read File Line By Line Howto – Convert Date to LocalDate Howto – Merge Streams Howto – Resolve NullPointerException in toMap Howto -Get Stream count Howto – Get Min and Max values in a Stream Howto – Convert InputStream to String
[ { "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": 525, "s": 398, "text": "Here we will see how to get common elements from two lists we can even say the intersection of two lists using different ways." }, { "code": null, "e": 591, "s": 525, "text": "Input:\na = {\"1\",\"2\",\"3\",\"4\",\"5\"}\nb = {\"1\",\"2\",\"3\"}\n\nResult: 1,2,3" }, { "code": null, "e": 704, "s": 591, "text": "retainAll() method from the Collection interface is used to remove the common elements from two different lists." }, { "code": null, "e": 881, "s": 704, "text": "List<Integer> list1 = new ArrayList<>(Arrays.asList(1,2,3,4,5));\nList<Integer> list2 = new ArrayList<>(Arrays.asList(1,2,3));\nlist1.retainAll(list2);\nSystem.out.println(list1);" }, { "code": null, "e": 889, "s": 881, "text": "Output:" }, { "code": null, "e": 899, "s": 889, "text": "[1, 2, 3]" }, { "code": null, "e": 989, "s": 899, "text": "We even get the common elements from two lists using java 8 stream API distinct() method." }, { "code": null, "e": 1282, "s": 989, "text": "List<Integer> list1 = new ArrayList<>(Arrays.asList(1,2,3,4,5));\nList<Integer> list2 = new ArrayList<>(Arrays.asList(1,2,3));\n\nList<Integer> result = list1.stream()\n .distinct()\n .filter(list2::contains)\n .collect(Collectors.toList());\n\nresult.forEach(System.out::print);" }, { "code": null, "e": 1290, "s": 1282, "text": "Output:" }, { "code": null, "e": 1294, "s": 1290, "text": "123" }, { "code": null, "e": 1374, "s": 1294, "text": "Getting common elements from two different lists using java 8 filter condition." }, { "code": null, "e": 1658, "s": 1374, "text": "List<Integer> list1 = new ArrayList<>(Arrays.asList(1,2,3,4,5));\nList<Integer> list2 = new ArrayList<>(Arrays.asList(1,2,3));\n\nList<Integer> finalList = list1.stream().filter(item-> !list2.contains(item)).collect(Collectors.toList());\n\nfinalList.stream().forEach(System.out::print);" }, { "code": null, "e": 1666, "s": 1658, "text": "Output:" }, { "code": null, "e": 1670, "s": 1666, "text": "123" }, { "code": null, "e": 1676, "s": 1670, "text": "Done!" }, { "code": null, "e": 1694, "s": 1676, "text": "Java 8 Stream API" }, { "code": null, "e": 1711, "s": 1694, "text": "Happy Learning 🙂" }, { "code": null, "e": 2289, "s": 1711, "text": "\nArrayList in Java\nJava 8 Stream Filter Example with Objects\nJava 8 Getting Min and Max values from a Stream\nJava 8 Stream API and Parallelism\nHow to get Stream count in Java 8\nHow to Merge Streams in Java 8\nJava 8 How to Convert List to String comma separated values\nPython List Data Structure In Depth\n2 ways to Create ArrayList in Java\nHow to calculate Employees Salaries Java 8 summingInt\nHow to Convert Iterable to Stream Java 8\nHow to add elements to ArrayList in Java\nHow to merge two lists in Python\njQuery Add Elements Example Tutorials\nJQuery Remove Elements Example\n" }, { "code": null, "e": 2307, "s": 2289, "text": "ArrayList in Java" }, { "code": null, "e": 2349, "s": 2307, "text": "Java 8 Stream Filter Example with Objects" }, { "code": null, "e": 2397, "s": 2349, "text": "Java 8 Getting Min and Max values from a Stream" }, { "code": null, "e": 2431, "s": 2397, "text": "Java 8 Stream API and Parallelism" }, { "code": null, "e": 2465, "s": 2431, "text": "How to get Stream count in Java 8" }, { "code": null, "e": 2496, "s": 2465, "text": "How to Merge Streams in Java 8" }, { "code": null, "e": 2556, "s": 2496, "text": "Java 8 How to Convert List to String comma separated values" }, { "code": null, "e": 2592, "s": 2556, "text": "Python List Data Structure In Depth" }, { "code": null, "e": 2627, "s": 2592, "text": "2 ways to Create ArrayList in Java" }, { "code": null, "e": 2681, "s": 2627, "text": "How to calculate Employees Salaries Java 8 summingInt" }, { "code": null, "e": 2722, "s": 2681, "text": "How to Convert Iterable to Stream Java 8" }, { "code": null, "e": 2763, "s": 2722, "text": "How to add elements to ArrayList in Java" }, { "code": null, "e": 2796, "s": 2763, "text": "How to merge two lists in Python" }, { "code": null, "e": 2834, "s": 2796, "text": "jQuery Add Elements Example Tutorials" }, { "code": null, "e": 2865, "s": 2834, "text": "JQuery Remove Elements Example" }, { "code": null, "e": 3295, "s": 2865, "text": "\n\n\n\n\n\nVarun\nMarch 16, 2022 at 2:32 am - Reply \n\nHow can I do this for n number of lists?\n\n\n\n\n\n\n\n\n\nshree Dhar\nMarch 19, 2022 at 6:47 am - Reply \n\nFor Common Elements from two lists using java8 filter:\nfilter is not using properly.\nCurrent query – list1.stream().filter(item-> !list2.contains(item)).collect(Collectors.toList());\nCorrect query – list1.stream().filter(item-> list2.contains(item)).collect(Collectors.toList());\n\n\n\n\n" }, { "code": null, "e": 3387, "s": 3295, "text": "\n\n\n\n\nVarun\nMarch 16, 2022 at 2:32 am - Reply \n\nHow can I do this for n number of lists?\n\n\n\n" }, { "code": null, "e": 3428, "s": 3387, "text": "How can I do this for n number of lists?" }, { "code": null, "e": 3764, "s": 3428, "text": "\n\n\n\n\nshree Dhar\nMarch 19, 2022 at 6:47 am - Reply \n\nFor Common Elements from two lists using java8 filter:\nfilter is not using properly.\nCurrent query – list1.stream().filter(item-> !list2.contains(item)).collect(Collectors.toList());\nCorrect query – list1.stream().filter(item-> list2.contains(item)).collect(Collectors.toList());\n\n\n\n" }, { "code": null, "e": 4044, "s": 3764, "text": "For Common Elements from two lists using java8 filter:\nfilter is not using properly.\nCurrent query – list1.stream().filter(item-> !list2.contains(item)).collect(Collectors.toList());\nCorrect query – list1.stream().filter(item-> list2.contains(item)).collect(Collectors.toList());" }, { "code": null, "e": 4050, "s": 4048, "text": "Δ" }, { "code": null, "e": 4075, "s": 4050, "text": " Java8 – Install Windows" }, { "code": null, "e": 4092, "s": 4075, "text": " Java8 – foreach" }, { "code": null, "e": 4120, "s": 4092, "text": " Java8 – forEach with index" }, { "code": null, "e": 4151, "s": 4120, "text": " Java8 – Stream Filter Objects" }, { "code": null, "e": 4183, "s": 4151, "text": " Java8 – Comparator Userdefined" }, { "code": null, "e": 4203, "s": 4183, "text": " Java8 – GroupingBy" }, { "code": null, "e": 4223, "s": 4203, "text": " Java8 – SummingInt" }, { "code": null, "e": 4247, "s": 4223, "text": " Java8 – walk ReadFiles" }, { "code": null, "e": 4277, "s": 4247, "text": " Java8 – JAVA_HOME on Windows" }, { "code": null, "e": 4309, "s": 4277, "text": " Howto – Install Java on Mac OS" }, { "code": null, "e": 4345, "s": 4309, "text": " Howto – Convert Iterable to Stream" }, { "code": null, "e": 4389, "s": 4345, "text": " Howto – Get common elements from two Lists" }, { "code": null, "e": 4421, "s": 4389, "text": " Howto – Convert List to String" }, { "code": null, "e": 4462, "s": 4421, "text": " Howto – Concatenate Arrays using Stream" }, { "code": null, "e": 4499, "s": 4462, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 4539, "s": 4499, "text": " Howto – Filter null values from Stream" }, { "code": null, "e": 4568, "s": 4539, "text": " Howto – Convert List to Map" }, { "code": null, "e": 4600, "s": 4568, "text": " Howto – Convert Stream to List" }, { "code": null, "e": 4620, "s": 4600, "text": " Howto – Sort a Map" }, { "code": null, "e": 4642, "s": 4620, "text": " Howto – Filter a Map" }, { "code": null, "e": 4672, "s": 4642, "text": " Howto – Get Current UTC Time" }, { "code": null, "e": 4723, "s": 4672, "text": " Howto – Verify an Array contains a specific value" }, { "code": null, "e": 4759, "s": 4723, "text": " Howto – Convert ArrayList to Array" }, { "code": null, "e": 4791, "s": 4759, "text": " Howto – Read File Line By Line" }, { "code": null, "e": 4826, "s": 4791, "text": " Howto – Convert Date to LocalDate" }, { "code": null, "e": 4849, "s": 4826, "text": " Howto – Merge Streams" }, { "code": null, "e": 4896, "s": 4849, "text": " Howto – Resolve NullPointerException in toMap" }, { "code": null, "e": 4921, "s": 4896, "text": " Howto -Get Stream count" }, { "code": null, "e": 4965, "s": 4921, "text": " Howto – Get Min and Max values in a Stream" } ]
TypeScript | String toLowerCase() Method - GeeksforGeeks
03 Mar, 2021 The toLowerCase() is an inbuilt function in TypeScript which is used to convert the characters within a string to lowercase. Syntax: string.toLowerCase( ) Parameter: This methods does not accepts any parameter. Return Value: This method returns the string in lowercase. Below examples illustrate the String toLowerCase() Method in TypeScript. Example : TypeScript // Original stringsvar str = "Geeksforgeeks - Best Platform"; // use of String toLowerCase() Methodvar newstr = str.toLowerCase() console.log(newstr); Output: geeksforgeeks - best platform Example 2: TypeScript // Original stringsvar str = "TypeScript - String toLowerCase()"; // use of String toLowerCase() Methodvar newstr = str.toLowerCase() console.log(newstr); Output: typescript - string tolowercase() pratikraut0000 TypeScript 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 Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? 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": 25635, "s": 25607, "text": "\n03 Mar, 2021" }, { "code": null, "e": 25760, "s": 25635, "text": "The toLowerCase() is an inbuilt function in TypeScript which is used to convert the characters within a string to lowercase." }, { "code": null, "e": 25768, "s": 25760, "text": "Syntax:" }, { "code": null, "e": 25791, "s": 25768, "text": "string.toLowerCase( ) " }, { "code": null, "e": 25979, "s": 25791, "text": "Parameter: This methods does not accepts any parameter. Return Value: This method returns the string in lowercase. Below examples illustrate the String toLowerCase() Method in TypeScript." }, { "code": null, "e": 25990, "s": 25979, "text": "Example : " }, { "code": null, "e": 26001, "s": 25990, "text": "TypeScript" }, { "code": "// Original stringsvar str = \"Geeksforgeeks - Best Platform\"; // use of String toLowerCase() Methodvar newstr = str.toLowerCase() console.log(newstr);", "e": 26153, "s": 26001, "text": null }, { "code": null, "e": 26162, "s": 26153, "text": "Output: " }, { "code": null, "e": 26192, "s": 26162, "text": "geeksforgeeks - best platform" }, { "code": null, "e": 26204, "s": 26192, "text": "Example 2: " }, { "code": null, "e": 26215, "s": 26204, "text": "TypeScript" }, { "code": "// Original stringsvar str = \"TypeScript - String toLowerCase()\"; // use of String toLowerCase() Methodvar newstr = str.toLowerCase() console.log(newstr);", "e": 26371, "s": 26215, "text": null }, { "code": null, "e": 26380, "s": 26371, "text": "Output: " }, { "code": null, "e": 26414, "s": 26380, "text": "typescript - string tolowercase()" }, { "code": null, "e": 26435, "s": 26420, "text": "pratikraut0000" }, { "code": null, "e": 26446, "s": 26435, "text": "TypeScript" }, { "code": null, "e": 26457, "s": 26446, "text": "JavaScript" }, { "code": null, "e": 26474, "s": 26457, "text": "Web Technologies" }, { "code": null, "e": 26572, "s": 26474, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26612, "s": 26572, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26657, "s": 26612, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26718, "s": 26657, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26790, "s": 26718, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26842, "s": 26790, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 26882, "s": 26842, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26915, "s": 26882, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26960, "s": 26915, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27003, "s": 26960, "text": "How to fetch data from an API in ReactJS ?" } ]
How to convert right linear grammar to left linear grammar?
For every finite automata (FA) there exists a regular grammar and for every regular grammar there is a left linear and right linear regular grammar. Consider a regular grammar − a(a+b)* A → aB B → aB|bB|e For the given regular expression, the above grammar is right linear grammar. Now, convert the above right linear grammar to left linear grammar. The rule to follow for conversion is, Finite Automata → Right linear The reverse of right linear →left linear grammar. So, A → BaB → Ba|Bb|e A → Ba B → Ba|Bb|e Finally for every right linear there is a Consider a language {bnabma| n>=2, m>=2} The right linear grammar for the given language is − bn ⇒ A→bA|b A is on right side bm ⇒ B→bB|b B is on right side The complete expression grammar is − S→AaBa A→bA|b B→bB|b. The left grammar for the above right linear grammar is, bn ⇒ A→Ab|b bm ⇒ B→Bb|b The complete expression grammar is as follows − S→AaBa A→Ab|b B→Bb|b
[ { "code": null, "e": 1211, "s": 1062, "text": "For every finite automata (FA) there exists a regular grammar and for every regular grammar there is a left linear and right linear regular grammar." }, { "code": null, "e": 1240, "s": 1211, "text": "Consider a regular grammar −" }, { "code": null, "e": 1270, "s": 1240, "text": " a(a+b)*\nA → aB\nB → aB|bB|e" }, { "code": null, "e": 1347, "s": 1270, "text": "For the given regular expression, the above grammar is right linear grammar." }, { "code": null, "e": 1415, "s": 1347, "text": "Now, convert the above right linear grammar to left linear grammar." }, { "code": null, "e": 1453, "s": 1415, "text": "The rule to follow for conversion is," }, { "code": null, "e": 1484, "s": 1453, "text": "Finite Automata → Right linear" }, { "code": null, "e": 1534, "s": 1484, "text": "The reverse of right linear →left linear grammar." }, { "code": null, "e": 1538, "s": 1534, "text": "So," }, { "code": null, "e": 1556, "s": 1538, "text": "A → BaB → Ba|Bb|e" }, { "code": null, "e": 1563, "s": 1556, "text": "A → Ba" }, { "code": null, "e": 1575, "s": 1563, "text": "B → Ba|Bb|e" }, { "code": null, "e": 1617, "s": 1575, "text": "Finally for every right linear there is a" }, { "code": null, "e": 1658, "s": 1617, "text": "Consider a language {bnabma| n>=2, m>=2}" }, { "code": null, "e": 1711, "s": 1658, "text": "The right linear grammar for the given language is −" }, { "code": null, "e": 1785, "s": 1711, "text": "bn ⇒ A→bA|b A is on right side\nbm ⇒ B→bB|b B is on right side" }, { "code": null, "e": 1822, "s": 1785, "text": "The complete expression grammar is −" }, { "code": null, "e": 1844, "s": 1822, "text": "S→AaBa\nA→bA|b\nB→bB|b." }, { "code": null, "e": 1900, "s": 1844, "text": "The left grammar for the above right linear grammar is," }, { "code": null, "e": 1924, "s": 1900, "text": "bn ⇒ A→Ab|b\nbm ⇒ B→Bb|b" }, { "code": null, "e": 1972, "s": 1924, "text": "The complete expression grammar is as follows −" }, { "code": null, "e": 1993, "s": 1972, "text": "S→AaBa\nA→Ab|b\nB→Bb|b" } ]
Random setSeed() method in Java with Examples - GeeksforGeeks
07 Jan, 2019 The setSeed() method of Random class sets the seed of the random number generator using a single long seed. Syntax: public void setSeed() Parameters: The function accepts a single parameter seed which is the initial seed. Return Value: This method has no return value. Exception: The function does not throws any exception. Program below demonstrates the above mentioned function: Program 1: // program to demonstrate the// function java.util.Random.setSeed() import java.util.*;public class GFG { public static void main(String[] args) { // create random object Random r = new Random(); // return the next pseudorandom integer value System.out.println("Random Integer value : " + r.nextInt()); // setting seed long s = 24; r.setSeed(s); // value after setting seed System.out.println("Random Integer value : " + r.nextInt()); }} Random Integer value : -2053473769 Random Integer value : -1152406585 Program 2: // program to demonstrate the// function java.util.Random.setSeed() import java.util.*;public class GFG { public static void main(String[] args) { // create random object Random r = new Random(); // return the next pseudorandom integer value System.out.println("Random Integer value : " + r.nextInt()); // setting seed long s = 29; r.setSeed(s); // value after setting seed System.out.println("Random Integer value : " + r.nextInt()); }} Random Integer value : -388369680 Random Integer value : -1154330330 Java-Functions Java-Random Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Multidimensional Arrays in Java Stream In Java Stack Class in Java Singleton Class in Java
[ { "code": null, "e": 24968, "s": 24940, "text": "\n07 Jan, 2019" }, { "code": null, "e": 25076, "s": 24968, "text": "The setSeed() method of Random class sets the seed of the random number generator using a single long seed." }, { "code": null, "e": 25084, "s": 25076, "text": "Syntax:" }, { "code": null, "e": 25108, "s": 25084, "text": "public void setSeed() \n" }, { "code": null, "e": 25192, "s": 25108, "text": "Parameters: The function accepts a single parameter seed which is the initial seed." }, { "code": null, "e": 25239, "s": 25192, "text": "Return Value: This method has no return value." }, { "code": null, "e": 25294, "s": 25239, "text": "Exception: The function does not throws any exception." }, { "code": null, "e": 25351, "s": 25294, "text": "Program below demonstrates the above mentioned function:" }, { "code": null, "e": 25362, "s": 25351, "text": "Program 1:" }, { "code": "// program to demonstrate the// function java.util.Random.setSeed() import java.util.*;public class GFG { public static void main(String[] args) { // create random object Random r = new Random(); // return the next pseudorandom integer value System.out.println(\"Random Integer value : \" + r.nextInt()); // setting seed long s = 24; r.setSeed(s); // value after setting seed System.out.println(\"Random Integer value : \" + r.nextInt()); }}", "e": 25909, "s": 25362, "text": null }, { "code": null, "e": 25980, "s": 25909, "text": "Random Integer value : -2053473769\nRandom Integer value : -1152406585\n" }, { "code": null, "e": 25991, "s": 25980, "text": "Program 2:" }, { "code": "// program to demonstrate the// function java.util.Random.setSeed() import java.util.*;public class GFG { public static void main(String[] args) { // create random object Random r = new Random(); // return the next pseudorandom integer value System.out.println(\"Random Integer value : \" + r.nextInt()); // setting seed long s = 29; r.setSeed(s); // value after setting seed System.out.println(\"Random Integer value : \" + r.nextInt()); }}", "e": 26564, "s": 25991, "text": null }, { "code": null, "e": 26634, "s": 26564, "text": "Random Integer value : -388369680\nRandom Integer value : -1154330330\n" }, { "code": null, "e": 26649, "s": 26634, "text": "Java-Functions" }, { "code": null, "e": 26661, "s": 26649, "text": "Java-Random" }, { "code": null, "e": 26666, "s": 26661, "text": "Java" }, { "code": null, "e": 26671, "s": 26666, "text": "Java" }, { "code": null, "e": 26769, "s": 26671, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26801, "s": 26769, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26852, "s": 26801, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26882, "s": 26852, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26901, "s": 26882, "text": "Interfaces in Java" }, { "code": null, "e": 26932, "s": 26901, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26950, "s": 26932, "text": "ArrayList in Java" }, { "code": null, "e": 26982, "s": 26950, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26997, "s": 26982, "text": "Stream In Java" }, { "code": null, "e": 27017, "s": 26997, "text": "Stack Class in Java" } ]
Python List Methods. A summary of the list methods Python... | by Robert Alterman | Towards Data Science
In Python, a list is a collection of pieces of data. A list is surrounded by square brackets [ ] with each item separated by a comma ( , ), and can contain anywhere from zero to infinity items (or however many your computer will allow). Strings, numbers, booleans, even other lists can be items in a list. Lists are ordered and mutable (changeable), meaning each item is assigned to a specific index and can be sorted, and has the ability to be altered. Once you have a list, you are able to manipulate that list using what’s known as a ‘method.’ Like string methods, to use a list method, you simply write the list followed by .[method](). For example, to run the append() method on the list [‘pepperoni’, ‘sausage’, ‘mushroom’], you would just write [‘pepperoni’, ‘sausage’, ‘mushroom’].append(‘onion’); if that list were set to a variable, you would do that variable.append(‘onion’). As you see with the append() example, some methods accept what are known as ‘arguments,’ which go in the parenthesis and further define what the method will do. The Python language has a lot of built-in methods, like append(), that allow you to easily alter lists. The append() method allows you to add another item to the end of your list. The method takes one required argument, which is the item you wish to add to your list. Syntax: list.append(item)toppings = ['pepperoni', 'sausage', 'mushroom']toppings.append('onion') --> ['pepperoni', 'sausage', 'mushroom', 'onion'] The extend() method is similar to append() in that it allows you to add onto your list; however, the extend() method allows you to add all of the items from another iterable (list, tuple, set, etc.) to the end of your list as separate items instead of one item. The method takes one required argument, the iterable. Syntax: list.extend(iterable)toppings = ['pepperoni', 'sausage', 'mushroom']more_toppings = ['onion', 'bacon']toppings.extend(more_toppings)--> ['pepperoni', 'sausage', 'mushroom', 'onion', 'bacon']To contrast...toppings.append(more_toppings)--> ['pepperoni', 'sausage', 'mushroom', ['onion', 'bacon']] As you can see above, when the extend() method is used with an iterable, each item in the iterable is added to the list as separate items no longer bounded. On the contrary, when the append() method is used with an iterable as the argument, the entire iterable is added to the list as one item. It’s always important to pay close attention to the commas and brackets present in a list. The pop() method allows you to remove an element from your list at a specified index value. The method can take one optional argument, the integer value of the index you wish to remove — by default, pop() will remove the last item in the list, as the default value is -1. Syntax: list.pop(index)toppings = ['pepperoni', 'sausage', 'mushroom']toppings.pop(1)--> ['pepperoni', 'mushroom']toppings.pop()--> ['pepperoni', 'sausage']If you wanted to retrieve the removed item...extra = toppings.pop(1)extra --> 'sausage' Like the pop() method, the remove() method allows you to remove an item from your list. The remove() method, though, removes the first occurrence of a specified value in a list. The method takes one required argument, the item you wish to remove. Syntax: list.remove(item)toppings = ['pepperoni', 'sausage', 'mushroom']toppings.remove('sausage')--> ['pepperoni', 'mushroom'] For both pop() and remove(), if the argument is out of range or does not exist in the list, respectively, you will get an error. The sort() method sorts a list by certain criteria. The method can take two optional arguments. The first argument is setting either reverse=True or reverse=False. By default, this argument is set to reverse=False, which will result in alphabetical order if the list consists of only strings, or ascending order if the list consists of only numbers. The second argument allows you to set a key= to a function that you can use to specify how exactly you want your list sorted if it’s more complex than the default ordering that the sort() method does. This could be a built-in Python function, a function you defined elsewhere in your program, or an in-line lambda function that you write. Syntax: list.sort(reverse=True|False, key=function)toppings = ['pepperoni', 'sausage', 'mushroom']toppings.sort()--> ['mushroom', 'pepperoni', 'sausage']toppings.sort(reverse=True)--> ['sausage', 'pepperoni', 'mushroom']toppings.sort(reverse=True, key=lambda x: len(x))--> ['pepperoni', 'mushroom', 'sausage']* Sorted in reverse order by length of the topping nameprices = [1.50, 2.00, 0.50]prices.sort(reverse=False)--> [0.50, 1.50, 2.00]prices.sort(reverse=True)--> [2.00, 1.50, 0.50]pies = [['bacon', 'ranch'], ['sausage', 'peppers']]pies.sort(reverse=True)--> [['sausage', 'peppers'], ['bacon', 'ranch']]* Sorts iterators by their first value The reverse() method simply reverses the order of the items in the list. The method takes no arguments. Syntax: list.reverse()toppings = ['pepperoni', 'sausage', 'mushroom']toppings.reverse()--> ['mushroom', 'sausage', 'pepperoni']prices = [1.50, 2.00, 0.50]prices.reverse()--> [0.50, 2.00, 1.50] The count() method returns the number of occurrences of a specified item in a list. The method takes one required argument, which is the item you wish to find the count of. This method can be useful if you wish to find out what items appear more than once in a list. Syntax: list.count(item)toppings = ['pepperoni', 'sausage', 'mushroom', 'sausage']toppings.count('sausage')--> 2toppings.count('pepperoni')--> 1toppings.count('bacon')--> 0 The index() method returns the index of the first occurrence of the specified item. The method takes one required argument, which is the item whose index you wish to find. If the item does not exist in the list, you will get an error. Syntax: list.index(item)toppings = ['pepperoni', 'sausage', 'mushroom', 'sausage']toppings.index('mushroom')--> 2toppings.index('pepperoni')--> 0 The insert() method inserts a specified item into a list at a specified index. The method takes two required arguments — the integer index you wish to insert the value at and the item you’d like to insert. Syntax: list.insert(index, index)toppings = ['pepperoni', 'sausage', 'mushroom']toppings.insert(1, 'onion')--> ['pepperoni', 'onion', 'sausage', 'mushroom'] The copy() method simply returns a copy of your list. The method takes no arguments. Syntax: list.copy()toppings = ['pepperoni', 'sausage', 'mushroom']toppings2 = toppings.copy()toppings2 --> ['pepperoni', 'sausage', 'mushroom'] The clear() method simply removes all items from a list, leaving an empty list. The method takes no arguments. Syntax: list.clear()toppings = ['pepperoni', 'sausage', 'mushroom']toppings.clear()--> [] And that’s that. With these aforementioned methods, you should be set to perform the operations you will need on Python lists. For more information and examples, make sure to check out the w3schools list. Happy coding and be sure to check out my blog on Python string methods below!
[ { "code": null, "e": 1324, "s": 172, "text": "In Python, a list is a collection of pieces of data. A list is surrounded by square brackets [ ] with each item separated by a comma ( , ), and can contain anywhere from zero to infinity items (or however many your computer will allow). Strings, numbers, booleans, even other lists can be items in a list. Lists are ordered and mutable (changeable), meaning each item is assigned to a specific index and can be sorted, and has the ability to be altered. Once you have a list, you are able to manipulate that list using what’s known as a ‘method.’ Like string methods, to use a list method, you simply write the list followed by .[method](). For example, to run the append() method on the list [‘pepperoni’, ‘sausage’, ‘mushroom’], you would just write [‘pepperoni’, ‘sausage’, ‘mushroom’].append(‘onion’); if that list were set to a variable, you would do that variable.append(‘onion’). As you see with the append() example, some methods accept what are known as ‘arguments,’ which go in the parenthesis and further define what the method will do. The Python language has a lot of built-in methods, like append(), that allow you to easily alter lists." }, { "code": null, "e": 1488, "s": 1324, "text": "The append() method allows you to add another item to the end of your list. The method takes one required argument, which is the item you wish to add to your list." }, { "code": null, "e": 1635, "s": 1488, "text": "Syntax: list.append(item)toppings = ['pepperoni', 'sausage', 'mushroom']toppings.append('onion') --> ['pepperoni', 'sausage', 'mushroom', 'onion']" }, { "code": null, "e": 1951, "s": 1635, "text": "The extend() method is similar to append() in that it allows you to add onto your list; however, the extend() method allows you to add all of the items from another iterable (list, tuple, set, etc.) to the end of your list as separate items instead of one item. The method takes one required argument, the iterable." }, { "code": null, "e": 2254, "s": 1951, "text": "Syntax: list.extend(iterable)toppings = ['pepperoni', 'sausage', 'mushroom']more_toppings = ['onion', 'bacon']toppings.extend(more_toppings)--> ['pepperoni', 'sausage', 'mushroom', 'onion', 'bacon']To contrast...toppings.append(more_toppings)--> ['pepperoni', 'sausage', 'mushroom', ['onion', 'bacon']]" }, { "code": null, "e": 2640, "s": 2254, "text": "As you can see above, when the extend() method is used with an iterable, each item in the iterable is added to the list as separate items no longer bounded. On the contrary, when the append() method is used with an iterable as the argument, the entire iterable is added to the list as one item. It’s always important to pay close attention to the commas and brackets present in a list." }, { "code": null, "e": 2912, "s": 2640, "text": "The pop() method allows you to remove an element from your list at a specified index value. The method can take one optional argument, the integer value of the index you wish to remove — by default, pop() will remove the last item in the list, as the default value is -1." }, { "code": null, "e": 3156, "s": 2912, "text": "Syntax: list.pop(index)toppings = ['pepperoni', 'sausage', 'mushroom']toppings.pop(1)--> ['pepperoni', 'mushroom']toppings.pop()--> ['pepperoni', 'sausage']If you wanted to retrieve the removed item...extra = toppings.pop(1)extra --> 'sausage'" }, { "code": null, "e": 3403, "s": 3156, "text": "Like the pop() method, the remove() method allows you to remove an item from your list. The remove() method, though, removes the first occurrence of a specified value in a list. The method takes one required argument, the item you wish to remove." }, { "code": null, "e": 3531, "s": 3403, "text": "Syntax: list.remove(item)toppings = ['pepperoni', 'sausage', 'mushroom']toppings.remove('sausage')--> ['pepperoni', 'mushroom']" }, { "code": null, "e": 3660, "s": 3531, "text": "For both pop() and remove(), if the argument is out of range or does not exist in the list, respectively, you will get an error." }, { "code": null, "e": 4349, "s": 3660, "text": "The sort() method sorts a list by certain criteria. The method can take two optional arguments. The first argument is setting either reverse=True or reverse=False. By default, this argument is set to reverse=False, which will result in alphabetical order if the list consists of only strings, or ascending order if the list consists of only numbers. The second argument allows you to set a key= to a function that you can use to specify how exactly you want your list sorted if it’s more complex than the default ordering that the sort() method does. This could be a built-in Python function, a function you defined elsewhere in your program, or an in-line lambda function that you write." }, { "code": null, "e": 4996, "s": 4349, "text": "Syntax: list.sort(reverse=True|False, key=function)toppings = ['pepperoni', 'sausage', 'mushroom']toppings.sort()--> ['mushroom', 'pepperoni', 'sausage']toppings.sort(reverse=True)--> ['sausage', 'pepperoni', 'mushroom']toppings.sort(reverse=True, key=lambda x: len(x))--> ['pepperoni', 'mushroom', 'sausage']* Sorted in reverse order by length of the topping nameprices = [1.50, 2.00, 0.50]prices.sort(reverse=False)--> [0.50, 1.50, 2.00]prices.sort(reverse=True)--> [2.00, 1.50, 0.50]pies = [['bacon', 'ranch'], ['sausage', 'peppers']]pies.sort(reverse=True)--> [['sausage', 'peppers'], ['bacon', 'ranch']]* Sorts iterators by their first value" }, { "code": null, "e": 5100, "s": 4996, "text": "The reverse() method simply reverses the order of the items in the list. The method takes no arguments." }, { "code": null, "e": 5293, "s": 5100, "text": "Syntax: list.reverse()toppings = ['pepperoni', 'sausage', 'mushroom']toppings.reverse()--> ['mushroom', 'sausage', 'pepperoni']prices = [1.50, 2.00, 0.50]prices.reverse()--> [0.50, 2.00, 1.50]" }, { "code": null, "e": 5560, "s": 5293, "text": "The count() method returns the number of occurrences of a specified item in a list. The method takes one required argument, which is the item you wish to find the count of. This method can be useful if you wish to find out what items appear more than once in a list." }, { "code": null, "e": 5733, "s": 5560, "text": "Syntax: list.count(item)toppings = ['pepperoni', 'sausage', 'mushroom', 'sausage']toppings.count('sausage')--> 2toppings.count('pepperoni')--> 1toppings.count('bacon')--> 0" }, { "code": null, "e": 5968, "s": 5733, "text": "The index() method returns the index of the first occurrence of the specified item. The method takes one required argument, which is the item whose index you wish to find. If the item does not exist in the list, you will get an error." }, { "code": null, "e": 6114, "s": 5968, "text": "Syntax: list.index(item)toppings = ['pepperoni', 'sausage', 'mushroom', 'sausage']toppings.index('mushroom')--> 2toppings.index('pepperoni')--> 0" }, { "code": null, "e": 6320, "s": 6114, "text": "The insert() method inserts a specified item into a list at a specified index. The method takes two required arguments — the integer index you wish to insert the value at and the item you’d like to insert." }, { "code": null, "e": 6477, "s": 6320, "text": "Syntax: list.insert(index, index)toppings = ['pepperoni', 'sausage', 'mushroom']toppings.insert(1, 'onion')--> ['pepperoni', 'onion', 'sausage', 'mushroom']" }, { "code": null, "e": 6562, "s": 6477, "text": "The copy() method simply returns a copy of your list. The method takes no arguments." }, { "code": null, "e": 6706, "s": 6562, "text": "Syntax: list.copy()toppings = ['pepperoni', 'sausage', 'mushroom']toppings2 = toppings.copy()toppings2 --> ['pepperoni', 'sausage', 'mushroom']" }, { "code": null, "e": 6817, "s": 6706, "text": "The clear() method simply removes all items from a list, leaving an empty list. The method takes no arguments." }, { "code": null, "e": 6907, "s": 6817, "text": "Syntax: list.clear()toppings = ['pepperoni', 'sausage', 'mushroom']toppings.clear()--> []" }, { "code": null, "e": 7112, "s": 6907, "text": "And that’s that. With these aforementioned methods, you should be set to perform the operations you will need on Python lists. For more information and examples, make sure to check out the w3schools list." } ]
What You Should Know About Unsigned, Signed Integers and Casting in Rust | by Shinichi Okada | Jul, 2020 | Towards Data Science | Towards Data Science
[Updated 2021–02–18. Code changed to Gist and added links] Table of ContentsIntroduction🦀 Unsigned Integer Types🦀 Signed Integer Types🦀 Signed, Ones’ Complement and Two’s Complement🦀 Sign-and-Magnitude🦀 Ones’ Complement🦀 Two’s Complement🦀 4-bit Signed Binary Number Comparison🦀 Rust signed two’s complement integer types🦀 Casting in Rust🦀 Casting to an Unsigned Type🦀 Casting to a Signed Type🦀 Bitwise Negation🦀 Adding a Negative NumberConclusion Rust has two data type subsets, scalar, and compound. The scalar types are integers, floating numbers, Booleans, and characters. The compound types are arrays and tuples. In this article we are going to see why the following code fails: fn main() { let a: i16 = 2; let b: u16 = 4; println!("{}", a+b);} And why casting 128 to i8 is -128. Output: 128 as a i8 is : -128 To understand better about the casting, we need to review Signed, Ones’ Complement, and Two’s Complement. We will also cover adding a negative number, bitwise negation, and converting a binary to an unsigned and signed decimal. Let’s start with Rust integer types first. towardsdatascience.com Unsigned integer types in Rust start with u and it has 8, 16, 32, 64, and 128-bit. The minimum and maximum values are from 0 to 2n-1. For example u8 has 0 to 28-1, which is 255. The following table shows all the details for unsigned integers. Output: u8 has the max value of 255.u16 has the max value of 65535.u32 has the max value of 4294967295.u64 has the max value of 18446744073709551615.u128 has the max value of 340282366920938463463374607431768211455. If you try to assign a negative number to an unsigned type, it will fail. fn main() { let u:u32 = -1; println!("{} in binary is {:b}", u, u);}error[E0600]: cannot apply unary operator `-` to type `u32` --> main.rs" data-line="2" data-column="17">main.rs:2:17 |2 | let u:u32 = -1; | ^^ cannot apply unary operator `-` | = note: unsigned values cannot be negated - is one of Rust's unary operators and it is the negation operator for signed integer types and floating-point types. The default integer type in Rust is i32. Signed integer types in Rust start with i and it has 8, 16, 32, 64, and 128-bit. The minimum and maximum values are from -(2n−1) to 2n−1-1. The -1 in the n-1 is the sign bit (positive or negative), which we cover in the next section. For example i8 has -(27) to 27-1, which is -128 to 127. The following table shows all the details for signed integers. Output: i8 has the min value of -128.i8 has the max value of 127.i16 has the min value of -32768.i16 has the max value of 32767.i32 has the min value of -2147483648.i32 has the max value of 2147483647.i64 has the min value of -9223372036854775808.i64 has the max value of 9223372036854775807.i128 has the min value of -170141183460469231731687303715884105728.i128 has the max value of 170141183460469231731687303715884105727. In computing, signed number representations are required to encode negative numbers in binary number systems. Let’s examine sign-and-magnitude, ones’ complement, and two’s complement. Sign-and-Magnitude is also called Signed Magnitude. The first bit (called the most significant bit or MSB) tells if it is positive by 0 or a negative by 1. The rest is called magnitude bits. As I mentioned it before that signed integer types have the min and the max from -(2n−1) to 2n−1-1 where n stands for the number of bits. Since we use the first bit for the positive and negative signs we have n-1 in the 2n−1. For 4-bit the min and max are from -(23) to 23–1, which is -8 to +7. As you see in the diagram above, the positive and the negative have the same digits except for the sign bit. The problem of the signed magnitude is that there are two zeros, 0000 and 1000. The first bit (MSB) is the same as the signed magnitude. It tells a positive by 0 or negative by 1. The rest of the bits will take the compliment, which means if it is 1 the complement is 0 and if it is 0, then the complement is 1. The signed ones’ complement has the same problem as the signed magnitude. There are two zeros, 0000 and 1111. In the binary numbering system, the radix (base) is two. That’s why the radix complement is called two’s complement and the diminished radix complement is called ones’ complement. Two’s complement can avoid multiple representations of 0, and it avoids keeping track of carrying bits in case of overflow. We again use the first bit (MSB) for the + and - signs. We take the complement of the number and we add 1 to get the opposite number. This works from positive to negative and vice versa. For zero that is 0000 in the binary, the complement is 1111 and adding 1 results in 1 0000. The 1 is called an "overflow" bit. Overflow occurs when the sum of the most significant (left-most) column produces a carry forward. This overflow or carry bit can be ignored. The following table shows the comparison of three signed number representations. Now let’s compare negative numbers of signed two’s complement from the above table (from -1 to -7) to Rust’s signed integers. Output: -1 in binary is 11111111111111111111111111111111-2 in binary is 11111111111111111111111111111110-3 in binary is 11111111111111111111111111111101-4 in binary is 11111111111111111111111111111100-5 in binary is 11111111111111111111111111111011-6 in binary is 11111111111111111111111111111010-7 in binary is 11111111111111111111111111111001 They are exactly the same except Rust uses the default 32-bit. Rust’s signed integer types are called the signed two’s complement integer types. Casting means changing the data type of a piece of data from one type to another. as keyword turns primitive types into other primitive types. We can use as keyword to solve the code in the introduction. When you cast from a small length to a larger length, for example from 8-bit to 16-bit, there won’t be any problem but when you cast down, you may have a problem. Method 1 When you cast to an unsigned type, T, T::MAX + 1 is added or subtracted until the value fits into the new type. Example 1: Casting 1000 from the default, i32 to u8 u8 has the max number of 255, so we subtract 255+1, which is 256 from 1000 until it gets less than 255. 1000 - 256 = 744 1000 - 256 - 256 = 488 1000 - 256 - 256 - 256 = 232 Output: 1000 as a u8 is : 232 Method 2 100010 in decimal is 11 1110 10002 in binary. We can take the last 8 bits, which is 1110 1000 and it is 232 in decimal. An interesting number is 25610. Output: 256 as a u8 is : 0 25610 is 1000000002 in binary. If you take the last 8 bits it is 00000000. Method 1 This is the same as above but you need to be aware that the min/max number of the data type. i8's min and max numbers are -128 and 127. So the number needs to be between them. Casting 128 to i8 : 128-256=-128 Casting 1000 to i8: 1000 - 256 = 7441000 - 256 - 256 = 4881000 - 256 - 256 - 256 = 2321000 - 256 - 256 - 256 - 256 = -24 Output: 128 as a i8 is : -1281000 as a i8 is : -24232 as a i8 is : -24257 as a i8 is : 1130 as a i8 is : -126514 as a i8 is : 2 Method 2 100010 in decimal is 11 1110 10002 in binary. The MSB within 8-bit is 1, so it is a negative number. Then use 2’s complement. The complement is 000101112 and we add 12 becomes 000110002. Finally, it is -2410. When the MSB within 8-bit is 0, it is a positive number. Then take the first 8 least significant bits (LSB). Rust uses ! for the Bitwise Negation (Bitwise NOT). This produces different results depends on the type. Output: u is 2u in binary is 10i is 2i in binary is 10Bitwise negation !u is 4294967293Bitwise negation !i is -3 As you see !2 with the unsigned type returns 4294967293 and with the signed type returns -3. The bitwise negation on a signed integer returns the two’s complement as we saw previously in Rust signed two’s complement integer types. The subtraction is the same as adding a negative number. 5 - 2 = 5 + (-2) = 3 This applies to binary as well. 0101 - 0010 = 0101 + (-0010) // (1)= 0101 + 1110 // (2)= 0011 // this is 3 in decimal number. We find -0010 by finding the two’s complement of 0010 that is 1110. We covered Rust integer types, three types of signed binary numbers, casting to an unsigned type and a signed type. I hope you have a better idea of what’s going on when you are dealing with Rust integers and casting. Please stay tuned for the next post. Get full access to every story on Medium by becoming a member.
[ { "code": null, "e": 231, "s": 172, "text": "[Updated 2021–02–18. Code changed to Gist and added links]" }, { "code": null, "e": 619, "s": 231, "text": "Table of ContentsIntroduction🦀 Unsigned Integer Types🦀 Signed Integer Types🦀 Signed, Ones’ Complement and Two’s Complement🦀 Sign-and-Magnitude🦀 Ones’ Complement🦀 Two’s Complement🦀 4-bit Signed Binary Number Comparison🦀 Rust signed two’s complement integer types🦀 Casting in Rust🦀 Casting to an Unsigned Type🦀 Casting to a Signed Type🦀 Bitwise Negation🦀 Adding a Negative NumberConclusion" }, { "code": null, "e": 790, "s": 619, "text": "Rust has two data type subsets, scalar, and compound. The scalar types are integers, floating numbers, Booleans, and characters. The compound types are arrays and tuples." }, { "code": null, "e": 856, "s": 790, "text": "In this article we are going to see why the following code fails:" }, { "code": null, "e": 931, "s": 856, "text": "fn main() { let a: i16 = 2; let b: u16 = 4; println!(\"{}\", a+b);}" }, { "code": null, "e": 966, "s": 931, "text": "And why casting 128 to i8 is -128." }, { "code": null, "e": 974, "s": 966, "text": "Output:" }, { "code": null, "e": 996, "s": 974, "text": "128 as a i8 is : -128" }, { "code": null, "e": 1102, "s": 996, "text": "To understand better about the casting, we need to review Signed, Ones’ Complement, and Two’s Complement." }, { "code": null, "e": 1224, "s": 1102, "text": "We will also cover adding a negative number, bitwise negation, and converting a binary to an unsigned and signed decimal." }, { "code": null, "e": 1267, "s": 1224, "text": "Let’s start with Rust integer types first." }, { "code": null, "e": 1290, "s": 1267, "text": "towardsdatascience.com" }, { "code": null, "e": 1424, "s": 1290, "text": "Unsigned integer types in Rust start with u and it has 8, 16, 32, 64, and 128-bit. The minimum and maximum values are from 0 to 2n-1." }, { "code": null, "e": 1533, "s": 1424, "text": "For example u8 has 0 to 28-1, which is 255. The following table shows all the details for unsigned integers." }, { "code": null, "e": 1541, "s": 1533, "text": "Output:" }, { "code": null, "e": 1749, "s": 1541, "text": "u8 has the max value of 255.u16 has the max value of 65535.u32 has the max value of 4294967295.u64 has the max value of 18446744073709551615.u128 has the max value of 340282366920938463463374607431768211455." }, { "code": null, "e": 1823, "s": 1749, "text": "If you try to assign a negative number to an unsigned type, it will fail." }, { "code": null, "e": 2140, "s": 1823, "text": "fn main() { let u:u32 = -1; println!(\"{} in binary is {:b}\", u, u);}error[E0600]: cannot apply unary operator `-` to type `u32` --> main.rs\" data-line=\"2\" data-column=\"17\">main.rs:2:17 |2 | let u:u32 = -1; | ^^ cannot apply unary operator `-` | = note: unsigned values cannot be negated" }, { "code": null, "e": 2258, "s": 2140, "text": "- is one of Rust's unary operators and it is the negation operator for signed integer types and floating-point types." }, { "code": null, "e": 2533, "s": 2258, "text": "The default integer type in Rust is i32. Signed integer types in Rust start with i and it has 8, 16, 32, 64, and 128-bit. The minimum and maximum values are from -(2n−1) to 2n−1-1. The -1 in the n-1 is the sign bit (positive or negative), which we cover in the next section." }, { "code": null, "e": 2652, "s": 2533, "text": "For example i8 has -(27) to 27-1, which is -128 to 127. The following table shows all the details for signed integers." }, { "code": null, "e": 2660, "s": 2652, "text": "Output:" }, { "code": null, "e": 3078, "s": 2660, "text": "i8 has the min value of -128.i8 has the max value of 127.i16 has the min value of -32768.i16 has the max value of 32767.i32 has the min value of -2147483648.i32 has the max value of 2147483647.i64 has the min value of -9223372036854775808.i64 has the max value of 9223372036854775807.i128 has the min value of -170141183460469231731687303715884105728.i128 has the max value of 170141183460469231731687303715884105727." }, { "code": null, "e": 3262, "s": 3078, "text": "In computing, signed number representations are required to encode negative numbers in binary number systems. Let’s examine sign-and-magnitude, ones’ complement, and two’s complement." }, { "code": null, "e": 3453, "s": 3262, "text": "Sign-and-Magnitude is also called Signed Magnitude. The first bit (called the most significant bit or MSB) tells if it is positive by 0 or a negative by 1. The rest is called magnitude bits." }, { "code": null, "e": 3679, "s": 3453, "text": "As I mentioned it before that signed integer types have the min and the max from -(2n−1) to 2n−1-1 where n stands for the number of bits. Since we use the first bit for the positive and negative signs we have n-1 in the 2n−1." }, { "code": null, "e": 3748, "s": 3679, "text": "For 4-bit the min and max are from -(23) to 23–1, which is -8 to +7." }, { "code": null, "e": 3857, "s": 3748, "text": "As you see in the diagram above, the positive and the negative have the same digits except for the sign bit." }, { "code": null, "e": 3937, "s": 3857, "text": "The problem of the signed magnitude is that there are two zeros, 0000 and 1000." }, { "code": null, "e": 4169, "s": 3937, "text": "The first bit (MSB) is the same as the signed magnitude. It tells a positive by 0 or negative by 1. The rest of the bits will take the compliment, which means if it is 1 the complement is 0 and if it is 0, then the complement is 1." }, { "code": null, "e": 4279, "s": 4169, "text": "The signed ones’ complement has the same problem as the signed magnitude. There are two zeros, 0000 and 1111." }, { "code": null, "e": 4459, "s": 4279, "text": "In the binary numbering system, the radix (base) is two. That’s why the radix complement is called two’s complement and the diminished radix complement is called ones’ complement." }, { "code": null, "e": 4583, "s": 4459, "text": "Two’s complement can avoid multiple representations of 0, and it avoids keeping track of carrying bits in case of overflow." }, { "code": null, "e": 4770, "s": 4583, "text": "We again use the first bit (MSB) for the + and - signs. We take the complement of the number and we add 1 to get the opposite number. This works from positive to negative and vice versa." }, { "code": null, "e": 5038, "s": 4770, "text": "For zero that is 0000 in the binary, the complement is 1111 and adding 1 results in 1 0000. The 1 is called an \"overflow\" bit. Overflow occurs when the sum of the most significant (left-most) column produces a carry forward. This overflow or carry bit can be ignored." }, { "code": null, "e": 5119, "s": 5038, "text": "The following table shows the comparison of three signed number representations." }, { "code": null, "e": 5245, "s": 5119, "text": "Now let’s compare negative numbers of signed two’s complement from the above table (from -1 to -7) to Rust’s signed integers." }, { "code": null, "e": 5253, "s": 5245, "text": "Output:" }, { "code": null, "e": 5590, "s": 5253, "text": "-1 in binary is 11111111111111111111111111111111-2 in binary is 11111111111111111111111111111110-3 in binary is 11111111111111111111111111111101-4 in binary is 11111111111111111111111111111100-5 in binary is 11111111111111111111111111111011-6 in binary is 11111111111111111111111111111010-7 in binary is 11111111111111111111111111111001" }, { "code": null, "e": 5735, "s": 5590, "text": "They are exactly the same except Rust uses the default 32-bit. Rust’s signed integer types are called the signed two’s complement integer types." }, { "code": null, "e": 5817, "s": 5735, "text": "Casting means changing the data type of a piece of data from one type to another." }, { "code": null, "e": 5939, "s": 5817, "text": "as keyword turns primitive types into other primitive types. We can use as keyword to solve the code in the introduction." }, { "code": null, "e": 6102, "s": 5939, "text": "When you cast from a small length to a larger length, for example from 8-bit to 16-bit, there won’t be any problem but when you cast down, you may have a problem." }, { "code": null, "e": 6111, "s": 6102, "text": "Method 1" }, { "code": null, "e": 6223, "s": 6111, "text": "When you cast to an unsigned type, T, T::MAX + 1 is added or subtracted until the value fits into the new type." }, { "code": null, "e": 6275, "s": 6223, "text": "Example 1: Casting 1000 from the default, i32 to u8" }, { "code": null, "e": 6379, "s": 6275, "text": "u8 has the max number of 255, so we subtract 255+1, which is 256 from 1000 until it gets less than 255." }, { "code": null, "e": 6466, "s": 6379, "text": "1000 - 256 = 744 1000 - 256 - 256 = 488 1000 - 256 - 256 - 256 = 232" }, { "code": null, "e": 6474, "s": 6466, "text": "Output:" }, { "code": null, "e": 6496, "s": 6474, "text": "1000 as a u8 is : 232" }, { "code": null, "e": 6505, "s": 6496, "text": "Method 2" }, { "code": null, "e": 6625, "s": 6505, "text": "100010 in decimal is 11 1110 10002 in binary. We can take the last 8 bits, which is 1110 1000 and it is 232 in decimal." }, { "code": null, "e": 6657, "s": 6625, "text": "An interesting number is 25610." }, { "code": null, "e": 6665, "s": 6657, "text": "Output:" }, { "code": null, "e": 6684, "s": 6665, "text": "256 as a u8 is : 0" }, { "code": null, "e": 6759, "s": 6684, "text": "25610 is 1000000002 in binary. If you take the last 8 bits it is 00000000." }, { "code": null, "e": 6768, "s": 6759, "text": "Method 1" }, { "code": null, "e": 6861, "s": 6768, "text": "This is the same as above but you need to be aware that the min/max number of the data type." }, { "code": null, "e": 6944, "s": 6861, "text": "i8's min and max numbers are -128 and 127. So the number needs to be between them." }, { "code": null, "e": 6964, "s": 6944, "text": "Casting 128 to i8 :" }, { "code": null, "e": 6977, "s": 6964, "text": "128-256=-128" }, { "code": null, "e": 6997, "s": 6977, "text": "Casting 1000 to i8:" }, { "code": null, "e": 7098, "s": 6997, "text": "1000 - 256 = 7441000 - 256 - 256 = 4881000 - 256 - 256 - 256 = 2321000 - 256 - 256 - 256 - 256 = -24" }, { "code": null, "e": 7106, "s": 7098, "text": "Output:" }, { "code": null, "e": 7226, "s": 7106, "text": "128 as a i8 is : -1281000 as a i8 is : -24232 as a i8 is : -24257 as a i8 is : 1130 as a i8 is : -126514 as a i8 is : 2" }, { "code": null, "e": 7235, "s": 7226, "text": "Method 2" }, { "code": null, "e": 7444, "s": 7235, "text": "100010 in decimal is 11 1110 10002 in binary. The MSB within 8-bit is 1, so it is a negative number. Then use 2’s complement. The complement is 000101112 and we add 12 becomes 000110002. Finally, it is -2410." }, { "code": null, "e": 7553, "s": 7444, "text": "When the MSB within 8-bit is 0, it is a positive number. Then take the first 8 least significant bits (LSB)." }, { "code": null, "e": 7658, "s": 7553, "text": "Rust uses ! for the Bitwise Negation (Bitwise NOT). This produces different results depends on the type." }, { "code": null, "e": 7666, "s": 7658, "text": "Output:" }, { "code": null, "e": 7771, "s": 7666, "text": "u is 2u in binary is 10i is 2i in binary is 10Bitwise negation !u is 4294967293Bitwise negation !i is -3" }, { "code": null, "e": 7864, "s": 7771, "text": "As you see !2 with the unsigned type returns 4294967293 and with the signed type returns -3." }, { "code": null, "e": 8002, "s": 7864, "text": "The bitwise negation on a signed integer returns the two’s complement as we saw previously in Rust signed two’s complement integer types." }, { "code": null, "e": 8059, "s": 8002, "text": "The subtraction is the same as adding a negative number." }, { "code": null, "e": 8080, "s": 8059, "text": "5 - 2 = 5 + (-2) = 3" }, { "code": null, "e": 8112, "s": 8080, "text": "This applies to binary as well." }, { "code": null, "e": 8219, "s": 8112, "text": "0101 - 0010 = 0101 + (-0010) // (1)= 0101 + 1110 // (2)= 0011 // this is 3 in decimal number." }, { "code": null, "e": 8287, "s": 8219, "text": "We find -0010 by finding the two’s complement of 0010 that is 1110." }, { "code": null, "e": 8505, "s": 8287, "text": "We covered Rust integer types, three types of signed binary numbers, casting to an unsigned type and a signed type. I hope you have a better idea of what’s going on when you are dealing with Rust integers and casting." }, { "code": null, "e": 8542, "s": 8505, "text": "Please stay tuned for the next post." } ]
DocumentDB - Data Modeling
While schema-free databases, like DocumentDB, make it super easy to embrace changes to your data model, you should still spend some time thinking about your data. You have a lot of options. Naturally, you can just work JSON object graphs or even raw strings of JSON text, but you can also use dynamic objects that lets you bind to properties at runtime without defining a class at compile time. You have a lot of options. Naturally, you can just work JSON object graphs or even raw strings of JSON text, but you can also use dynamic objects that lets you bind to properties at runtime without defining a class at compile time. You can also work with real C# objects, or Entities as they are called, which might be your business domain classes. You can also work with real C# objects, or Entities as they are called, which might be your business domain classes. Let’s take a look at the document's hierarchal structure. It has a few top-level properties like the required id, as well as lastName and isRegistered, but it also has nested properties. { "id": "AndersenFamily", "lastName": "Andersen", "parents": [ { "firstName": "Thomas", "relationship": "father" }, { "firstName": "Mary Kay", "relationship": "mother" } ], "children": [ { "firstName": "Henriette Thaulow", "gender": "female", "grade": 5, "pets": [ { "givenName": "Fluffy", "type": "Rabbit" } ] } ], "location": { "state": "WA", "county": "King", "city": "Seattle"}, "isRegistered": true } For instance, the parents property is supplied as a JSON array as denoted by the square brackets. For instance, the parents property is supplied as a JSON array as denoted by the square brackets. We also have another array for children, even though there's only one child in the array in this example. So this is how you model the equivalent of one-to-many relationships within a document. We also have another array for children, even though there's only one child in the array in this example. So this is how you model the equivalent of one-to-many relationships within a document. You simply use arrays where each element in the array could be a simple value or another complex object, even another array. You simply use arrays where each element in the array could be a simple value or another complex object, even another array. So one family can have multiple parents and multiple children and if you look at the child objects, they have a pet’s property that is itself a nested array for a oneto-many relationship between children and pets. So one family can have multiple parents and multiple children and if you look at the child objects, they have a pet’s property that is itself a nested array for a oneto-many relationship between children and pets. For the location property, we're combining three related properties, the state, county, and city into an object. For the location property, we're combining three related properties, the state, county, and city into an object. Embedding an object this way rather than embedding an array of objects is similar to having a one-to-one relationship between two rows in separate tables in a relational database. Embedding an object this way rather than embedding an array of objects is similar to having a one-to-one relationship between two rows in separate tables in a relational database. When you start modeling data in a document store, such as DocumentDB, try to treat your entities as self-contained documents represented in JSON. When working with relational databases, we always normalize data. Normalizing your data typically involves taking an entity, such as a customer, and breaking it down into discreet pieces of data, like contact details and addresses. Normalizing your data typically involves taking an entity, such as a customer, and breaking it down into discreet pieces of data, like contact details and addresses. To read a customer, with all their contact details and addresses, you need to use JOINS to effectively aggregate your data at run time. To read a customer, with all their contact details and addresses, you need to use JOINS to effectively aggregate your data at run time. Now let's take a look at how we would model the same data as a self-contained entity in a document database. { "id": "1", "firstName": "Mark", "lastName": "Upston", "addresses": [ { "line1": "232 Main Street", "line2": "Unit 1", "city": "Brooklyn", "state": "NY", "zip": 11229 } ], "contactDetails": [ {"email": "mark.upston@xyz.com"}, {"phone": "+1 356 545-86455", "extension": 5555} ] } As you can see that we have denormalized the customer record where all the information of the customer is embedded into a single JSON document. In NoSQL we have a free schema, so you can add contact details and addresses in different format as well. In NoSQL, you can retrieve a customer record from the database in a single read operation. Similarly, updating a record is also a single write operation. Following are the steps to create documents using .Net SDK. Step 1 − Instantiate DocumentClient. Then we will query for the myfirstdb database and also query for MyCollection collection, which we store in this private variable collection so that's it's accessible throughout the class. private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id = 'myfirstdb'").AsEnumerable().First(); collection = client.CreateDocumentCollectionQuery(database.CollectionsLink, "SELECT * FROM c WHERE c.id = 'MyCollection'").AsEnumerable().First(); await CreateDocuments(client); } } Step 2 − Create some documents in CreateDocuments task. private async static Task CreateDocuments(DocumentClient client) { Console.WriteLine(); Console.WriteLine("**** Create Documents ****"); Console.WriteLine(); dynamic document1Definition = new { name = "New Customer 1", address = new { addressType = "Main Office", addressLine1 = "123 Main Street", location = new { city = "Brooklyn", stateProvinceName = "New York" }, postalCode = "11229", countryRegionName = "United States" }, }; Document document1 = await CreateDocument(client, document1Definition); Console.WriteLine("Created document {0} from dynamic object", document1.Id); Console.WriteLine(); } The first document will be generated from this dynamic object. This might look like JSON, but of course it isn't. This is C# code and we're creating a real .NET object, but there's no class definition. Instead the properties are inferred from the way the object is initialized. You can notice also that we haven't supplied an Id property for this document. Step 3 − Now let's take a look at the CreateDocument and it looks like the same pattern we saw for creating databases and collections. private async static Task<Document> CreateDocument(DocumentClient client, object documentObject) { var result = await client.CreateDocumentAsync(collection.SelfLink, documentObject); var document = result.Resource; Console.WriteLine("Created new document: {0}\r\n{1}", document.Id, document); return result; } Step 4 − This time we call CreateDocumentAsync specifying the SelfLink of the collection we want to add the document to. We get back a response with a resource property that, in this case, represents the new document with its system-generated properties. In the following CreateDocuments task, we have created three documents. In the first document, the Document object is a defined class in the SDK that inherits from resource and so it has all the common resource properties, but it also includes the dynamic properties that define the schema-free document itself. In the first document, the Document object is a defined class in the SDK that inherits from resource and so it has all the common resource properties, but it also includes the dynamic properties that define the schema-free document itself. private async static Task CreateDocuments(DocumentClient client) { Console.WriteLine(); Console.WriteLine("**** Create Documents ****"); Console.WriteLine(); dynamic document1Definition = new { name = "New Customer 1", address = new { addressType = "Main Office", addressLine1 = "123 Main Street", location = new { city = "Brooklyn", stateProvinceName = "New York" }, postalCode = "11229", countryRegionName = "United States" }, }; Document document1 = await CreateDocument(client, document1Definition); Console.WriteLine("Created document {0} from dynamic object", document1.Id); Console.WriteLine(); var document2Definition = @" { ""name"": ""New Customer 2"", ""address"": { ""addressType"": ""Main Office"", ""addressLine1"": ""123 Main Street"", ""location"": { ""city"": ""Brooklyn"", ""stateProvinceName"": ""New York"" }, ""postalCode"": ""11229"", ""countryRegionName"": ""United States"" } }"; Document document2 = await CreateDocument(client, document2Definition); Console.WriteLine("Created document {0} from JSON string", document2.Id); Console.WriteLine(); var document3Definition = new Customer { Name = "New Customer 3", Address = new Address { AddressType = "Main Office", AddressLine1 = "123 Main Street", Location = new Location { City = "Brooklyn", StateProvinceName = "New York" }, PostalCode = "11229", CountryRegionName = "United States" }, }; Document document3 = await CreateDocument(client, document3Definition); Console.WriteLine("Created document {0} from typed object", document3.Id); Console.WriteLine(); } This second document just works with a raw JSON string. Now we step into an overload for CreateDocument that uses the JavaScriptSerializer to de-serialize the string into an object, which it then passes on to the same CreateDocument method that we used to create the first document. This second document just works with a raw JSON string. Now we step into an overload for CreateDocument that uses the JavaScriptSerializer to de-serialize the string into an object, which it then passes on to the same CreateDocument method that we used to create the first document. In the third document, we have used the C# object Customer which is defined in our application. In the third document, we have used the C# object Customer which is defined in our application. Let’s take a look at this customer, it has an Id and address property where the address is a nested object with its own properties including location, which is yet another nested object. using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DocumentDBDemo { public class Customer { [JsonProperty(PropertyName = "id")] public string Id { get; set; } // Must be nullable, unless generating unique values for new customers on client [JsonProperty(PropertyName = "name")] public string Name { get; set; } [JsonProperty(PropertyName = "address")] public Address Address { get; set; } } public class Address { [JsonProperty(PropertyName = "addressType")] public string AddressType { get; set; } [JsonProperty(PropertyName = "addressLine1")] public string AddressLine1 { get; set; } [JsonProperty(PropertyName = "location")] public Location Location { get; set; } [JsonProperty(PropertyName = "postalCode")] public string PostalCode { get; set; } [JsonProperty(PropertyName = "countryRegionName")] public string CountryRegionName { get; set; } } public class Location { [JsonProperty(PropertyName = "city")] public string City { get; set; } [JsonProperty(PropertyName = "stateProvinceName")] public string StateProvinceName { get; set; } } } We also have JSON property attributes in place because we want to maintain proper conventions on both sides of the fence. So I just create my New Customer object along with its nested child objects and call into CreateDocument once more. Although our customer object does have an Id property we didn't supply a value for it and so DocumentDB generated one based on the GUID, just like it did for the previous two documents. When the above code is compiled and executed you will receive the following output. **** Create Documents **** Created new document: 575882f0-236c-4c3d-81b9-d27780206b2c { "name": "New Customer 1", "address": { "addressType": "Main Office", "addressLine1": "123 Main Street", "location": { "city": "Brooklyn", "stateProvinceName": "New York" }, "postalCode": "11229", "countryRegionName": "United States" }, "id": "575882f0-236c-4c3d-81b9-d27780206b2c", "_rid": "kV5oANVXnwDGPgAAAAAAAA==", "_ts": 1450037545, "_self": "dbs/kV5oAA==/colls/kV5oANVXnwA=/docs/kV5oANVXnwDGPgAAAAAAAA==/", "_etag": "\"00006fce-0000-0000-0000-566dd1290000\"", "_attachments": "attachments/" } Created document 575882f0-236c-4c3d-81b9-d27780206b2c from dynamic object Created new document: 8d7ad239-2148-4fab-901b-17a85d331056 { "name": "New Customer 2", "address": { "addressType": "Main Office", "addressLine1": "123 Main Street", "location": { "city": "Brooklyn", "stateProvinceName": "New York" }, "postalCode": "11229", "countryRegionName": "United States" }, "id": "8d7ad239-2148-4fab-901b-17a85d331056", "_rid": "kV5oANVXnwDHPgAAAAAAAA==", "_ts": 1450037545, "_self": "dbs/kV5oAA==/colls/kV5oANVXnwA=/docs/kV5oANVXnwDHPgAAAAAAAA==/", "_etag": "\"000070ce-0000-0000-0000-566dd1290000\"", "_attachments": "attachments/" } Created document 8d7ad239-2148-4fab-901b-17a85d331056 from JSON string Created new document: 49f399a8-80c9-4844-ac28-cd1dee689968 { "id": "49f399a8-80c9-4844-ac28-cd1dee689968", "name": "New Customer 3", "address": { "addressType": "Main Office", "addressLine1": "123 Main Street", "location": { "city": "Brooklyn", "stateProvinceName": "New York" }, "postalCode": "11229", "countryRegionName": "United States" }, "_rid": "kV5oANVXnwDIPgAAAAAAAA==", "_ts": 1450037546, "_self": "dbs/kV5oAA==/colls/kV5oANVXnwA=/docs/kV5oANVXnwDIPgAAAAAAAA==/", "_etag": "\"000071ce-0000-0000-0000-566dd12a0000\"", "_attachments": "attachments/" } Created document 49f399a8-80c9-4844-ac28-cd1dee689968 from typed object Print Add Notes Bookmark this page
[ { "code": null, "e": 2443, "s": 2280, "text": "While schema-free databases, like DocumentDB, make it super easy to embrace changes to your data model, you should still spend some time thinking about your data." }, { "code": null, "e": 2675, "s": 2443, "text": "You have a lot of options. Naturally, you can just work JSON object graphs or even raw strings of JSON text, but you can also use dynamic objects that lets you bind to properties at runtime without defining a class at compile time." }, { "code": null, "e": 2907, "s": 2675, "text": "You have a lot of options. Naturally, you can just work JSON object graphs or even raw strings of JSON text, but you can also use dynamic objects that lets you bind to properties at runtime without defining a class at compile time." }, { "code": null, "e": 3024, "s": 2907, "text": "You can also work with real C# objects, or Entities as they are called, which might be your business domain classes." }, { "code": null, "e": 3141, "s": 3024, "text": "You can also work with real C# objects, or Entities as they are called, which might be your business domain classes." }, { "code": null, "e": 3328, "s": 3141, "text": "Let’s take a look at the document's hierarchal structure. It has a few top-level properties like the required id, as well as lastName and isRegistered, but it also has nested properties." }, { "code": null, "e": 3840, "s": 3328, "text": "{ \n \"id\": \"AndersenFamily\", \n \"lastName\": \"Andersen\", \n\t\n \"parents\": [ \n { \"firstName\": \"Thomas\", \"relationship\": \"father\" }, \n { \"firstName\": \"Mary Kay\", \"relationship\": \"mother\" } \n ],\n\t\n \"children\": [ \n { \n \"firstName\": \"Henriette Thaulow\", \n \"gender\": \"female\", \n \"grade\": 5, \n \"pets\": [ { \"givenName\": \"Fluffy\", \"type\": \"Rabbit\" } ] \n } \n ], \n\t\n \"location\": { \"state\": \"WA\", \"county\": \"King\", \"city\": \"Seattle\"}, \n \"isRegistered\": true \n}" }, { "code": null, "e": 3938, "s": 3840, "text": "For instance, the parents property is supplied as a JSON array as denoted by the square brackets." }, { "code": null, "e": 4036, "s": 3938, "text": "For instance, the parents property is supplied as a JSON array as denoted by the square brackets." }, { "code": null, "e": 4230, "s": 4036, "text": "We also have another array for children, even though there's only one child in the array in this example. So this is how you model the equivalent of one-to-many relationships within a document." }, { "code": null, "e": 4424, "s": 4230, "text": "We also have another array for children, even though there's only one child in the array in this example. So this is how you model the equivalent of one-to-many relationships within a document." }, { "code": null, "e": 4549, "s": 4424, "text": "You simply use arrays where each element in the array could be a simple value or another complex object, even another array." }, { "code": null, "e": 4674, "s": 4549, "text": "You simply use arrays where each element in the array could be a simple value or another complex object, even another array." }, { "code": null, "e": 4888, "s": 4674, "text": "So one family can have multiple parents and multiple children and if you look at the child objects, they have a pet’s property that is itself a nested array for a oneto-many relationship between children and pets." }, { "code": null, "e": 5102, "s": 4888, "text": "So one family can have multiple parents and multiple children and if you look at the child objects, they have a pet’s property that is itself a nested array for a oneto-many relationship between children and pets." }, { "code": null, "e": 5215, "s": 5102, "text": "For the location property, we're combining three related properties, the state, county, and city into an object." }, { "code": null, "e": 5328, "s": 5215, "text": "For the location property, we're combining three related properties, the state, county, and city into an object." }, { "code": null, "e": 5508, "s": 5328, "text": "Embedding an object this way rather than embedding an array of objects is similar to having a one-to-one relationship between two rows in separate tables in a relational database." }, { "code": null, "e": 5688, "s": 5508, "text": "Embedding an object this way rather than embedding an array of objects is similar to having a one-to-one relationship between two rows in separate tables in a relational database." }, { "code": null, "e": 5900, "s": 5688, "text": "When you start modeling data in a document store, such as DocumentDB, try to treat your entities as self-contained documents represented in JSON. When working with relational databases, we always normalize data." }, { "code": null, "e": 6066, "s": 5900, "text": "Normalizing your data typically involves taking an entity, such as a customer, and breaking it down into discreet pieces of data, like contact details and addresses." }, { "code": null, "e": 6232, "s": 6066, "text": "Normalizing your data typically involves taking an entity, such as a customer, and breaking it down into discreet pieces of data, like contact details and addresses." }, { "code": null, "e": 6368, "s": 6232, "text": "To read a customer, with all their contact details and addresses, you need to use JOINS to effectively aggregate your data at run time." }, { "code": null, "e": 6504, "s": 6368, "text": "To read a customer, with all their contact details and addresses, you need to use JOINS to effectively aggregate your data at run time." }, { "code": null, "e": 6613, "s": 6504, "text": "Now let's take a look at how we would model the same data as a self-contained entity in a document database." }, { "code": null, "e": 7012, "s": 6613, "text": "{\n \"id\": \"1\", \n \"firstName\": \"Mark\", \n \"lastName\": \"Upston\", \n\t\n \"addresses\": [ \n { \n \"line1\": \"232 Main Street\", \n \"line2\": \"Unit 1\", \n \"city\": \"Brooklyn\", \n \"state\": \"NY\", \n \"zip\": 11229\n }\n ],\n\t\n \"contactDetails\": [ \n {\"email\": \"mark.upston@xyz.com\"}, \n {\"phone\": \"+1 356 545-86455\", \"extension\": 5555} \n ]\n} " }, { "code": null, "e": 7156, "s": 7012, "text": "As you can see that we have denormalized the customer record where all the information of the customer is embedded into a single JSON document." }, { "code": null, "e": 7416, "s": 7156, "text": "In NoSQL we have a free schema, so you can add contact details and addresses in different format as well. In NoSQL, you can retrieve a customer record from the database in a single read operation. Similarly, updating a record is also a single write operation." }, { "code": null, "e": 7476, "s": 7416, "text": "Following are the steps to create documents using .Net SDK." }, { "code": null, "e": 7702, "s": 7476, "text": "Step 1 − Instantiate DocumentClient. Then we will query for the myfirstdb database and also query for MyCollection collection, which we store in this private variable collection so that's it's accessible throughout the class." }, { "code": null, "e": 8232, "s": 7702, "text": "private static async Task CreateDocumentClient() { \n // Create a new instance of the DocumentClient\n\t\n using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { \n database = client.CreateDatabaseQuery(\"SELECT * FROM c WHERE c.id =\n 'myfirstdb'\").AsEnumerable().First(); \n\t\t\t\n collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,\n \"SELECT * FROM c WHERE c.id = 'MyCollection'\").AsEnumerable().First(); \n\t\t\t\n await CreateDocuments(client); \n }\n\n}" }, { "code": null, "e": 8288, "s": 8232, "text": "Step 2 − Create some documents in CreateDocuments task." }, { "code": null, "e": 9001, "s": 8288, "text": "private async static Task CreateDocuments(DocumentClient client) {\n Console.WriteLine(); \n Console.WriteLine(\"**** Create Documents ****\"); \n Console.WriteLine();\n\t\n dynamic document1Definition = new {\n name = \"New Customer 1\", address = new { \n addressType = \"Main Office\", \n addressLine1 = \"123 Main Street\", \n location = new { \n city = \"Brooklyn\", stateProvinceName = \"New York\"\n }, \n postalCode = \"11229\", countryRegionName = \"United States\" \n }, \n };\n\t\n Document document1 = await CreateDocument(client, document1Definition); \n Console.WriteLine(\"Created document {0} from dynamic object\", document1.Id); \n Console.WriteLine(); \n}" }, { "code": null, "e": 9358, "s": 9001, "text": "The first document will be generated from this dynamic object. This might look like JSON, but of course it isn't. This is C# code and we're creating a real .NET object, but there's no class definition. Instead the properties are inferred from the way the object is initialized. You can notice also that we haven't supplied an Id property for this document." }, { "code": null, "e": 9493, "s": 9358, "text": "Step 3 − Now let's take a look at the CreateDocument and it looks like the same pattern we saw for creating databases and collections." }, { "code": null, "e": 9826, "s": 9493, "text": "private async static Task<Document> CreateDocument(DocumentClient client,\n object documentObject) {\n var result = await client.CreateDocumentAsync(collection.SelfLink, documentObject); \n\t\n var document = result.Resource; \n Console.WriteLine(\"Created new document: {0}\\r\\n{1}\", document.Id, document); \n\t\n return result; \n}" }, { "code": null, "e": 10081, "s": 9826, "text": "Step 4 − This time we call CreateDocumentAsync specifying the SelfLink of the collection we want to add the document to. We get back a response with a resource property that, in this case, represents the new document with its system-generated properties." }, { "code": null, "e": 10153, "s": 10081, "text": "In the following CreateDocuments task, we have created three documents." }, { "code": null, "e": 10393, "s": 10153, "text": "In the first document, the Document object is a defined class in the SDK that inherits from resource and so it has all the common resource properties, but it also includes the dynamic properties that define the schema-free document itself." }, { "code": null, "e": 10633, "s": 10393, "text": "In the first document, the Document object is a defined class in the SDK that inherits from resource and so it has all the common resource properties, but it also includes the dynamic properties that define the schema-free document itself." }, { "code": null, "e": 12522, "s": 10633, "text": "private async static Task CreateDocuments(DocumentClient client) {\n Console.WriteLine(); \n Console.WriteLine(\"**** Create Documents ****\"); \n Console.WriteLine();\n\t\n dynamic document1Definition = new {\n name = \"New Customer 1\", address = new {\n addressType = \"Main Office\", \n addressLine1 = \"123 Main Street\", \n location = new {\n city = \"Brooklyn\", stateProvinceName = \"New York\" \n }, \n postalCode = \"11229\", \n countryRegionName = \"United States\" \n }, \n };\n\t\n Document document1 = await CreateDocument(client, document1Definition); \n Console.WriteLine(\"Created document {0} from dynamic object\", document1.Id); \n Console.WriteLine();\n\t\n var document2Definition = @\" {\n \"\"name\"\": \"\"New Customer 2\"\", \n\t\t\n \"\"address\"\": { \n \"\"addressType\"\": \"\"Main Office\"\", \n \"\"addressLine1\"\": \"\"123 Main Street\"\", \n \"\"location\"\": { \n \"\"city\"\": \"\"Brooklyn\"\", \"\"stateProvinceName\"\": \"\"New York\"\" \n }, \n \"\"postalCode\"\": \"\"11229\"\", \n \"\"countryRegionName\"\": \"\"United States\"\" \n } \n }\"; \n\t\n Document document2 = await CreateDocument(client, document2Definition); \n Console.WriteLine(\"Created document {0} from JSON string\", document2.Id);\n Console.WriteLine();\n\t\n var document3Definition = new Customer {\n Name = \"New Customer 3\", \n\t\t\n Address = new Address {\n AddressType = \"Main Office\", \n AddressLine1 = \"123 Main Street\", \n Location = new Location {\n City = \"Brooklyn\", StateProvinceName = \"New York\" \n }, \n PostalCode = \"11229\", \n CountryRegionName = \"United States\" \n }, \n };\n\t\n Document document3 = await CreateDocument(client, document3Definition); \n Console.WriteLine(\"Created document {0} from typed object\", document3.Id); \n Console.WriteLine(); \n}" }, { "code": null, "e": 12805, "s": 12522, "text": "This second document just works with a raw JSON string. Now we step into an overload for CreateDocument that uses the JavaScriptSerializer to de-serialize the string into an object, which it then passes on to the same CreateDocument method that we used to create the first document." }, { "code": null, "e": 13088, "s": 12805, "text": "This second document just works with a raw JSON string. Now we step into an overload for CreateDocument that uses the JavaScriptSerializer to de-serialize the string into an object, which it then passes on to the same CreateDocument method that we used to create the first document." }, { "code": null, "e": 13184, "s": 13088, "text": "In the third document, we have used the C# object Customer which is defined in our application." }, { "code": null, "e": 13280, "s": 13184, "text": "In the third document, we have used the C# object Customer which is defined in our application." }, { "code": null, "e": 13467, "s": 13280, "text": "Let’s take a look at this customer, it has an Id and address property where the address is a nested object with its own properties including location, which is yet another nested object." }, { "code": null, "e": 14811, "s": 13467, "text": "using Newtonsoft.Json; \n\nusing System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace DocumentDBDemo {\n \n public class Customer { \n [JsonProperty(PropertyName = \"id\")] \n public string Id { get; set; }\n // Must be nullable, unless generating unique values for new customers on client \n [JsonProperty(PropertyName = \"name\")] \n public string Name { get; set; } \n [JsonProperty(PropertyName = \"address\")] \n public Address Address { get; set; } \n }\n\t\n public class Address {\n [JsonProperty(PropertyName = \"addressType\")] \n public string AddressType { get; set; } \n\t\t\n [JsonProperty(PropertyName = \"addressLine1\")] \n public string AddressLine1 { get; set; } \n\t\t\n [JsonProperty(PropertyName = \"location\")] \n public Location Location { get; set; } \n\t\t\n [JsonProperty(PropertyName = \"postalCode\")] \n public string PostalCode { get; set; } \n\t\t\n [JsonProperty(PropertyName = \"countryRegionName\")] \n public string CountryRegionName { get; set; } \n }\n\t\n public class Location { \n [JsonProperty(PropertyName = \"city\")] \n public string City { get; set; } \n\t\t\n [JsonProperty(PropertyName = \"stateProvinceName\")]\n public string StateProvinceName { get; set; } \n } \n}" }, { "code": null, "e": 14933, "s": 14811, "text": "We also have JSON property attributes in place because we want to maintain proper conventions on both sides of the fence." }, { "code": null, "e": 15235, "s": 14933, "text": "So I just create my New Customer object along with its nested child objects and call into CreateDocument once more. Although our customer object does have an Id property we didn't supply a value for it and so DocumentDB generated one based on the GUID, just like it did for the previous two documents." }, { "code": null, "e": 15319, "s": 15235, "text": "When the above code is compiled and executed you will receive the following output." }, { "code": null, "e": 17467, "s": 15319, "text": "**** Create Documents **** \nCreated new document: 575882f0-236c-4c3d-81b9-d27780206b2c \n{ \n \"name\": \"New Customer 1\", \n \"address\": { \n \"addressType\": \"Main Office\", \n \"addressLine1\": \"123 Main Street\", \n \"location\": { \n \"city\": \"Brooklyn\", \n \"stateProvinceName\": \"New York\" \n }, \n \"postalCode\": \"11229\", \n \"countryRegionName\": \"United States\" \n }, \n \"id\": \"575882f0-236c-4c3d-81b9-d27780206b2c\", \n \"_rid\": \"kV5oANVXnwDGPgAAAAAAAA==\", \n \"_ts\": 1450037545, \n \"_self\": \"dbs/kV5oAA==/colls/kV5oANVXnwA=/docs/kV5oANVXnwDGPgAAAAAAAA==/\", \n \"_etag\": \"\\\"00006fce-0000-0000-0000-566dd1290000\\\"\", \n \"_attachments\": \"attachments/\" \n} \nCreated document 575882f0-236c-4c3d-81b9-d27780206b2c from dynamic object \nCreated new document: 8d7ad239-2148-4fab-901b-17a85d331056 \n{ \n \"name\": \"New Customer 2\", \n \"address\": {\n \"addressType\": \"Main Office\", \n \"addressLine1\": \"123 Main Street\", \n \"location\": { \n \"city\": \"Brooklyn\", \n \"stateProvinceName\": \"New York\" \n }, \n \"postalCode\": \"11229\", \n \"countryRegionName\": \"United States\" \n }, \n \"id\": \"8d7ad239-2148-4fab-901b-17a85d331056\", \n \"_rid\": \"kV5oANVXnwDHPgAAAAAAAA==\", \n \"_ts\": 1450037545, \n \"_self\": \"dbs/kV5oAA==/colls/kV5oANVXnwA=/docs/kV5oANVXnwDHPgAAAAAAAA==/\", \n \"_etag\": \"\\\"000070ce-0000-0000-0000-566dd1290000\\\"\", \n \"_attachments\": \"attachments/\" \n} \nCreated document 8d7ad239-2148-4fab-901b-17a85d331056 from JSON string \nCreated new document: 49f399a8-80c9-4844-ac28-cd1dee689968 \n{ \n \"id\": \"49f399a8-80c9-4844-ac28-cd1dee689968\", \n \"name\": \"New Customer 3\", \n \"address\": { \n \"addressType\": \"Main Office\", \n \"addressLine1\": \"123 Main Street\", \n \"location\": { \n \"city\": \"Brooklyn\", \n \"stateProvinceName\": \"New York\" \n }, \n \"postalCode\": \"11229\", \n \"countryRegionName\": \"United States\" \n }, \n \"_rid\": \"kV5oANVXnwDIPgAAAAAAAA==\", \n \"_ts\": 1450037546, \n \"_self\": \"dbs/kV5oAA==/colls/kV5oANVXnwA=/docs/kV5oANVXnwDIPgAAAAAAAA==/\", \n \"_etag\": \"\\\"000071ce-0000-0000-0000-566dd12a0000\\\"\", \n \"_attachments\": \"attachments/\" \n}\nCreated document 49f399a8-80c9-4844-ac28-cd1dee689968 from typed object\n" }, { "code": null, "e": 17474, "s": 17467, "text": " Print" }, { "code": null, "e": 17485, "s": 17474, "text": " Add Notes" } ]
How do we add a single-line input field in HTML?
Use the <isindex> tag to add a single-line input field. The HTML <isindex> tag is used for querying a document through a text field. The tag can be used anywhere but head tag is preferable. Note: It is a deprecated tag and should not be used. The following are the attributes − Try the following code − <!Doctype html> <html> <head> <title>HTML isindex Tag</title> <isindex prompt = "Search" /> </head> </html>
[ { "code": null, "e": 1305, "s": 1062, "text": "Use the <isindex> tag to add a single-line input field. The HTML <isindex> tag is used for querying a document through a text field. The tag can be used anywhere but head tag is preferable. Note: It is a deprecated tag and should not be used." }, { "code": null, "e": 1340, "s": 1305, "text": "The following are the attributes −" }, { "code": null, "e": 1365, "s": 1340, "text": "Try the following code −" }, { "code": null, "e": 1491, "s": 1365, "text": "<!Doctype html>\n<html>\n <head>\n <title>HTML isindex Tag</title>\n <isindex prompt = \"Search\" />\n </head>\n</html>" } ]
Group Sparse Regularization for Deep Neural Networks | by Himaprasoon P.T | Towards Data Science
Paper summary of Group Sparse Regularization for Deep Neural Networks With the advancement in hardware technologies and thereby reduced costs, training large neural networks has become a lot easier. Due to this, it has become common to throw in large networks for even simple tasks. Having too many layers in a network can lead to multiple problems like, Overfitting Need for Network Pruning before deploying to production / mobile / IOT devices Then there is the problem of feature selection. Feature selection is the process of searching for a subset of all the features which are important for modeling. This is done usually as a separate pipeline before modeling starts. Sparse group regularization(SGR) tackles these three problems/ issues Optimizing weights of neural networkOptimizing the number of neurons for each hidden layerFeature Selection Optimizing weights of neural network Optimizing the number of neurons for each hidden layer Feature Selection and creates a single process/pipeline for tackling all of these. In neural networks, feature selection can be considered as pruning of nodes at input layer and that is how it is addressed in sparse group regularization. If all the incoming and outgoing weights of a neuron are 0, then that node can be removed. In the above ANN image, the red connections are weights which are zero. As all the connections from input feature X2 are zeros, this feature can be removed. Similarly for node H3, as all the outgoing weights are zeros, this node can also be removed. This is the idea of sparsity used in pruning of nodes and features. L1 regularization (Lasso) is one way in which sparsity of weights can be achieved. In this technique the sum of absolute values of the weights are penalized during training. New Cost = Cost + λ ||w|| As the weights are penalized by their absolute magnitude, sparsity can be achieved using L1 regularization. Click here to know more about L1 and L2 regularization. However, using L1(Lasso) alone cannot guarantee a systematic sparsity using which nodes can be removed. In order to remove a node, all the outgoing weights from the node should be zero. L1 can result to a different type of sparsity where it is unstructured. See the image below Here 2 weights are zero but none of the nodes can be removed. Therefore L1 alone cannot help in pruning. This is where sparse group regularization comes to the picture. To get a structured sparsity for pruning, we need to group outgoing connections from each neuron and force them to be zero. In order to do so, 3 different types of groups of weights are considered, Input Groups Gin : an element gi ∈ Gin, i = 1, . . . , d is the vector of all outgoing connections from the ith input neuron to the network. In the image above (Figure 3), there are two input groups(Green). The input group of x1 will contain all the weights from x1 to the hidden layer. Input groups are used for feature selection.Hidden Groups : Gh: in this case, a single element g ∈ Gh corresponds to the vector of all outgoing connections from one of the neurons in the hidden layers of the network. In figure 3 there are two output groups ( same as number of hidden nodes).Bias groups: Gb: these are one-dimensional groups (scalars) corresponding to the biases on the network. Instead of considering each bias as a separate group, a single group containing all the bias variables can also be used. Input Groups Gin : an element gi ∈ Gin, i = 1, . . . , d is the vector of all outgoing connections from the ith input neuron to the network. In the image above (Figure 3), there are two input groups(Green). The input group of x1 will contain all the weights from x1 to the hidden layer. Input groups are used for feature selection. Hidden Groups : Gh: in this case, a single element g ∈ Gh corresponds to the vector of all outgoing connections from one of the neurons in the hidden layers of the network. In figure 3 there are two output groups ( same as number of hidden nodes). Bias groups: Gb: these are one-dimensional groups (scalars) corresponding to the biases on the network. Instead of considering each bias as a separate group, a single group containing all the bias variables can also be used. Total set of Groups G is Sparse Group Regularization can be written as, where |g| denotes the dimensionality of the vector g, and it ensures that each group gets weighted uniformly. Here the L2 norm of each group is used. As L2 norm cannot create sparsity unlike L1, a thresholding step is done to convert low weights to zeros. This formulation is still suboptimal (even after thresholding) to get high level of sparsity. To enforce this, a combination of lasso and sparse group penalty is used. Sparse Group Lasso penalty is defined as, where the second term is the L1 norm of the weights. Figure 4 shows a comparison between the three types of regularization penalties discussed in this blog. The 2x5 matrix represent the weight matrix between a 2 dimensional input layer and a 5 dimensional output layer. The lasso penalty (l1) removes connections without taking node level considerations. In the image, it has resulted in 40% sparsity of connections. The second neuron in the output layer (5 dim) may be removed as all the incoming connections from both the input nodes are grayed out (See column 2 in Lasso in Figure 4). In Group Lasso (After thresholding in Sparse Group Regularization) , all the connections from the second neuron input layer are zero and therefore can be removed. The sparse group lasso penalty combines the advantages from both the previous formulations. Two nodes (2nd and 5th) from the output layer can be removed and also the second input neuron can be removed as well. The number of connections are reduced to 70% and leads to a very compact network. [1] Simone Scardapane , Amir Hussain and Aurelio Uncini , Group Sparse Regularization for Deep Neural Networks 2017
[ { "code": null, "e": 242, "s": 172, "text": "Paper summary of Group Sparse Regularization for Deep Neural Networks" }, { "code": null, "e": 527, "s": 242, "text": "With the advancement in hardware technologies and thereby reduced costs, training large neural networks has become a lot easier. Due to this, it has become common to throw in large networks for even simple tasks. Having too many layers in a network can lead to multiple problems like," }, { "code": null, "e": 539, "s": 527, "text": "Overfitting" }, { "code": null, "e": 618, "s": 539, "text": "Need for Network Pruning before deploying to production / mobile / IOT devices" }, { "code": null, "e": 847, "s": 618, "text": "Then there is the problem of feature selection. Feature selection is the process of searching for a subset of all the features which are important for modeling. This is done usually as a separate pipeline before modeling starts." }, { "code": null, "e": 917, "s": 847, "text": "Sparse group regularization(SGR) tackles these three problems/ issues" }, { "code": null, "e": 1025, "s": 917, "text": "Optimizing weights of neural networkOptimizing the number of neurons for each hidden layerFeature Selection" }, { "code": null, "e": 1062, "s": 1025, "text": "Optimizing weights of neural network" }, { "code": null, "e": 1117, "s": 1062, "text": "Optimizing the number of neurons for each hidden layer" }, { "code": null, "e": 1135, "s": 1117, "text": "Feature Selection" }, { "code": null, "e": 1355, "s": 1135, "text": "and creates a single process/pipeline for tackling all of these. In neural networks, feature selection can be considered as pruning of nodes at input layer and that is how it is addressed in sparse group regularization." }, { "code": null, "e": 1446, "s": 1355, "text": "If all the incoming and outgoing weights of a neuron are 0, then that node can be removed." }, { "code": null, "e": 1764, "s": 1446, "text": "In the above ANN image, the red connections are weights which are zero. As all the connections from input feature X2 are zeros, this feature can be removed. Similarly for node H3, as all the outgoing weights are zeros, this node can also be removed. This is the idea of sparsity used in pruning of nodes and features." }, { "code": null, "e": 1938, "s": 1764, "text": "L1 regularization (Lasso) is one way in which sparsity of weights can be achieved. In this technique the sum of absolute values of the weights are penalized during training." }, { "code": null, "e": 1964, "s": 1938, "text": "New Cost = Cost + λ ||w||" }, { "code": null, "e": 2072, "s": 1964, "text": "As the weights are penalized by their absolute magnitude, sparsity can be achieved using L1 regularization." }, { "code": null, "e": 2128, "s": 2072, "text": "Click here to know more about L1 and L2 regularization." }, { "code": null, "e": 2406, "s": 2128, "text": "However, using L1(Lasso) alone cannot guarantee a systematic sparsity using which nodes can be removed. In order to remove a node, all the outgoing weights from the node should be zero. L1 can result to a different type of sparsity where it is unstructured. See the image below" }, { "code": null, "e": 2575, "s": 2406, "text": "Here 2 weights are zero but none of the nodes can be removed. Therefore L1 alone cannot help in pruning. This is where sparse group regularization comes to the picture." }, { "code": null, "e": 2773, "s": 2575, "text": "To get a structured sparsity for pruning, we need to group outgoing connections from each neuron and force them to be zero. In order to do so, 3 different types of groups of weights are considered," }, { "code": null, "e": 3576, "s": 2773, "text": "Input Groups Gin : an element gi ∈ Gin, i = 1, . . . , d is the vector of all outgoing connections from the ith input neuron to the network. In the image above (Figure 3), there are two input groups(Green). The input group of x1 will contain all the weights from x1 to the hidden layer. Input groups are used for feature selection.Hidden Groups : Gh: in this case, a single element g ∈ Gh corresponds to the vector of all outgoing connections from one of the neurons in the hidden layers of the network. In figure 3 there are two output groups ( same as number of hidden nodes).Bias groups: Gb: these are one-dimensional groups (scalars) corresponding to the biases on the network. Instead of considering each bias as a separate group, a single group containing all the bias variables can also be used." }, { "code": null, "e": 3908, "s": 3576, "text": "Input Groups Gin : an element gi ∈ Gin, i = 1, . . . , d is the vector of all outgoing connections from the ith input neuron to the network. In the image above (Figure 3), there are two input groups(Green). The input group of x1 will contain all the weights from x1 to the hidden layer. Input groups are used for feature selection." }, { "code": null, "e": 4156, "s": 3908, "text": "Hidden Groups : Gh: in this case, a single element g ∈ Gh corresponds to the vector of all outgoing connections from one of the neurons in the hidden layers of the network. In figure 3 there are two output groups ( same as number of hidden nodes)." }, { "code": null, "e": 4381, "s": 4156, "text": "Bias groups: Gb: these are one-dimensional groups (scalars) corresponding to the biases on the network. Instead of considering each bias as a separate group, a single group containing all the bias variables can also be used." }, { "code": null, "e": 4406, "s": 4381, "text": "Total set of Groups G is" }, { "code": null, "e": 4453, "s": 4406, "text": "Sparse Group Regularization can be written as," }, { "code": null, "e": 4709, "s": 4453, "text": "where |g| denotes the dimensionality of the vector g, and it ensures that each group gets weighted uniformly. Here the L2 norm of each group is used. As L2 norm cannot create sparsity unlike L1, a thresholding step is done to convert low weights to zeros." }, { "code": null, "e": 4919, "s": 4709, "text": "This formulation is still suboptimal (even after thresholding) to get high level of sparsity. To enforce this, a combination of lasso and sparse group penalty is used. Sparse Group Lasso penalty is defined as," }, { "code": null, "e": 4972, "s": 4919, "text": "where the second term is the L1 norm of the weights." }, { "code": null, "e": 5189, "s": 4972, "text": "Figure 4 shows a comparison between the three types of regularization penalties discussed in this blog. The 2x5 matrix represent the weight matrix between a 2 dimensional input layer and a 5 dimensional output layer." }, { "code": null, "e": 5507, "s": 5189, "text": "The lasso penalty (l1) removes connections without taking node level considerations. In the image, it has resulted in 40% sparsity of connections. The second neuron in the output layer (5 dim) may be removed as all the incoming connections from both the input nodes are grayed out (See column 2 in Lasso in Figure 4)." }, { "code": null, "e": 5670, "s": 5507, "text": "In Group Lasso (After thresholding in Sparse Group Regularization) , all the connections from the second neuron input layer are zero and therefore can be removed." }, { "code": null, "e": 5962, "s": 5670, "text": "The sparse group lasso penalty combines the advantages from both the previous formulations. Two nodes (2nd and 5th) from the output layer can be removed and also the second input neuron can be removed as well. The number of connections are reduced to 70% and leads to a very compact network." } ]
VSAM - Cluster
VSAM cluster is defined in JCL. JCL uses IDCAMS utility to create a cluster. IDCAMS is a utility, developed by IBM, for access method services. It is used to primarily define VSAM datasets. The following syntax shows the main parameters which are grouped under Define Cluster, Data and Index. .DEFINE CLUSTER (NAME(vsam-file-name) - BLOCKS(number) - VOLUMES(volume-serial) - [INDEXED / NONINDEXED / NUMBERED / LINEAR] - RECSZ(average maximum) - [FREESPACE(CI-Percentage,CA-Percentage)] - CISZ(number) - [KEYS(length offset)] - [READPW(password)] - [FOR(days)|TO(date)] - [UPDATEPW(password)] - [REUSE / NOREUSE] ) - DATA - (NAME(vsam-file-name.data)) - INDEX - (NAME(vsam-file-name.index)) - CATALOG(catalog-name[/password])) Parameters at the CLUSTER level apply to the entire cluster. Parameters at the DATA or INDEX level apply only to the data or index component. We will discuss each parameter in detail in the following table − DEFINE CLUSTER Define Cluster command is used to define a cluster and specify parameter attributes for the cluster and its components. NAME NAME specifies the name of VSAM file for which we are defining the cluster. BLOCKS Blocks specifies the number of blocks assigned for the cluster. VOLUMES Volumes specifies one or more volumes that will contain the cluster or component. INDEXED / NONINDEXED / NUMBERED / LINEAR This parameter can take three values INDEXED, NONINDEXED or NUMBERED depending upon the type of dataset we are creating. For key-sequenced(KSDS) files INDEXED option is used. For entry-sequenced(ESDS) files the NONINDEXED option is used. For relative-record(RRDS) files the NUMBERED option is required. For Linear(LDS) files the LINEAR option is required. The default value of this parameter is INDEXED. We will discuss more about KSDS, ESDS, RRDS and LDS in coming modules. RECSZ Record Size parameter has two values which are Average and Maximum record size. The Average specifies the average length of the logical records in the file and the Maximum denotes the length of the records. FREESPACE Freespace specifies the percentage of free space to reserve for the control intervals (CI) and control areas (CA) of the data component. The default value of this parameter is zero percentage. CISZ CISZ is known as Control interval size. It specifies the size of control intervals. KEYS Keys parameter is defined only in key-sequenced (KSDS) files. It specifies the length and offset of primary key from first column. The range of value of this parameter are from 1 to 255 bytes. READPW Value in READPW parameter specifies the password of read level. FOR/TO The value of this parameter specifies the amount of time in terms of date and days for retaining the file. The default value for this parameter is zero days. UPDATEPW Value in UPDATEPW parameter specifies the password of update level. REUSE / NOREUSE REUSE parameter allows clusters to be defined that may be reset to empty status without deleting and re-defining them. DATA - NAME The DATA part of the cluster contains the dataset name which contains the actual data of the file. INDEX-NAME The INDEX part of the cluster contains the primary key and the memory pointer for the corresponding record in the data part. It is defined when a Key Sequenced cluster is used. CATALOG Catalog parameter denotes the catalog under which the file will be defined. We will discuss about catalog separately in upcoming modules. Following is a basic example to show how to define a cluster in JCL − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = IDCAMS //SYSPRINT DD SYSOUT = * //SYSIN DD * DEFINE CLUSTER (NAME(MY.VSAM.KSDSFILE) - INDEXED - RECSZ(80 80) - TRACKS(1,1) - KEYS(5 0) - CISZ(4096) - FREESPACE(3 3) ) - DATA (NAME(MY.VSAM.KSDSFILE.DATA)) - INDEX (NAME(MY.VSAM.KSDSFILE.INDEX)) /* If you will execute the above JCL on Mainframes server. It should execute with MAXCC = 0 and it will create MY.VSAM.KSDSFILE VSAM file. To delete a VSAM file, the VSAM cluster needs to be deleted using IDCAMS utility. DELETE command removes the entry of the VSAM cluster from the catalog and optionally removes the file, thereby freeing up the space occupied by the object. If the VSAM data set is not expired then it will not be deleted. To delete such types of datasets use PURGE option. DELETE data-set-name CLUSTER [ERASE / NOERASE] [FORCE / NOFORCE] [PURGE / NOPURGE] [SCRATCH / NOSCRATCH] Above syntax shows the parameters which we can use with Delete statement. We will discuss each of them in detail in following table − ERASE / NOERASE ERASE option is specified to override the ERASE attribute specified for the object in the catalog. NOERASE option is taken by default. FORCE / NOFORCE FORCE option is specified to delete the SPACE and USERCATALOG even if they are not empty. NOFORCE option is taken by default. PURGE / NOPURGE PURGE option is used to delete the VSAM dataset if dataset has not expired. NOPURGE option is taken by default. SCRATCH / NOSCRATCH SCRATCH option is specified to remove the associated entry for the object from the Volume Table of Contents. It is mainly used for non-vsam datasets like GDGs. NOSCRATCH option is taken by default. Following is a basic example to show how to delete a cluster in JCL − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEPNAME EXEC PGM = IDCAMS //SYSPRINT DD SYSOUT = * //SYSIN DD * DELETE MY.VSAM.KSDSFILE CLUSTER PURGE /* If you will execute the above JCL on Mainframes server. It should execute with MAXCC = 0 and it will delete MY.VSAM.KSDSFILE VSAM file. 8 Lectures 1 hours Nishant Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 1955, "s": 1765, "text": "VSAM cluster is defined in JCL. JCL uses IDCAMS utility to create a cluster. IDCAMS is a utility, developed by IBM, for access method services. It is used to primarily define VSAM datasets." }, { "code": null, "e": 2058, "s": 1955, "text": "The following syntax shows the main parameters which are grouped under Define Cluster, Data and Index." }, { "code": null, "e": 2825, "s": 2058, "text": ".DEFINE CLUSTER (NAME(vsam-file-name) -\nBLOCKS(number) -\nVOLUMES(volume-serial) -\n[INDEXED / NONINDEXED / NUMBERED / LINEAR] -\nRECSZ(average maximum) -\n[FREESPACE(CI-Percentage,CA-Percentage)] -\nCISZ(number) -\n[KEYS(length offset)] -\n[READPW(password)] -\n[FOR(days)|TO(date)] -\n[UPDATEPW(password)] -\n[REUSE / NOREUSE] ) -\nDATA -\n (NAME(vsam-file-name.data)) -\nINDEX -\n (NAME(vsam-file-name.index)) -\nCATALOG(catalog-name[/password])) \n" }, { "code": null, "e": 2967, "s": 2825, "text": "Parameters at the CLUSTER level apply to the entire cluster. Parameters at the DATA or INDEX level apply only to the data or index component." }, { "code": null, "e": 3033, "s": 2967, "text": "We will discuss each parameter in detail in the following table −" }, { "code": null, "e": 3048, "s": 3033, "text": "DEFINE CLUSTER" }, { "code": null, "e": 3168, "s": 3048, "text": "Define Cluster command is used to define a cluster and specify parameter attributes for the cluster and its components." }, { "code": null, "e": 3173, "s": 3168, "text": "NAME" }, { "code": null, "e": 3249, "s": 3173, "text": "NAME specifies the name of VSAM file for which we are defining the cluster." }, { "code": null, "e": 3256, "s": 3249, "text": "BLOCKS" }, { "code": null, "e": 3320, "s": 3256, "text": "Blocks specifies the number of blocks assigned for the cluster." }, { "code": null, "e": 3328, "s": 3320, "text": "VOLUMES" }, { "code": null, "e": 3410, "s": 3328, "text": "Volumes specifies one or more volumes that will contain the cluster or component." }, { "code": null, "e": 3451, "s": 3410, "text": "INDEXED / NONINDEXED / NUMBERED / LINEAR" }, { "code": null, "e": 3926, "s": 3451, "text": "This parameter can take three values INDEXED, NONINDEXED or NUMBERED depending upon the type of dataset we are creating. For key-sequenced(KSDS) files INDEXED option is used. For entry-sequenced(ESDS) files the NONINDEXED option is used. For relative-record(RRDS) files the NUMBERED option is required. For Linear(LDS) files the LINEAR option is required. The default value of this parameter is INDEXED. We will discuss more about KSDS, ESDS, RRDS and LDS in coming modules." }, { "code": null, "e": 3932, "s": 3926, "text": "RECSZ" }, { "code": null, "e": 4139, "s": 3932, "text": "Record Size parameter has two values which are Average and Maximum record size. The Average specifies the average length of the logical records in the file and the Maximum denotes the length of the records." }, { "code": null, "e": 4149, "s": 4139, "text": "FREESPACE" }, { "code": null, "e": 4342, "s": 4149, "text": "Freespace specifies the percentage of free space to reserve for the control intervals (CI) and control areas (CA) of the data component. The default value of this parameter is zero percentage." }, { "code": null, "e": 4347, "s": 4342, "text": "CISZ" }, { "code": null, "e": 4431, "s": 4347, "text": "CISZ is known as Control interval size. It specifies the size of control intervals." }, { "code": null, "e": 4436, "s": 4431, "text": "KEYS" }, { "code": null, "e": 4629, "s": 4436, "text": "Keys parameter is defined only in key-sequenced (KSDS) files. It specifies the length and offset of primary key from first column. The range of value of this parameter are from 1 to 255 bytes." }, { "code": null, "e": 4636, "s": 4629, "text": "READPW" }, { "code": null, "e": 4700, "s": 4636, "text": "Value in READPW parameter specifies the password of read level." }, { "code": null, "e": 4707, "s": 4700, "text": "FOR/TO" }, { "code": null, "e": 4865, "s": 4707, "text": "The value of this parameter specifies the amount of time in terms of date and days for retaining the file. The default value for this parameter is zero days." }, { "code": null, "e": 4874, "s": 4865, "text": "UPDATEPW" }, { "code": null, "e": 4942, "s": 4874, "text": "Value in UPDATEPW parameter specifies the password of update level." }, { "code": null, "e": 4958, "s": 4942, "text": "REUSE / NOREUSE" }, { "code": null, "e": 5077, "s": 4958, "text": "REUSE parameter allows clusters to be defined that may be reset to empty status without deleting and re-defining them." }, { "code": null, "e": 5089, "s": 5077, "text": "DATA - NAME" }, { "code": null, "e": 5188, "s": 5089, "text": "The DATA part of the cluster contains the dataset name which contains the actual data of the file." }, { "code": null, "e": 5199, "s": 5188, "text": "INDEX-NAME" }, { "code": null, "e": 5376, "s": 5199, "text": "The INDEX part of the cluster contains the primary key and the memory pointer for the corresponding record in the data part. It is defined when a Key Sequenced cluster is used." }, { "code": null, "e": 5384, "s": 5376, "text": "CATALOG" }, { "code": null, "e": 5522, "s": 5384, "text": "Catalog parameter denotes the catalog under which the file will be defined. We will discuss about catalog separately in upcoming modules." }, { "code": null, "e": 5592, "s": 5522, "text": "Following is a basic example to show how to define a cluster in JCL −" }, { "code": null, "e": 6145, "s": 5592, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = IDCAMS\n//SYSPRINT DD SYSOUT = *\n//SYSIN DD *\n DEFINE CLUSTER (NAME(MY.VSAM.KSDSFILE) -\n INDEXED -\n RECSZ(80 80) -\n TRACKS(1,1) -\n KEYS(5 0) -\n CISZ(4096) - \n FREESPACE(3 3) ) -\n DATA (NAME(MY.VSAM.KSDSFILE.DATA)) -\n INDEX (NAME(MY.VSAM.KSDSFILE.INDEX))\n/*" }, { "code": null, "e": 6281, "s": 6145, "text": "If you will execute the above JCL on Mainframes server. It should execute with MAXCC = 0 and it will create MY.VSAM.KSDSFILE VSAM file." }, { "code": null, "e": 6635, "s": 6281, "text": "To delete a VSAM file, the VSAM cluster needs to be deleted using IDCAMS utility. DELETE command removes the entry of the VSAM cluster from the catalog and optionally removes the file, thereby freeing up the space occupied by the object. If the VSAM data set is not expired then it will not be deleted. To delete such types of datasets use PURGE option." }, { "code": null, "e": 6746, "s": 6635, "text": "DELETE data-set-name CLUSTER \n[ERASE / NOERASE] \n[FORCE / NOFORCE] \n[PURGE / NOPURGE] \n[SCRATCH / NOSCRATCH]\n" }, { "code": null, "e": 6880, "s": 6746, "text": "Above syntax shows the parameters which we can use with Delete statement. We will discuss each of them in detail in following table −" }, { "code": null, "e": 6896, "s": 6880, "text": "ERASE / NOERASE" }, { "code": null, "e": 7031, "s": 6896, "text": "ERASE option is specified to override the ERASE attribute specified for the object in the catalog. NOERASE option is taken by default." }, { "code": null, "e": 7047, "s": 7031, "text": "FORCE / NOFORCE" }, { "code": null, "e": 7173, "s": 7047, "text": "FORCE option is specified to delete the SPACE and USERCATALOG even if they are not empty. NOFORCE option is taken by default." }, { "code": null, "e": 7189, "s": 7173, "text": "PURGE / NOPURGE" }, { "code": null, "e": 7301, "s": 7189, "text": "PURGE option is used to delete the VSAM dataset if dataset has not expired. NOPURGE option is taken by default." }, { "code": null, "e": 7321, "s": 7301, "text": "SCRATCH / NOSCRATCH" }, { "code": null, "e": 7519, "s": 7321, "text": "SCRATCH option is specified to remove the associated entry for the object from the Volume Table of Contents. It is mainly used for non-vsam datasets like GDGs. NOSCRATCH option is taken by default." }, { "code": null, "e": 7589, "s": 7519, "text": "Following is a basic example to show how to delete a cluster in JCL −" }, { "code": null, "e": 7758, "s": 7589, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEPNAME EXEC PGM = IDCAMS\n//SYSPRINT DD SYSOUT = *\n//SYSIN DD *\n DELETE MY.VSAM.KSDSFILE CLUSTER\n\tPURGE\n/*" }, { "code": null, "e": 7894, "s": 7758, "text": "If you will execute the above JCL on Mainframes server. It should execute with MAXCC = 0 and it will delete MY.VSAM.KSDSFILE VSAM file." }, { "code": null, "e": 7926, "s": 7894, "text": "\n 8 Lectures \n 1 hours \n" }, { "code": null, "e": 7941, "s": 7926, "text": " Nishant Malik" }, { "code": null, "e": 7948, "s": 7941, "text": " Print" }, { "code": null, "e": 7959, "s": 7948, "text": " Add Notes" } ]
How to use StringBuilder in C#?
With StringBuilder, you can expand the number of characters in the string. String cannot be changed once it is created, but StringBuildercan be expanded. It does not create a new object in the memory. Initialize StringBuilder. StringBuilder str = new StringBuilder(); Let us see an example to learn how to work with StringBuilder in C#. Live Demo using System; using System.Text; public class Program { public static void Main() { StringBuilder str = new StringBuilder("Web World!!",30); str.Replace("World", "Arena"); Console.WriteLine(str); } } Web Arena!! Above the Replace() method of StringBuilder is used to to replace a string in C#.
[ { "code": null, "e": 1263, "s": 1062, "text": "With StringBuilder, you can expand the number of characters in the string. String cannot be changed once it is created, but StringBuildercan be expanded. It does not create a new object in the memory." }, { "code": null, "e": 1289, "s": 1263, "text": "Initialize StringBuilder." }, { "code": null, "e": 1330, "s": 1289, "text": "StringBuilder str = new StringBuilder();" }, { "code": null, "e": 1399, "s": 1330, "text": "Let us see an example to learn how to work with StringBuilder in C#." }, { "code": null, "e": 1410, "s": 1399, "text": " Live Demo" }, { "code": null, "e": 1634, "s": 1410, "text": "using System;\nusing System.Text;\npublic class Program {\n public static void Main() {\n StringBuilder str = new StringBuilder(\"Web World!!\",30);\n str.Replace(\"World\", \"Arena\");\n Console.WriteLine(str);\n }\n}" }, { "code": null, "e": 1646, "s": 1634, "text": "Web Arena!!" }, { "code": null, "e": 1728, "s": 1646, "text": "Above the Replace() method of StringBuilder is used to to replace a string in C#." } ]
Interactive map using Geographical Information in Plotly Express | by Tamjid Ahsan | Towards Data Science
Visualizations are very powerful tools for any data science project. It helps the reader to understand what is happening. For some dataset it is very helpful to be able to see the data on a map for presenting insights also while doing the analysis. There are a lot of packages out there which can achieve this goal, all with their respective strengths and weaknesses. Namely Folium, Plotly, Mapbox, Bokeh and so on. In this post, I am showing how I plot my data on maps when doing analysis of data with geographic information using Plotly. For this demonstration, I am using a house rental price dataset of San Francisco, California. This dataset contains following features to begin with. After initial cleaning I wanted to get zip code information of the individual houses. I used uszipcode package to get those information from latitude and longitude data. Additionally pandas and Plotly express is used. Code for this is following: # data manipulationimport pandas as pd# data cleaningimport reimport missingno# data visualizationimport plotly.express as px I used this to group data by zip codes to get average rental price per zip code, and visualize on a map. This is the end result. Code: This approach utilizes geojason file that contains zip code boundaries of zip codes in the USA. Those are courtesy of OpenDataDE, files can be found here. To get those information useful for using in plotly, this line is used. for feature in zipcode_data['features']: feature['id'] = feature['properties']['ZCTA5CE10'] More on this from plotly documentation can be found here. To get the location of each house on a interactive map, I used following code: More on this from plotly documentation can be found here. For a static output use this instead of showing the object by using fig.show(). You can also save this as image by tinkering the output type. import plotly.io as plyIoimg_bytes = fig.to_image(format="png", width=1200, height=700, scale=1)from IPython.display import Imagedisplay(Image(img_bytes)) All the workings and files can be found here on GitHub. An extension of this project on House price prediction using these data can be found here on Github. That’s all for today. Until next time!
[ { "code": null, "e": 421, "s": 172, "text": "Visualizations are very powerful tools for any data science project. It helps the reader to understand what is happening. For some dataset it is very helpful to be able to see the data on a map for presenting insights also while doing the analysis." }, { "code": null, "e": 588, "s": 421, "text": "There are a lot of packages out there which can achieve this goal, all with their respective strengths and weaknesses. Namely Folium, Plotly, Mapbox, Bokeh and so on." }, { "code": null, "e": 712, "s": 588, "text": "In this post, I am showing how I plot my data on maps when doing analysis of data with geographic information using Plotly." }, { "code": null, "e": 862, "s": 712, "text": "For this demonstration, I am using a house rental price dataset of San Francisco, California. This dataset contains following features to begin with." }, { "code": null, "e": 1108, "s": 862, "text": "After initial cleaning I wanted to get zip code information of the individual houses. I used uszipcode package to get those information from latitude and longitude data. Additionally pandas and Plotly express is used. Code for this is following:" }, { "code": null, "e": 1234, "s": 1108, "text": "# data manipulationimport pandas as pd# data cleaningimport reimport missingno# data visualizationimport plotly.express as px" }, { "code": null, "e": 1363, "s": 1234, "text": "I used this to group data by zip codes to get average rental price per zip code, and visualize on a map. This is the end result." }, { "code": null, "e": 1369, "s": 1363, "text": "Code:" }, { "code": null, "e": 1596, "s": 1369, "text": "This approach utilizes geojason file that contains zip code boundaries of zip codes in the USA. Those are courtesy of OpenDataDE, files can be found here. To get those information useful for using in plotly, this line is used." }, { "code": null, "e": 1699, "s": 1596, "text": "for feature in zipcode_data['features']: feature['id'] = feature['properties']['ZCTA5CE10']" }, { "code": null, "e": 1757, "s": 1699, "text": "More on this from plotly documentation can be found here." }, { "code": null, "e": 1836, "s": 1757, "text": "To get the location of each house on a interactive map, I used following code:" }, { "code": null, "e": 1894, "s": 1836, "text": "More on this from plotly documentation can be found here." }, { "code": null, "e": 2036, "s": 1894, "text": "For a static output use this instead of showing the object by using fig.show(). You can also save this as image by tinkering the output type." }, { "code": null, "e": 2191, "s": 2036, "text": "import plotly.io as plyIoimg_bytes = fig.to_image(format=\"png\", width=1200, height=700, scale=1)from IPython.display import Imagedisplay(Image(img_bytes))" }, { "code": null, "e": 2348, "s": 2191, "text": "All the workings and files can be found here on GitHub. An extension of this project on House price prediction using these data can be found here on Github." } ]
Use Iterator to remove an element from a Collection in Java
An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown. A program that demonstrates this is given as follows. Live Demo import java.util.ArrayList; import java.util.Iterator; public class Demo { public static void main(String[] args) { ArrayList<String> aList = new ArrayList<String>(); aList.add("Apple"); aList.add("Mango"); aList.add("Guava"); aList.add("Orange"); aList.add("Peach"); System.out.println("The ArrayList elements are: "); for (String s: aList) { System.out.println(s); } Iterator i = aList.iterator(); String str = ""; while (i.hasNext()) { str = (String) i.next(); if (str.equals("Orange")) { i.remove(); System.out.println("\nThe element Orange is removed"); break; } } System.out.println("\nThe ArrayList elements are: "); for (String s: aList) { System.out.println(s); } } } The output of the above program is as follows The ArrayList elements are: Apple Mango Guava Orange Peach The element Orange is removed The ArrayList elements are: Apple Mango Guava Peach
[ { "code": null, "e": 1314, "s": 1062, "text": "An element can be removed from a Collection using the Iterator method remove(). This method\nremoves the current element in the Collection. If the remove() method is not preceded by the\nnext() method, then the exception IllegalStateException is thrown." }, { "code": null, "e": 1368, "s": 1314, "text": "A program that demonstrates this is given as follows." }, { "code": null, "e": 1379, "s": 1368, "text": " Live Demo" }, { "code": null, "e": 2239, "s": 1379, "text": "import java.util.ArrayList;\nimport java.util.Iterator;\npublic class Demo {\n public static void main(String[] args) {\n ArrayList<String> aList = new ArrayList<String>();\n aList.add(\"Apple\");\n aList.add(\"Mango\");\n aList.add(\"Guava\");\n aList.add(\"Orange\");\n aList.add(\"Peach\");\n System.out.println(\"The ArrayList elements are: \");\n for (String s: aList) {\n System.out.println(s);\n }\n Iterator i = aList.iterator();\n String str = \"\";\n while (i.hasNext()) {\n str = (String) i.next();\n if (str.equals(\"Orange\")) {\n i.remove();\n System.out.println(\"\\nThe element Orange is removed\");\n break;\n }\n }\n System.out.println(\"\\nThe ArrayList elements are: \");\n for (String s: aList) {\n System.out.println(s);\n }\n }\n}" }, { "code": null, "e": 2285, "s": 2239, "text": "The output of the above program is as follows" }, { "code": null, "e": 2428, "s": 2285, "text": "The ArrayList elements are:\nApple\nMango\nGuava\nOrange\nPeach\n\nThe element Orange is removed\n\nThe ArrayList elements are:\nApple\nMango\nGuava\nPeach" } ]
Creating Slide to Shut Down Shortcut in Windows 10 - GeeksforGeeks
31 Aug, 2021 If you’re looking for a smart and interactive way to Shut down your PC, then this trick is going very useful for you. Instead of that traditional long process of shutting down the PC, the ‘Slide to Shut down’ feature allows you to shut down your Windows 10 PC by sliding, or dragging the window down. Let’s understand how we can create a ‘Slide to Shut down’ shortcut. Slide to Shut down Window. Below are the steps mentioned on how to add the shortcut for Slide To Shut Down. Step 1: Right-click on an empty space on the desktop, select ‘New’ and click the ‘Shortcut’. Create New shortcut on the Desktop. Step 2: Paste the following path in the location section. %windir%\System32\SlideToShutDown.exe Step 3: Click ‘Next’. Paste this path to the location section. Step 4: Give the name for the shortcut (Ex. SlideToShutDown) and Click on ‘Finish’. Give a name to the shortcut. Step 5: Right-click on the newly created shortcut and select ‘Properties’. Shortcut Properties. Step 6: In the Shortcut tab, select the ‘Change icon’ button. Step 7: After clicking ‘Change Icon’, one pop-up will appear on the screen. Click ‘OK’ to confirm that the file path you specified doesn’t contain icons. Step 8: You can choose the icon from the list provided by windows, Select the icon from the list which is most relevant to your shortcut and then click ‘OK’. Step 9: To apply this icon to our shortcut, click on ‘Apply’ and again Click on ‘OK’. Now the Setup for this shortcut is completed, and the shortcut is created on your desktop. When you double-click on this icon, it will launch Slide to Shut down your PC, then you can click and drag the window down, or also you can press Enter key to shut down your PC. Also, you can right-click on the shortcut and “Pin to the taskbar” for faster access to the Shutdown experience. user282 Technical Scripter 2020 Technical Scripter TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Find the Wi-Fi Password Using CMD in Windows? How to Run a Python Script using Docker? Docker - COPY Instruction Running Python script on GPU. Setting up the environment in Java How to setup cron jobs in Ubuntu How to set up Command Prompt for Python in Windows10 ? How to Add External JAR File to an IntelliJ IDEA Project? Top Programming Languages for Android App Development 'dd' command in Linux
[ { "code": null, "e": 24498, "s": 24470, "text": "\n31 Aug, 2021" }, { "code": null, "e": 24867, "s": 24498, "text": "If you’re looking for a smart and interactive way to Shut down your PC, then this trick is going very useful for you. Instead of that traditional long process of shutting down the PC, the ‘Slide to Shut down’ feature allows you to shut down your Windows 10 PC by sliding, or dragging the window down. Let’s understand how we can create a ‘Slide to Shut down’ shortcut." }, { "code": null, "e": 24894, "s": 24867, "text": "Slide to Shut down Window." }, { "code": null, "e": 24976, "s": 24894, "text": "Below are the steps mentioned on how to add the shortcut for Slide To Shut Down. " }, { "code": null, "e": 25071, "s": 24976, "text": "Step 1: Right-click on an empty space on the desktop, select ‘New’ and click the ‘Shortcut’. " }, { "code": null, "e": 25107, "s": 25071, "text": "Create New shortcut on the Desktop." }, { "code": null, "e": 25165, "s": 25107, "text": "Step 2: Paste the following path in the location section." }, { "code": null, "e": 25204, "s": 25165, "text": " %windir%\\System32\\SlideToShutDown.exe" }, { "code": null, "e": 25226, "s": 25204, "text": "Step 3: Click ‘Next’." }, { "code": null, "e": 25267, "s": 25226, "text": "Paste this path to the location section." }, { "code": null, "e": 25351, "s": 25267, "text": "Step 4: Give the name for the shortcut (Ex. SlideToShutDown) and Click on ‘Finish’." }, { "code": null, "e": 25380, "s": 25351, "text": "Give a name to the shortcut." }, { "code": null, "e": 25455, "s": 25380, "text": "Step 5: Right-click on the newly created shortcut and select ‘Properties’." }, { "code": null, "e": 25476, "s": 25455, "text": "Shortcut Properties." }, { "code": null, "e": 25538, "s": 25476, "text": "Step 6: In the Shortcut tab, select the ‘Change icon’ button." }, { "code": null, "e": 25693, "s": 25538, "text": "Step 7: After clicking ‘Change Icon’, one pop-up will appear on the screen. Click ‘OK’ to confirm that the file path you specified doesn’t contain icons. " }, { "code": null, "e": 25851, "s": 25693, "text": "Step 8: You can choose the icon from the list provided by windows, Select the icon from the list which is most relevant to your shortcut and then click ‘OK’." }, { "code": null, "e": 25937, "s": 25851, "text": "Step 9: To apply this icon to our shortcut, click on ‘Apply’ and again Click on ‘OK’." }, { "code": null, "e": 26206, "s": 25937, "text": "Now the Setup for this shortcut is completed, and the shortcut is created on your desktop. When you double-click on this icon, it will launch Slide to Shut down your PC, then you can click and drag the window down, or also you can press Enter key to shut down your PC." }, { "code": null, "e": 26319, "s": 26206, "text": "Also, you can right-click on the shortcut and “Pin to the taskbar” for faster access to the Shutdown experience." }, { "code": null, "e": 26327, "s": 26319, "text": "user282" }, { "code": null, "e": 26351, "s": 26327, "text": "Technical Scripter 2020" }, { "code": null, "e": 26370, "s": 26351, "text": "Technical Scripter" }, { "code": null, "e": 26379, "s": 26370, "text": "TechTips" }, { "code": null, "e": 26477, "s": 26379, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26486, "s": 26477, "text": "Comments" }, { "code": null, "e": 26499, "s": 26486, "text": "Old Comments" }, { "code": null, "e": 26552, "s": 26499, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 26593, "s": 26552, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 26619, "s": 26593, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26649, "s": 26619, "text": "Running Python script on GPU." }, { "code": null, "e": 26684, "s": 26649, "text": "Setting up the environment in Java" }, { "code": null, "e": 26717, "s": 26684, "text": "How to setup cron jobs in Ubuntu" }, { "code": null, "e": 26772, "s": 26717, "text": "How to set up Command Prompt for Python in Windows10 ?" }, { "code": null, "e": 26830, "s": 26772, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 26884, "s": 26830, "text": "Top Programming Languages for Android App Development" } ]
How to animate a pcolormesh in Matplotlib?
To animate pcolormesh in matplotlib, we can take the following steps − Create a figure and a set of subplots. Create a figure and a set of subplots. Create x, y and t data points using numpy. Create x, y and t data points using numpy. Create X3, Y3 and T3, return coordinate matrices from coordinate vectors using meshgrid. Create X3, Y3 and T3, return coordinate matrices from coordinate vectors using meshgrid. Create a pseudocolor plot with a non-regular rectangular grid using pcolormesh() method. Create a pseudocolor plot with a non-regular rectangular grid using pcolormesh() method. Make a colorbar with colormesh axis. Make a colorbar with colormesh axis. Animate pcolormesh using Animation() class method. Animate pcolormesh using Animation() class method. To display the figure, use show() method. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt, animation plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True fig, ax = plt.subplots() x = np.linspace(-3, 3, 91) t = np.linspace(0, 25, 30) y = np.linspace(-3, 3, 91) X3, Y3, T3 = np.meshgrid(x, y, t) sinT3 = np.sin(2 * np.pi * T3 / T3.max(axis=2)[..., np.newaxis]) G = (X3 ** 2 + Y3 ** 2) * sinT3 cax = ax.pcolormesh(x, y, G[:-1, :-1, 0], vmin=-1, vmax=1, cmap='Blues') fig.colorbar(cax) def animate(i): cax.set_array(G[:-1, :-1, i].flatten()) anim = animation.FuncAnimation(fig, animate, interval=100, frames=len(t) - 1) anim.save('517.gif') plt.show()
[ { "code": null, "e": 1133, "s": 1062, "text": "To animate pcolormesh in matplotlib, we can take the following steps −" }, { "code": null, "e": 1172, "s": 1133, "text": "Create a figure and a set of subplots." }, { "code": null, "e": 1211, "s": 1172, "text": "Create a figure and a set of subplots." }, { "code": null, "e": 1254, "s": 1211, "text": "Create x, y and t data points using numpy." }, { "code": null, "e": 1297, "s": 1254, "text": "Create x, y and t data points using numpy." }, { "code": null, "e": 1386, "s": 1297, "text": "Create X3, Y3 and T3, return coordinate matrices from coordinate vectors using meshgrid." }, { "code": null, "e": 1475, "s": 1386, "text": "Create X3, Y3 and T3, return coordinate matrices from coordinate vectors using meshgrid." }, { "code": null, "e": 1564, "s": 1475, "text": "Create a pseudocolor plot with a non-regular rectangular grid using pcolormesh() method." }, { "code": null, "e": 1653, "s": 1564, "text": "Create a pseudocolor plot with a non-regular rectangular grid using pcolormesh() method." }, { "code": null, "e": 1690, "s": 1653, "text": "Make a colorbar with colormesh axis." }, { "code": null, "e": 1727, "s": 1690, "text": "Make a colorbar with colormesh axis." }, { "code": null, "e": 1778, "s": 1727, "text": "Animate pcolormesh using Animation() class method." }, { "code": null, "e": 1829, "s": 1778, "text": "Animate pcolormesh using Animation() class method." }, { "code": null, "e": 1871, "s": 1829, "text": "To display the figure, use show() method." }, { "code": null, "e": 1913, "s": 1871, "text": "To display the figure, use show() method." }, { "code": null, "e": 2567, "s": 1913, "text": "import numpy as np\nfrom matplotlib import pyplot as plt, animation\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig, ax = plt.subplots()\nx = np.linspace(-3, 3, 91)\nt = np.linspace(0, 25, 30)\ny = np.linspace(-3, 3, 91)\nX3, Y3, T3 = np.meshgrid(x, y, t)\nsinT3 = np.sin(2 * np.pi * T3 / T3.max(axis=2)[..., np.newaxis])\nG = (X3 ** 2 + Y3 ** 2) * sinT3\ncax = ax.pcolormesh(x, y, G[:-1, :-1, 0], vmin=-1, vmax=1, cmap='Blues')\nfig.colorbar(cax)\n\ndef animate(i):\n cax.set_array(G[:-1, :-1, i].flatten())\n\nanim = animation.FuncAnimation(fig, animate, interval=100, frames=len(t) - 1)\nanim.save('517.gif')\nplt.show()" } ]
How to Join Pandas DataFrames using Merge? - GeeksforGeeks
10 Jul, 2020 Joining and merging DataFrames is that the core process to start out out with data analysis and machine learning tasks. It’s one of the toolkits which each Data Analyst or Data Scientist should master because in most cases data comes from multiple sources and files. In this tutorial, you’ll how to join data frames in pandas using the merge technique. More specifically, we will practice the concatenation of DataFrames along row and column. The most widely used operation related to DataFrames is the merging operation. Two DataFrames might hold different kinds of information about the same entity and they may have some same columns, so we need to combine the two data frames in pandas for better reliability code. To join these DataFrames, pandas provides various functions like join(), concat(), merge(), etc. In this section, you will practice using the merge() function of pandas. There are basically four methods of merging: inner join outer join right join left join From the name itself, it is clear enough that the inner join keeps rows where the merge “on” value exists in both the left and right dataframes. Now let us create two dataframes and then try merging them using inner. import numpy as npimport pandas as pd left = pd.DataFrame({'Sr.no': ['1', '2', '3', '4', '5'], 'Name': ['Rashmi', 'Arun', 'John', 'Kshitu', 'Bresha'], 'Roll No': ['1', '2', '3', '4', '5']}) right = pd.DataFrame({'Sr.no': ['2', '4', '6', '7', '8'], 'Gender': ['F', 'M', 'M', 'F', 'F'], 'Interest': ['Writing', 'Cricket', 'Dancing', 'Chess', 'Sleeping']}) # Merging the dataframes pd.merge(left, right, how ='inner', on ='Sr.no') Output: An outer join returns all the rows from the left dataframe, all the rows from the right dataframe, and matches up rows where possible, with NaNs elsewhere. But if the dataframe is complete, then we get the same output. import numpy as npimport pandas as pd left = pd.DataFrame({'Sr.no': ['1', '2', '3', '4', '5'], 'Name': ['Rashmi', 'Arun', 'John', 'Kshitu', 'Bresha'], 'Roll No': ['1', '2', '3', '4', '5']}) right = pd.DataFrame({'Sr.no': ['2', '4', '6', '7', '8'], 'Gender': ['F', 'M', 'M', 'F', 'F'], 'Interest': ['Writing', 'Cricket', 'Dancing', 'Chess', 'Sleeping']}) # Merging the dataframes pd.merge(left, right, how ='outer', on ='Sr.no') Output: With a left join, all the records from the first dataframe will be displayed, irrespective of whether the keys in the first dataframe can be found in the second dataframe. Whereas, for the second dataframe, only the records with the keys in the second dataframe that can be found in the first dataframe will be displayed. import numpy as npimport pandas as pd left = pd.DataFrame({'Sr.no': ['1', '2', '3', '4', '5'], 'Name': ['Rashmi', 'Arun', 'John', 'Kshitu', 'Bresha'], 'Roll No': ['1', '2', '3', '4', '5']}) right = pd.DataFrame({'Sr.no': ['2', '4', '6', '7', '8'], 'Gender': ['F', 'M', 'M', 'F', 'F'], 'Interest': ['Writing', 'Cricket', 'Dancing', 'Chess', 'Sleeping']}) # Merging the dataframes pd.merge(left, right, how ='left', on ='Sr.no') Output:Note the Output Carefully. For a right join, all the records from the second dataframe will be displayed. However, only the records with the keys in the first dataframe that can be found in the second dataframe will be displayed. import numpy as npimport pandas as pd left = pd.DataFrame({'Sr.no': ['1', '2', '3', '4', '5'], 'Name': ['Rashmi', 'Arun', 'John', 'Kshitu', 'Bresha'], 'Roll No': ['1', '2', '3', '4', '5']}) right = pd.DataFrame({'Sr.no': ['2', '4', '6', '7', '8'], 'Gender': ['F', 'M', 'M', 'F', 'F'], 'Interest': ['Writing', 'Cricket', 'Dancing', 'Chess', 'Sleeping']}) # Merging the dataframes pd.merge(left, right, how ='right', on ='Sr.no') Output: Python pandas-dataFrame Python-pandas 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 Convert Python Dictionary To JSON? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24318, "s": 24290, "text": "\n10 Jul, 2020" }, { "code": null, "e": 24761, "s": 24318, "text": "Joining and merging DataFrames is that the core process to start out out with data analysis and machine learning tasks. It’s one of the toolkits which each Data Analyst or Data Scientist should master because in most cases data comes from multiple sources and files. In this tutorial, you’ll how to join data frames in pandas using the merge technique. More specifically, we will practice the concatenation of DataFrames along row and column." }, { "code": null, "e": 25207, "s": 24761, "text": "The most widely used operation related to DataFrames is the merging operation. Two DataFrames might hold different kinds of information about the same entity and they may have some same columns, so we need to combine the two data frames in pandas for better reliability code. To join these DataFrames, pandas provides various functions like join(), concat(), merge(), etc. In this section, you will practice using the merge() function of pandas." }, { "code": null, "e": 25252, "s": 25207, "text": "There are basically four methods of merging:" }, { "code": null, "e": 25263, "s": 25252, "text": "inner join" }, { "code": null, "e": 25274, "s": 25263, "text": "outer join" }, { "code": null, "e": 25285, "s": 25274, "text": "right join" }, { "code": null, "e": 25295, "s": 25285, "text": "left join" }, { "code": null, "e": 25440, "s": 25295, "text": "From the name itself, it is clear enough that the inner join keeps rows where the merge “on” value exists in both the left and right dataframes." }, { "code": null, "e": 25512, "s": 25440, "text": "Now let us create two dataframes and then try merging them using inner." }, { "code": "import numpy as npimport pandas as pd left = pd.DataFrame({'Sr.no': ['1', '2', '3', '4', '5'], 'Name': ['Rashmi', 'Arun', 'John', 'Kshitu', 'Bresha'], 'Roll No': ['1', '2', '3', '4', '5']}) right = pd.DataFrame({'Sr.no': ['2', '4', '6', '7', '8'], 'Gender': ['F', 'M', 'M', 'F', 'F'], 'Interest': ['Writing', 'Cricket', 'Dancing', 'Chess', 'Sleeping']}) # Merging the dataframes pd.merge(left, right, how ='inner', on ='Sr.no') ", "e": 26133, "s": 25512, "text": null }, { "code": null, "e": 26141, "s": 26133, "text": "Output:" }, { "code": null, "e": 26360, "s": 26141, "text": "An outer join returns all the rows from the left dataframe, all the rows from the right dataframe, and matches up rows where possible, with NaNs elsewhere. But if the dataframe is complete, then we get the same output." }, { "code": "import numpy as npimport pandas as pd left = pd.DataFrame({'Sr.no': ['1', '2', '3', '4', '5'], 'Name': ['Rashmi', 'Arun', 'John', 'Kshitu', 'Bresha'], 'Roll No': ['1', '2', '3', '4', '5']}) right = pd.DataFrame({'Sr.no': ['2', '4', '6', '7', '8'], 'Gender': ['F', 'M', 'M', 'F', 'F'], 'Interest': ['Writing', 'Cricket', 'Dancing', 'Chess', 'Sleeping']}) # Merging the dataframes pd.merge(left, right, how ='outer', on ='Sr.no')", "e": 26980, "s": 26360, "text": null }, { "code": null, "e": 26988, "s": 26980, "text": "Output:" }, { "code": null, "e": 27310, "s": 26988, "text": "With a left join, all the records from the first dataframe will be displayed, irrespective of whether the keys in the first dataframe can be found in the second dataframe. Whereas, for the second dataframe, only the records with the keys in the second dataframe that can be found in the first dataframe will be displayed." }, { "code": "import numpy as npimport pandas as pd left = pd.DataFrame({'Sr.no': ['1', '2', '3', '4', '5'], 'Name': ['Rashmi', 'Arun', 'John', 'Kshitu', 'Bresha'], 'Roll No': ['1', '2', '3', '4', '5']}) right = pd.DataFrame({'Sr.no': ['2', '4', '6', '7', '8'], 'Gender': ['F', 'M', 'M', 'F', 'F'], 'Interest': ['Writing', 'Cricket', 'Dancing', 'Chess', 'Sleeping']}) # Merging the dataframes pd.merge(left, right, how ='left', on ='Sr.no')", "e": 27963, "s": 27310, "text": null }, { "code": null, "e": 27997, "s": 27963, "text": "Output:Note the Output Carefully." }, { "code": null, "e": 28200, "s": 27997, "text": "For a right join, all the records from the second dataframe will be displayed. However, only the records with the keys in the first dataframe that can be found in the second dataframe will be displayed." }, { "code": "import numpy as npimport pandas as pd left = pd.DataFrame({'Sr.no': ['1', '2', '3', '4', '5'], 'Name': ['Rashmi', 'Arun', 'John', 'Kshitu', 'Bresha'], 'Roll No': ['1', '2', '3', '4', '5']}) right = pd.DataFrame({'Sr.no': ['2', '4', '6', '7', '8'], 'Gender': ['F', 'M', 'M', 'F', 'F'], 'Interest': ['Writing', 'Cricket', 'Dancing', 'Chess', 'Sleeping']}) # Merging the dataframes pd.merge(left, right, how ='right', on ='Sr.no') ", "e": 28821, "s": 28200, "text": null }, { "code": null, "e": 28829, "s": 28821, "text": "Output:" }, { "code": null, "e": 28853, "s": 28829, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28867, "s": 28853, "text": "Python-pandas" }, { "code": null, "e": 28874, "s": 28867, "text": "Python" }, { "code": null, "e": 28972, "s": 28874, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28981, "s": 28972, "text": "Comments" }, { "code": null, "e": 28994, "s": 28981, "text": "Old Comments" }, { "code": null, "e": 29026, "s": 28994, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29068, "s": 29026, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29123, "s": 29068, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 29179, "s": 29123, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29221, "s": 29179, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29243, "s": 29221, "text": "Defaultdict in Python" }, { "code": null, "e": 29282, "s": 29243, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29313, "s": 29282, "text": "Python | os.path.join() method" }, { "code": null, "e": 29342, "s": 29313, "text": "Create a directory in Python" } ]
Searching or Sorting a list of Objects Based on an Attribute in Python | by Allison Stafford | Towards Data Science
Often, when you have a group of objects, you might be looking to sort them based not on their location in memory, but on an attribute of interest. Today, we’ll look at Python’s built in tool for doing just this: operator.attrgetter, as well as the related tools in this toolkit and alternate methods to achieve similar goals (using lambdas and iterators/comprehensions). For our data set today, we’re going to be using a fictional data set of a pack of 100 dogs. The dog student class has attributes: name, yr, strengths, areas_for_growth, works_well_with, not_works_well_with, has_sat_by, has_not_sat_by, and notes. It has methods that add, get, remove, and these attributes, plus get_n_not_works_well and get_n_works_well that returns the number of friends/frenemies in their respective lists. Attrgetter is an attribute getter. You can use it in a couple ways: You can create an attrgetter “callable object that fetches attr from its operand” (from the docs). You can create an attrgetter “callable object that fetches attr from its operand” (from the docs). from operator import attrgetterfriend_getter = attrgetter('works_well_with')print(friend_getter(dog_pack[1])) Here friend_getter returns dog_pack[1]’s works_well_with list: [Student('Qeb', 12), Student('Putty', 6), Student('Douglas', 3), Student('Denali', 5), Student('Asher', 12), Student('Portia', 3), Student('Suki', 2), Student('Olive', 14), Student('Peri', 8), Student('Mari', 5), Student('Snowflake', 2), Student('Guayaba', 12)] I’m still looking for a context in which you would do this over dog_pack[1].works_well_with. We’ll see one example I ran into below, but I’m not sure I’m convinced. 2. You can use attrgetter with functions that expect a function argument. For example, as the key to sorted(), max(), min(); or with map(), itertools.groupby(), etc. To get the oldest dog: # to get the object with the characteristic (max yr)oldest = max(dog_pack, key=attrgetter("yr"))print(f"Oldest Dog\nname: {oldest.name}\nage: {oldest.yr}", f"Strengths: {oldest.strengths}") printing: Oldest Dogname: Abbeyage: 15Strengths: ['snuggly', 'snuggly', 'plays well', 'fetch'] Here we actually have multiple oldest dogs, so we’ll want to use a filtering/conditional list comprehension to get a list oldest dogs: [d for d in dog_pack if d.yr == max(d.yr for d in dog_pack)] returning [Student(Abbey, 15), Student(Radar, 15), Student(Pinot, 15), Student(Lucci, 15), Student(Leona Mae Alcott Helmsley Cole, 15), Student(Stella, 15), Student(Whiskers, 15)] Don’t forget that if we want the values themselves, and not the objects with the value, there’s no need to use attrgetter. max(d.yr for d in dog_pack) Which returns 15. Methodcaller works very similarly to attrgetter, but when you want to use the return of a class’ method instead of a class’ attribute. For example, if I want to get the dog student that works well with the fewest other students: min_works_well = min(dog_pack, key=methodcaller('get_n_works_well'))print(f"""Works Well With The Fewest Dogs name: {min_works_well.name} works well with: {min_works_well.get_n_works_well()} dogs strengths: {min_works_well.strengths} areas for growth: {min_works_well.areas_for_growth}""") returning: Works Well With The Fewest Dogsname: Pringlesworks well with: 4 dogsstrengths: ['leave it', 'snuggly', 'comes when called']areas for growth: ['playing with others'] Another difference between attrgetter and methodcaller is that with attrgetter, additional arguments are additional attributes to get, while with methodcaller they are passed as arguments to the method. attrgetter works on classes, while itemgetter works on other data structures (lists, tuples, dictionaries, etc). If our dog_pack were structured as a list of dictionaries: oldest = max(dogs_dict_list, key=itemgetter('yr'))print(f"Oldest dog\nname: {oldest['name']}", f"strengths: {oldest['strengths']}") itemgetter uses ‘yr’ as the key and returns: Oldest dogname: Dolliestrengths: ['plays well', 'ignores food on the sidewalk'] If it were structured as this list of tuples: dogs_tups = [('Bella', 5, 'labrador', 'yellow'), ('Dollie', 12, 'austrailian sheppard', 'cream, brown')]youngest = min(dogs_tups, key=itemgetter(1))print(f"Youngest Dog:\nname: {youngest[0]}\nbreed: {youngest[2]}") itemgetter would use the argument 1 as the index and return Youngest Dog:name: Bellabreed: labrador Like attrgetter, itemgetter returns a tuple of lookup values when supplied multiple arguments. If you wanted to sort our dogs, not by one of these first-tier attributes, but by a component of an attribute, I’ve seen four options: If the attribute is a class, you can access an attribute of your attribute by passing the second attribute name to attrgetter along with the first. For example if we alter the name attribute to create an instance of the class Name, we can sort by first name with sorted(dog_pack, key=attrgetter("name.first") as in the docs’ example.If you have access to the class, or the class has a method that returns the sub-attribute you are interested in, you can use methodcaller to access/sort by that sub-attribute. If the attribute is a class, you can access an attribute of your attribute by passing the second attribute name to attrgetter along with the first. For example if we alter the name attribute to create an instance of the class Name, we can sort by first name with sorted(dog_pack, key=attrgetter("name.first") as in the docs’ example. If you have access to the class, or the class has a method that returns the sub-attribute you are interested in, you can use methodcaller to access/sort by that sub-attribute. from operator import methodcallersorted(dog_pack, key=methodcaller("get_area_for_growth", 0)) Here growth_sorted is a list of the dogs sorted by their first area for growth (alphabetically). Note again that methodcaller passes additional arguments to the method. This is in contrast with attrgetter, where additional arguments are read as additional attributes to get, supporting multi-attribute keys. For multiple-attribute keys with methodcaller, you would need a lambda function. 3. Use a lambda or defined function. sorted(dog_pack, key=lambda x: (x.get_area_for_growth(0), x.name.first) or equivalently: def first_growth_first_name(x): "Returns the first area for growth and first name of Dog x" first_growth = x.get_area_for_growth(0) first_name = x.name.first return (first_growth, first_name)sorted(dog_pack, key=first_growth_first_name) 4. Combine lambda and attrgetter/methodcaller. sorted(dog_pack[0:5], key = lambda x: attrgetter("strengths")(x)[0]) This example feels pretty convoluted to me and depends on every dog in the pack having strength at that location. But it might be the way to go in some situation. I am not sure about the relative compute time here with the combination of attrgetter and lambda as compared to lambda and direct attribute access. It seems like the built in functions operate somewhat faster, which may or may not be important for your scenario. Folks on the internet seem to disagree as to which is more elegant/pythonic/nice looking. The use of strings blocks the autocomplete functionality of many code editors, which requires one to type/spell/know what attribute they want. Not ideal. Not a dealbreaker for me. Each of these can easily be substituted with a lambda function (or defined function): Sorting our dog pack by year then name: sorted(dog_pack, key=attrgetter(“yr”, "name.first")) becomes sorted(dog_pack, key=lambda x: (x.yr, x.name.first)) dogs_tups = [('Bella', 5, 'labrador', 'yellow'), ('Dollie', 12, 'austrailian sheppard', 'cream, brown')] Sorting these dog tuples by breed: sorted(dogs_tups, key=itemgetter(2) becomes sorted(dog_pack, key=lambda x: x[2]) Sorting our dog pack by the number of dogs they play well with: sorted(dog_pack, key=methodcaller(“get_n_works_well”)) becomes sorted(dog_pack, key=lambda x: x.get_n_works_well()) If you need to process the attribute data before sorting/getting the max/getting the min/whatever, then you may need to use an alternative to attrgetter. For example, originally, my dog names had non-standardized capitalization. If you don’t have access to the class, you can correct for this using: sorted(dog_pack, key=lambda x: x.name.first.lower()) or if you are looking for dogs with names that start with A: [d for d in dog_pack if d.name.first.lower() < 'b'] Check out the GitHub repository here. Happy coding!
[ { "code": null, "e": 543, "s": 172, "text": "Often, when you have a group of objects, you might be looking to sort them based not on their location in memory, but on an attribute of interest. Today, we’ll look at Python’s built in tool for doing just this: operator.attrgetter, as well as the related tools in this toolkit and alternate methods to achieve similar goals (using lambdas and iterators/comprehensions)." }, { "code": null, "e": 968, "s": 543, "text": "For our data set today, we’re going to be using a fictional data set of a pack of 100 dogs. The dog student class has attributes: name, yr, strengths, areas_for_growth, works_well_with, not_works_well_with, has_sat_by, has_not_sat_by, and notes. It has methods that add, get, remove, and these attributes, plus get_n_not_works_well and get_n_works_well that returns the number of friends/frenemies in their respective lists." }, { "code": null, "e": 1036, "s": 968, "text": "Attrgetter is an attribute getter. You can use it in a couple ways:" }, { "code": null, "e": 1135, "s": 1036, "text": "You can create an attrgetter “callable object that fetches attr from its operand” (from the docs)." }, { "code": null, "e": 1234, "s": 1135, "text": "You can create an attrgetter “callable object that fetches attr from its operand” (from the docs)." }, { "code": null, "e": 1344, "s": 1234, "text": "from operator import attrgetterfriend_getter = attrgetter('works_well_with')print(friend_getter(dog_pack[1]))" }, { "code": null, "e": 1407, "s": 1344, "text": "Here friend_getter returns dog_pack[1]’s works_well_with list:" }, { "code": null, "e": 1669, "s": 1407, "text": "[Student('Qeb', 12), Student('Putty', 6), Student('Douglas', 3), Student('Denali', 5), Student('Asher', 12), Student('Portia', 3), Student('Suki', 2), Student('Olive', 14), Student('Peri', 8), Student('Mari', 5), Student('Snowflake', 2), Student('Guayaba', 12)]" }, { "code": null, "e": 1834, "s": 1669, "text": "I’m still looking for a context in which you would do this over dog_pack[1].works_well_with. We’ll see one example I ran into below, but I’m not sure I’m convinced." }, { "code": null, "e": 2000, "s": 1834, "text": "2. You can use attrgetter with functions that expect a function argument. For example, as the key to sorted(), max(), min(); or with map(), itertools.groupby(), etc." }, { "code": null, "e": 2023, "s": 2000, "text": "To get the oldest dog:" }, { "code": null, "e": 2219, "s": 2023, "text": "# to get the object with the characteristic (max yr)oldest = max(dog_pack, key=attrgetter(\"yr\"))print(f\"Oldest Dog\\nname: {oldest.name}\\nage: {oldest.yr}\", f\"Strengths: {oldest.strengths}\")" }, { "code": null, "e": 2229, "s": 2219, "text": "printing:" }, { "code": null, "e": 2314, "s": 2229, "text": "Oldest Dogname: Abbeyage: 15Strengths: ['snuggly', 'snuggly', 'plays well', 'fetch']" }, { "code": null, "e": 2449, "s": 2314, "text": "Here we actually have multiple oldest dogs, so we’ll want to use a filtering/conditional list comprehension to get a list oldest dogs:" }, { "code": null, "e": 2510, "s": 2449, "text": "[d for d in dog_pack if d.yr == max(d.yr for d in dog_pack)]" }, { "code": null, "e": 2520, "s": 2510, "text": "returning" }, { "code": null, "e": 2690, "s": 2520, "text": "[Student(Abbey, 15), Student(Radar, 15), Student(Pinot, 15), Student(Lucci, 15), Student(Leona Mae Alcott Helmsley Cole, 15), Student(Stella, 15), Student(Whiskers, 15)]" }, { "code": null, "e": 2813, "s": 2690, "text": "Don’t forget that if we want the values themselves, and not the objects with the value, there’s no need to use attrgetter." }, { "code": null, "e": 2841, "s": 2813, "text": "max(d.yr for d in dog_pack)" }, { "code": null, "e": 2859, "s": 2841, "text": "Which returns 15." }, { "code": null, "e": 2994, "s": 2859, "text": "Methodcaller works very similarly to attrgetter, but when you want to use the return of a class’ method instead of a class’ attribute." }, { "code": null, "e": 3088, "s": 2994, "text": "For example, if I want to get the dog student that works well with the fewest other students:" }, { "code": null, "e": 3414, "s": 3088, "text": "min_works_well = min(dog_pack, key=methodcaller('get_n_works_well'))print(f\"\"\"Works Well With The Fewest Dogs name: {min_works_well.name} works well with: {min_works_well.get_n_works_well()} dogs strengths: {min_works_well.strengths} areas for growth: {min_works_well.areas_for_growth}\"\"\")" }, { "code": null, "e": 3425, "s": 3414, "text": "returning:" }, { "code": null, "e": 3590, "s": 3425, "text": "Works Well With The Fewest Dogsname: Pringlesworks well with: 4 dogsstrengths: ['leave it', 'snuggly', 'comes when called']areas for growth: ['playing with others']" }, { "code": null, "e": 3793, "s": 3590, "text": "Another difference between attrgetter and methodcaller is that with attrgetter, additional arguments are additional attributes to get, while with methodcaller they are passed as arguments to the method." }, { "code": null, "e": 3906, "s": 3793, "text": "attrgetter works on classes, while itemgetter works on other data structures (lists, tuples, dictionaries, etc)." }, { "code": null, "e": 3965, "s": 3906, "text": "If our dog_pack were structured as a list of dictionaries:" }, { "code": null, "e": 4102, "s": 3965, "text": "oldest = max(dogs_dict_list, key=itemgetter('yr'))print(f\"Oldest dog\\nname: {oldest['name']}\", f\"strengths: {oldest['strengths']}\")" }, { "code": null, "e": 4147, "s": 4102, "text": "itemgetter uses ‘yr’ as the key and returns:" }, { "code": null, "e": 4227, "s": 4147, "text": "Oldest dogname: Dolliestrengths: ['plays well', 'ignores food on the sidewalk']" }, { "code": null, "e": 4273, "s": 4227, "text": "If it were structured as this list of tuples:" }, { "code": null, "e": 4501, "s": 4273, "text": "dogs_tups = [('Bella', 5, 'labrador', 'yellow'), ('Dollie', 12, 'austrailian sheppard', 'cream, brown')]youngest = min(dogs_tups, key=itemgetter(1))print(f\"Youngest Dog:\\nname: {youngest[0]}\\nbreed: {youngest[2]}\")" }, { "code": null, "e": 4561, "s": 4501, "text": "itemgetter would use the argument 1 as the index and return" }, { "code": null, "e": 4601, "s": 4561, "text": "Youngest Dog:name: Bellabreed: labrador" }, { "code": null, "e": 4696, "s": 4601, "text": "Like attrgetter, itemgetter returns a tuple of lookup values when supplied multiple arguments." }, { "code": null, "e": 4831, "s": 4696, "text": "If you wanted to sort our dogs, not by one of these first-tier attributes, but by a component of an attribute, I’ve seen four options:" }, { "code": null, "e": 5340, "s": 4831, "text": "If the attribute is a class, you can access an attribute of your attribute by passing the second attribute name to attrgetter along with the first. For example if we alter the name attribute to create an instance of the class Name, we can sort by first name with sorted(dog_pack, key=attrgetter(\"name.first\") as in the docs’ example.If you have access to the class, or the class has a method that returns the sub-attribute you are interested in, you can use methodcaller to access/sort by that sub-attribute." }, { "code": null, "e": 5674, "s": 5340, "text": "If the attribute is a class, you can access an attribute of your attribute by passing the second attribute name to attrgetter along with the first. For example if we alter the name attribute to create an instance of the class Name, we can sort by first name with sorted(dog_pack, key=attrgetter(\"name.first\") as in the docs’ example." }, { "code": null, "e": 5850, "s": 5674, "text": "If you have access to the class, or the class has a method that returns the sub-attribute you are interested in, you can use methodcaller to access/sort by that sub-attribute." }, { "code": null, "e": 5944, "s": 5850, "text": "from operator import methodcallersorted(dog_pack, key=methodcaller(\"get_area_for_growth\", 0))" }, { "code": null, "e": 6041, "s": 5944, "text": "Here growth_sorted is a list of the dogs sorted by their first area for growth (alphabetically)." }, { "code": null, "e": 6333, "s": 6041, "text": "Note again that methodcaller passes additional arguments to the method. This is in contrast with attrgetter, where additional arguments are read as additional attributes to get, supporting multi-attribute keys. For multiple-attribute keys with methodcaller, you would need a lambda function." }, { "code": null, "e": 6370, "s": 6333, "text": "3. Use a lambda or defined function." }, { "code": null, "e": 6473, "s": 6370, "text": "sorted(dog_pack, key=lambda x: (x.get_area_for_growth(0), x.name.first)" }, { "code": null, "e": 6490, "s": 6473, "text": "or equivalently:" }, { "code": null, "e": 6739, "s": 6490, "text": "def first_growth_first_name(x): \"Returns the first area for growth and first name of Dog x\" first_growth = x.get_area_for_growth(0) first_name = x.name.first return (first_growth, first_name)sorted(dog_pack, key=first_growth_first_name)" }, { "code": null, "e": 6786, "s": 6739, "text": "4. Combine lambda and attrgetter/methodcaller." }, { "code": null, "e": 6855, "s": 6786, "text": "sorted(dog_pack[0:5], key = lambda x: attrgetter(\"strengths\")(x)[0])" }, { "code": null, "e": 7166, "s": 6855, "text": "This example feels pretty convoluted to me and depends on every dog in the pack having strength at that location. But it might be the way to go in some situation. I am not sure about the relative compute time here with the combination of attrgetter and lambda as compared to lambda and direct attribute access." }, { "code": null, "e": 7551, "s": 7166, "text": "It seems like the built in functions operate somewhat faster, which may or may not be important for your scenario. Folks on the internet seem to disagree as to which is more elegant/pythonic/nice looking. The use of strings blocks the autocomplete functionality of many code editors, which requires one to type/spell/know what attribute they want. Not ideal. Not a dealbreaker for me." }, { "code": null, "e": 7637, "s": 7551, "text": "Each of these can easily be substituted with a lambda function (or defined function):" }, { "code": null, "e": 7677, "s": 7637, "text": "Sorting our dog pack by year then name:" }, { "code": null, "e": 7738, "s": 7677, "text": "sorted(dog_pack, key=attrgetter(“yr”, \"name.first\")) becomes" }, { "code": null, "e": 7791, "s": 7738, "text": "sorted(dog_pack, key=lambda x: (x.yr, x.name.first))" }, { "code": null, "e": 7909, "s": 7791, "text": "dogs_tups = [('Bella', 5, 'labrador', 'yellow'), ('Dollie', 12, 'austrailian sheppard', 'cream, brown')]" }, { "code": null, "e": 7944, "s": 7909, "text": "Sorting these dog tuples by breed:" }, { "code": null, "e": 7988, "s": 7944, "text": "sorted(dogs_tups, key=itemgetter(2) becomes" }, { "code": null, "e": 8025, "s": 7988, "text": "sorted(dog_pack, key=lambda x: x[2])" }, { "code": null, "e": 8089, "s": 8025, "text": "Sorting our dog pack by the number of dogs they play well with:" }, { "code": null, "e": 8152, "s": 8089, "text": "sorted(dog_pack, key=methodcaller(“get_n_works_well”)) becomes" }, { "code": null, "e": 8205, "s": 8152, "text": "sorted(dog_pack, key=lambda x: x.get_n_works_well())" }, { "code": null, "e": 8359, "s": 8205, "text": "If you need to process the attribute data before sorting/getting the max/getting the min/whatever, then you may need to use an alternative to attrgetter." }, { "code": null, "e": 8505, "s": 8359, "text": "For example, originally, my dog names had non-standardized capitalization. If you don’t have access to the class, you can correct for this using:" }, { "code": null, "e": 8558, "s": 8505, "text": "sorted(dog_pack, key=lambda x: x.name.first.lower())" }, { "code": null, "e": 8619, "s": 8558, "text": "or if you are looking for dogs with names that start with A:" }, { "code": null, "e": 8671, "s": 8619, "text": "[d for d in dog_pack if d.name.first.lower() < 'b']" } ]
Brand Management - Quick Guide
“A product is something made in the factory; a brand is something the customer buys. A product can be copied or imitated by a competitor; a brand is unique. A product can be outdated; a successful brand is timeless.” − Stephen King (WPP Group, London) Today, the commodity marketplace is flooded with various brands. The requirement of the seller’s brand to stand out among other parallel brands is crucial. Hence, there is a fierce competition among the sellers to make their products or services stand out in the market, thereby winning new consumers and retaining the existing ones. At times, it even leads to diverting the consumers following other brands to the seller’s brand. To remain competitive in the marketplace, strong brand management is required. Brand Management begins with understanding the term 'brand'. Brand may be defined from the brand owner’s perspective or the consumer’s perspective. There are various popular definitions of a brand − “A name, term, design, symbol, or any other feature that identifies one seller’s good or service as distinct from those of other sellers. The legal term for brand is trademark. A brand may identify one item, a family of items, or all items of that seller. If used for the firm as a whole, the preferred term is trade name.” - American Marketing Association “A name, term, design, symbol, or any other feature that identifies one seller’s good or service as distinct from those of other sellers. The legal term for brand is trademark. A brand may identify one item, a family of items, or all items of that seller. If used for the firm as a whole, the preferred term is trade name.” - American Marketing Association “A type of product manufactured by a particular company under a particular name.” − Oxford English dictionary “A type of product manufactured by a particular company under a particular name.” − Oxford English dictionary “A name, term, sign, symbol, design, or a combination of these used to identify the goods or services of one seller or group of sellers and to differentiate them from those of competitors.” − A product-oriented definition “A name, term, sign, symbol, design, or a combination of these used to identify the goods or services of one seller or group of sellers and to differentiate them from those of competitors.” − A product-oriented definition “The promise of the bundles of attributes that someone buys and provide satisfaction . . .” − A consumer-oriented definition “The promise of the bundles of attributes that someone buys and provide satisfaction . . .” − A consumer-oriented definition The fundamental purpose of branding is differentiation. A brand is a means of differentiating the seller’s product from other competing products. Brand has the following characteristics − Tangible characteristics − Price, physical product, packaging, etc. Intangible characteristics − Customer’s experience with the brand, brand position, and brand image. Here are some important objectives of a brand − To establish an identity for the product or a group of products. To establish an identity for the product or a group of products. To protect the product or service legally for its unique features. To protect the product or service legally for its unique features. To acquire place for the product in consumers’ minds for high and consistent quality. To acquire place for the product in consumers’ minds for high and consistent quality. To persuade the consumer to buy the product by promising to serve their needs in a unique way. To persuade the consumer to buy the product by promising to serve their needs in a unique way. To create and send the message of strong reliable business among consumers. To create and send the message of strong reliable business among consumers. Brand management is an art of creating a brand and maintaining it. It is nothing but developing a promise to the consumer, materializing that promise, and maintaining the same for a product, a group of products, or services. Brand management helps to manage the tangible and intangible characteristics of a brand. A competent Brand Management includes building brand identity, launching the brand, and maintaining the brand position in the market. Brand management builds and maintains the corporate image of a business. The concept of branding exists since approximately hundred years. It is a single most compelling thing about a brand that differentiates it from the competing brands. The brand essence serves as a metric to evaluate the seller's marketing strategies. The most important brand essences arise from consumers' needs. Brand essence can be described in just a few words. For example, Volvo − Safe travel. Disney − Fun family entertainment. There are seven contributing elements of brand essence − Authenticity − If the brand makes a promise and fails to keep, then it is rejected. The consumers expect the sellers to be genuine and truthful. Authenticity − If the brand makes a promise and fails to keep, then it is rejected. The consumers expect the sellers to be genuine and truthful. Consistency − The essence of a brand is lost if it is not consistent in providing what it promised to the consumer. Also, a brand should use its logo consistently over time. Consistency − The essence of a brand is lost if it is not consistent in providing what it promised to the consumer. Also, a brand should use its logo consistently over time. Durability − The brand essence remains same over time. Even if packaging and logos change, the essence does not change. Durability − The brand essence remains same over time. Even if packaging and logos change, the essence does not change. Experience − It is the consumers experience with the brand. Experience − It is the consumers experience with the brand. Uniqueness − It is how different a brand is from its competitors. Uniqueness − It is how different a brand is from its competitors. Relevance − It is the relevance of a brand to the consumer. Relevance − It is the relevance of a brand to the consumer. Single mindedness − It is sticking to only one thing about the brand which keeps the brand focused. Single mindedness − It is sticking to only one thing about the brand which keeps the brand focused. There are eight essential elements of a brand as given below − Brand Name − This is what the people get to see everywhere. It must be as simple and memorable as possible, meaningful, easy to pronounce, and unique. Brand Name − This is what the people get to see everywhere. It must be as simple and memorable as possible, meaningful, easy to pronounce, and unique. Logo − This can be anything from a piece of text to the abstract designs. It may be entirely unrelated to the corporate activities. It must be relevant to the product or service, iconic, and attractive. Logo − This can be anything from a piece of text to the abstract designs. It may be entirely unrelated to the corporate activities. It must be relevant to the product or service, iconic, and attractive. Tone − This is how the seller communicates with the consumer. It can be professional, friendly, or formal. It builds consumer’s perception about the brand. Tone − This is how the seller communicates with the consumer. It can be professional, friendly, or formal. It builds consumer’s perception about the brand. Jingle − It must be pleasant to hear and hum, relevant to the product, easy to remember, and easy to understand over a large age group to connect consumer with the brand. Jingle − It must be pleasant to hear and hum, relevant to the product, easy to remember, and easy to understand over a large age group to connect consumer with the brand. Slogan − It summarizes overall value proposition. It should be short, easy to remember, and catchy. For example, KFC’s slogan is “Finger Lickin’ Good” and Britannia’s is “Eat Healthy, Think Better”. Slogan − It summarizes overall value proposition. It should be short, easy to remember, and catchy. For example, KFC’s slogan is “Finger Lickin’ Good” and Britannia’s is “Eat Healthy, Think Better”. Packaging − It needs to be catchy and advertising, drawing people to see the product inside. Also, it needs to be compact, yet attractive. Packaging − It needs to be catchy and advertising, drawing people to see the product inside. Also, it needs to be compact, yet attractive. Universal Resource Locator (URL) − It forms the domain name on the internet. A seller can register all prospective variations of brand name URLs or can buy the existing URL of a business. Universal Resource Locator (URL) − It forms the domain name on the internet. A seller can register all prospective variations of brand name URLs or can buy the existing URL of a business. Characters/Mascots − It is a special symbol, either still, animated, or real life entity such as an animal or a human character. For example, Vodafone’s Zoozoo characters are played in its various advertisements by humans wearing special white body suits. Characters/Mascots − It is a special symbol, either still, animated, or real life entity such as an animal or a human character. For example, Vodafone’s Zoozoo characters are played in its various advertisements by humans wearing special white body suits. They are not the same. Let us see the difference between them − Here are some commonly used terms in Brand Management − The humans have frequent needs as well as occasional needs in the life. They are varied in number of ways such as day-to-day living needs, social needs, health and medication needs, contemporary lifestyle needs, to name a few. According to this need-based market segmentation, the brands are diversified in different sectors such as personal care, home care, commodities, entertainment, healthcare, pharmaceutical, luxuries, and services. There are two basic approaches of brands according to ownership − The brands can be further categorized depending on the human needs or the context as given − The FMCG items such as grocery, toiletries, easy-to-cook foods, are essential for our daily lives. They are called fast moving because they are the quickest to get sold from the supermarket shelves. They are also called Consumer Packaged Goods (CPG) brands. They are inexpensive and tangible products which can be produced in advance and can be stored to be consumed later. The brand managers need to handle these brands tactfully to generate more revenue as there is fierce competition in the FMCG market. If a product does not meet the consumer’s expectations, there is always other brand ready to take the advantage. Examples of FMCG − Unilever’s Dove Bodycare, Colgate Palmolive’s oral care, Godrej, Dabur, Burges Olive Oil, etc. They are the products or services which consumers buy depending upon their price. There is no quantitative differentiation for commodities across the market. Milk, sugar, oil, grains and cereals, metals, wool and rubber, and natural gas, are all commodities. Since it is not easy to pursue the consumers to pay more price for the parallel product he can get at a lesser price, the sellers need to put in a lot of effort on color, logo, brand character, and packaging to differentiate the product so it makes a significant impact on the consumers’ mind. Also, the seller needs to keep on adding value to the product. Examples of commodities − TATA Salt, General Mill’s Pillsbury whole wheat flour, etc. They are not essential but highly desired out of one’s own perception and self-worth. The desirability is based on the consumer’s demand of high quality, fine craftsmanship, exclusivity, precision, and beauty. Also, peer recognition, appreciation, and approval of high status are the underlying needs which promote luxury brands. High-end automobiles, jewelry, cosmetics, accessories, properties, and perfumes come under luxury brands. These brands are divided into three categories − Prestige Brands − Mercedes-Benz, Rolex, Swarovski, etc. represent high craftsmanship and lavishness. They are regarded as the mark of high social status. Prestige Brands − Mercedes-Benz, Rolex, Swarovski, etc. represent high craftsmanship and lavishness. They are regarded as the mark of high social status. Premium Brands − They are mass luxury brands. For example, Calvin Klein and Tommy Hilfiger. Premium Brands − They are mass luxury brands. For example, Calvin Klein and Tommy Hilfiger. Fashion Brands − They bring fashion products such as apparels and accessories under “hot trends” and target mass consumers. They bring products according to the seasons. Fashion Brands − They bring fashion products such as apparels and accessories under “hot trends” and target mass consumers. They bring products according to the seasons. Most luxury companies are small to medium sized enterprises. Presence of luxury brands must be maintained all over the world to reinforce the brand image in the consumer’s mind. They are available in flagship stores. Under these brands, a business makes a commercial transaction with another business. Such transactions occur when one business provides resources to another business for manufacturing some product, and when one business supplies or rents out the products to another business. B2B companies must pursue global branding as they have less number of customers than B2C companies and more number of transactions with other businesses. For example, restaurants buy cooking energy, raw materials, crockery, furniture, lights, etc. from different businesses. Retailers buy a product from original manufacturer for reselling it. McDonalds, Pizza Hut, IBM, GE, Microsoft, and Oracle are B2B brands to name a few. These brands cover the products which are commonly known as drugs or medicines used to diagnose, treat, and prevent a disease. There are more than 70,000 registered brands of drugs. Pharmaceutical brands are different than consumer brands in various prominent ways. Unlike consumer products, where requirement can be generated through creative advertising and other promotional means, a pharmaceutical company cannot create a need that is not there. Any new pharmaceutical product cannot create demand without underlying medical need. In addition, the product features of prescription drugs cannot be changed to meet consumer needs or preferences without clinical development outcomes and receiving approval from the regulatory authorities. Examples of pharmaceutical brands − Simila Expert Care nutrition for infants from Abbott Laboratories, USA and Dr Reddy’s NiseTM. The service sector has spurred the economic growth of many countries. Services are produced and consumed in real time. The output of a service brand is intangible, such as experience of the consumer. In service branding, the speed of processing the consumer’s request, punctuality in delivery, quality, and degree of attending special needs, and responsiveness are the factors the service provider caters for. Because of its intangible nature and dependency on dynamic nature of humans who provide it, branding of service is difficult. The domestic and industrial appliances, automobiles, etc. are sold with the promise of quality servicing. The quality and cost claimed by the services belonging to the same industry can vary to a great extent. Service brands are categorized into the following types − Classic Service Brands − They include banks, beauty salons, consultation services, car rentals, and airline services. Classic Service Brands − They include banks, beauty salons, consultation services, car rentals, and airline services. Pure Service Brands − They include association memberships. Pure Service Brands − They include association memberships. Professional Service Brands − They include advisors, consultants, travel agents, estate agents, etc. Professional Service Brands − They include advisors, consultants, travel agents, estate agents, etc. Retail Service Brands − They include restaurants, fashion stores, supermarkets, etc. Retail Service Brands − They include restaurants, fashion stores, supermarkets, etc. Examples of service brands − Ford, Airtel, Axis Bank, Air India, Café Coffee Day by Coffee Day Global Ltd., Lifestyle fashion retailing by Landmark, ICICI Prudential Life Insurance, etc. These brands portray their entire image, such as the company’s value, competency, vision, motives, missions, products/services etc. through web to the online consumer. EBrands work to create a direct relationship between the brand owner and the customer via Internet. Due to their wide reachability, it is easy for the e-brands to survive among competitors and gain reputation among consumers. The consumers are loyal to the sellers whose online commercial transaction schemes are familiar, tested, and established. When the e-Brands provide features such as facility to compare various products, listing products within a specified cost or feature segment, easy and reliable payment modes, then the e-Brands can make place in their consumers’ minds. Examples of e-Brand − Flipkart, Amazon, etc. Countries, like companies, apply branding to help themselves market for investment, tourism, and exports. The ‘Country of Origin’ is commonly referenced by the term ‘Made in...’ which depicts an association with the product’s place of origin, which works as effectively as product quality. Consumers are aware of the origin of the product and ethics used behind creating that product. Some associations of countries and products are France = fashion, wine, and cheese, Italy = design, India = spices, Denmark = chocolate, Germany = automotive, Japan = electronics, etc. Today, the brands apart from being associated with their countries also need to show their strong connection with the country such as having a manufacturing setup in the country, influx of designs emerging from the talent present in the country, or having a part of production process set up in that country. For the simple reason, the consumers are more likely to buy the product or service if they are authentic. The brand managers need to emphasize on such points while branding. The Country Brand Index (CBI) measures and ranks the countries on the strength and power of their nation’s brand. Examples of brand messaging by some countries − “Botswana Our pride, your destination.”, “Canada – Keep exploring”. Brand equity is the heart of brand management. The brand managers are engaged in building strong brand equity as it directly affects the consumer’s buying decisions, defines market share of the product, and determines the brand position in the market. Strong brand equity can not only make the brand strong but also help the brand establish, survive, and perform well in the long run. Let us understand, what brand equity is and why it matters. This term came up in the marketing literature in 1980. This multidimensional concept has different meanings from the context of Accounts, Marketing, and Consumer. Accounting Context − It is a total value of a brand as a separable asset, when evaluated for selling. It is also called Brand Value. It is quantifiable. Accounting Context − It is a total value of a brand as a separable asset, when evaluated for selling. It is also called Brand Value. It is quantifiable. Marketing Context − It is the description of consumer’s associations and beliefs about the brand. It is non-quantifiable. Brand equity is tailored according to the needs and demands of the consumer. Marketing Context − It is the description of consumer’s associations and beliefs about the brand. It is non-quantifiable. Brand equity is tailored according to the needs and demands of the consumer. Consumer-based Context − It is a measure of consumers’ attachment to a brand. It is also called brand strength or loyalty. It is quantifiable. Consumer-based Context − It is a measure of consumers’ attachment to a brand. It is also called brand strength or loyalty. It is quantifiable. As per Amber and Styles (1996), Brand Equity is a store of profits which can be realized in future. For brand management, the brand equity is vital as it establishes and fosters the customer loyalty towards the brand, and directly influences the business growth may it be a well-established or a new business. There can be two motivations to study brand equity − Finance-based motivation − You can estimate the brand value more precisely for accounting purposes, such as to evaluate the brand as an asset for the purpose of reflecting in the balance sheet, or in case of merging or acquiring a business. Finance-based motivation − You can estimate the brand value more precisely for accounting purposes, such as to evaluate the brand as an asset for the purpose of reflecting in the balance sheet, or in case of merging or acquiring a business. Strategy-based motivation − You can study brand equity to improve productivity of marketing. Strategy-based motivation − You can study brand equity to improve productivity of marketing. It is a progressive loss of brand integrity due to weakening of essential brand elements. It also includes losing the respect of consumers and consistency of the brand. It is a gradual process. For example, a number of US airlines are facing brand decay since years. Here are some most important reasons of brand decay − Company fails to manage strategies, create new value, and acquire new customers or new marketplaces. Company fails to manage strategies, create new value, and acquire new customers or new marketplaces. Company treats the brand merely as a static asset than as a medium to create customer value. Company treats the brand merely as a static asset than as a medium to create customer value. Customer expectations are more than what a brand can deliver. Customer expectations are more than what a brand can deliver. Presence of issues in brand equity building. Presence of issues in brand equity building. Company palms off brand-customer relationship on customer service department. Company palms off brand-customer relationship on customer service department. Company halts innovations in products or services. The worst part is, customers start suggesting innovations. Company halts innovations in products or services. The worst part is, customers start suggesting innovations. David Aaker and Kelvin Lane Keller developed the brand equity models. Let us learn about both the models. David Aaker defines brand equity as a set of assets and liabilities linked to a brand that add value to or subtract value from the product or service under that brand. He developed a brand equity model (also called Five Assets Model) in which he identifies five brand equity components − The following factors depict the extent to which customers are loyal to a brand − Reduced Costs − Maintaining loyal customers is cheaper than charming new ones. Reduced Costs − Maintaining loyal customers is cheaper than charming new ones. Trade Leverage − The loyal customers generate steady source of revenue. Trade Leverage − The loyal customers generate steady source of revenue. Bringing New Customers − Existing customers boost brand awareness and can bring new customers. Bringing New Customers − Existing customers boost brand awareness and can bring new customers. Competitive Threats Response Time − Loyal customers take time to switch to a new product or service offered by other brand. Hence this buys time for the company to respond to competitive threats. Competitive Threats Response Time − Loyal customers take time to switch to a new product or service offered by other brand. Hence this buys time for the company to respond to competitive threats. The following measures depict the extent to which a brand is widely known among consumers − Association Anchors − Depending upon the brand strength, associations can be attached to the brand which influence brand awareness. Association Anchors − Depending upon the brand strength, associations can be attached to the brand which influence brand awareness. Familiarity − The consumers familiar with a brand will speak more about it and thus, influence brand awareness. Familiarity − The consumers familiar with a brand will speak more about it and thus, influence brand awareness. Substantiality − Consumers’ review on brand brings substantial and strong commitment towards the brand. Substantiality − Consumers’ review on brand brings substantial and strong commitment towards the brand. Consumer’s Consideration − At the time of purchasing, consumer looks for a particular brand. Consumer’s Consideration − At the time of purchasing, consumer looks for a particular brand. It is the extent to which a brand is believed to provide quality products. It can be measured on the following criteria − Quality − The quality itself is the reason to buy. Quality − The quality itself is the reason to buy. Brand Position − This is a level of differentiation as compared to competing brands. Higher the position, higher is the perceived quality. Brand Position − This is a level of differentiation as compared to competing brands. Higher the position, higher is the perceived quality. Price − When quality of the product is too complex to assess and consumer’s status comes into picture, the consumer takes price as a quality indicator. Price − When quality of the product is too complex to assess and consumer’s status comes into picture, the consumer takes price as a quality indicator. Wide Availability − Consumers take widely available product as a reliable one. Wide Availability − Consumers take widely available product as a reliable one. Number of Brand Extensions − The consumers tend to take a brand with more extensions as a measure of product guarantee. Number of Brand Extensions − The consumers tend to take a brand with more extensions as a measure of product guarantee. It is the degree to which a specific product/service is recognized within its product or service category. For example, a person asking for Xerox wants to actually make true copies of a paper document. Information Retrieval − It is the extent to which the brand name is able to retrieve or process the associations from consumer’s memory. Information Retrieval − It is the extent to which the brand name is able to retrieve or process the associations from consumer’s memory. Drive Purchasing − This is the extent to which brand associations drive consumers to purchase. Drive Purchasing − This is the extent to which brand associations drive consumers to purchase. Attitude − This is the extent to which brand associations create positive attitude in the consumer’s mind. Attitude − This is the extent to which brand associations create positive attitude in the consumer’s mind. Number of Brand Extensions − More the extensions, more the opportunity to add brand associations. Number of Brand Extensions − More the extensions, more the opportunity to add brand associations. They are patents, copyrights, trademarks, trade secrets, and other intellectual property rights. More the number of proprietary assets a brand has, greater is the brand’s competency in the market. This model is developed by Kelvin Lane Keller, a marketing professor at Dartmouth College. It is based on the idea that the power of a brand lies in what the consumer has heard, learnt, felt, and seen as a brand over time. Hence this model is also termed as Customer Based Brand Equity (CBBE) model. According to CBBE model, it takes answers to four basic questions for building brand equity starting from the base of the pyramid shown above − Who are you? (Brand Identity) What are you? (Brand Meaning) What do I feel or think about you? (Brand Responses) What type and extent of association I would like to have with you? (Brand Relationships) It is not only how often and easily the consumer can recall or recognize the brand but also where and when he thinks of the brand. The key is to create brand salience to acquiring correct brand identity. According to Keller, to make the brand meaningful it is essential to create a brand image and characteristics. Brand meaning arises out of brand associations, which can be imagery-related or function-related. The imagery-related associations depict how well the brand meets social and psychological needs of the consumer. The function-related association such as product or service performance is what the consumer looks for primarily. Regardless of the type of product or service, developing and delivering the product that completely satisfies the customer’s needs and demands is the prime objective of making the brand meaningful. A brand with the right identity and meaning creates a sense of relevance in the consumer’s mind. The companies must cater for the consumer’s response. Keller segregates these responses into consumer’s judgments and consumer’s feelings. Consumer Judgments − They are consumer’s personal opinions regarding the brand and how he has put imagery-related and performance-related associations together. There are four types of judgments crucial for creating a strong brand − Quality Credibility Consideration Superiority Consumer Judgments − They are consumer’s personal opinions regarding the brand and how he has put imagery-related and performance-related associations together. There are four types of judgments crucial for creating a strong brand − Quality Credibility Consideration Superiority Consumer Feelings − They are consumer’s emotional reactions to the brand. They can be mild, intense, positive, negative, driven from heart or head. There are six important feelings crucial in brand building − Warmth Fun Excitement Security Social approval Self-respect Consumer Feelings − They are consumer’s emotional reactions to the brand. They can be mild, intense, positive, negative, driven from heart or head. There are six important feelings crucial in brand building − Warmth Fun Excitement Security Social approval Self-respect It is the level of personal identification the consumer has with the brand. It is also called brand resonance, when a consumer has a deep psychological bonding with the brand. Brand resonance is the most difficult and highly desirable level to achieve. Keller categorizes this into four types − Behavioral Loyalty − Consumers may purchase a brand repeatedly or in high volume. Behavioral Loyalty − Consumers may purchase a brand repeatedly or in high volume. Attitudinal Attachment − Some consumers may buy a brand because it is their favorite possession or out of some pleasure. Attitudinal Attachment − Some consumers may buy a brand because it is their favorite possession or out of some pleasure. Sense of Community − Being identified with a brand community develops kinship in the consumer’s mind towards representatives, employees, or other people associated with the brand. Sense of Community − Being identified with a brand community develops kinship in the consumer’s mind towards representatives, employees, or other people associated with the brand. Active Engagement − Consumers invests time, money, energy, or other resources and participates actively in brand chat rooms, blogs, etc., beyond mere consumption of brand. Thus, the consumers strengthen the brand. Active Engagement − Consumers invests time, money, energy, or other resources and participates actively in brand chat rooms, blogs, etc., beyond mere consumption of brand. Thus, the consumers strengthen the brand. BrandZ is the world’s largest brand equity database created and updated by Millward Brown, a multinational company working in advertising, marketing communications, media, and brand equity research. This database was created in 1998 and is being updated continuously since then. It lists top 100 global brands since 2006. To compile this database, the raw data is collected from about two million consumers and professionals across more than 30 countries. It lists around 23000 brands. BrandZ is the only brand valuation tool that helps brand owners to find out how much brand alone can contribute to corporate value. Brand asset valuation evaluates a brand’s value, strength, and performance as compared to other brands in the market. An agency named Young and Rubicam developed a metric called Brand Asset Valuator (BAV), which measures brand vitality, which is the brand’s potential in terms of its future growth and brand power. The brand is analyzed in the following terms − Differentiation − How different and better is the brand from its competitors? Differentiation − How different and better is the brand from its competitors? Relevance − How closely the target audience can relate with the brand offer? Relevance − How closely the target audience can relate with the brand offer? Esteem − Has the brand built its esteem by keeping all promises it made to the target audience? Esteem − Has the brand built its esteem by keeping all promises it made to the target audience? Knowledge − How many of the target audience know the brand? Knowledge − How many of the target audience know the brand? Brand equity, being the heart of brand management is very. Peter Farquhar, in a paper he published on Managing Brand Equity, suggests three stages in building strong brand identity − Introduce − Introduce an innovative and quality product in the market. Use brand as a platform to launch future products. Customer’s positive recognition is very important. Introduce − Introduce an innovative and quality product in the market. Use brand as a platform to launch future products. Customer’s positive recognition is very important. Elaborate − Create brand awareness and associations so that the customers remember the brand and the positive opinions about it for a long time. Elaborate − Create brand awareness and associations so that the customers remember the brand and the positive opinions about it for a long time. Fortify − Make the brand create a positive consistent image in the customer’s mind. Develop brand extensions and create customer-brand emotional relationship to fortify the brand. Fortify − Make the brand create a positive consistent image in the customer’s mind. Develop brand extensions and create customer-brand emotional relationship to fortify the brand. In the contemporary market, three essential characteristics are required to manage the brand − brand identity, brand image, and brand positioning. Brand identity is nothing but the belief fostered by the brand, its uniqueness and key values. A brand has an identity when it is driven by a goal different from competing brands and is resistant to changes. A strong brand identity can be built when you have answers to these questions − What is the brand’s unique aim? What is the brand’s distinguishing feature? What need is satisfied by the brand? What are brand’s values? What is the brand’s field of competence? What is making the brand recognizable? Brand image is the set of beliefs, real and imaginary shortcomings about the brand developed over a time and held in the consumer’s mind. Brand image is built using communication media such as advertising, publicity by mouth, packaging, online marketing programs, social media, and other ways of promotions. When the company portfolio is growing, the brands tend to evolve. It is critically important to define the structure of the brands within a portfolio to keep the brand health strong. The brand managers need to take various decisions such as considering the right time to extend the existing brand, selecting appropriate brand name, whether or not to have different websites for multiple brands and so on. Since each of such decisions has direct implications on the future, a plan for brands is developed to provide clarity to the consumers. Brand architecture comes in play while presenting the brand efficiently. Let us learn more about brand architecture. It is the structure of the brand in an organizational entity that defines how various brands and sub-brands in a company’s portfolio are related to each other or are different from one another. Brand architecture provides a hierarchy that depicts the roles and relationships within the products and services that make a company’s portfolio and makes sure that the external stakeholders understand the value of what the brands offer. They can be varied from pure to hybrid. However, generally brand architecture is distinguished into two categories − House of brands and Branded house. Product Brand Range Brand Line Brand Endorsing Brand Umbrella brand Source brand Master brand Multiple brands or activities are brought together under a single name. There is complete freedom for the management of divisions, activities and the brands. For example, Mitsubishi Motors division and Mitsubishi Electricals division are completely unrelated except the fact that they come under Mitsubishi business. Both divisions manage their own advertising, and brand values, and obtain separate profits. It is a family of brands with high degree of unity. Here, the master brand structures the child brands in such a manner that they are capable of expressing the value of a parent brand. Master brand is the single brand acting as a driving force. For example, Google. Google books, Google maps, Google Translate, Google Mail, etc., all come under the master brand Google and only differentiate in their descriptions. Let us see the brand architecture strategies in detail − The brand is a kind of product brand, if the corporate brand name is hidden and every product is assigned a different name and one single positioning. Each new product is a new brand. In this type, the company name is well known and guarantees the quality of the products. For source brand, the products are on the forefront, while the company name remains in the background. When a variant is added to the existing brand, it is called line extension. The variant can be anything from color, packaging, nutritional value addition, or a new shape. Line brand targets a subset of the consumers. For example, Cadbury Bournville comes in three flavors − Raisin & Nut, Rich Cocoa, and Cranberry. Likewise Dairy Milk Silk comes in Orange Peel, Roast Almond, and Fruit & Nut variants. This is the simplest type, where all units and divisions of a business share the same brand. The brand name is used for different but related products. It involves creating a brand equity for a single brand. It is also referred to as Corporate, Umbrella, or Parent brand. In this type, the product or service benefits are less important than brand promise. It drives purchase decisions and defines consumer experience. Here, a parent brand consists of various operating units which are identified by their own brands. The parent endorses the products or services under itself and has a clear market presence. There is a synergy between the product name and the parent name. This architecture provides credibility, approval, and guarantee to another brand. For example, Marriot Residence Inn, Courtyard, and Fairfield Inn. In this type, all or many brands are kept with separate identities, names, and life cycles of their own. They often compete with each other. The parent does not provide any brand equity to benefit the sub-brands. This structure is found in FMCG companies. In this architecture, a principle brand supports to qualify other brands. The idea is, if the ingredient is good, it amplifies the brands better than they would have amplified independently without the ingredient. Thus, the ingredient brands turn out as energizer. For example, Intel Inc. Any computer brand’s ad says “Intel Inside”, depicting Intel processor enabled motherboard that comes with high power and speed of execution. It is a combination of monolithic, endorsement, and portfolio architectures. These are the most common solutions. Brand architecture needs to be revised when the companies change their strategies or the business has added important features which are beyond the existing brand structure. The following parameters should be considered while choosing an appropriate branding strategy − Marketing strategy Business model Culture Speed of innovation Added-value lever on which the product is based Brand vision Since most of the brand architectures are built over a substantial period of time in the domestic market, there are some all-time questions while launching the brand on the global canvas − Should the brand architecture be globalized? Should the brand architecture be globalized? Can the present brand architecture be taken to the new potential countries? Can the present brand architecture be taken to the new potential countries? How to handle internationalizing of brand architecture in different countries when there is difference in their respective infrastructure, civic rules and regulations, media costs, to name a few? How to handle internationalizing of brand architecture in different countries when there is difference in their respective infrastructure, civic rules and regulations, media costs, to name a few? For instance, it is definite that taking a brand architecture to Russia could be smoother than taking it to the US as the media and distribution costs are higher in the US. If a brand architecture is not proper, it can lead to unwelcome consequences. Few instances are as follows − When there are too many daughter brands, the parent brand loses the focus. In the bargain of achieving recognition for the daughter brand, the parent brand takes a backstep. While launching a daughter brand, it gets people’s attention and the daughter brand attracts all the investment on the advertisement. It gets remarkably successful thereby taking over the image of the parent brand. The solution to this is, turn daughter brand into a simple product. For example, Golf, the daughter brand of Volkswagen swallowed it up in image. Amul Lite, a daughter brand is swallowing parent brand Amul butter due to increased health-consciousness of consumers. The company makes innovative products or makes improvements in the existing product. When a superior product comes up, it is time to decide for the brand managers whether to extend the new product as a part of the original brand or launch it as a new product with a potential of becoming a brand in itself. While branding the new product out of innovation, the connection between the product and the company that develops it should not be weakened. The company grows by bringing out the best in its product. Every time a research and development team comes up with the innovative product, the brand managers have to decide on what to name that ‘new’ product. For example, a cement manufacturing company came up with an innovative cement that provides extremely smooth surface. Before introducing it into the market, brand managers need to be decide what to name the product. Is it fine to extend the name just as ‘new ultra smooth cement from...’? Or should it be given a name that can stand as a brand in itself later? Brand name is the mightiest form of its identity. It tells the objective of the program and reveals brand intentions. Some brand names and products apparently seem irrelevant. As in case of ‘Apple’, the microcomputers brand, Steve Jobs and the co-founder Steve Wozniak chose this name with the logo of a munched apple as they intended to give a new look to the conventional human-machine relationship. The apple logo tells that a computer machine is something to enjoy, rather than to fear about. Similarly, Amazon logo with a directed arrow from a-to-z depicts range, continuity, strength, and uninterrupted flow. Thus, to make a strong brand, almost any name can be chosen, with the fact that the brand managers need to put consistent efforts in making the brand name meaningful. Brand name is not a product. Hence while selecting brand name for a new product, the names which differentiate the product among its competitors must be chosen instead of those that describe what the product does. Instead of working behind a logo or a brand name, the companies have started coming up as brands themselves called corporate brands. They are choosing to become as widely visible as possible out of the consumer’s demand of responsibility and transparency. By presenting itself under corporate brand profile, the companies can attract students and executives in the employment market. In Asia, at the end of Procter and Gamble television ad, company signature is displayed for a few seconds as it is already visible and established as a corporate brand. In the US the P&G experience is different and it needs efforts to make itself more visible. Few companies have preferred to keep their own names separate from their brand names for the reason of getting affected in case of brand failure. There are other reasons of corporate visibility over product visibility. The multi-brand retailers, hyper chains are interested in corporate visibility of a company rather than product brands they sell as their basic B2B relation is with companies and not with brands. In today’s market, the customer has a very wide choice of products. When it comes to brands, he chooses brands but he tends to compare the products of different brands. Products increase customer’s choice whereas brands simplify decision making. To influence the customer’s buying decision and to get hold of the competitor’s market share, brand identity and positioning are essential. Brand management works with these two fundamental tools, brand identity and brand positioning. Let us understand these terms − It specifies that a brand has a goal that is different from the goals of other parallel brands in the same market segment and it has resistance to change. It is defined clearly and does not change over time. Brand identity is fixed in nature being tied to the fixed parameters such as brand’s vision, objective, field of competence, and overall brand charter. Brand positioning is emphasizing on the distinguishing characteristics of the brand, those that make the brand appealing to the consumers and stand out among its competitors. It specifies how the products of a brand penetrate the market to grow their market share while dealing with the competitor brands. Brand positioning is competition oriented and hence dynamic over a period of time. Brand identity can be represented by six faces of a hexagon or a prism as shown below − Brand Physique − It is the tangible and physical added value, as well as the backbone of a brand. It considers physical aspect of brand: How does it look, what does it do, the flagship product of the brand, which represents its qualities. For example, the dark color of Coke and colorless Sprite. Brand Physique − It is the tangible and physical added value, as well as the backbone of a brand. It considers physical aspect of brand: How does it look, what does it do, the flagship product of the brand, which represents its qualities. For example, the dark color of Coke and colorless Sprite. Brand Personality − If a brand were a person, what kind of person it would be? Would it be sincere (TATA Salt), exciting (Perk), rugged (Woodland), sophisticated (Mercedes), elite (Versace)? The brand has personality which speaks for its products and services. When a famous character, spokesperson, or a figurehead is used for branding, it gives the brand an instant personality. Brand Personality − If a brand were a person, what kind of person it would be? Would it be sincere (TATA Salt), exciting (Perk), rugged (Woodland), sophisticated (Mercedes), elite (Versace)? The brand has personality which speaks for its products and services. When a famous character, spokesperson, or a figurehead is used for branding, it gives the brand an instant personality. Culture − It is the set of values that governs and inspires the brand. Countries of origin, presence of brand over geographically diverse regions, changing society, etc., play an important role in building a brand’s culture. Culture − It is the set of values that governs and inspires the brand. Countries of origin, presence of brand over geographically diverse regions, changing society, etc., play an important role in building a brand’s culture. Customer Self-Image − It is what the brand is able to create in the customer’s mind and how the customers perceive about themselves after purchasing the product of a brand. Customer Self-Image − It is what the brand is able to create in the customer’s mind and how the customers perceive about themselves after purchasing the product of a brand. Customer Reflection − It is the perception of a customer about the brand after using the brand. For example, “The Thunderbird I purchased is value for price. It is giving me pleasure of leisure riding. Thanks to Royale Enfield.” Customer Reflection − It is the perception of a customer about the brand after using the brand. For example, “The Thunderbird I purchased is value for price. It is giving me pleasure of leisure riding. Thanks to Royale Enfield.” Relationship − Brands communicate, interact, transact with the consumer. It is the mode of conduct that defines the brand. This factor is vital for service brands. For example, banking where the cordial relationship develops faith in the customers when it comes to handling their money with respect. Relationship − Brands communicate, interact, transact with the consumer. It is the mode of conduct that defines the brand. This factor is vital for service brands. For example, banking where the cordial relationship develops faith in the customers when it comes to handling their money with respect. Let us consider the example of brand identity prism for Garnier’s BB cream − Keller defines brand image as awareness of brand name (whether and when customers know the brand and can recall it) and belief about brand image (customer’s associations with the brand). If either of both is created successfully while leaving the other one in poor state, it brings down the brand drastically. For example, Salman Khan is a brand in himself with very high awareness. But his image went bad due to the hit-and-run case and that spoiled his reputation. Creation of Brand knowledge is a collective effort of consumer, marketer, researchers, distributors, and ad agencies. Creating brand knowledge is extremely important for the company’s stakeholders. There can be a single brand portfolio or multiple brand portfolios. The companies decide courageously to create a new brand for its growth when the existing brand does not perform satisfactorily. There is a wide variety of consumers in terms of their behavior, economic status, tastes, genders, age groups, and preferences. If the market segmentation is too diverse, it becomes hard for a single brand to meet the demand of maximum consumers. Thus, the main objective of creating a multi-brand portfolio is to meet the demands of the segmented market in a better way. To avoid the conflicts with the existing brand and the market segment, the companies are inclined towards creating a new brand each time it ventures into a new market segment. A multi-brand portfolio covers large market segment and can stop entry of any new competitor in the market. Place and operate the brands within a portfolio with strong coordination. Place and operate the brands within a portfolio with strong coordination. Set clear and precise charter and identity for each brand. Set clear and precise charter and identity for each brand. Build strong brand architecture. Position the brands to increase their appropriateness and target market. Build strong brand architecture. Position the brands to increase their appropriateness and target market. Focus on a particular competitor for each brand. Focus on a particular competitor for each brand. Keep corporate organization and brand portfolio matched. Keep corporate organization and brand portfolio matched. Brand stays in the minds of consumers and helps the company to grow their market share and revenue. Here are few basic steps to build a strong brand − Study the market, need of the hour, competitors, and target audience. Study the purpose of what you wish to accomplish through the brand. Study the market, need of the hour, competitors, and target audience. Study the purpose of what you wish to accomplish through the brand. Decide brand personality, culture, and profile. Think of distinctive features to stand out from the competitors. Decide brand personality, culture, and profile. Think of distinctive features to stand out from the competitors. Identify how the stakeholders perceive the brand. Bridge the perception gaps. Identify how the stakeholders perceive the brand. Bridge the perception gaps. Decide where you want the brand to position in the market. Decide where you want the brand to position in the market. Create a plan and work on strategies where you want to place the brand. Create a plan and work on strategies where you want to place the brand. Communicate the brand to consumers via TV ads, social media, online marketing, etc. Communicate the brand to consumers via TV ads, social media, online marketing, etc. Make sure the consumers remember the brand. Make sure the consumers remember the brand. Evaluate if the consumers are influenced in a right way and if you have accomplished the purpose. Evaluate if the consumers are influenced in a right way and if you have accomplished the purpose. To identify brand positioning, the brand manager needs to study the market segment of venture. To establish a strong brand positioning, you need to get clear answers to the following questions − Brand for what benefit? For example, The Body Shop uses natural ingredients in its products and is environment-friendly. Tropicana packs real fruit juices in tetra packs, etc. Brand for what benefit? For example, The Body Shop uses natural ingredients in its products and is environment-friendly. Tropicana packs real fruit juices in tetra packs, etc. Brand for whom? It is the target audience of the brand grouped as gender, age, economic bracket, etc. For example, while Nike is top clothing brand for all income group, Gucci and Fossil remain high income handbags brands. Brand for whom? It is the target audience of the brand grouped as gender, age, economic bracket, etc. For example, while Nike is top clothing brand for all income group, Gucci and Fossil remain high income handbags brands. Brand for what reason? These are the facts that support claimed benefits. Brand for what reason? These are the facts that support claimed benefits. Brand against whom? This defines the way to attack competitors’ market share. Brand against whom? This defines the way to attack competitors’ market share. There is a standard formula to achieve brand positioning − For ... (target market of potential buyers or consumers) Brand X is ... (definition of frame of reference and category) Which gives the most ... (promise or consumer benefit) Because of ... (reason to believe) Where, The target market is the psychological and social profile of the consumers a brand aims to influence. The target market is the psychological and social profile of the consumers a brand aims to influence. Frame of reference is the nature of competition. Frame of reference is the nature of competition. Promise or consumer benefit is the feature that creates preference and drives decision after making choice. For example, Cadbury promises its Silk chocolate bars to be the smoothest ones among other Cadbury chocolate bars. Promise or consumer benefit is the feature that creates preference and drives decision after making choice. For example, Cadbury promises its Silk chocolate bars to be the smoothest ones among other Cadbury chocolate bars. The reason to believe is reinforcement of promise or consumer benefit. For example, Tropicana Products, the producer and marketer (a division of PepsiCo), promises to be delivering 100% pure fruit juices in its Pure Premium juices range. The reason to believe is reinforcement of promise or consumer benefit. For example, Tropicana Products, the producer and marketer (a division of PepsiCo), promises to be delivering 100% pure fruit juices in its Pure Premium juices range. Let us take an example of brand positioning conducted by Shoppers Stop, the retail chain in India that sells retail clothing, handbags, jewelry, perfumes, toys, home furnishing, and accessories. It has business of 20 billion dollars. It was founded in 1991 with first store at Mumbai and expanded rapidly across the country soon. The consumers perceived it as mass market brand and it started losing its shine in the retail competition in 2008. The brand managers and company management together carried out a store audit at all outlets, studied customer experiences, updated brand identity, and came up with new tagline, “Start something new”. It then repositioned the brand as premium, accessibleluxury sector. This position of bridge-to-luxury appealed young, middle-class consumers in India, who had their own money to spend at a young age. The new repositioning also added the credibility of Shoppers Stop to preset itself as a potential partner for international brands who were looking to enter the Indian market. The impact was, its share price grew 450% from 52-week low, sales rose more than 10%, and as newly acquired strength of positioning the brand, it started co-branding with international brands such as Chanel, Dior, Armani, Esprit, Tommy Hilfiger, Mothercare, Mustang, Austin Reed, and so on. Consumers are interested in brand values. When the consumer understands the brand value, he can interact with the business in a particular way. For defining and establishing brand values, you need to take an honest look at the product or service. You can proceed by using the following steps − Step 1 − Find out the answers for the following questions − What unique and competing feature my product/service has? Why should the target audience take interest in my product/service? What is my passion being a product manufacturer/service provider? Step 2 − Compile a list of values related to the product/service, such as − Simplicity Quality Affordability Timeliness Politeness Integrity Creativity Innovation Commitment Step 3 − Narrow down the list of values. Bring down the list of values which are absolutely indisputable for execution of your business. Recommended number of values is three to four. For example, if your brand’s value is timeliness then make sure you keep the promise of shipping and delivery of products always on time, handle and reply to your customer inquiries in timely manner, attend the customer’s call in the shortest possible time etc. Make sure that the value is always consistently honored, despite any internal or external situation. Step 4 − Use the list as a reference. Use the list of brand values while creating new products or services, dealing with clients, consumers, and partners. Venturing into global markets is inevitable for brands. A brand is global when it is visible and sold at every possible place in the world. The consumer around the world become aware of various international brands if they travel worldwide or just watch a satellite television at home. Before you take the brand in the global market, you need to cater to various aspects of the global consumer such as − Culture of Consumers − The values the consumers follow The customs they observe Particular symbols and language they use The tone of their behavior Consumer’s level of income and buying power Economic status of the country in terms of − Power supply Infrastructure Communication systems Distribution systems Laws and Regulations enforced − Is it lawful there too? Political stability of the country When the brand transits from local to global, it competes with other global brands. For example, Nokia battles Motorola and Samsung. The brand managers must manage the transnational brand to remain superior on the essentials such as the brand’s price, performance, features, and imagery. Brand promotion is the way to inform, remind, persuade convincingly, and influence the consumers to drive their decision towards purchasing the product or service under a brand. Marketing force of a company conducts brand promotion primarily, though the wholesalers and retailers also can do it. Brand promotion is required to − Promote information related to features, prices, and special schemes of the brand. Promote information related to features, prices, and special schemes of the brand. Differentiate the product by convincing the customers about the unique features of the brand. Differentiate the product by convincing the customers about the unique features of the brand. Create and increase the demand for the product. Create and increase the demand for the product. Build brand equity. Build brand equity. Stabilize the sales affected by natural, social, or political changes. For example, Nescafe promoted its new brand of 'iced coffee' to increase sales during summer. Stabilize the sales affected by natural, social, or political changes. For example, Nescafe promoted its new brand of 'iced coffee' to increase sales during summer. Outperform the competitor’s marketing efforts: In a highly competitive market, even a well-established brand has to be promoted to retain market share. For example, Coca Cola and Pepsi work to nullify each other's efforts. Outperform the competitor’s marketing efforts: In a highly competitive market, even a well-established brand has to be promoted to retain market share. For example, Coca Cola and Pepsi work to nullify each other's efforts. Build positive brand image. Build positive brand image. There are various brand promotion methods conducted to keep the brand noticeable − Organizing Contests − To attract the consumers, various contests are organized for consumers without having them to purchase the product and giving away gifts or prizes. Organizing Contests − To attract the consumers, various contests are organized for consumers without having them to purchase the product and giving away gifts or prizes. Promotion on Social Media − When the brand is promoted on social media, it is not perceived as “aggressively trying to sell”, rather as being able to communicate at a more personal level. Promotion on Social Media − When the brand is promoted on social media, it is not perceived as “aggressively trying to sell”, rather as being able to communicate at a more personal level. Product Giveaways − This strategy is used for promoting edibles, toiletries, foods, etc., where a small sample is given away to the consumers for free trial. Product Giveaways − This strategy is used for promoting edibles, toiletries, foods, etc., where a small sample is given away to the consumers for free trial. Point-of-Sale Promotion − These items are placed near the checkout counter in the store and are often purchased by consumers on impulse as they wait to be checked out. Point-of-Sale Promotion − These items are placed near the checkout counter in the store and are often purchased by consumers on impulse as they wait to be checked out. Customer Referral Incentive Programs − This is a way to bring new customers with the help of the existing customers by offering some incentives to the existing customers. Customer Referral Incentive Programs − This is a way to bring new customers with the help of the existing customers by offering some incentives to the existing customers. Causes and Charity − Some percent of the amount after selling the product is donated for a cause or charity thereby promoting the product. Charity and cause are the reasons which induce the feelings of helping in the customers. Causes and Charity − Some percent of the amount after selling the product is donated for a cause or charity thereby promoting the product. Charity and cause are the reasons which induce the feelings of helping in the customers. Promotional Gifts − It is giving away of gifts which the customers can practically use, such as caps, key chains, pens, etc. This helps the brand to always remain with the customers and creates an emotional attachment. Promotional Gifts − It is giving away of gifts which the customers can practically use, such as caps, key chains, pens, etc. This helps the brand to always remain with the customers and creates an emotional attachment. Customer Appreciation − It is organized with the objective of not selling the product or service. It is a way of creating a fond memory attached with the brand. It includes organizing in-store refreshment events with the offer of food treats of pizza, burger, beverages, etc. It is an effective way to bring new potential customers. Customer Appreciation − It is organized with the objective of not selling the product or service. It is a way of creating a fond memory attached with the brand. It includes organizing in-store refreshment events with the offer of food treats of pizza, burger, beverages, etc. It is an effective way to bring new potential customers. Another way of promoting brands is by employing a brand ambassador. A brand ambassador is a person who embodies the brand, influences the customers, creates brand awareness and a specific brand image, and generates sales opportunities. A brand ambassador usually represents only one brand at a time. The employing company considers the brand ambassador as a face of the company that speaks of the brand in their own words and boosts the positive image in the minds of consumers. The looks, talents, status, achievements, and reputation of a brand ambassador is useful for influencing large audience of consumers. In 2003, India’s largest chocolate brand, Cadbury went into worm controversy. To regain the consumer’s confidence, Cadbury contracted the Bollywood superstar Mr. Amitabh Bachchan for brand promotion. During his campaign, Cadbury not only restored the trust of consumers but also experienced boost in the sales of its flagship product Cadbury Dairy Milk (CDM). Celebrity branding is nothing but using celebrities to promote the brand. The celebrities are featured in both electronic and print media ads. They appear at brand launches, corporate events for social responsibility, and other such events. Celebrity brand endorsers are different from brand ambassadors as the former are not employed by the company as the latter. The popularity, fame, and charisma of the celebrities is useful in brand promotion. Celebrities can endorse multiple brands at the same time unlike brand ambassadors. Similarly, a company can have multiple celebrities to promote its brand. Online brand promotion comes with the challenge of integrating the marketing mix (putting the right product, at the right price, at the right time) with the multi-channel, multi-device digital marketing. Online brand promotion leverages the power of Internet to present the brand to worldwide audience. But it is a kind of double-edged sword as whatever good a brand has can reach globally so does the brand’s weaknesses. There are various ways to promote a brand online. Such as Publishing articles, news, spreading business links throughout the web, channeling the promotional schemes and ads towards the target audience, creating and updating the blogs and the forums. Publishing articles, news, spreading business links throughout the web, channeling the promotional schemes and ads towards the target audience, creating and updating the blogs and the forums. Creating and sharing videos, audios, and pictures of the brand on top ranking websites such as YouTube. Creating and sharing videos, audios, and pictures of the brand on top ranking websites such as YouTube. Creating the company’s business account on leading social networking websites such as Facebook, LinkedIn and promoting the brand by gaining new followers. Creating the company’s business account on leading social networking websites such as Facebook, LinkedIn and promoting the brand by gaining new followers. Engaging in social gaming such as Zynga, Kongregate, etc., under the name of the brand. Engaging in social gaming such as Zynga, Kongregate, etc., under the name of the brand. Brand extension is required for a company’s growth, profitability, and brand’s added reputation. It is an inevitable strategic move at some point of time in brand management. While extending a brand, all assumptions related to that brand held for a long time are revised and the brand’s identity is redefined. The brand managers need to identify growth opportunities and increase parent brand’s value. It is nothing but launching a product in a different category under an already established brand name. It is extending the existing brand promise with diverse products or services. The following diagram shows the matrix of brand growth. When a company introduces a new product, it has the following choices − New Brand, New Product (New Brand) New Brand, New Product (New Brand) New Brand, Existing Product (Multi-Brand) New Brand, Existing Product (Multi-Brand) Existing Brand, New Product (Brand Extension) Existing Brand, New Product (Brand Extension) Existing Brand, Existing Product (Line Extension) Existing Brand, Existing Product (Line Extension) The last two in the above list are the types of brand extensions. A variation of existing product launched under the existing brand. It often adds different flavor, package size or shape. Here, established brand is the parent brand. For example, Coke is basic brand with Diet Coke as extension. A new product is launched under existing brand. It often adds a product of different category. The new associated brand is a sub-brand. For example, ITC brand with Sunfeast cookies, Vivel shampoo, Bingo chips as its sub-brands. In 1994, Titan Industries Ltd. extended the brand Tanishq, India’s only national jewelry brand. Let us see yet another excellent example of systematic brand extension, Nivea. Just like product launching, brand extension demands time, resource allocation, energy, and associated risks. When the brand is exposed into unknown market, it might face dominance among established competitors. In addition, the brand image can come into trouble too. Bypass efforts, time, and cost for developing a new brand. Leverages the reputation attached to the parent/family brand. Saves costs on follow-ups and introductory marketing programs. Reduces perceived risk of customer about the product. Elevates the parent brand image. On failure, brand extension can hurt the parent brand image. It can cannibalize parent brand if the sub-brand is more successful than parent brand. Creates confusion among customers if not communicated appropriately. Can dilute brand meaning. Brand adaption is nothing but introducing and engaging the consumer with the brand. It involves five steps − Awareness − Customer knows the brand but does not have complete information. Awareness − Customer knows the brand but does not have complete information. Interest − Customer tries to find more information on the brand. Interest − Customer tries to find more information on the brand. Evaluation − Customer tries to know how beneficial the brand would be. Evaluation − Customer tries to know how beneficial the brand would be. Trial − Makes first purchase to determine its usefulness or worth. Trial − Makes first purchase to determine its usefulness or worth. Adapt/Reject − Becomes a loyal customer or looks for some other parallel brand. Adapt/Reject − Becomes a loyal customer or looks for some other parallel brand. The brand adaption practices involves the following steps − Develop internal (brand managers and representatives) and external launching (consumer and prospects) of brand. Develop internal (brand managers and representatives) and external launching (consumer and prospects) of brand. Impart positive attitude towards the brand among sales managers and marketers. Impart positive attitude towards the brand among sales managers and marketers. Create high customer demands and expectations about the brand. Create high customer demands and expectations about the brand. Provide training for the sales and customer care force to practically deliver the brand promise. Provide training for the sales and customer care force to practically deliver the brand promise. There are various scenarios where a brand has successfully extended or failed to extend. For example, Bic ballpoint pens. It extended successfully into disposable razors but the extension into perfumes was a failure. The factors that influence acceptability of a brand extension are mainly − Perceived risk − It is the evaluation of uncertainty about the type and degree of expected loss after making the consumer makes a choice. Perceived risk − It is the evaluation of uncertainty about the type and degree of expected loss after making the consumer makes a choice. Consumer’s Innovativeness − Personal trait or desire of consumers to try a new brand/product and thereby experience something new. Consumer’s Innovativeness − Personal trait or desire of consumers to try a new brand/product and thereby experience something new. Product Similarity − Greater the degree of similarity of the extended product with the original product, more is the chance of transferring the positive effect. Product Similarity − Greater the degree of similarity of the extended product with the original product, more is the chance of transferring the positive effect. Parent Brand Reputation and Strength − Brand’s reputation is associated with the consumer’s perception of the quality of the brand. Strong and reputed brands leverage extension than weak brands. Parent Brand Reputation and Strength − Brand’s reputation is associated with the consumer’s perception of the quality of the brand. Strong and reputed brands leverage extension than weak brands. A company requires to rebrand when it decides to change any of its brand elements such as brand name, logo, slogan, or even a small change in the message for better communication and more relevant brand promise. Rebranding is extremely important, expensive to execute, and risky. There are multiple reasons behind why companies initiate rebranding. These reasons can be categorized into two types − proactive or reactive. Let us take a deeper look. It happens when a company anticipates and prepares for future changes in the market. To prevent or prepare for future potential threats by competitors. To prevent or prepare for future potential threats by competitors. To plan for international growth, rebranding the products and services into a consolidated brand thereby saving money over time and creating a greater sense of brand unity. To plan for international growth, rebranding the products and services into a consolidated brand thereby saving money over time and creating a greater sense of brand unity. To enter into a category of business, product, or market which no longer remains cohesive to the existing brand identity. In case of Apple Inc., as the company evolved into new businesses beyond computers, the original brand name Apple Computers became too restrictive. It was then changed to Apple Inc. At the same time, Apple Inc. updated its logo depicting its progress. To enter into a category of business, product, or market which no longer remains cohesive to the existing brand identity. In case of Apple Inc., as the company evolved into new businesses beyond computers, the original brand name Apple Computers became too restrictive. It was then changed to Apple Inc. At the same time, Apple Inc. updated its logo depicting its progress. To attract new audience, or want to appeal to it. In case of McDonald’s ads, it refers to itself as McDonald’s to target a different demographic from its traditional audience. To attract new audience, or want to appeal to it. In case of McDonald’s ads, it refers to itself as McDonald’s to target a different demographic from its traditional audience. To increase the brand relevance in consumer’s mind, the company might decide to rebrand. For example, when the use of printed Yellow Pages directories started declining, Yellow Pages rebranded to YP. To increase the brand relevance in consumer’s mind, the company might decide to rebrand. For example, when the use of printed Yellow Pages directories started declining, Yellow Pages rebranded to YP. This branding occurs when the companies need to react to a significant change. Reactive rebranding might happen in the following situations − When companies need to work on negative brand image. For example, during 1990-2000, the London based men’s clothes making company Burberry’s public image was associated with hooliganism and violence. The brand had lost its image so badly that the clubs and pubs in UK had started banning entry for the people wearing Burberry. The company worked to disassociate itself from such an image by changing styles of the product, changing their logo, and applying excellence in everything. When companies need to work on negative brand image. For example, during 1990-2000, the London based men’s clothes making company Burberry’s public image was associated with hooliganism and violence. The brand had lost its image so badly that the clubs and pubs in UK had started banning entry for the people wearing Burberry. The company worked to disassociate itself from such an image by changing styles of the product, changing their logo, and applying excellence in everything. When companies merge or acquire other companies, or when they separate. For example, California based Intel rival and chipmaker, Advanced Micro Devices (AMD) is considering to split shortly. When companies merge or acquire other companies, or when they separate. For example, California based Intel rival and chipmaker, Advanced Micro Devices (AMD) is considering to split shortly. When there are legal issues with branding. Trademarks are often the root cause for rebranding. For example, an Australian business tries to expand into USA and finds that its existing name is already trademarked and not available for use in USA. When there are legal issues with branding. Trademarks are often the root cause for rebranding. For example, an Australian business tries to expand into USA and finds that its existing name is already trademarked and not available for use in USA. When a competitor manifests a company’s brand as useless or outdated, then rebranding helps to get an opportunity to facelift the brand to effectively strike back in the market. When a competitor manifests a company’s brand as useless or outdated, then rebranding helps to get an opportunity to facelift the brand to effectively strike back in the market. When changes take place in business regulations, laws, competitors, etc. When changes take place in business regulations, laws, competitors, etc. When a company lands up into a significant controversy or negative publicity, it considers rebranding to rebuild the trust of consumers and stakeholders. It cuts up all the ties with the issues in picture and moves on with the new form of brand. When a company lands up into a significant controversy or negative publicity, it considers rebranding to rebuild the trust of consumers and stakeholders. It cuts up all the ties with the issues in picture and moves on with the new form of brand. Relaunching a brand is reintroducing a brand into the market. Relaunching implies that a company was marketing the brand but stopped doing so for some reasons. Relaunching is an opportunity to set new objectives for the brand. Relaunching a brand can demand the changes ranging from the aspects as minor as logo prints on stationery and cutlery, staff uniforms, to as major as website of the company, changes in premises, etc. When a company relaunches a brand, it hopes to avoid the mistakes from past experience and wants to set a strong foot in the market. A brand manager needs to consider the following do’s and don’ts while relaunching a brand − Analyzing the marketplace and target market segment. Analyzing the marketplace and target market segment. Knowing about the competitor brands. Knowing about the competitor brands. Conducting SWOT (Strengths, Weaknesses, Opportunities, and Threats) analysis. Conducting SWOT (Strengths, Weaknesses, Opportunities, and Threats) analysis. Positioning the brand in an appropriate new form. Positioning the brand in an appropriate new form. Avoiding too many changes in too short time. This type of strategy can lead to the risk of not retaining consumer’s attention and interest for a long time. In future, it can make the company and its products unrecognizable to its existing customers. Let the consumer know about the new form the brand has taken. Avoiding too many changes in too short time. This type of strategy can lead to the risk of not retaining consumer’s attention and interest for a long time. In future, it can make the company and its products unrecognizable to its existing customers. Let the consumer know about the new form the brand has taken. Communicating clearly about the brand relaunch. Creating awareness among people about new objectives and distinctive offers. Making the changes gradually and noticeably. Communicating clearly about the brand relaunch. Creating awareness among people about new objectives and distinctive offers. Making the changes gradually and noticeably. Let us see an example of NIVEA FOR MEN relaunch. In 1980, NIVEA introduced an alcohol-free, non-itching aftershave balm for men. It went popular with consumers, and then by 1993, NIVEA FOR MEN included a range of skincare products for men. By 2008, more and more men were investing in skincare and grooming products. NIVEA FOR MEN brand understood this as an opportunity to claim more market share in the growing category. To achieve this, NIVEA employed a strategic marketing to relaunch and reorganize. NIVEA assessed the marketplace, evaluated its own business, brands, and products. It also assessed the brand’s position and the state of the market. It conducted SWOT analysis and revealed some interesting facts such as women are an important target market for the brand NIVEA FOR MEN as they are instrumental in buying male grooming products for their partners as well as helping them to choose new ones. Well-informed with SWOT analysis data, NIVEA FOR MEN brand management set objectives for relaunch. Using research data to forecast trends, the marketing force set SMART (Specific, Measurable, Achievable, Realistic) objectives. This helped in increasing sales, growing market share, and improving its brand image. NIVEA FOR MEN adopted a range of key performance indicators to assess the success of the NIVEA FOR MEN relaunch in the UK. It revealed that − NIVEA FOR MEN is the market leader in many countries and is consistently gaining additional market share. NIVEA FOR MEN is the market leader in many countries and is consistently gaining additional market share. Internationally, NIVEA FOR MEN skincare products sale increased by almost 20 percent. Internationally, NIVEA FOR MEN skincare products sale increased by almost 20 percent. The NIVEA FOR MEN brand image improved in the minds of consumers. The NIVEA FOR MEN brand image improved in the minds of consumers. NIVEA FOR MEN entertained its customers’ feedback and added products to its line and reformed the existing products. NIVEA FOR MEN entertained its customers’ feedback and added products to its line and reformed the existing products. Co-branding is now no more a new strategy used by companies for generating higher level of interest and excitement about the products and services. As every single strategy of branding comes with benefits and risks, co-branding is not an exception. Let us see all about co-branding in detail. When a company uses multiple brands together to introduce a single product or service, the practice is called Co-branding. It is also called Brand Partnership, piggyback franchising, or combination franchising. There can be two or more than two brands in alliance to achieve an appeal to the consumers that an individual brand could achieve. Co-branding provides a way for companies to integrate the marketing forces from each of the brands such that they work cooperatively to associate any of the logos, color schemes, or other brand identifiers to a specific product. The objective of co-branding is to combine strengths of multiple brands for business growth. There are various types of co-branding as follows − Ingredient Co-branding − Multiple brands provide distinctive ingredient or component to the carrier brand. For example, Intel chip inside all computers. Ingredient Co-branding − Multiple brands provide distinctive ingredient or component to the carrier brand. For example, Intel chip inside all computers. Product-Service Co-branding − It is a co-branding between a product and a service. For example, Best Western International, Inc. owns and operates a chain of hotels with state-of-the-art amenities and services to its customers. It runs an exclusive rewards program for Harley Davidson owners. The participating riders get lavish privileged treatment at the hotel. Product-Service Co-branding − It is a co-branding between a product and a service. For example, Best Western International, Inc. owns and operates a chain of hotels with state-of-the-art amenities and services to its customers. It runs an exclusive rewards program for Harley Davidson owners. The participating riders get lavish privileged treatment at the hotel. Alliance Co-branding − Multiple brand serve the same target audience. For example, Etihad Airways Partners, is a new brand which brings like-minded airlines together to offer customers more choice in flight schedules and enhanced frequent flyer benefits. Alliance Co-branding − Multiple brand serve the same target audience. For example, Etihad Airways Partners, is a new brand which brings like-minded airlines together to offer customers more choice in flight schedules and enhanced frequent flyer benefits. Supplier-Retailer Co-branding − Starbucks Wi-Fi started from AT&T in the most number of metropolitan cities in USA since 2008. Supplier-Retailer Co-branding − Starbucks Wi-Fi started from AT&T in the most number of metropolitan cities in USA since 2008. Promotional Co-branding − It is an alliance of a brand with persons or events. Promotional Co-branding − It is an alliance of a brand with persons or events. There are various situations when companies go for co-branding. They are − When introducing one company's product or services to the loyal consumers of another company. For example, the “Intel Inside” campaign. Within a year of the campaign, Intel started co-branding with around 300 computer manufacturer companies. When introducing one company's product or services to the loyal consumers of another company. For example, the “Intel Inside” campaign. Within a year of the campaign, Intel started co-branding with around 300 computer manufacturer companies. When a company wants to leverage the effect of one established and affectionate brand for marketing another brand. When a company wants to leverage the effect of one established and affectionate brand for marketing another brand. When companies want to save costs on branding and other resources in this age of economic competition. For example, the businesses such as fast-food restaurants share the same place of working, counter, menu pamphlets, or sometimes the staff. When companies want to save costs on branding and other resources in this age of economic competition. For example, the businesses such as fast-food restaurants share the same place of working, counter, menu pamphlets, or sometimes the staff. When one brand is providing complementing products or services that other brand requires. When one brand is providing complementing products or services that other brand requires. Co-branding comes with inevitable risks. Before the brand managers of brand A go for co-branding with brand B, they must consider the following points − If brand A is well established and generating excellent revenue, brand B would get the benefit of A’s positive perception and experience. In such case, brand A’s perception gets diluted. If brand A is well established and generating excellent revenue, brand B would get the benefit of A’s positive perception and experience. In such case, brand A’s perception gets diluted. There is a risk of any of the brands A or B underperforming or failing. In such case, the underperforming brand negatively impacts the over-performing brand and destroys its reputation for none of its mistake. There is a risk of any of the brands A or B underperforming or failing. In such case, the underperforming brand negatively impacts the over-performing brand and destroys its reputation for none of its mistake. If brand B is to some extent depending upon brand A’s equity, then brand B may be taken as weak or secondary. Brand A and B should be fit or compatible from the perspective of attributes and benefits. For example, co-branding of ice cream parlor and dry-fruit shop is natural so is co-branding of clothes brand with footwear brand. If brand B is to some extent depending upon brand A’s equity, then brand B may be taken as weak or secondary. Brand A and B should be fit or compatible from the perspective of attributes and benefits. For example, co-branding of ice cream parlor and dry-fruit shop is natural so is co-branding of clothes brand with footwear brand. Brand A and B both should have common core values and corporate philosophies. This is beneficial for both brands and reduces the risk of negative reputation if one of them fails. Brand A and B both should have common core values and corporate philosophies. This is beneficial for both brands and reduces the risk of negative reputation if one of them fails. Here are basic rough guidelines for co-branding − Know your partner in co-branding. Go for co-branding only with the companies that share complementary values. Know your partner in co-branding. Go for co-branding only with the companies that share complementary values. Co-brand only if the company has same ethics, core values, and common vision. Co-brand only if the company has same ethics, core values, and common vision. Choose co-branding only with brands whose products are best-in-class status. Choose co-branding only with brands whose products are best-in-class status. Co-brand if the partner and company’s brand share the same target audience. Co-brand if the partner and company’s brand share the same target audience. Co-brand only if the company can retain full review and approval rights on all elements of communications. Co-brand only if the company can retain full review and approval rights on all elements of communications. These guidelines bring down the opportunities of growth of the company but the good news is, it reduces the risks associated with co-branding. Apart from creating additional appeal to the consumers, the objective of co-branding is increasing revenue. The ultimate goal of co-branding is one plus one = more than two. If the co-branding is done using innovative ideas and effective strategies with the right partner, it can prove to be very beneficial for business growth. Co-branding helps to − Make the product or service under the brands resistant to imitation by local or private brands. Make the product or service under the brands resistant to imitation by local or private brands. Combine various perceptions about multiple brands. Combine various perceptions about multiple brands. Increase the credibility of the product or service in the market. Increase the credibility of the product or service in the market. Increase revenue of both businesses, if done effectively Increase revenue of both businesses, if done effectively Save costs of the company for launching a new brand, advertising, and promoting the brand through shared resources. Save costs of the company for launching a new brand, advertising, and promoting the brand through shared resources. Bring benefits from all brands and helps all brands participating in co-branding to prosper. Bring benefits from all brands and helps all brands participating in co-branding to prosper. For example, Coca Cola, the soft drinks giant has paired itself with McDonalds and made it sure it is associated with the brand that is consumed by millions of consumers around the world. Just by being together, both giants in restaurants and beverage industry respectively are earning billions of dollars revenue every year. The consumers follow their favorite celebrity and they wish to look, appear, and conduct the way the celebrity does. The companies grip this nerve of consumer behavior to brand their products with celebrity endorsement. The companies use the success and status of the celebrity to brand its products. The product alone cannot achieve consumers’ awareness and recognition as far and wide as a celebrity can help it to achieve. In India, Artist Booking India is a celebrity management and celebrity brand endorsement agency powered by B-Town Entertainment Pvt. Ltd. It has a strong network of TV serials, movies, writers, directors, and musicians in Bollywood. It provides solution right from selecting a right celebrity for the brand, applying strategies for optimizing the celebrity’s association with the brand to logistics. The contemporary celebrity endorsers can be overused by endorsing too many varied products. The contemporary celebrity endorsers can be overused by endorsing too many varied products. There must be a reasonable fit or match between the product and the celebrity endorser to appeal the consumers. There must be a reasonable fit or match between the product and the celebrity endorser to appeal the consumers. Celebrity endorsers can get into controversies, which can affect the brand adversely. Celebrity endorsers can get into controversies, which can affect the brand adversely. Celebrity can distract the consumer’s focus from the brand by overshadowing the brand. Celebrity can distract the consumer’s focus from the brand by overshadowing the brand. A number of consumers do not connect with the brand because they think that the endorsing celebrity is doing it just for money and do not necessarily believe in the brand they are endorsing. A number of consumers do not connect with the brand because they think that the endorsing celebrity is doing it just for money and do not necessarily believe in the brand they are endorsing. Since the idea of branding came into existence and settled in practice, some brands such as Nike, Coca Cola, Nivea, Amazon, etc., have been ruling the marketplace as successful ones. They were novice and had started as ordinary names with some innovative products or services at some point of time. With the efforts required for growing in the contemporary market, these brands became leading, exemplary, and powerful. In this chapter, we see what makes a brand successful over a long frame of time and how to asses brand performance. Brand launching is not the same as product or service launching. Products change but a brand is to stay. Brand launch is a long-term project unlike product launch. When a brand launches a product say P, and advertises for it, the competitors copy it after some time. Since all products go obsolete after some time, the brand chooses to replace the product P with some new product NewP, advocating its benefits and upgrading its quality to the consumer. This NewP often gets the benefit of the previous known product P. This is how a brand comes into life. From this point onwards, the products under the brand are sold by brand itself and not by mere advertising. Here, the product name (common noun) becomes a brand name (Proper noun). Over a time, brand gets more unique, builds its way of communication, and develops a rich meaning. Thus, a brand starts with a product and continues growing with multiple products. This was all about how a new product is converted to a brand. But launching a new brand is different. A successful brand launching needs treating a brand as a large entity than as a product. Right from the start, a new brand is considered as a complete entity in itself endowed with functional and non-functional values and presenting as if it is well-established. Take the following steps while launching a new brand in the market − Step 1 − Draft the brand program. Try to get the answers for the following questions − Existence − Why is the brand necessary? What will the consumers miss if the brand does not exist? Existence − Why is the brand necessary? What will the consumers miss if the brand does not exist? Vision − What is brand’s vision in some X product category? Vision − What is brand’s vision in some X product category? Ambition − What does the brand want to change in its consumer’s life? Ambition − What does the brand want to change in its consumer’s life? Values − What will the brand never compromise on? Values − What will the brand never compromise on? Know-How − What are brand’s capabilities? Know-How − What are brand’s capabilities? Territory − Where is the brand providing its lawful benefits? What are its product categories? Territory − Where is the brand providing its lawful benefits? What are its product categories? Style, Tone, and Language − How a brand is going to communicate? Style, Tone, and Language − How a brand is going to communicate? Reflection − What image the brand wants its consumers to render about itself? Reflection − What image the brand wants its consumers to render about itself? Step 2 − Define brand identity prism. Step 3 − Create brand positioning. Identify potential added values for the brand based on its image, identity, and heritage. Identify potential added values for the brand based on its image, identity, and heritage. Explore four major scenarios: Why? Against whom? For whom? When? Explore four major scenarios: Why? Against whom? For whom? When? Test the above scenarios, redefine or eliminate them if required. Conduct consumer studies, ideas and formulations. Test the above scenarios, redefine or eliminate them if required. Conduct consumer studies, ideas and formulations. Conduct strategic evaluation of potential sales and profits in the marketspace. Conduct strategic evaluation of potential sales and profits in the marketspace. Step 4 − Determine flagship product of the brand. Carefully choose which product or service you think you should introduce as a first campaign. This star product is going to form the brand’s identity subsequently. Step 5 − Choose a strong brand name. Choose it by estimating the future changes the brand can undergo. Look for meaningful, short, and easy to pronounce names. Do not choose a deceptive or descriptive name. Step 6 − Create brand slogan and jingle that is easy, meaningful, and memorable by consumers. Step 7 − Reach out to opinion leaders (people who are influencers) and conduct brand advertisements in various media to create awareness among the consumers. Many brands have been with us for a long time and many are still struggling for survival. Why do some brands sustain by escaping the effects of time and why do some brands vanish? There are many reasons why brands start performing low and eventually lead to vanishing − A brand not being able to withstand market changes and competitors. A brand not being able to withstand market changes and competitors. New cheaper entrants in the market, which destabilize added value of the established brand. New cheaper entrants in the market, which destabilize added value of the established brand. A brand not able to suffice consumer’s needs, or customized requirements. A brand not able to suffice consumer’s needs, or customized requirements. A brand not able to attract upcoming generation of consumers all over again when current consumers grow old. A brand not able to attract upcoming generation of consumers all over again when current consumers grow old. A brand marketing and management team lacking foresightedness. A brand marketing and management team lacking foresightedness. These are few most common facts why brands start to decline. To last for a long term, the following vital points a brand must adhere to − Keep on innovating on the fronts of product quality, design, and consumer’s convenience. Keep on innovating on the fronts of product quality, design, and consumer’s convenience. Always keep its reputation good. Always keep its reputation good. Always remain contemporary with the changes in the consumer’s culture, preferences, economic and technological changes, and new market openings in the world. Always remain contemporary with the changes in the consumer’s culture, preferences, economic and technological changes, and new market openings in the world. Always keep itself noticeable to the target market. Always keep itself noticeable to the target market. Work on not to lose its market share for cheap copies of the products. Work on not to lose its market share for cheap copies of the products. Work on acquiring superior image and then keeping it. Work on acquiring superior image and then keeping it. Price its products appropriately depending upon the target market’s income. Price its products appropriately depending upon the target market’s income. Present itself in the quality environment which is as high as its product offers. Present itself in the quality environment which is as high as its product offers. Control the relationship with the opinion leaders and distribution of products. Control the relationship with the opinion leaders and distribution of products. Defend its intellectual properties against theft or sneaking intrusion. Defend its intellectual properties against theft or sneaking intrusion. A brand cannot survive if it does not change according to the market changes. Brand management needs to cater to different branding policies to introduce the product in different countries around the world. The market is not the same worldwide. First, the growth takes place in developing countries, then in underdeveloped countries, and finally in developed countries. In developing countries such as India, the economic growth rate is fast and there are favorable business conditions. It is also revealed that the customer in developing countries is more brand cautious than that of in the developed countries. In developed countries of USA and Europe, the market is matured. There is not much significant growth and innovation taking place. In such matured markets, brand needs to stimulate the new desires and new experiences of the consumer. Brand managers need to work by considering changes in the domains of politics, economics, evolution of society, technology, consumer behavior and fads, all of which play an important role while branding in different markets. When it comes to brand name changes, some examples flash such as Anderson → Accenture, Datsun → Nissan, Pal → Pedigree, and Phillips → Whirlpool, Backrub → Google, to name a few. Brand transfer is a lot more than brand’s name change. A brand’s established name has links with emotional associations, empathy, and preference in its consumers’ mind. The loyalty and trust of the customers cannot be transferred easily to just one entity: the brand name. The brand image is required to be transferred. A brand’s name is changed in the following scenarios − When the existing name sounds weak or is not able to establish its position in the market. When the existing name sounds weak or is not able to establish its position in the market. When a brand wants to present its upgraded product or service. When a brand wants to present its upgraded product or service. When a brand wants to introduce more clarity in its name. When a brand wants to introduce more clarity in its name. When a brand needs to distant itself from negating effects of the existing name. When a brand needs to distant itself from negating effects of the existing name. When a brand wants to get instant recognition in the market while expanding globally. When a brand wants to get instant recognition in the market while expanding globally. There are few estimations the brand managers need to work on − Estimate and quantify the costs It includes the costs required for changing − Promotional properties such as banners, hoardings, website ads, business properties such as letterheads and business cards. Company literatures such as white papers, data sheets, and presentations. Electronic properties such as website, newsletter, blogs, etc. Other in-house properties such as templates, folder names, network node names, etc. Estimate and quantify the costs It includes the costs required for changing − Promotional properties such as banners, hoardings, website ads, business properties such as letterheads and business cards. Promotional properties such as banners, hoardings, website ads, business properties such as letterheads and business cards. Company literatures such as white papers, data sheets, and presentations. Company literatures such as white papers, data sheets, and presentations. Electronic properties such as website, newsletter, blogs, etc. Electronic properties such as website, newsletter, blogs, etc. Other in-house properties such as templates, folder names, network node names, etc. Other in-house properties such as templates, folder names, network node names, etc. Judge the benefits and losses Try to find out answers for the following questions − How long the existing name is in use? How much goodwill has the existing name built? How would it affect the consumers? How would it affect the market share of the brand? Judge the benefits and losses Try to find out answers for the following questions − How long the existing name is in use? How much goodwill has the existing name built? How long the existing name is in use? How much goodwill has the existing name built? How would it affect the consumers? How would it affect the consumers? How would it affect the market share of the brand? How would it affect the market share of the brand? Analyze target audience and market Consider the target audience, culture, language, symbols, and preferences. Consider the average purchasing frequency of the customer. Identify the characteristics the customer associates with the brand. Analyze target audience and market Consider the target audience, culture, language, symbols, and preferences. Consider the target audience, culture, language, symbols, and preferences. Consider the average purchasing frequency of the customer. Consider the average purchasing frequency of the customer. Identify the characteristics the customer associates with the brand. Identify the characteristics the customer associates with the brand. To handle actual brand transfer, follow the given steps − Chalk out a plan of brand transfer. Chalk out a plan of brand transfer. Let every department know, that it is going to be a combined effort of all departments in the company. Let every department know, that it is going to be a combined effort of all departments in the company. Warn the employees, retailers, opinion leaders and prescribers well in advance. Warn the employees, retailers, opinion leaders and prescribers well in advance. Communicate clearly to the customers about the brand change. Communicate clearly to the customers about the brand change. Invest time for all customers to know about the brand transfer. Invest time for all customers to know about the brand transfer. Keep the transitional period of the brand transfer minimal. Keep the transitional period of the brand transfer minimal. The following three factors facilitate brand image transfer − Product Resemblance When consumers consider source brand’s product and target brand’s product or product category similar. For example, it is more likely for a pasteurized milk brand to boost a lowcalorie cheese brand than a soap brand. Target Group Resemblance If the target brand aims for the same target group as the source brand, there are high chances of target brand succeeding as the initial purchases of a target brand will mainly be made by consumers of the source brand. When the target brand tailors to another target group then initial sales will not be significantly high. Family Resemblance Family resemblance means that the look and feel of the source brand and the target brand have to be largely the same. The consumers are perceived by symbols and colors while assessing the brand hence a similar style can transfer their associations with the source brand to the target brand. Image transfer may still become successful, provided the marketing communication is clear and aggressive, and advertising campaign is intensive. Brand leveraging is the strategy to use the power of an existing brand name to support a company’s entry into a new but related product category by communicating valuable product information to the consumer. For example, the manufacturer of tea maker uses its brand name strength to launch tea vending machine. Here, in spite of tea and tea-vending machine belonging to different product categories, there is a strong correlation between the two items that the brand name has a mighty impact on consumers of both categories. Brand leveraging is an important form of new product introduction because − Strong brand leveraging provides consumers with a sense of familiarity. Strong brand leveraging provides consumers with a sense of familiarity. It carries positive brand characteristics and attitudes into a new product category. It carries positive brand characteristics and attitudes into a new product category. Strong leveraging perceives instant recognition to the brand. Consumers are more likely to try leveraged product. Strong leveraging perceives instant recognition to the brand. Consumers are more likely to try leveraged product. As the products belong to the different categories, they do not compete for market share. As the products belong to the different categories, they do not compete for market share. More products mean greater shelf space for the brand and in turn more opportunities for sale. More products mean greater shelf space for the brand and in turn more opportunities for sale. The cost of introducing a brand-leveraged product is less than introducing an independent new product. The cost of introducing a brand-leveraged product is less than introducing an independent new product. A full line permits coordination of product offerings, such as bagels and cream cheese, potato chips and ranch dip, peanut butter and jelly, etc. A full line permits coordination of product offerings, such as bagels and cream cheese, potato chips and ranch dip, peanut butter and jelly, etc. A greater number of products increase efficiency of manufacturing facilities and raw materials. A greater number of products increase efficiency of manufacturing facilities and raw materials. The brand managers can create a strong brand leveraging, by maintaining the quality of all products in different categories under the brand. The brand managers need to decide which products can be leveraged under a brand. It is very important for them to leverage a brand only into related or associated categories of the original product. In order to make the best decision for the brand, they need to find answers for the following questions − Is the new product related to the established product family? Is the new product related to the established product family? Does the established brand has characteristics that can be effectively carried on into new categories? Does the established brand has characteristics that can be effectively carried on into new categories? What will be the appropriate leveraging strategy? What will be the appropriate leveraging strategy? What will be the impact on original brand name? Will it be strengthened or diluted? What will be the impact on original brand name? Will it be strengthened or diluted? Does the company have essential facilities to manufacture and distribute a new and differentiated product? Does the company have essential facilities to manufacture and distribute a new and differentiated product? Will sales of the new product cover the cost of product development and marketing? Will sales of the new product cover the cost of product development and marketing? If leveraging fails, what are the policies to revert or to keep original brand’s reputation? If leveraging fails, what are the policies to revert or to keep original brand’s reputation? A brand leveraging strategy can be extremely successful and profitable if it is correctly implemented and provides new products with the right image. Brand valuation is an interesting topic in brand management. The brand valuation is not just restricted to acquisitions and mergers but it is also important for the company management to make policies for future, to train the marketing team, to use it for information system, and provide as a reference for product or brand managers to plan their strategies. In the entire process of brand development and management, it is essential for the brand managers to assess the progress of brand development. The companies are interested in brand audit as the owner of the organization. Brand audit is an assessment of where the brand stands in the market at its present status. It is conducted by the company itself to judge the inclination of the brand. It reveals the loopholes in brand development or management process. Brand audit is conducted − When the companies are rebranding, acquiring business, or merging the businesses. When the companies are rebranding, acquiring business, or merging the businesses. When the communication in management team and employees, or interpersonal relations among employees are unhealthy. When the communication in management team and employees, or interpersonal relations among employees are unhealthy. When brand, the strong foundation of the organization that inspires and empowers the employees is found weak. When brand, the strong foundation of the organization that inspires and empowers the employees is found weak. The CEO of a company along with his marketing and brand management heads generally conducts brand audit. It can be an in-house team as said or an outside agency on hire. There are two categories in which brand auditing is done − Brand positioning Brand value Brand promise or brand essence Culture of the organization Product/service positioning HR policies Corporate identity such as logos, and brand elements Collaterals such as brochures, printed material, trade fair displays Advertisement Website Search Engine Optimization (SEO) Social media News Public Relations Company literature such as white papers, blogs, case studies, books Reviews and testimonials Videos Customer service system Sales procedures, touch points There is little standardization and more opinions in the market about brand equity measurement. Brand equity is measured in both quantitative and qualitative brand research. The brand equity performance can be measured by collecting data of brand performance. It includes − Taking face-to-face interviews with focus groups. Considering large sample audience to collect the data. By analyzing present customers as well as prospective customers. By conducting periodic surveys. Conducting experiments that examine consumers’ attitude and behavior. There are three mainstay drivers or metrics of brand equity − The company management is interested in financial aspect of brand equity to know how profitable the brand is performing in the market. Under the financial metrics, the brand managers with marketing team should track the following − Cost for winning new customers Cost for retaining existing customers Growth rate Market share of the brand Marketing investments Price sensitivity Profitability Revenue These are some of the many financial metrics given. By keeping the track of the trends, a brand manager can ensure that the brand is building positive equity. Also, they can use this data to explain how important the brand asset is for the company to bear brand extensions or to determine marketing budgets. The strength metrics include measurement of the following aspects − Brand awareness Brand knowledge Brand loyalty Aided and unaided brand recall Buzz in the market It is very important for the brand managers to understand what consumers know, think, and feel about various brands. Under consumer metrics, the brand managers need to measure the following − Consumer sentiments Consumer perception Emotional connection with brand Beliefs about the brand Relevance of brand for the market segment Consumer’s purchasing decision and other driving factors of the brand Consumer’s opinions and feelings about the brand Brand associations in the consumer’s mind It is very difficult to find the right talent in the market. Organizations are always interested in attracting the talented employees thereby reducing the cost of grooming and training the new employees. It is the practice of creating and establishing the reputation of an organization as a place to work by associating recruitment and external HR practices with the organization as a brand. It is a way of attracting and keeping employees by − Good pay package Ethical organization culture Comfortable and enjoyable workplace Rewards, perks, appraisals, and benefits Excellent management performance It forms a perception in the employee’s mind about what it would be like to work in the organization. It attracts not only potential employees, but also the specific ones who can fit well within the organization. For example, the software products giant Microsoft has provided its Microsoft Careers website. Apart from featuring job opportunities, there is a blog that presents articles about how it would be to work at the company by profiling the experience of the present employees. In addition, it provides a separate Facebook page as ‘Women at Microsoft,’ to give a unique insight into the women working at the company. The YouTube video on Microsoft Career features more than 100 videos where potential employees can get to know the aspects of working with Microsoft. It is the practice of associating an employee’s behavior and opinions with the image, characteristics, and attributes that the organization wants to project to its external stakeholders. Here, the employee is a small version of a brand ambassador It tries to influence the interactions among employees within the organization as well as among employees and external stakeholders. This way, an organization demonstrates its characteristics it desires to show through its employees. Employee branding includes − On-job training Customer service or customer interaction training Company orientation Education programs associated with corporate brands Evaluation and reward programs For example, Cisco Networking Academy, program under Cisco Corporate Social Responsibility, is an IT skills and career building program available to learning institutions and individuals worldwide. A poplar CEO of a company can bring in more deal flow and generate more revenue. Brand CEO is the leader who creates a vision for the brand and leads his teams by speaking with actions more than words. With high rank in management hierarchy and authority, a CEO can play an instrumental role in branding. CEOs are expected to have profiles on LinkedIn, but if they have presence across every prominent social media platform, their focus on reaching consumers directly dilutes. A smart CEO finds out on which social media the target audience spends time and focuses the efforts there. It establishes credibility of the brand and helps to bring up CEO’s reputation as an industry expert. It is an opportunity to connect to the audience in person when a CEO is physically in front of the target audience. Being an author of the book grants the command on the subject. Writing a book and introducing it among large audience, signing events are excellent opportunities for CEO for brand campaigns. When a CEO gets an award as an industry expert, the credibility and reliability elevates. Some examples of popular CEO brands are as follows − 9 Lectures 47 mins Aleksandar Cucukovic 18 Lectures 2 hours Rob Cubbon 10 Lectures 1 hours Bernard Kelvin Clive 24 Lectures 1 hours J Aatish Rao 31 Lectures 2.5 hours Being Commerce 31 Lectures 2.5 hours Being Commerce Print Add Notes Bookmark this page
[ { "code": null, "e": 2267, "s": 2050, "text": "“A product is something made in the factory; a brand is something the customer buys. A product can be copied or imitated by a competitor; a brand is unique. A product can be outdated; a successful brand is timeless.”" }, { "code": null, "e": 2302, "s": 2267, "text": "− Stephen King (WPP Group, London)" }, { "code": null, "e": 2812, "s": 2302, "text": "Today, the commodity marketplace is flooded with various brands. The requirement of the seller’s brand to stand out among other parallel brands is crucial. Hence, there is a fierce competition among the sellers to make their products or services stand out in the market, thereby winning new consumers and retaining the existing ones. At times, it even leads to diverting the consumers following other brands to the seller’s brand. To remain competitive in the marketplace, strong brand management is required." }, { "code": null, "e": 2873, "s": 2812, "text": "Brand Management begins with understanding the term 'brand'." }, { "code": null, "e": 3011, "s": 2873, "text": "Brand may be defined from the brand owner’s perspective or the consumer’s perspective. There are various popular definitions of a brand −" }, { "code": null, "e": 3368, "s": 3011, "text": "“A name, term, design, symbol, or any other feature that identifies one seller’s good or service as distinct from those of other sellers. The legal term for brand is trademark. A brand may identify one item, a family of items, or all items of that seller. If used for the firm as a whole, the preferred term is trade name.” - American Marketing Association" }, { "code": null, "e": 3725, "s": 3368, "text": "“A name, term, design, symbol, or any other feature that identifies one seller’s good or service as distinct from those of other sellers. The legal term for brand is trademark. A brand may identify one item, a family of items, or all items of that seller. If used for the firm as a whole, the preferred term is trade name.” - American Marketing Association" }, { "code": null, "e": 3835, "s": 3725, "text": "“A type of product manufactured by a particular company under a particular name.” − Oxford English dictionary" }, { "code": null, "e": 3945, "s": 3835, "text": "“A type of product manufactured by a particular company under a particular name.” − Oxford English dictionary" }, { "code": null, "e": 4167, "s": 3945, "text": "“A name, term, sign, symbol, design, or a combination of these used to identify the goods or services of one seller or group of sellers and to differentiate them from those of competitors.” − A product-oriented definition" }, { "code": null, "e": 4389, "s": 4167, "text": "“A name, term, sign, symbol, design, or a combination of these used to identify the goods or services of one seller or group of sellers and to differentiate them from those of competitors.” − A product-oriented definition" }, { "code": null, "e": 4514, "s": 4389, "text": "“The promise of the bundles of attributes that someone buys and provide satisfaction . . .” − A consumer-oriented definition" }, { "code": null, "e": 4639, "s": 4514, "text": "“The promise of the bundles of attributes that someone buys and provide satisfaction . . .” − A consumer-oriented definition" }, { "code": null, "e": 4785, "s": 4639, "text": "The fundamental purpose of branding is differentiation. A brand is a means of differentiating the seller’s product from other competing products." }, { "code": null, "e": 4827, "s": 4785, "text": "Brand has the following characteristics −" }, { "code": null, "e": 4895, "s": 4827, "text": "Tangible characteristics − Price, physical product, packaging, etc." }, { "code": null, "e": 4995, "s": 4895, "text": "Intangible characteristics − Customer’s experience with the brand, brand position, and brand image." }, { "code": null, "e": 5043, "s": 4995, "text": "Here are some important objectives of a brand −" }, { "code": null, "e": 5108, "s": 5043, "text": "To establish an identity for the product or a group of products." }, { "code": null, "e": 5173, "s": 5108, "text": "To establish an identity for the product or a group of products." }, { "code": null, "e": 5240, "s": 5173, "text": "To protect the product or service legally for its unique features." }, { "code": null, "e": 5307, "s": 5240, "text": "To protect the product or service legally for its unique features." }, { "code": null, "e": 5393, "s": 5307, "text": "To acquire place for the product in consumers’ minds for high and consistent quality." }, { "code": null, "e": 5479, "s": 5393, "text": "To acquire place for the product in consumers’ minds for high and consistent quality." }, { "code": null, "e": 5574, "s": 5479, "text": "To persuade the consumer to buy the product by promising to serve their needs in a unique way." }, { "code": null, "e": 5669, "s": 5574, "text": "To persuade the consumer to buy the product by promising to serve their needs in a unique way." }, { "code": null, "e": 5745, "s": 5669, "text": "To create and send the message of strong reliable business among consumers." }, { "code": null, "e": 5821, "s": 5745, "text": "To create and send the message of strong reliable business among consumers." }, { "code": null, "e": 6046, "s": 5821, "text": "Brand management is an art of creating a brand and maintaining it. It is nothing but developing a promise to the consumer, materializing that promise, and maintaining the same for a product, a group of products, or services." }, { "code": null, "e": 6342, "s": 6046, "text": "Brand management helps to manage the tangible and intangible characteristics of a brand. A competent Brand Management includes building brand identity, launching the brand, and maintaining the brand position in the market. Brand management builds and maintains the corporate image of a business." }, { "code": null, "e": 6408, "s": 6342, "text": "The concept of branding exists since approximately hundred years." }, { "code": null, "e": 6708, "s": 6408, "text": "It is a single most compelling thing about a brand that differentiates it from the competing brands. The brand essence serves as a metric to evaluate the seller's marketing strategies. The most important brand essences arise from consumers' needs. Brand essence can be described in just a few words." }, { "code": null, "e": 6777, "s": 6708, "text": "For example, Volvo − Safe travel. Disney − Fun family entertainment." }, { "code": null, "e": 6834, "s": 6777, "text": "There are seven contributing elements of brand essence −" }, { "code": null, "e": 6979, "s": 6834, "text": "Authenticity − If the brand makes a promise and fails to keep, then it is rejected. The consumers expect the sellers to be genuine and truthful." }, { "code": null, "e": 7124, "s": 6979, "text": "Authenticity − If the brand makes a promise and fails to keep, then it is rejected. The consumers expect the sellers to be genuine and truthful." }, { "code": null, "e": 7298, "s": 7124, "text": "Consistency − The essence of a brand is lost if it is not consistent in providing what it promised to the consumer. Also, a brand should use its logo consistently over time." }, { "code": null, "e": 7472, "s": 7298, "text": "Consistency − The essence of a brand is lost if it is not consistent in providing what it promised to the consumer. Also, a brand should use its logo consistently over time." }, { "code": null, "e": 7592, "s": 7472, "text": "Durability − The brand essence remains same over time. Even if packaging and logos change, the essence does not change." }, { "code": null, "e": 7712, "s": 7592, "text": "Durability − The brand essence remains same over time. Even if packaging and logos change, the essence does not change." }, { "code": null, "e": 7772, "s": 7712, "text": "Experience − It is the consumers experience with the brand." }, { "code": null, "e": 7832, "s": 7772, "text": "Experience − It is the consumers experience with the brand." }, { "code": null, "e": 7898, "s": 7832, "text": "Uniqueness − It is how different a brand is from its competitors." }, { "code": null, "e": 7964, "s": 7898, "text": "Uniqueness − It is how different a brand is from its competitors." }, { "code": null, "e": 8024, "s": 7964, "text": "Relevance − It is the relevance of a brand to the consumer." }, { "code": null, "e": 8084, "s": 8024, "text": "Relevance − It is the relevance of a brand to the consumer." }, { "code": null, "e": 8184, "s": 8084, "text": "Single mindedness − It is sticking to only one thing about the brand which keeps the brand focused." }, { "code": null, "e": 8284, "s": 8184, "text": "Single mindedness − It is sticking to only one thing about the brand which keeps the brand focused." }, { "code": null, "e": 8347, "s": 8284, "text": "There are eight essential elements of a brand as given below −" }, { "code": null, "e": 8498, "s": 8347, "text": "Brand Name − This is what the people get to see everywhere. It must be as simple and memorable as possible, meaningful, easy to pronounce, and unique." }, { "code": null, "e": 8649, "s": 8498, "text": "Brand Name − This is what the people get to see everywhere. It must be as simple and memorable as possible, meaningful, easy to pronounce, and unique." }, { "code": null, "e": 8852, "s": 8649, "text": "Logo − This can be anything from a piece of text to the abstract designs. It may be entirely unrelated to the corporate activities. It must be relevant to the product or service, iconic, and attractive." }, { "code": null, "e": 9055, "s": 8852, "text": "Logo − This can be anything from a piece of text to the abstract designs. It may be entirely unrelated to the corporate activities. It must be relevant to the product or service, iconic, and attractive." }, { "code": null, "e": 9211, "s": 9055, "text": "Tone − This is how the seller communicates with the consumer. It can be professional, friendly, or formal. It builds consumer’s perception about the brand." }, { "code": null, "e": 9367, "s": 9211, "text": "Tone − This is how the seller communicates with the consumer. It can be professional, friendly, or formal. It builds consumer’s perception about the brand." }, { "code": null, "e": 9538, "s": 9367, "text": "Jingle − It must be pleasant to hear and hum, relevant to the product, easy to remember, and easy to understand over a large age group to connect consumer with the brand." }, { "code": null, "e": 9709, "s": 9538, "text": "Jingle − It must be pleasant to hear and hum, relevant to the product, easy to remember, and easy to understand over a large age group to connect consumer with the brand." }, { "code": null, "e": 9908, "s": 9709, "text": "Slogan − It summarizes overall value proposition. It should be short, easy to remember, and catchy. For example, KFC’s slogan is “Finger Lickin’ Good” and Britannia’s is “Eat Healthy, Think Better”." }, { "code": null, "e": 10107, "s": 9908, "text": "Slogan − It summarizes overall value proposition. It should be short, easy to remember, and catchy. For example, KFC’s slogan is “Finger Lickin’ Good” and Britannia’s is “Eat Healthy, Think Better”." }, { "code": null, "e": 10246, "s": 10107, "text": "Packaging − It needs to be catchy and advertising, drawing people to see the product inside. Also, it needs to be compact, yet attractive." }, { "code": null, "e": 10385, "s": 10246, "text": "Packaging − It needs to be catchy and advertising, drawing people to see the product inside. Also, it needs to be compact, yet attractive." }, { "code": null, "e": 10573, "s": 10385, "text": "Universal Resource Locator (URL) − It forms the domain name on the internet. A seller can register all prospective variations of brand name URLs or can buy the existing URL of a business." }, { "code": null, "e": 10761, "s": 10573, "text": "Universal Resource Locator (URL) − It forms the domain name on the internet. A seller can register all prospective variations of brand name URLs or can buy the existing URL of a business." }, { "code": null, "e": 11017, "s": 10761, "text": "Characters/Mascots − It is a special symbol, either still, animated, or real life entity such as an animal or a human character. For example, Vodafone’s Zoozoo characters are played in its various advertisements by humans wearing special white body suits." }, { "code": null, "e": 11273, "s": 11017, "text": "Characters/Mascots − It is a special symbol, either still, animated, or real life entity such as an animal or a human character. For example, Vodafone’s Zoozoo characters are played in its various advertisements by humans wearing special white body suits." }, { "code": null, "e": 11337, "s": 11273, "text": "They are not the same. Let us see the difference between them −" }, { "code": null, "e": 11393, "s": 11337, "text": "Here are some commonly used terms in Brand Management −" }, { "code": null, "e": 11832, "s": 11393, "text": "The humans have frequent needs as well as occasional needs in the life. They are varied in number of ways such as day-to-day living needs, social needs, health and medication needs, contemporary lifestyle needs, to name a few. According to this need-based market segmentation, the brands are diversified in different sectors such as personal care, home care, commodities, entertainment, healthcare, pharmaceutical, luxuries, and services." }, { "code": null, "e": 11898, "s": 11832, "text": "There are two basic approaches of brands according to ownership −" }, { "code": null, "e": 11991, "s": 11898, "text": "The brands can be further categorized depending on the human needs or the context as given −" }, { "code": null, "e": 12365, "s": 11991, "text": "The FMCG items such as grocery, toiletries, easy-to-cook foods, are essential for our daily lives. They are called fast moving because they are the quickest to get sold from the supermarket shelves. They are also called Consumer Packaged Goods (CPG) brands. They are inexpensive and tangible products which can be produced in advance and can be stored to be consumed later." }, { "code": null, "e": 12611, "s": 12365, "text": "The brand managers need to handle these brands tactfully to generate more revenue as there is fierce competition in the FMCG market. If a product does not meet the consumer’s expectations, there is always other brand ready to take the advantage." }, { "code": null, "e": 12725, "s": 12611, "text": "Examples of FMCG − Unilever’s Dove Bodycare, Colgate Palmolive’s oral care, Godrej, Dabur, Burges Olive Oil, etc." }, { "code": null, "e": 12984, "s": 12725, "text": "They are the products or services which consumers buy depending upon their price. There is no quantitative differentiation for commodities across the market. Milk, sugar, oil, grains and cereals, metals, wool and rubber, and natural gas, are all commodities." }, { "code": null, "e": 13341, "s": 12984, "text": "Since it is not easy to pursue the consumers to pay more price for the parallel product he can get at a lesser price, the sellers need to put in a lot of effort on color, logo, brand character, and packaging to differentiate the product so it makes a significant impact on the consumers’ mind. Also, the seller needs to keep on adding value to the product." }, { "code": null, "e": 13427, "s": 13341, "text": "Examples of commodities − TATA Salt, General Mill’s Pillsbury whole wheat flour, etc." }, { "code": null, "e": 13863, "s": 13427, "text": "They are not essential but highly desired out of one’s own perception and self-worth. The desirability is based on the consumer’s demand of high quality, fine craftsmanship, exclusivity, precision, and beauty. Also, peer recognition, appreciation, and approval of high status are the underlying needs which promote luxury brands. High-end automobiles, jewelry, cosmetics, accessories, properties, and perfumes come under luxury brands." }, { "code": null, "e": 13912, "s": 13863, "text": "These brands are divided into three categories −" }, { "code": null, "e": 14066, "s": 13912, "text": "Prestige Brands − Mercedes-Benz, Rolex, Swarovski, etc. represent high craftsmanship and lavishness. They are regarded as the mark of high social status." }, { "code": null, "e": 14220, "s": 14066, "text": "Prestige Brands − Mercedes-Benz, Rolex, Swarovski, etc. represent high craftsmanship and lavishness. They are regarded as the mark of high social status." }, { "code": null, "e": 14312, "s": 14220, "text": "Premium Brands − They are mass luxury brands. For example, Calvin Klein and Tommy Hilfiger." }, { "code": null, "e": 14404, "s": 14312, "text": "Premium Brands − They are mass luxury brands. For example, Calvin Klein and Tommy Hilfiger." }, { "code": null, "e": 14574, "s": 14404, "text": "Fashion Brands − They bring fashion products such as apparels and accessories under “hot trends” and target mass consumers. They bring products according to the seasons." }, { "code": null, "e": 14744, "s": 14574, "text": "Fashion Brands − They bring fashion products such as apparels and accessories under “hot trends” and target mass consumers. They bring products according to the seasons." }, { "code": null, "e": 14961, "s": 14744, "text": "Most luxury companies are small to medium sized enterprises. Presence of luxury brands must be maintained all over the world to reinforce the brand image in the consumer’s mind. They are available in flagship stores." }, { "code": null, "e": 15237, "s": 14961, "text": "Under these brands, a business makes a commercial transaction with another business. Such transactions occur when one business provides resources to another business for manufacturing some product, and when one business supplies or rents out the products to another business." }, { "code": null, "e": 15391, "s": 15237, "text": "B2B companies must pursue global branding as they have less number of customers than B2C companies and more number of transactions with other businesses." }, { "code": null, "e": 15664, "s": 15391, "text": "For example, restaurants buy cooking energy, raw materials, crockery, furniture, lights, etc. from different businesses. Retailers buy a product from original manufacturer for reselling it. McDonalds, Pizza Hut, IBM, GE, Microsoft, and Oracle are B2B brands to name a few." }, { "code": null, "e": 15846, "s": 15664, "text": "These brands cover the products which are commonly known as drugs or medicines used to diagnose, treat, and prevent a disease. There are more than 70,000 registered brands of drugs." }, { "code": null, "e": 16114, "s": 15846, "text": "Pharmaceutical brands are different than consumer brands in various prominent ways. Unlike consumer products, where requirement can be generated through creative advertising and other promotional means, a pharmaceutical company cannot create a need that is not there." }, { "code": null, "e": 16405, "s": 16114, "text": "Any new pharmaceutical product cannot create demand without underlying medical need. In addition, the product features of prescription drugs cannot be changed to meet consumer needs or preferences without clinical development outcomes and receiving approval from the regulatory authorities." }, { "code": null, "e": 16535, "s": 16405, "text": "Examples of pharmaceutical brands − Simila Expert Care nutrition for infants from Abbott Laboratories, USA and Dr Reddy’s NiseTM." }, { "code": null, "e": 16735, "s": 16535, "text": "The service sector has spurred the economic growth of many countries. Services are produced and consumed in real time. The output of a service brand is intangible, such as experience of the consumer." }, { "code": null, "e": 17071, "s": 16735, "text": "In service branding, the speed of processing the consumer’s request, punctuality in delivery, quality, and degree of attending special needs, and responsiveness are the factors the service provider caters for. Because of its intangible nature and dependency on dynamic nature of humans who provide it, branding of service is difficult." }, { "code": null, "e": 17339, "s": 17071, "text": "The domestic and industrial appliances, automobiles, etc. are sold with the promise of quality servicing. The quality and cost claimed by the services belonging to the same industry can vary to a great extent. Service brands are categorized into the following types −" }, { "code": null, "e": 17457, "s": 17339, "text": "Classic Service Brands − They include banks, beauty salons, consultation services, car rentals, and airline services." }, { "code": null, "e": 17575, "s": 17457, "text": "Classic Service Brands − They include banks, beauty salons, consultation services, car rentals, and airline services." }, { "code": null, "e": 17635, "s": 17575, "text": "Pure Service Brands − They include association memberships." }, { "code": null, "e": 17695, "s": 17635, "text": "Pure Service Brands − They include association memberships." }, { "code": null, "e": 17796, "s": 17695, "text": "Professional Service Brands − They include advisors, consultants, travel agents, estate agents, etc." }, { "code": null, "e": 17897, "s": 17796, "text": "Professional Service Brands − They include advisors, consultants, travel agents, estate agents, etc." }, { "code": null, "e": 17982, "s": 17897, "text": "Retail Service Brands − They include restaurants, fashion stores, supermarkets, etc." }, { "code": null, "e": 18067, "s": 17982, "text": "Retail Service Brands − They include restaurants, fashion stores, supermarkets, etc." }, { "code": null, "e": 18255, "s": 18067, "text": "Examples of service brands − Ford, Airtel, Axis Bank, Air India, Café Coffee Day by Coffee Day Global Ltd., Lifestyle fashion retailing by Landmark, ICICI Prudential Life Insurance, etc." }, { "code": null, "e": 18650, "s": 18255, "text": "These brands portray their entire image, such as the company’s value, competency, vision, motives, missions, products/services etc. through web to the online consumer. EBrands work to create a direct relationship between the brand owner and the customer via Internet. Due to their wide reachability, it is easy for the e-brands to survive among competitors and gain reputation among consumers." }, { "code": null, "e": 19007, "s": 18650, "text": "The consumers are loyal to the sellers whose online commercial transaction schemes are familiar, tested, and established. When the e-Brands provide features such as facility to compare various products, listing products within a specified cost or feature segment, easy and reliable payment modes, then the e-Brands can make place in their consumers’ minds." }, { "code": null, "e": 19052, "s": 19007, "text": "Examples of e-Brand − Flipkart, Amazon, etc." }, { "code": null, "e": 19342, "s": 19052, "text": "Countries, like companies, apply branding to help themselves market for investment, tourism, and exports. The ‘Country of Origin’ is commonly referenced by the term ‘Made in...’ which depicts an association with the product’s place of origin, which works as effectively as product quality." }, { "code": null, "e": 19622, "s": 19342, "text": "Consumers are aware of the origin of the product and ethics used behind creating that product. Some associations of countries and products are France = fashion, wine, and cheese, Italy = design, India = spices, Denmark = chocolate, Germany = automotive, Japan = electronics, etc." }, { "code": null, "e": 20105, "s": 19622, "text": "Today, the brands apart from being associated with their countries also need to show their strong connection with the country such as having a manufacturing setup in the country, influx of designs emerging from the talent present in the country, or having a part of production process set up in that country. For the simple reason, the consumers are more likely to buy the product or service if they are authentic. The brand managers need to emphasize on such points while branding." }, { "code": null, "e": 20219, "s": 20105, "text": "The Country Brand Index (CBI) measures and ranks the countries on the strength and power of their nation’s brand." }, { "code": null, "e": 20336, "s": 20219, "text": "Examples of brand messaging by some countries − “Botswana Our pride, your destination.”, “Canada – Keep exploring”." }, { "code": null, "e": 20721, "s": 20336, "text": "Brand equity is the heart of brand management. The brand managers are engaged in building strong brand equity as it directly affects the consumer’s buying decisions, defines market share of the product, and determines the brand position in the market. Strong brand equity can not only make the brand strong but also help the brand establish, survive, and perform well in the long run." }, { "code": null, "e": 20781, "s": 20721, "text": "Let us understand, what brand equity is and why it matters." }, { "code": null, "e": 20944, "s": 20781, "text": "This term came up in the marketing literature in 1980. This multidimensional concept has different meanings from the context of Accounts, Marketing, and Consumer." }, { "code": null, "e": 21097, "s": 20944, "text": "Accounting Context − It is a total value of a brand as a separable asset, when evaluated for selling. It is also called Brand Value. It is quantifiable." }, { "code": null, "e": 21250, "s": 21097, "text": "Accounting Context − It is a total value of a brand as a separable asset, when evaluated for selling. It is also called Brand Value. It is quantifiable." }, { "code": null, "e": 21449, "s": 21250, "text": "Marketing Context − It is the description of consumer’s associations and beliefs about the brand. It is non-quantifiable. Brand equity is tailored according to the needs and demands of the consumer." }, { "code": null, "e": 21648, "s": 21449, "text": "Marketing Context − It is the description of consumer’s associations and beliefs about the brand. It is non-quantifiable. Brand equity is tailored according to the needs and demands of the consumer." }, { "code": null, "e": 21791, "s": 21648, "text": "Consumer-based Context − It is a measure of consumers’ attachment to a brand. It is also called brand strength or loyalty. It is quantifiable." }, { "code": null, "e": 21934, "s": 21791, "text": "Consumer-based Context − It is a measure of consumers’ attachment to a brand. It is also called brand strength or loyalty. It is quantifiable." }, { "code": null, "e": 22034, "s": 21934, "text": "As per Amber and Styles (1996), Brand Equity is a store of profits which can be realized in future." }, { "code": null, "e": 22244, "s": 22034, "text": "For brand management, the brand equity is vital as it establishes and fosters the customer loyalty towards the brand, and directly influences the business growth may it be a well-established or a new business." }, { "code": null, "e": 22297, "s": 22244, "text": "There can be two motivations to study brand equity −" }, { "code": null, "e": 22538, "s": 22297, "text": "Finance-based motivation − You can estimate the brand value more precisely for accounting purposes, such as to evaluate the brand as an asset for the purpose of reflecting in the balance sheet, or in case of merging or acquiring a business." }, { "code": null, "e": 22779, "s": 22538, "text": "Finance-based motivation − You can estimate the brand value more precisely for accounting purposes, such as to evaluate the brand as an asset for the purpose of reflecting in the balance sheet, or in case of merging or acquiring a business." }, { "code": null, "e": 22872, "s": 22779, "text": "Strategy-based motivation − You can study brand equity to improve productivity of marketing." }, { "code": null, "e": 22965, "s": 22872, "text": "Strategy-based motivation − You can study brand equity to improve productivity of marketing." }, { "code": null, "e": 23232, "s": 22965, "text": "It is a progressive loss of brand integrity due to weakening of essential brand elements. It also includes losing the respect of consumers and consistency of the brand. It is a gradual process. For example, a number of US airlines are facing brand decay since years." }, { "code": null, "e": 23286, "s": 23232, "text": "Here are some most important reasons of brand decay −" }, { "code": null, "e": 23387, "s": 23286, "text": "Company fails to manage strategies, create new value, and acquire new customers or new marketplaces." }, { "code": null, "e": 23488, "s": 23387, "text": "Company fails to manage strategies, create new value, and acquire new customers or new marketplaces." }, { "code": null, "e": 23581, "s": 23488, "text": "Company treats the brand merely as a static asset than as a medium to create customer value." }, { "code": null, "e": 23674, "s": 23581, "text": "Company treats the brand merely as a static asset than as a medium to create customer value." }, { "code": null, "e": 23736, "s": 23674, "text": "Customer expectations are more than what a brand can deliver." }, { "code": null, "e": 23798, "s": 23736, "text": "Customer expectations are more than what a brand can deliver." }, { "code": null, "e": 23843, "s": 23798, "text": "Presence of issues in brand equity building." }, { "code": null, "e": 23888, "s": 23843, "text": "Presence of issues in brand equity building." }, { "code": null, "e": 23966, "s": 23888, "text": "Company palms off brand-customer relationship on customer service department." }, { "code": null, "e": 24044, "s": 23966, "text": "Company palms off brand-customer relationship on customer service department." }, { "code": null, "e": 24154, "s": 24044, "text": "Company halts innovations in products or services. The worst part is, customers start suggesting innovations." }, { "code": null, "e": 24264, "s": 24154, "text": "Company halts innovations in products or services. The worst part is, customers start suggesting innovations." }, { "code": null, "e": 24370, "s": 24264, "text": "David Aaker and Kelvin Lane Keller developed the brand equity models. Let us learn about both the models." }, { "code": null, "e": 24658, "s": 24370, "text": "David Aaker defines brand equity as a set of assets and liabilities linked to a brand that add value to or subtract value from the product or service under that brand. He developed a brand equity model (also called Five Assets Model) in which he identifies five brand equity components −" }, { "code": null, "e": 24740, "s": 24658, "text": "The following factors depict the extent to which customers are loyal to a brand −" }, { "code": null, "e": 24819, "s": 24740, "text": "Reduced Costs − Maintaining loyal customers is cheaper than charming new ones." }, { "code": null, "e": 24898, "s": 24819, "text": "Reduced Costs − Maintaining loyal customers is cheaper than charming new ones." }, { "code": null, "e": 24970, "s": 24898, "text": "Trade Leverage − The loyal customers generate steady source of revenue." }, { "code": null, "e": 25042, "s": 24970, "text": "Trade Leverage − The loyal customers generate steady source of revenue." }, { "code": null, "e": 25137, "s": 25042, "text": "Bringing New Customers − Existing customers boost brand awareness and can bring new customers." }, { "code": null, "e": 25232, "s": 25137, "text": "Bringing New Customers − Existing customers boost brand awareness and can bring new customers." }, { "code": null, "e": 25428, "s": 25232, "text": "Competitive Threats Response Time − Loyal customers take time to switch to a new product or service offered by other brand. Hence this buys time for the company to respond to competitive threats." }, { "code": null, "e": 25624, "s": 25428, "text": "Competitive Threats Response Time − Loyal customers take time to switch to a new product or service offered by other brand. Hence this buys time for the company to respond to competitive threats." }, { "code": null, "e": 25716, "s": 25624, "text": "The following measures depict the extent to which a brand is widely known among consumers −" }, { "code": null, "e": 25848, "s": 25716, "text": "Association Anchors − Depending upon the brand strength, associations can be attached to the brand which influence brand awareness." }, { "code": null, "e": 25980, "s": 25848, "text": "Association Anchors − Depending upon the brand strength, associations can be attached to the brand which influence brand awareness." }, { "code": null, "e": 26092, "s": 25980, "text": "Familiarity − The consumers familiar with a brand will speak more about it and thus, influence brand awareness." }, { "code": null, "e": 26204, "s": 26092, "text": "Familiarity − The consumers familiar with a brand will speak more about it and thus, influence brand awareness." }, { "code": null, "e": 26308, "s": 26204, "text": "Substantiality − Consumers’ review on brand brings substantial and strong commitment towards the brand." }, { "code": null, "e": 26412, "s": 26308, "text": "Substantiality − Consumers’ review on brand brings substantial and strong commitment towards the brand." }, { "code": null, "e": 26505, "s": 26412, "text": "Consumer’s Consideration − At the time of purchasing, consumer looks for a particular brand." }, { "code": null, "e": 26598, "s": 26505, "text": "Consumer’s Consideration − At the time of purchasing, consumer looks for a particular brand." }, { "code": null, "e": 26720, "s": 26598, "text": "It is the extent to which a brand is believed to provide quality products. It can be measured on the following criteria −" }, { "code": null, "e": 26771, "s": 26720, "text": "Quality − The quality itself is the reason to buy." }, { "code": null, "e": 26822, "s": 26771, "text": "Quality − The quality itself is the reason to buy." }, { "code": null, "e": 26961, "s": 26822, "text": "Brand Position − This is a level of differentiation as compared to competing brands. Higher the position, higher is the perceived quality." }, { "code": null, "e": 27100, "s": 26961, "text": "Brand Position − This is a level of differentiation as compared to competing brands. Higher the position, higher is the perceived quality." }, { "code": null, "e": 27252, "s": 27100, "text": "Price − When quality of the product is too complex to assess and consumer’s status comes into picture, the consumer takes price as a quality indicator." }, { "code": null, "e": 27404, "s": 27252, "text": "Price − When quality of the product is too complex to assess and consumer’s status comes into picture, the consumer takes price as a quality indicator." }, { "code": null, "e": 27483, "s": 27404, "text": "Wide Availability − Consumers take widely available product as a reliable one." }, { "code": null, "e": 27562, "s": 27483, "text": "Wide Availability − Consumers take widely available product as a reliable one." }, { "code": null, "e": 27682, "s": 27562, "text": "Number of Brand Extensions − The consumers tend to take a brand with more extensions as a measure of product guarantee." }, { "code": null, "e": 27802, "s": 27682, "text": "Number of Brand Extensions − The consumers tend to take a brand with more extensions as a measure of product guarantee." }, { "code": null, "e": 28004, "s": 27802, "text": "It is the degree to which a specific product/service is recognized within its product or service category. For example, a person asking for Xerox wants to actually make true copies of a paper document." }, { "code": null, "e": 28141, "s": 28004, "text": "Information Retrieval − It is the extent to which the brand name is able to retrieve or process the associations from consumer’s memory." }, { "code": null, "e": 28278, "s": 28141, "text": "Information Retrieval − It is the extent to which the brand name is able to retrieve or process the associations from consumer’s memory." }, { "code": null, "e": 28373, "s": 28278, "text": "Drive Purchasing − This is the extent to which brand associations drive consumers to purchase." }, { "code": null, "e": 28468, "s": 28373, "text": "Drive Purchasing − This is the extent to which brand associations drive consumers to purchase." }, { "code": null, "e": 28575, "s": 28468, "text": "Attitude − This is the extent to which brand associations create positive attitude in the consumer’s mind." }, { "code": null, "e": 28682, "s": 28575, "text": "Attitude − This is the extent to which brand associations create positive attitude in the consumer’s mind." }, { "code": null, "e": 28780, "s": 28682, "text": "Number of Brand Extensions − More the extensions, more the opportunity to add brand associations." }, { "code": null, "e": 28878, "s": 28780, "text": "Number of Brand Extensions − More the extensions, more the opportunity to add brand associations." }, { "code": null, "e": 29075, "s": 28878, "text": "They are patents, copyrights, trademarks, trade secrets, and other intellectual property rights. More the number of proprietary assets a brand has, greater is the brand’s competency in the market." }, { "code": null, "e": 29375, "s": 29075, "text": "This model is developed by Kelvin Lane Keller, a marketing professor at Dartmouth College. It is based on the idea that the power of a brand lies in what the consumer has heard, learnt, felt, and seen as a brand over time. Hence this model is also termed as Customer Based Brand Equity (CBBE) model." }, { "code": null, "e": 29519, "s": 29375, "text": "According to CBBE model, it takes answers to four basic questions for building brand equity starting from the base of the pyramid shown above −" }, { "code": null, "e": 29549, "s": 29519, "text": "Who are you? (Brand Identity)" }, { "code": null, "e": 29580, "s": 29549, "text": "What are you? (Brand Meaning) " }, { "code": null, "e": 29633, "s": 29580, "text": "What do I feel or think about you? (Brand Responses)" }, { "code": null, "e": 29722, "s": 29633, "text": "What type and extent of association I would like to have with you? (Brand Relationships)" }, { "code": null, "e": 29926, "s": 29722, "text": "It is not only how often and easily the consumer can recall or recognize the brand but also where and when he thinks of the brand. The key is to create brand salience to acquiring correct brand identity." }, { "code": null, "e": 30135, "s": 29926, "text": "According to Keller, to make the brand meaningful it is essential to create a brand image and characteristics. Brand meaning arises out of brand associations, which can be imagery-related or function-related." }, { "code": null, "e": 30362, "s": 30135, "text": "The imagery-related associations depict how well the brand meets social and psychological needs of the consumer. The function-related association such as product or service performance is what the consumer looks for primarily." }, { "code": null, "e": 30657, "s": 30362, "text": "Regardless of the type of product or service, developing and delivering the product that completely satisfies the customer’s needs and demands is the prime objective of making the brand meaningful. A brand with the right identity and meaning creates a sense of relevance in the consumer’s mind." }, { "code": null, "e": 30796, "s": 30657, "text": "The companies must cater for the consumer’s response. Keller segregates these responses into consumer’s judgments and consumer’s feelings." }, { "code": null, "e": 31079, "s": 30796, "text": "Consumer Judgments − They are consumer’s personal opinions regarding the brand and how he has put imagery-related and performance-related associations together. There are four types of judgments crucial for creating a strong brand −\n\nQuality\nCredibility\nConsideration\nSuperiority\n\n" }, { "code": null, "e": 31313, "s": 31079, "text": "Consumer Judgments − They are consumer’s personal opinions regarding the brand and how he has put imagery-related and performance-related associations together. There are four types of judgments crucial for creating a strong brand −" }, { "code": null, "e": 31321, "s": 31313, "text": "Quality" }, { "code": null, "e": 31333, "s": 31321, "text": "Credibility" }, { "code": null, "e": 31347, "s": 31333, "text": "Consideration" }, { "code": null, "e": 31359, "s": 31347, "text": "Superiority" }, { "code": null, "e": 31631, "s": 31359, "text": "Consumer Feelings − They are consumer’s emotional reactions to the brand. They can be mild, intense, positive, negative, driven from heart or head. There are six important feelings crucial in brand building −\n\nWarmth\nFun\nExcitement\nSecurity\nSocial approval\nSelf-respect\n\n" }, { "code": null, "e": 31840, "s": 31631, "text": "Consumer Feelings − They are consumer’s emotional reactions to the brand. They can be mild, intense, positive, negative, driven from heart or head. There are six important feelings crucial in brand building −" }, { "code": null, "e": 31847, "s": 31840, "text": "Warmth" }, { "code": null, "e": 31851, "s": 31847, "text": "Fun" }, { "code": null, "e": 31862, "s": 31851, "text": "Excitement" }, { "code": null, "e": 31871, "s": 31862, "text": "Security" }, { "code": null, "e": 31887, "s": 31871, "text": "Social approval" }, { "code": null, "e": 31900, "s": 31887, "text": "Self-respect" }, { "code": null, "e": 32195, "s": 31900, "text": "It is the level of personal identification the consumer has with the brand. It is also called brand resonance, when a consumer has a deep psychological bonding with the brand. Brand resonance is the most difficult and highly desirable level to achieve. Keller categorizes this into four types −" }, { "code": null, "e": 32277, "s": 32195, "text": "Behavioral Loyalty − Consumers may purchase a brand repeatedly or in high volume." }, { "code": null, "e": 32359, "s": 32277, "text": "Behavioral Loyalty − Consumers may purchase a brand repeatedly or in high volume." }, { "code": null, "e": 32480, "s": 32359, "text": "Attitudinal Attachment − Some consumers may buy a brand because it is their favorite possession or out of some pleasure." }, { "code": null, "e": 32601, "s": 32480, "text": "Attitudinal Attachment − Some consumers may buy a brand because it is their favorite possession or out of some pleasure." }, { "code": null, "e": 32781, "s": 32601, "text": "Sense of Community − Being identified with a brand community develops kinship in the consumer’s mind towards representatives, employees, or other people associated with the brand." }, { "code": null, "e": 32961, "s": 32781, "text": "Sense of Community − Being identified with a brand community develops kinship in the consumer’s mind towards representatives, employees, or other people associated with the brand." }, { "code": null, "e": 33175, "s": 32961, "text": "Active Engagement − Consumers invests time, money, energy, or other resources and participates actively in brand chat rooms, blogs, etc., beyond mere consumption of brand. Thus, the consumers strengthen the brand." }, { "code": null, "e": 33389, "s": 33175, "text": "Active Engagement − Consumers invests time, money, energy, or other resources and participates actively in brand chat rooms, blogs, etc., beyond mere consumption of brand. Thus, the consumers strengthen the brand." }, { "code": null, "e": 33588, "s": 33389, "text": "BrandZ is the world’s largest brand equity database created and updated by Millward Brown, a multinational company working in advertising, marketing communications, media, and brand equity research." }, { "code": null, "e": 33875, "s": 33588, "text": "This database was created in 1998 and is being updated continuously since then. It lists top 100 global brands since 2006. To compile this database, the raw data is collected from about two million consumers and professionals across more than 30 countries. It lists around 23000 brands." }, { "code": null, "e": 34007, "s": 33875, "text": "BrandZ is the only brand valuation tool that helps brand owners to find out how much brand alone can contribute to corporate value." }, { "code": null, "e": 34322, "s": 34007, "text": "Brand asset valuation evaluates a brand’s value, strength, and performance as compared to other brands in the market. An agency named Young and Rubicam developed a metric called Brand Asset Valuator (BAV), which measures brand vitality, which is the brand’s potential in terms of its future growth and brand power." }, { "code": null, "e": 34369, "s": 34322, "text": "The brand is analyzed in the following terms −" }, { "code": null, "e": 34447, "s": 34369, "text": "Differentiation − How different and better is the brand from its competitors?" }, { "code": null, "e": 34525, "s": 34447, "text": "Differentiation − How different and better is the brand from its competitors?" }, { "code": null, "e": 34602, "s": 34525, "text": "Relevance − How closely the target audience can relate with the brand offer?" }, { "code": null, "e": 34679, "s": 34602, "text": "Relevance − How closely the target audience can relate with the brand offer?" }, { "code": null, "e": 34775, "s": 34679, "text": "Esteem − Has the brand built its esteem by keeping all promises it made to the target audience?" }, { "code": null, "e": 34871, "s": 34775, "text": "Esteem − Has the brand built its esteem by keeping all promises it made to the target audience?" }, { "code": null, "e": 34931, "s": 34871, "text": "Knowledge − How many of the target audience know the brand?" }, { "code": null, "e": 34991, "s": 34931, "text": "Knowledge − How many of the target audience know the brand?" }, { "code": null, "e": 35174, "s": 34991, "text": "Brand equity, being the heart of brand management is very. Peter Farquhar, in a paper he published on Managing Brand Equity, suggests three stages in building strong brand identity −" }, { "code": null, "e": 35347, "s": 35174, "text": "Introduce − Introduce an innovative and quality product in the market. Use brand as a platform to launch future products. Customer’s positive recognition is very important." }, { "code": null, "e": 35520, "s": 35347, "text": "Introduce − Introduce an innovative and quality product in the market. Use brand as a platform to launch future products. Customer’s positive recognition is very important." }, { "code": null, "e": 35665, "s": 35520, "text": "Elaborate − Create brand awareness and associations so that the customers remember the brand and the positive opinions about it for a long time." }, { "code": null, "e": 35810, "s": 35665, "text": "Elaborate − Create brand awareness and associations so that the customers remember the brand and the positive opinions about it for a long time." }, { "code": null, "e": 35991, "s": 35810, "text": "Fortify − Make the brand create a positive consistent image in the customer’s mind. Develop brand extensions and create customer-brand emotional relationship to fortify the brand." }, { "code": null, "e": 36172, "s": 35991, "text": "Fortify − Make the brand create a positive consistent image in the customer’s mind. Develop brand extensions and create customer-brand emotional relationship to fortify the brand." }, { "code": null, "e": 36319, "s": 36172, "text": "In the contemporary market, three essential characteristics are required to manage the brand − brand identity, brand image, and brand positioning." }, { "code": null, "e": 36527, "s": 36319, "text": "Brand identity is nothing but the belief fostered by the brand, its uniqueness and key values. A brand has an identity when it is driven by a goal different from competing brands and is resistant to changes." }, { "code": null, "e": 36607, "s": 36527, "text": "A strong brand identity can be built when you have answers to these questions −" }, { "code": null, "e": 36639, "s": 36607, "text": "What is the brand’s unique aim?" }, { "code": null, "e": 36683, "s": 36639, "text": "What is the brand’s distinguishing feature?" }, { "code": null, "e": 36720, "s": 36683, "text": "What need is satisfied by the brand?" }, { "code": null, "e": 36745, "s": 36720, "text": "What are brand’s values?" }, { "code": null, "e": 36786, "s": 36745, "text": "What is the brand’s field of competence?" }, { "code": null, "e": 36825, "s": 36786, "text": "What is making the brand recognizable?" }, { "code": null, "e": 36963, "s": 36825, "text": "Brand image is the set of beliefs, real and imaginary shortcomings about the brand developed over a time and held in the consumer’s mind." }, { "code": null, "e": 37133, "s": 36963, "text": "Brand image is built using communication media such as advertising, publicity by mouth, packaging, online marketing programs, social media, and other ways of promotions." }, { "code": null, "e": 37316, "s": 37133, "text": "When the company portfolio is growing, the brands tend to evolve. It is critically important to define the structure of the brands within a portfolio to keep the brand health strong." }, { "code": null, "e": 37674, "s": 37316, "text": "The brand managers need to take various decisions such as considering the right time to extend the existing brand, selecting appropriate brand name, whether or not to have different websites for multiple brands and so on. Since each of such decisions has direct implications on the future, a plan for brands is developed to provide clarity to the consumers." }, { "code": null, "e": 37791, "s": 37674, "text": "Brand architecture comes in play while presenting the brand efficiently. Let us learn more about brand architecture." }, { "code": null, "e": 37985, "s": 37791, "text": "It is the structure of the brand in an organizational entity that defines how various brands and sub-brands in a company’s portfolio are related to each other or are different from one another." }, { "code": null, "e": 38224, "s": 37985, "text": "Brand architecture provides a hierarchy that depicts the roles and relationships within the products and services that make a company’s portfolio and makes sure that the external stakeholders understand the value of what the brands offer." }, { "code": null, "e": 38376, "s": 38224, "text": "They can be varied from pure to hybrid. However, generally brand architecture is distinguished into two categories − House of brands and Branded house." }, { "code": null, "e": 38390, "s": 38376, "text": "Product Brand" }, { "code": null, "e": 38402, "s": 38390, "text": "Range Brand" }, { "code": null, "e": 38413, "s": 38402, "text": "Line Brand" }, { "code": null, "e": 38429, "s": 38413, "text": "Endorsing Brand" }, { "code": null, "e": 38444, "s": 38429, "text": "Umbrella brand" }, { "code": null, "e": 38457, "s": 38444, "text": "Source brand" }, { "code": null, "e": 38470, "s": 38457, "text": "Master brand" }, { "code": null, "e": 38628, "s": 38470, "text": "Multiple brands or activities are brought together under a single name. There is complete freedom for the management of divisions, activities and the brands." }, { "code": null, "e": 38641, "s": 38628, "text": "For example," }, { "code": null, "e": 38879, "s": 38641, "text": "Mitsubishi Motors division and Mitsubishi Electricals division are completely unrelated except the fact that they come under Mitsubishi business. Both divisions manage their own advertising, and brand values, and obtain separate profits." }, { "code": null, "e": 39124, "s": 38879, "text": "It is a family of brands with high degree of unity. Here, the master brand structures the child brands in such a manner that they are capable of expressing the value of a parent brand. Master brand is the single brand acting as a driving force." }, { "code": null, "e": 39145, "s": 39124, "text": "For example, Google." }, { "code": null, "e": 39294, "s": 39145, "text": "Google books, Google maps, Google Translate, Google Mail, etc., all come under the master brand Google and only differentiate in their descriptions." }, { "code": null, "e": 39351, "s": 39294, "text": "Let us see the brand architecture strategies in detail −" }, { "code": null, "e": 39535, "s": 39351, "text": "The brand is a kind of product brand, if the corporate brand name is hidden and every product is assigned a different name and one single positioning. Each new product is a new brand." }, { "code": null, "e": 39727, "s": 39535, "text": "In this type, the company name is well known and guarantees the quality of the products. For source brand, the products are on the forefront, while the company name remains in the background." }, { "code": null, "e": 39944, "s": 39727, "text": "When a variant is added to the existing brand, it is called line extension. The variant can be anything from color, packaging, nutritional value addition, or a new shape. Line brand targets a subset of the consumers." }, { "code": null, "e": 40129, "s": 39944, "text": "For example, Cadbury Bournville comes in three flavors − Raisin & Nut, Rich Cocoa, and Cranberry. Likewise Dairy Milk Silk comes in Orange Peel, Roast Almond, and Fruit & Nut variants." }, { "code": null, "e": 40548, "s": 40129, "text": "This is the simplest type, where all units and divisions of a business share the same brand. The brand name is used for different but related products. It involves creating a brand equity for a single brand. It is also referred to as Corporate, Umbrella, or Parent brand. In this type, the product or service benefits are less important than brand promise. It drives purchase decisions and defines consumer experience." }, { "code": null, "e": 40885, "s": 40548, "text": "Here, a parent brand consists of various operating units which are identified by their own brands. The parent endorses the products or services under itself and has a clear market presence. There is a synergy between the product name and the parent name. This architecture provides credibility, approval, and guarantee to another brand." }, { "code": null, "e": 40951, "s": 40885, "text": "For example, Marriot Residence Inn, Courtyard, and Fairfield Inn." }, { "code": null, "e": 41207, "s": 40951, "text": "In this type, all or many brands are kept with separate identities, names, and life cycles of their own. They often compete with each other. The parent does not provide any brand equity to benefit the sub-brands. This structure is found in FMCG companies." }, { "code": null, "e": 41472, "s": 41207, "text": "In this architecture, a principle brand supports to qualify other brands. The idea is, if the ingredient is good, it amplifies the brands better than they would have amplified independently without the ingredient. Thus, the ingredient brands turn out as energizer." }, { "code": null, "e": 41638, "s": 41472, "text": "For example, Intel Inc. Any computer brand’s ad says “Intel Inside”, depicting Intel processor enabled motherboard that comes with high power and speed of execution." }, { "code": null, "e": 41752, "s": 41638, "text": "It is a combination of monolithic, endorsement, and portfolio architectures. These are the most common solutions." }, { "code": null, "e": 41926, "s": 41752, "text": "Brand architecture needs to be revised when the companies change their strategies or the business has added important features which are beyond the existing brand structure." }, { "code": null, "e": 42022, "s": 41926, "text": "The following parameters should be considered while choosing an appropriate branding strategy −" }, { "code": null, "e": 42041, "s": 42022, "text": "Marketing strategy" }, { "code": null, "e": 42056, "s": 42041, "text": "Business model" }, { "code": null, "e": 42064, "s": 42056, "text": "Culture" }, { "code": null, "e": 42084, "s": 42064, "text": "Speed of innovation" }, { "code": null, "e": 42132, "s": 42084, "text": "Added-value lever on which the product is based" }, { "code": null, "e": 42145, "s": 42132, "text": "Brand vision" }, { "code": null, "e": 42334, "s": 42145, "text": "Since most of the brand architectures are built over a substantial period of time in the domestic market, there are some all-time questions while launching the brand on the global canvas −" }, { "code": null, "e": 42379, "s": 42334, "text": "Should the brand architecture be globalized?" }, { "code": null, "e": 42424, "s": 42379, "text": "Should the brand architecture be globalized?" }, { "code": null, "e": 42500, "s": 42424, "text": "Can the present brand architecture be taken to the new potential countries?" }, { "code": null, "e": 42576, "s": 42500, "text": "Can the present brand architecture be taken to the new potential countries?" }, { "code": null, "e": 42772, "s": 42576, "text": "How to handle internationalizing of brand architecture in different countries when there is difference in their respective infrastructure, civic rules and regulations, media costs, to name a few?" }, { "code": null, "e": 42968, "s": 42772, "text": "How to handle internationalizing of brand architecture in different countries when there is difference in their respective infrastructure, civic rules and regulations, media costs, to name a few?" }, { "code": null, "e": 43141, "s": 42968, "text": "For instance, it is definite that taking a brand architecture to Russia could be smoother than taking it to the US as the media and distribution costs are higher in the US." }, { "code": null, "e": 43250, "s": 43141, "text": "If a brand architecture is not proper, it can lead to unwelcome consequences. Few instances are as follows −" }, { "code": null, "e": 43707, "s": 43250, "text": "When there are too many daughter brands, the parent brand loses the focus. In the bargain of achieving recognition for the daughter brand, the parent brand takes a backstep. While launching a daughter brand, it gets people’s attention and the daughter brand attracts all the investment on the advertisement. It gets remarkably successful thereby taking over the image of the parent brand. The solution to this is, turn daughter brand into a simple product." }, { "code": null, "e": 43904, "s": 43707, "text": "For example, Golf, the daughter brand of Volkswagen swallowed it up in image. Amul Lite, a daughter brand is swallowing parent brand Amul butter due to increased health-consciousness of consumers." }, { "code": null, "e": 44211, "s": 43904, "text": "The company makes innovative products or makes improvements in the existing product. When a superior product comes up, it is time to decide for the brand managers whether to extend the new product as a part of the original brand or launch it as a new product with a potential of becoming a brand in itself." }, { "code": null, "e": 44353, "s": 44211, "text": "While branding the new product out of innovation, the connection between the product and the company that develops it should not be weakened." }, { "code": null, "e": 44563, "s": 44353, "text": "The company grows by bringing out the best in its product. Every time a research and development team comes up with the innovative product, the brand managers have to decide on what to name that ‘new’ product." }, { "code": null, "e": 44924, "s": 44563, "text": "For example, a cement manufacturing company came up with an innovative cement that provides extremely smooth surface. Before introducing it into the market, brand managers need to be decide what to name the product. Is it fine to extend the name just as ‘new ultra smooth cement from...’? Or should it be given a name that can stand as a brand in itself later?" }, { "code": null, "e": 45100, "s": 44924, "text": "Brand name is the mightiest form of its identity. It tells the objective of the program and reveals brand intentions. Some brand names and products apparently seem irrelevant." }, { "code": null, "e": 45539, "s": 45100, "text": "As in case of ‘Apple’, the microcomputers brand, Steve Jobs and the co-founder Steve Wozniak chose this name with the logo of a munched apple as they intended to give a new look to the conventional human-machine relationship. The apple logo tells that a computer machine is something to enjoy, rather than to fear about. Similarly, Amazon logo with a directed arrow from a-to-z depicts range, continuity, strength, and uninterrupted flow." }, { "code": null, "e": 45706, "s": 45539, "text": "Thus, to make a strong brand, almost any name can be chosen, with the fact that the brand managers need to put consistent efforts in making the brand name meaningful." }, { "code": null, "e": 45920, "s": 45706, "text": "Brand name is not a product. Hence while selecting brand name for a new product, the names which differentiate the product among its competitors must be chosen instead of those that describe what the product does." }, { "code": null, "e": 46176, "s": 45920, "text": "Instead of working behind a logo or a brand name, the companies have started coming up as brands themselves called corporate brands. They are choosing to become as widely visible as possible out of the consumer’s demand of responsibility and transparency." }, { "code": null, "e": 46565, "s": 46176, "text": "By presenting itself under corporate brand profile, the companies can attract students and executives in the employment market. In Asia, at the end of Procter and Gamble television ad, company signature is displayed for a few seconds as it is already visible and established as a corporate brand. In the US the P&G experience is different and it needs efforts to make itself more visible." }, { "code": null, "e": 46980, "s": 46565, "text": "Few companies have preferred to keep their own names separate from their brand names for the reason of getting affected in case of brand failure. There are other reasons of corporate visibility over product visibility. The multi-brand retailers, hyper chains are interested in corporate visibility of a company rather than product brands they sell as their basic B2B relation is with companies and not with brands." }, { "code": null, "e": 47366, "s": 46980, "text": "In today’s market, the customer has a very wide choice of products. When it comes to brands, he chooses brands but he tends to compare the products of different brands. Products increase customer’s choice whereas brands simplify decision making. To influence the customer’s buying decision and to get hold of the competitor’s market share, brand identity and positioning are essential." }, { "code": null, "e": 47493, "s": 47366, "text": "Brand management works with these two fundamental tools, brand identity and brand positioning. Let us understand these terms −" }, { "code": null, "e": 47701, "s": 47493, "text": "It specifies that a brand has a goal that is different from the goals of other parallel brands in the same market segment and it has resistance to change. It is defined clearly and does not change over time." }, { "code": null, "e": 47853, "s": 47701, "text": "Brand identity is fixed in nature being tied to the fixed parameters such as brand’s vision, objective, field of competence, and overall brand charter." }, { "code": null, "e": 48242, "s": 47853, "text": "Brand positioning is emphasizing on the distinguishing characteristics of the brand, those that make the brand appealing to the consumers and stand out among its competitors. It specifies how the products of a brand penetrate the market to grow their market share while dealing with the competitor brands. Brand positioning is competition oriented and hence dynamic over a period of time." }, { "code": null, "e": 48330, "s": 48242, "text": "Brand identity can be represented by six faces of a hexagon or a prism as shown below −" }, { "code": null, "e": 48627, "s": 48330, "text": "Brand Physique − It is the tangible and physical added value, as well as the backbone of a brand. It considers physical aspect of brand: How does it look, what does it do, the flagship product of the brand, which represents its qualities. For example, the dark color of Coke and colorless Sprite." }, { "code": null, "e": 48924, "s": 48627, "text": "Brand Physique − It is the tangible and physical added value, as well as the backbone of a brand. It considers physical aspect of brand: How does it look, what does it do, the flagship product of the brand, which represents its qualities. For example, the dark color of Coke and colorless Sprite." }, { "code": null, "e": 49305, "s": 48924, "text": "Brand Personality − If a brand were a person, what kind of person it would be? Would it be sincere (TATA Salt), exciting (Perk), rugged (Woodland), sophisticated (Mercedes), elite (Versace)? The brand has personality which speaks for its products and services.\nWhen a famous character, spokesperson, or a figurehead is used for branding, it gives the brand an instant personality." }, { "code": null, "e": 49566, "s": 49305, "text": "Brand Personality − If a brand were a person, what kind of person it would be? Would it be sincere (TATA Salt), exciting (Perk), rugged (Woodland), sophisticated (Mercedes), elite (Versace)? The brand has personality which speaks for its products and services." }, { "code": null, "e": 49686, "s": 49566, "text": "When a famous character, spokesperson, or a figurehead is used for branding, it gives the brand an instant personality." }, { "code": null, "e": 49911, "s": 49686, "text": "Culture − It is the set of values that governs and inspires the brand. Countries of origin, presence of brand over geographically diverse regions, changing society, etc., play an important role in building a brand’s culture." }, { "code": null, "e": 50136, "s": 49911, "text": "Culture − It is the set of values that governs and inspires the brand. Countries of origin, presence of brand over geographically diverse regions, changing society, etc., play an important role in building a brand’s culture." }, { "code": null, "e": 50309, "s": 50136, "text": "Customer Self-Image − It is what the brand is able to create in the customer’s mind and how the customers perceive about themselves after purchasing the product of a brand." }, { "code": null, "e": 50482, "s": 50309, "text": "Customer Self-Image − It is what the brand is able to create in the customer’s mind and how the customers perceive about themselves after purchasing the product of a brand." }, { "code": null, "e": 50711, "s": 50482, "text": "Customer Reflection − It is the perception of a customer about the brand after using the brand. For example, “The Thunderbird I purchased is value for price. It is giving me pleasure of leisure riding. Thanks to Royale Enfield.”" }, { "code": null, "e": 50940, "s": 50711, "text": "Customer Reflection − It is the perception of a customer about the brand after using the brand. For example, “The Thunderbird I purchased is value for price. It is giving me pleasure of leisure riding. Thanks to Royale Enfield.”" }, { "code": null, "e": 51240, "s": 50940, "text": "Relationship − Brands communicate, interact, transact with the consumer. It is the mode of conduct that defines the brand. This factor is vital for service brands. For example, banking where the cordial relationship develops faith in the customers when it comes to handling their money with respect." }, { "code": null, "e": 51540, "s": 51240, "text": "Relationship − Brands communicate, interact, transact with the consumer. It is the mode of conduct that defines the brand. This factor is vital for service brands. For example, banking where the cordial relationship develops faith in the customers when it comes to handling their money with respect." }, { "code": null, "e": 51617, "s": 51540, "text": "Let us consider the example of brand identity prism for Garnier’s BB cream −" }, { "code": null, "e": 51927, "s": 51617, "text": "Keller defines brand image as awareness of brand name (whether and when customers know the brand and can recall it) and belief about brand image (customer’s associations with the brand). If either of both is created successfully while leaving the other one in poor state, it brings down the brand drastically." }, { "code": null, "e": 52084, "s": 51927, "text": "For example, Salman Khan is a brand in himself with very high awareness. But his image went bad due to the hit-and-run case and that spoiled his reputation." }, { "code": null, "e": 52202, "s": 52084, "text": "Creation of Brand knowledge is a collective effort of consumer, marketer, researchers, distributors, and ad agencies." }, { "code": null, "e": 52282, "s": 52202, "text": "Creating brand knowledge is extremely important for the company’s stakeholders." }, { "code": null, "e": 52478, "s": 52282, "text": "There can be a single brand portfolio or multiple brand portfolios. The companies decide courageously to create a new brand for its growth when the existing brand does not perform satisfactorily." }, { "code": null, "e": 52850, "s": 52478, "text": "There is a wide variety of consumers in terms of their behavior, economic status, tastes, genders, age groups, and preferences. If the market segmentation is too diverse, it becomes hard for a single brand to meet the demand of maximum consumers. Thus, the main objective of creating a multi-brand portfolio is to meet the demands of the segmented market in a better way." }, { "code": null, "e": 53134, "s": 52850, "text": "To avoid the conflicts with the existing brand and the market segment, the companies are inclined towards creating a new brand each time it ventures into a new market segment. A multi-brand portfolio covers large market segment and can stop entry of any new competitor in the market." }, { "code": null, "e": 53208, "s": 53134, "text": "Place and operate the brands within a portfolio with strong coordination." }, { "code": null, "e": 53282, "s": 53208, "text": "Place and operate the brands within a portfolio with strong coordination." }, { "code": null, "e": 53341, "s": 53282, "text": "Set clear and precise charter and identity for each brand." }, { "code": null, "e": 53400, "s": 53341, "text": "Set clear and precise charter and identity for each brand." }, { "code": null, "e": 53506, "s": 53400, "text": "Build strong brand architecture. Position the brands to increase their appropriateness and target market." }, { "code": null, "e": 53612, "s": 53506, "text": "Build strong brand architecture. Position the brands to increase their appropriateness and target market." }, { "code": null, "e": 53661, "s": 53612, "text": "Focus on a particular competitor for each brand." }, { "code": null, "e": 53710, "s": 53661, "text": "Focus on a particular competitor for each brand." }, { "code": null, "e": 53767, "s": 53710, "text": "Keep corporate organization and brand portfolio matched." }, { "code": null, "e": 53824, "s": 53767, "text": "Keep corporate organization and brand portfolio matched." }, { "code": null, "e": 53975, "s": 53824, "text": "Brand stays in the minds of consumers and helps the company to grow their market share and revenue. Here are few basic steps to build a strong brand −" }, { "code": null, "e": 54113, "s": 53975, "text": "Study the market, need of the hour, competitors, and target audience. Study the purpose of what you wish to accomplish through the brand." }, { "code": null, "e": 54251, "s": 54113, "text": "Study the market, need of the hour, competitors, and target audience. Study the purpose of what you wish to accomplish through the brand." }, { "code": null, "e": 54364, "s": 54251, "text": "Decide brand personality, culture, and profile. Think of distinctive features to stand out from the competitors." }, { "code": null, "e": 54477, "s": 54364, "text": "Decide brand personality, culture, and profile. Think of distinctive features to stand out from the competitors." }, { "code": null, "e": 54555, "s": 54477, "text": "Identify how the stakeholders perceive the brand. Bridge the perception gaps." }, { "code": null, "e": 54633, "s": 54555, "text": "Identify how the stakeholders perceive the brand. Bridge the perception gaps." }, { "code": null, "e": 54692, "s": 54633, "text": "Decide where you want the brand to position in the market." }, { "code": null, "e": 54751, "s": 54692, "text": "Decide where you want the brand to position in the market." }, { "code": null, "e": 54823, "s": 54751, "text": "Create a plan and work on strategies where you want to place the brand." }, { "code": null, "e": 54895, "s": 54823, "text": "Create a plan and work on strategies where you want to place the brand." }, { "code": null, "e": 54979, "s": 54895, "text": "Communicate the brand to consumers via TV ads, social media, online marketing, etc." }, { "code": null, "e": 55063, "s": 54979, "text": "Communicate the brand to consumers via TV ads, social media, online marketing, etc." }, { "code": null, "e": 55107, "s": 55063, "text": "Make sure the consumers remember the brand." }, { "code": null, "e": 55151, "s": 55107, "text": "Make sure the consumers remember the brand." }, { "code": null, "e": 55249, "s": 55151, "text": "Evaluate if the consumers are influenced in a right way and if you have accomplished the purpose." }, { "code": null, "e": 55347, "s": 55249, "text": "Evaluate if the consumers are influenced in a right way and if you have accomplished the purpose." }, { "code": null, "e": 55542, "s": 55347, "text": "To identify brand positioning, the brand manager needs to study the market segment of venture. To establish a strong brand positioning, you need to get clear answers to the following questions −" }, { "code": null, "e": 55718, "s": 55542, "text": "Brand for what benefit?\nFor example, The Body Shop uses natural ingredients in its products and is environment-friendly. Tropicana packs real fruit juices in tetra packs, etc." }, { "code": null, "e": 55742, "s": 55718, "text": "Brand for what benefit?" }, { "code": null, "e": 55894, "s": 55742, "text": "For example, The Body Shop uses natural ingredients in its products and is environment-friendly. Tropicana packs real fruit juices in tetra packs, etc." }, { "code": null, "e": 56117, "s": 55894, "text": "Brand for whom?\nIt is the target audience of the brand grouped as gender, age, economic bracket, etc. For example, while Nike is top clothing brand for all income group, Gucci and Fossil remain high income handbags brands." }, { "code": null, "e": 56133, "s": 56117, "text": "Brand for whom?" }, { "code": null, "e": 56340, "s": 56133, "text": "It is the target audience of the brand grouped as gender, age, economic bracket, etc. For example, while Nike is top clothing brand for all income group, Gucci and Fossil remain high income handbags brands." }, { "code": null, "e": 56414, "s": 56340, "text": "Brand for what reason?\nThese are the facts that support claimed benefits." }, { "code": null, "e": 56437, "s": 56414, "text": "Brand for what reason?" }, { "code": null, "e": 56488, "s": 56437, "text": "These are the facts that support claimed benefits." }, { "code": null, "e": 56566, "s": 56488, "text": "Brand against whom?\nThis defines the way to attack competitors’ market share." }, { "code": null, "e": 56586, "s": 56566, "text": "Brand against whom?" }, { "code": null, "e": 56644, "s": 56586, "text": "This defines the way to attack competitors’ market share." }, { "code": null, "e": 56703, "s": 56644, "text": "There is a standard formula to achieve brand positioning −" }, { "code": null, "e": 56916, "s": 56703, "text": "For ... (target market of potential buyers or consumers)\nBrand X is ... (definition of frame of reference and category)\nWhich gives the most ... (promise or consumer benefit) \nBecause of ... (reason to believe) \n" }, { "code": null, "e": 56923, "s": 56916, "text": "Where," }, { "code": null, "e": 57025, "s": 56923, "text": "The target market is the psychological and social profile of the consumers a brand aims to influence." }, { "code": null, "e": 57127, "s": 57025, "text": "The target market is the psychological and social profile of the consumers a brand aims to influence." }, { "code": null, "e": 57176, "s": 57127, "text": "Frame of reference is the nature of competition." }, { "code": null, "e": 57225, "s": 57176, "text": "Frame of reference is the nature of competition." }, { "code": null, "e": 57448, "s": 57225, "text": "Promise or consumer benefit is the feature that creates preference and drives decision after making choice. For example, Cadbury promises its Silk chocolate bars to be the smoothest ones among other Cadbury chocolate bars." }, { "code": null, "e": 57671, "s": 57448, "text": "Promise or consumer benefit is the feature that creates preference and drives decision after making choice. For example, Cadbury promises its Silk chocolate bars to be the smoothest ones among other Cadbury chocolate bars." }, { "code": null, "e": 57909, "s": 57671, "text": "The reason to believe is reinforcement of promise or consumer benefit. For example, Tropicana Products, the producer and marketer (a division of PepsiCo), promises to be delivering 100% pure fruit juices in its Pure Premium juices range." }, { "code": null, "e": 58147, "s": 57909, "text": "The reason to believe is reinforcement of promise or consumer benefit. For example, Tropicana Products, the producer and marketer (a division of PepsiCo), promises to be delivering 100% pure fruit juices in its Pure Premium juices range." }, { "code": null, "e": 58592, "s": 58147, "text": "Let us take an example of brand positioning conducted by Shoppers Stop, the retail chain in India that sells retail clothing, handbags, jewelry, perfumes, toys, home furnishing, and accessories. It has business of 20 billion dollars. It was founded in 1991 with first store at Mumbai and expanded rapidly across the country soon. The consumers perceived it as mass market brand and it started losing its shine in the retail competition in 2008." }, { "code": null, "e": 59168, "s": 58592, "text": "The brand managers and company management together carried out a store audit at all outlets, studied customer experiences, updated brand identity, and came up with new tagline, “Start something new”. It then repositioned the brand as premium, accessibleluxury sector. This position of bridge-to-luxury appealed young, middle-class consumers in India, who had their own money to spend at a young age. The new repositioning also added the credibility of Shoppers Stop to preset itself as a potential partner for international brands who were looking to enter the Indian market." }, { "code": null, "e": 59459, "s": 59168, "text": "The impact was, its share price grew 450% from 52-week low, sales rose more than 10%, and as newly acquired strength of positioning the brand, it started co-branding with international brands such as Chanel, Dior, Armani, Esprit, Tommy Hilfiger, Mothercare, Mustang, Austin Reed, and so on." }, { "code": null, "e": 59603, "s": 59459, "text": "Consumers are interested in brand values. When the consumer understands the brand value, he can interact with the business in a particular way." }, { "code": null, "e": 59753, "s": 59603, "text": "For defining and establishing brand values, you need to take an honest look at the product or service. You can proceed by using the following steps −" }, { "code": null, "e": 59813, "s": 59753, "text": "Step 1 − Find out the answers for the following questions −" }, { "code": null, "e": 59871, "s": 59813, "text": "What unique and competing feature my product/service has?" }, { "code": null, "e": 59939, "s": 59871, "text": "Why should the target audience take interest in my product/service?" }, { "code": null, "e": 60005, "s": 59939, "text": "What is my passion being a product manufacturer/service provider?" }, { "code": null, "e": 60081, "s": 60005, "text": "Step 2 − Compile a list of values related to the product/service, such as −" }, { "code": null, "e": 60092, "s": 60081, "text": "Simplicity" }, { "code": null, "e": 60100, "s": 60092, "text": "Quality" }, { "code": null, "e": 60114, "s": 60100, "text": "Affordability" }, { "code": null, "e": 60125, "s": 60114, "text": "Timeliness" }, { "code": null, "e": 60136, "s": 60125, "text": "Politeness" }, { "code": null, "e": 60146, "s": 60136, "text": "Integrity" }, { "code": null, "e": 60157, "s": 60146, "text": "Creativity" }, { "code": null, "e": 60168, "s": 60157, "text": "Innovation" }, { "code": null, "e": 60179, "s": 60168, "text": "Commitment" }, { "code": null, "e": 60220, "s": 60179, "text": "Step 3 − Narrow down the list of values." }, { "code": null, "e": 60363, "s": 60220, "text": "Bring down the list of values which are absolutely indisputable for execution of your business. Recommended number of values is three to four." }, { "code": null, "e": 60726, "s": 60363, "text": "For example, if your brand’s value is timeliness then make sure you keep the promise of shipping and delivery of products always on time, handle and reply to your customer inquiries in timely manner, attend the customer’s call in the shortest possible time etc. Make sure that the value is always consistently honored, despite any internal or external situation." }, { "code": null, "e": 60764, "s": 60726, "text": "Step 4 − Use the list as a reference." }, { "code": null, "e": 60881, "s": 60764, "text": "Use the list of brand values while creating new products or services, dealing with clients, consumers, and partners." }, { "code": null, "e": 61167, "s": 60881, "text": "Venturing into global markets is inevitable for brands. A brand is global when it is visible and sold at every possible place in the world. The consumer around the world become aware of various international brands if they travel worldwide or just watch a satellite television at home." }, { "code": null, "e": 61285, "s": 61167, "text": "Before you take the brand in the global market, you need to cater to various aspects of the global consumer such as −" }, { "code": null, "e": 61308, "s": 61285, "text": "Culture of Consumers −" }, { "code": null, "e": 61340, "s": 61308, "text": "The values the consumers follow" }, { "code": null, "e": 61365, "s": 61340, "text": "The customs they observe" }, { "code": null, "e": 61406, "s": 61365, "text": "Particular symbols and language they use" }, { "code": null, "e": 61433, "s": 61406, "text": "The tone of their behavior" }, { "code": null, "e": 61477, "s": 61433, "text": "Consumer’s level of income and buying power" }, { "code": null, "e": 61522, "s": 61477, "text": "Economic status of the country in terms of −" }, { "code": null, "e": 61535, "s": 61522, "text": "Power supply" }, { "code": null, "e": 61550, "s": 61535, "text": "Infrastructure" }, { "code": null, "e": 61572, "s": 61550, "text": "Communication systems" }, { "code": null, "e": 61593, "s": 61572, "text": "Distribution systems" }, { "code": null, "e": 61625, "s": 61593, "text": "Laws and Regulations enforced −" }, { "code": null, "e": 61649, "s": 61625, "text": "Is it lawful there too?" }, { "code": null, "e": 61684, "s": 61649, "text": "Political stability of the country" }, { "code": null, "e": 61972, "s": 61684, "text": "When the brand transits from local to global, it competes with other global brands. For example, Nokia battles Motorola and Samsung. The brand managers must manage the transnational brand to remain superior on the essentials such as the brand’s price, performance, features, and imagery." }, { "code": null, "e": 62268, "s": 61972, "text": "Brand promotion is the way to inform, remind, persuade convincingly, and influence the consumers to drive their decision towards purchasing the product or service under a brand. Marketing force of a company conducts brand promotion primarily, though the wholesalers and retailers also can do it." }, { "code": null, "e": 62301, "s": 62268, "text": "Brand promotion is required to −" }, { "code": null, "e": 62384, "s": 62301, "text": "Promote information related to features, prices, and special schemes of the brand." }, { "code": null, "e": 62467, "s": 62384, "text": "Promote information related to features, prices, and special schemes of the brand." }, { "code": null, "e": 62561, "s": 62467, "text": "Differentiate the product by convincing the customers about the unique features of the brand." }, { "code": null, "e": 62655, "s": 62561, "text": "Differentiate the product by convincing the customers about the unique features of the brand." }, { "code": null, "e": 62703, "s": 62655, "text": "Create and increase the demand for the product." }, { "code": null, "e": 62751, "s": 62703, "text": "Create and increase the demand for the product." }, { "code": null, "e": 62771, "s": 62751, "text": "Build brand equity." }, { "code": null, "e": 62791, "s": 62771, "text": "Build brand equity." }, { "code": null, "e": 62956, "s": 62791, "text": "Stabilize the sales affected by natural, social, or political changes. For example, Nescafe promoted its new brand of 'iced coffee' to increase sales during summer." }, { "code": null, "e": 63121, "s": 62956, "text": "Stabilize the sales affected by natural, social, or political changes. For example, Nescafe promoted its new brand of 'iced coffee' to increase sales during summer." }, { "code": null, "e": 63344, "s": 63121, "text": "Outperform the competitor’s marketing efforts: In a highly competitive market, even a well-established brand has to be promoted to retain market share. For example, Coca Cola and Pepsi work to nullify each other's efforts." }, { "code": null, "e": 63567, "s": 63344, "text": "Outperform the competitor’s marketing efforts: In a highly competitive market, even a well-established brand has to be promoted to retain market share. For example, Coca Cola and Pepsi work to nullify each other's efforts." }, { "code": null, "e": 63595, "s": 63567, "text": "Build positive brand image." }, { "code": null, "e": 63623, "s": 63595, "text": "Build positive brand image." }, { "code": null, "e": 63706, "s": 63623, "text": "There are various brand promotion methods conducted to keep the brand noticeable −" }, { "code": null, "e": 63876, "s": 63706, "text": "Organizing Contests − To attract the consumers, various contests are organized for consumers without having them to purchase the product and giving away gifts or prizes." }, { "code": null, "e": 64046, "s": 63876, "text": "Organizing Contests − To attract the consumers, various contests are organized for consumers without having them to purchase the product and giving away gifts or prizes." }, { "code": null, "e": 64234, "s": 64046, "text": "Promotion on Social Media − When the brand is promoted on social media, it is not perceived as “aggressively trying to sell”, rather as being able to communicate at a more personal level." }, { "code": null, "e": 64422, "s": 64234, "text": "Promotion on Social Media − When the brand is promoted on social media, it is not perceived as “aggressively trying to sell”, rather as being able to communicate at a more personal level." }, { "code": null, "e": 64580, "s": 64422, "text": "Product Giveaways − This strategy is used for promoting edibles, toiletries, foods, etc., where a small sample is given away to the consumers for free trial." }, { "code": null, "e": 64738, "s": 64580, "text": "Product Giveaways − This strategy is used for promoting edibles, toiletries, foods, etc., where a small sample is given away to the consumers for free trial." }, { "code": null, "e": 64906, "s": 64738, "text": "Point-of-Sale Promotion − These items are placed near the checkout counter in the store and are often purchased by consumers on impulse as they wait to be checked out." }, { "code": null, "e": 65074, "s": 64906, "text": "Point-of-Sale Promotion − These items are placed near the checkout counter in the store and are often purchased by consumers on impulse as they wait to be checked out." }, { "code": null, "e": 65245, "s": 65074, "text": "Customer Referral Incentive Programs − This is a way to bring new customers with the help of the existing customers by offering some incentives to the existing customers." }, { "code": null, "e": 65416, "s": 65245, "text": "Customer Referral Incentive Programs − This is a way to bring new customers with the help of the existing customers by offering some incentives to the existing customers." }, { "code": null, "e": 65644, "s": 65416, "text": "Causes and Charity − Some percent of the amount after selling the product is donated for a cause or charity thereby promoting the product. Charity and cause are the reasons which induce the feelings of helping in the customers." }, { "code": null, "e": 65872, "s": 65644, "text": "Causes and Charity − Some percent of the amount after selling the product is donated for a cause or charity thereby promoting the product. Charity and cause are the reasons which induce the feelings of helping in the customers." }, { "code": null, "e": 66091, "s": 65872, "text": "Promotional Gifts − It is giving away of gifts which the customers can practically use, such as caps, key chains, pens, etc. This helps the brand to always remain with the customers and creates an emotional attachment." }, { "code": null, "e": 66310, "s": 66091, "text": "Promotional Gifts − It is giving away of gifts which the customers can practically use, such as caps, key chains, pens, etc. This helps the brand to always remain with the customers and creates an emotional attachment." }, { "code": null, "e": 66643, "s": 66310, "text": "Customer Appreciation − It is organized with the objective of not selling the product or service. It is a way of creating a fond memory attached with the brand. It includes organizing in-store refreshment events with the offer of food treats of pizza, burger, beverages, etc. It is an effective way to bring new potential customers." }, { "code": null, "e": 66976, "s": 66643, "text": "Customer Appreciation − It is organized with the objective of not selling the product or service. It is a way of creating a fond memory attached with the brand. It includes organizing in-store refreshment events with the offer of food treats of pizza, burger, beverages, etc. It is an effective way to bring new potential customers." }, { "code": null, "e": 67212, "s": 66976, "text": "Another way of promoting brands is by employing a brand ambassador. A brand ambassador is a person who embodies the brand, influences the customers, creates brand awareness and a specific brand image, and generates sales opportunities." }, { "code": null, "e": 67589, "s": 67212, "text": "A brand ambassador usually represents only one brand at a time. The employing company considers the brand ambassador as a face of the company that speaks of the brand in their own words and boosts the positive image in the minds of consumers. The looks, talents, status, achievements, and reputation of a brand ambassador is useful for influencing large audience of consumers." }, { "code": null, "e": 67949, "s": 67589, "text": "In 2003, India’s largest chocolate brand, Cadbury went into worm controversy. To regain the consumer’s confidence, Cadbury contracted the Bollywood superstar Mr. Amitabh Bachchan for brand promotion. During his campaign, Cadbury not only restored the trust of consumers but also experienced boost in the sales of its flagship product Cadbury Dairy Milk (CDM)." }, { "code": null, "e": 68190, "s": 67949, "text": "Celebrity branding is nothing but using celebrities to promote the brand. The celebrities are featured in both electronic and print media ads. They appear at brand launches, corporate events for social responsibility, and other such events." }, { "code": null, "e": 68554, "s": 68190, "text": "Celebrity brand endorsers are different from brand ambassadors as the former are not employed by the company as the latter. The popularity, fame, and charisma of the celebrities is useful in brand promotion. Celebrities can endorse multiple brands at the same time unlike brand ambassadors. Similarly, a company can have multiple celebrities to promote its brand." }, { "code": null, "e": 68758, "s": 68554, "text": "Online brand promotion comes with the challenge of integrating the marketing mix (putting the right product, at the right price, at the right time) with the multi-channel, multi-device digital marketing." }, { "code": null, "e": 69034, "s": 68758, "text": "Online brand promotion leverages the power of Internet to present the brand to worldwide audience. But it is a kind of double-edged sword as whatever good a brand has can reach globally so does the brand’s weaknesses. There are various ways to promote a brand online. Such as" }, { "code": null, "e": 69226, "s": 69034, "text": "Publishing articles, news, spreading business links throughout the web, channeling the promotional schemes and ads towards the target audience, creating and updating the blogs and the forums." }, { "code": null, "e": 69418, "s": 69226, "text": "Publishing articles, news, spreading business links throughout the web, channeling the promotional schemes and ads towards the target audience, creating and updating the blogs and the forums." }, { "code": null, "e": 69522, "s": 69418, "text": "Creating and sharing videos, audios, and pictures of the brand on top ranking websites such as YouTube." }, { "code": null, "e": 69626, "s": 69522, "text": "Creating and sharing videos, audios, and pictures of the brand on top ranking websites such as YouTube." }, { "code": null, "e": 69781, "s": 69626, "text": "Creating the company’s business account on leading social networking websites such as Facebook, LinkedIn and promoting the brand by gaining new followers." }, { "code": null, "e": 69936, "s": 69781, "text": "Creating the company’s business account on leading social networking websites such as Facebook, LinkedIn and promoting the brand by gaining new followers." }, { "code": null, "e": 70024, "s": 69936, "text": "Engaging in social gaming such as Zynga, Kongregate, etc., under the name of the brand." }, { "code": null, "e": 70112, "s": 70024, "text": "Engaging in social gaming such as Zynga, Kongregate, etc., under the name of the brand." }, { "code": null, "e": 70287, "s": 70112, "text": "Brand extension is required for a company’s growth, profitability, and brand’s added reputation. It is an inevitable strategic move at some point of time in brand management." }, { "code": null, "e": 70514, "s": 70287, "text": "While extending a brand, all assumptions related to that brand held for a long time are revised and the brand’s identity is redefined. The brand managers need to identify growth opportunities and increase parent brand’s value." }, { "code": null, "e": 70695, "s": 70514, "text": "It is nothing but launching a product in a different category under an already established brand name. It is extending the existing brand promise with diverse products or services." }, { "code": null, "e": 70751, "s": 70695, "text": "The following diagram shows the matrix of brand growth." }, { "code": null, "e": 70823, "s": 70751, "text": "When a company introduces a new product, it has the following choices −" }, { "code": null, "e": 70858, "s": 70823, "text": "New Brand, New Product (New Brand)" }, { "code": null, "e": 70893, "s": 70858, "text": "New Brand, New Product (New Brand)" }, { "code": null, "e": 70935, "s": 70893, "text": "New Brand, Existing Product (Multi-Brand)" }, { "code": null, "e": 70977, "s": 70935, "text": "New Brand, Existing Product (Multi-Brand)" }, { "code": null, "e": 71023, "s": 70977, "text": "Existing Brand, New Product (Brand Extension)" }, { "code": null, "e": 71069, "s": 71023, "text": "Existing Brand, New Product (Brand Extension)" }, { "code": null, "e": 71119, "s": 71069, "text": "Existing Brand, Existing Product (Line Extension)" }, { "code": null, "e": 71169, "s": 71119, "text": "Existing Brand, Existing Product (Line Extension)" }, { "code": null, "e": 71235, "s": 71169, "text": "The last two in the above list are the types of brand extensions." }, { "code": null, "e": 71402, "s": 71235, "text": "A variation of existing product launched under the existing brand. It often adds different flavor, package size or shape. Here, established brand is the parent brand." }, { "code": null, "e": 71464, "s": 71402, "text": "For example, Coke is basic brand with Diet Coke as extension." }, { "code": null, "e": 71600, "s": 71464, "text": "A new product is launched under existing brand. It often adds a product of different category. The new associated brand is a sub-brand." }, { "code": null, "e": 71788, "s": 71600, "text": "For example, ITC brand with Sunfeast cookies, Vivel shampoo, Bingo chips as its sub-brands. In 1994, Titan Industries Ltd. extended the brand Tanishq, India’s only national jewelry brand." }, { "code": null, "e": 71867, "s": 71788, "text": "Let us see yet another excellent example of systematic brand extension, Nivea." }, { "code": null, "e": 72135, "s": 71867, "text": "Just like product launching, brand extension demands time, resource allocation, energy, and associated risks. When the brand is exposed into unknown market, it might face dominance among established competitors. In addition, the brand image can come into trouble too." }, { "code": null, "e": 72194, "s": 72135, "text": "Bypass efforts, time, and cost for developing a new brand." }, { "code": null, "e": 72256, "s": 72194, "text": "Leverages the reputation attached to the parent/family brand." }, { "code": null, "e": 72319, "s": 72256, "text": "Saves costs on follow-ups and introductory marketing programs." }, { "code": null, "e": 72373, "s": 72319, "text": "Reduces perceived risk of customer about the product." }, { "code": null, "e": 72406, "s": 72373, "text": "Elevates the parent brand image." }, { "code": null, "e": 72467, "s": 72406, "text": "On failure, brand extension can hurt the parent brand image." }, { "code": null, "e": 72554, "s": 72467, "text": "It can cannibalize parent brand if the sub-brand is more successful than parent brand." }, { "code": null, "e": 72623, "s": 72554, "text": "Creates confusion among customers if not communicated appropriately." }, { "code": null, "e": 72649, "s": 72623, "text": "Can dilute brand meaning." }, { "code": null, "e": 72758, "s": 72649, "text": "Brand adaption is nothing but introducing and engaging the consumer with the brand. It involves five steps −" }, { "code": null, "e": 72835, "s": 72758, "text": "Awareness − Customer knows the brand but does not have complete information." }, { "code": null, "e": 72912, "s": 72835, "text": "Awareness − Customer knows the brand but does not have complete information." }, { "code": null, "e": 72977, "s": 72912, "text": "Interest − Customer tries to find more information on the brand." }, { "code": null, "e": 73042, "s": 72977, "text": "Interest − Customer tries to find more information on the brand." }, { "code": null, "e": 73113, "s": 73042, "text": "Evaluation − Customer tries to know how beneficial the brand would be." }, { "code": null, "e": 73184, "s": 73113, "text": "Evaluation − Customer tries to know how beneficial the brand would be." }, { "code": null, "e": 73251, "s": 73184, "text": "Trial − Makes first purchase to determine its usefulness or worth." }, { "code": null, "e": 73318, "s": 73251, "text": "Trial − Makes first purchase to determine its usefulness or worth." }, { "code": null, "e": 73398, "s": 73318, "text": "Adapt/Reject − Becomes a loyal customer or looks for some other parallel brand." }, { "code": null, "e": 73478, "s": 73398, "text": "Adapt/Reject − Becomes a loyal customer or looks for some other parallel brand." }, { "code": null, "e": 73538, "s": 73478, "text": "The brand adaption practices involves the following steps −" }, { "code": null, "e": 73650, "s": 73538, "text": "Develop internal (brand managers and representatives) and external launching (consumer and prospects) of brand." }, { "code": null, "e": 73762, "s": 73650, "text": "Develop internal (brand managers and representatives) and external launching (consumer and prospects) of brand." }, { "code": null, "e": 73841, "s": 73762, "text": "Impart positive attitude towards the brand among sales managers and marketers." }, { "code": null, "e": 73920, "s": 73841, "text": "Impart positive attitude towards the brand among sales managers and marketers." }, { "code": null, "e": 73983, "s": 73920, "text": "Create high customer demands and expectations about the brand." }, { "code": null, "e": 74046, "s": 73983, "text": "Create high customer demands and expectations about the brand." }, { "code": null, "e": 74143, "s": 74046, "text": "Provide training for the sales and customer care force to practically deliver the brand promise." }, { "code": null, "e": 74240, "s": 74143, "text": "Provide training for the sales and customer care force to practically deliver the brand promise." }, { "code": null, "e": 74457, "s": 74240, "text": "There are various scenarios where a brand has successfully extended or failed to extend. For example, Bic ballpoint pens. It extended successfully into disposable razors but the extension into perfumes was a failure." }, { "code": null, "e": 74532, "s": 74457, "text": "The factors that influence acceptability of a brand extension are mainly −" }, { "code": null, "e": 74670, "s": 74532, "text": "Perceived risk − It is the evaluation of uncertainty about the type and degree of expected loss after making the consumer makes a choice." }, { "code": null, "e": 74808, "s": 74670, "text": "Perceived risk − It is the evaluation of uncertainty about the type and degree of expected loss after making the consumer makes a choice." }, { "code": null, "e": 74939, "s": 74808, "text": "Consumer’s Innovativeness − Personal trait or desire of consumers to try a new brand/product and thereby experience something new." }, { "code": null, "e": 75070, "s": 74939, "text": "Consumer’s Innovativeness − Personal trait or desire of consumers to try a new brand/product and thereby experience something new." }, { "code": null, "e": 75231, "s": 75070, "text": "Product Similarity − Greater the degree of similarity of the extended product with the original product, more is the chance of transferring the positive effect." }, { "code": null, "e": 75392, "s": 75231, "text": "Product Similarity − Greater the degree of similarity of the extended product with the original product, more is the chance of transferring the positive effect." }, { "code": null, "e": 75587, "s": 75392, "text": "Parent Brand Reputation and Strength − Brand’s reputation is associated with the consumer’s perception of the quality of the brand. Strong and reputed brands leverage extension than weak brands." }, { "code": null, "e": 75782, "s": 75587, "text": "Parent Brand Reputation and Strength − Brand’s reputation is associated with the consumer’s perception of the quality of the brand. Strong and reputed brands leverage extension than weak brands." }, { "code": null, "e": 76062, "s": 75782, "text": "A company requires to rebrand when it decides to change any of its brand elements such as brand name, logo, slogan, or even a small change in the message for better communication and more relevant brand promise. Rebranding is extremely important, expensive to execute, and risky." }, { "code": null, "e": 76231, "s": 76062, "text": "There are multiple reasons behind why companies initiate rebranding. These reasons can be categorized into two types − proactive or reactive. Let us take a deeper look." }, { "code": null, "e": 76316, "s": 76231, "text": "It happens when a company anticipates and prepares for future changes in the market." }, { "code": null, "e": 76383, "s": 76316, "text": "To prevent or prepare for future potential threats by competitors." }, { "code": null, "e": 76450, "s": 76383, "text": "To prevent or prepare for future potential threats by competitors." }, { "code": null, "e": 76623, "s": 76450, "text": "To plan for international growth, rebranding the products and services into a consolidated brand thereby saving money over time and creating a greater sense of brand unity." }, { "code": null, "e": 76796, "s": 76623, "text": "To plan for international growth, rebranding the products and services into a consolidated brand thereby saving money over time and creating a greater sense of brand unity." }, { "code": null, "e": 77170, "s": 76796, "text": "To enter into a category of business, product, or market which no longer remains cohesive to the existing brand identity. In case of Apple Inc., as the company evolved into new businesses beyond computers, the original brand name Apple Computers became too restrictive. It was then changed to Apple Inc. At the same time, Apple Inc. updated its logo depicting its progress." }, { "code": null, "e": 77544, "s": 77170, "text": "To enter into a category of business, product, or market which no longer remains cohesive to the existing brand identity. In case of Apple Inc., as the company evolved into new businesses beyond computers, the original brand name Apple Computers became too restrictive. It was then changed to Apple Inc. At the same time, Apple Inc. updated its logo depicting its progress." }, { "code": null, "e": 77720, "s": 77544, "text": "To attract new audience, or want to appeal to it. In case of McDonald’s ads, it refers to itself as McDonald’s to target a different demographic from its traditional audience." }, { "code": null, "e": 77896, "s": 77720, "text": "To attract new audience, or want to appeal to it. In case of McDonald’s ads, it refers to itself as McDonald’s to target a different demographic from its traditional audience." }, { "code": null, "e": 78096, "s": 77896, "text": "To increase the brand relevance in consumer’s mind, the company might decide to rebrand. For example, when the use of printed Yellow Pages directories started declining, Yellow Pages rebranded to YP." }, { "code": null, "e": 78296, "s": 78096, "text": "To increase the brand relevance in consumer’s mind, the company might decide to rebrand. For example, when the use of printed Yellow Pages directories started declining, Yellow Pages rebranded to YP." }, { "code": null, "e": 78438, "s": 78296, "text": "This branding occurs when the companies need to react to a significant change. Reactive rebranding might happen in the following situations −" }, { "code": null, "e": 78922, "s": 78438, "text": "When companies need to work on negative brand image.\nFor example, during 1990-2000, the London based men’s clothes making company Burberry’s public image was associated with hooliganism and violence. The brand had lost its image so badly that the clubs and pubs in UK had started banning entry for the people wearing Burberry. The company worked to disassociate itself from such an image by changing styles of the product, changing their logo, and applying excellence in everything.\n" }, { "code": null, "e": 78975, "s": 78922, "text": "When companies need to work on negative brand image." }, { "code": null, "e": 79405, "s": 78975, "text": "For example, during 1990-2000, the London based men’s clothes making company Burberry’s public image was associated with hooliganism and violence. The brand had lost its image so badly that the clubs and pubs in UK had started banning entry for the people wearing Burberry. The company worked to disassociate itself from such an image by changing styles of the product, changing their logo, and applying excellence in everything." }, { "code": null, "e": 79596, "s": 79405, "text": "When companies merge or acquire other companies, or when they separate. For example, California based Intel rival and chipmaker, Advanced Micro Devices (AMD) is considering to split shortly." }, { "code": null, "e": 79787, "s": 79596, "text": "When companies merge or acquire other companies, or when they separate. For example, California based Intel rival and chipmaker, Advanced Micro Devices (AMD) is considering to split shortly." }, { "code": null, "e": 80033, "s": 79787, "text": "When there are legal issues with branding. Trademarks are often the root cause for rebranding. For example, an Australian business tries to expand into USA and finds that its existing name is already trademarked and not available for use in USA." }, { "code": null, "e": 80279, "s": 80033, "text": "When there are legal issues with branding. Trademarks are often the root cause for rebranding. For example, an Australian business tries to expand into USA and finds that its existing name is already trademarked and not available for use in USA." }, { "code": null, "e": 80457, "s": 80279, "text": "When a competitor manifests a company’s brand as useless or outdated, then rebranding helps to get an opportunity to facelift the brand to effectively strike back in the market." }, { "code": null, "e": 80635, "s": 80457, "text": "When a competitor manifests a company’s brand as useless or outdated, then rebranding helps to get an opportunity to facelift the brand to effectively strike back in the market." }, { "code": null, "e": 80708, "s": 80635, "text": "When changes take place in business regulations, laws, competitors, etc." }, { "code": null, "e": 80781, "s": 80708, "text": "When changes take place in business regulations, laws, competitors, etc." }, { "code": null, "e": 81027, "s": 80781, "text": "When a company lands up into a significant controversy or negative publicity, it considers rebranding to rebuild the trust of consumers and stakeholders. It cuts up all the ties with the issues in picture and moves on with the new form of brand." }, { "code": null, "e": 81273, "s": 81027, "text": "When a company lands up into a significant controversy or negative publicity, it considers rebranding to rebuild the trust of consumers and stakeholders. It cuts up all the ties with the issues in picture and moves on with the new form of brand." }, { "code": null, "e": 81500, "s": 81273, "text": "Relaunching a brand is reintroducing a brand into the market. Relaunching implies that a company was marketing the brand but stopped doing so for some reasons. Relaunching is an opportunity to set new objectives for the brand." }, { "code": null, "e": 81700, "s": 81500, "text": "Relaunching a brand can demand the changes ranging from the aspects as minor as logo prints on stationery and cutlery, staff uniforms, to as major as website of the company, changes in premises, etc." }, { "code": null, "e": 81925, "s": 81700, "text": "When a company relaunches a brand, it hopes to avoid the mistakes from past experience and wants to set a strong foot in the market. A brand manager needs to consider the following do’s and don’ts while relaunching a brand −" }, { "code": null, "e": 81978, "s": 81925, "text": "Analyzing the marketplace and target market segment." }, { "code": null, "e": 82031, "s": 81978, "text": "Analyzing the marketplace and target market segment." }, { "code": null, "e": 82068, "s": 82031, "text": "Knowing about the competitor brands." }, { "code": null, "e": 82105, "s": 82068, "text": "Knowing about the competitor brands." }, { "code": null, "e": 82183, "s": 82105, "text": "Conducting SWOT (Strengths, Weaknesses, Opportunities, and Threats) analysis." }, { "code": null, "e": 82261, "s": 82183, "text": "Conducting SWOT (Strengths, Weaknesses, Opportunities, and Threats) analysis." }, { "code": null, "e": 82311, "s": 82261, "text": "Positioning the brand in an appropriate new form." }, { "code": null, "e": 82361, "s": 82311, "text": "Positioning the brand in an appropriate new form." }, { "code": null, "e": 82673, "s": 82361, "text": "Avoiding too many changes in too short time. This type of strategy can lead to the risk of not retaining consumer’s attention and interest for a long time. In future, it can make the company and its products unrecognizable to its existing customers. Let the consumer know about the new form the brand has taken." }, { "code": null, "e": 82985, "s": 82673, "text": "Avoiding too many changes in too short time. This type of strategy can lead to the risk of not retaining consumer’s attention and interest for a long time. In future, it can make the company and its products unrecognizable to its existing customers. Let the consumer know about the new form the brand has taken." }, { "code": null, "e": 83155, "s": 82985, "text": "Communicating clearly about the brand relaunch. Creating awareness among people about new objectives and distinctive offers. Making the changes gradually and noticeably." }, { "code": null, "e": 83325, "s": 83155, "text": "Communicating clearly about the brand relaunch. Creating awareness among people about new objectives and distinctive offers. Making the changes gradually and noticeably." }, { "code": null, "e": 83565, "s": 83325, "text": "Let us see an example of NIVEA FOR MEN relaunch. In 1980, NIVEA introduced an alcohol-free, non-itching aftershave balm for men. It went popular with consumers, and then by 1993, NIVEA FOR MEN included a range of skincare products for men." }, { "code": null, "e": 83830, "s": 83565, "text": "By 2008, more and more men were investing in skincare and grooming products. NIVEA FOR MEN brand understood this as an opportunity to claim more market share in the growing category. To achieve this, NIVEA employed a strategic marketing to relaunch and reorganize." }, { "code": null, "e": 84236, "s": 83830, "text": "NIVEA assessed the marketplace, evaluated its own business, brands, and products. It also assessed the brand’s position and the state of the market. It conducted SWOT analysis and revealed some interesting facts such as women are an important target market for the brand NIVEA FOR MEN as they are instrumental in buying male grooming products for their partners as well as helping them to choose new ones." }, { "code": null, "e": 84549, "s": 84236, "text": "Well-informed with SWOT analysis data, NIVEA FOR MEN brand management set objectives for relaunch. Using research data to forecast trends, the marketing force set SMART (Specific, Measurable, Achievable, Realistic) objectives. This helped in increasing sales, growing market share, and improving its brand image." }, { "code": null, "e": 84691, "s": 84549, "text": "NIVEA FOR MEN adopted a range of key performance indicators to assess the success of the NIVEA FOR MEN relaunch in the UK. It revealed that −" }, { "code": null, "e": 84797, "s": 84691, "text": "NIVEA FOR MEN is the market leader in many countries and is consistently gaining additional market share." }, { "code": null, "e": 84903, "s": 84797, "text": "NIVEA FOR MEN is the market leader in many countries and is consistently gaining additional market share." }, { "code": null, "e": 84989, "s": 84903, "text": "Internationally, NIVEA FOR MEN skincare products sale increased by almost 20 percent." }, { "code": null, "e": 85075, "s": 84989, "text": "Internationally, NIVEA FOR MEN skincare products sale increased by almost 20 percent." }, { "code": null, "e": 85142, "s": 85075, "text": "The NIVEA FOR MEN brand image improved in the minds of consumers. " }, { "code": null, "e": 85209, "s": 85142, "text": "The NIVEA FOR MEN brand image improved in the minds of consumers. " }, { "code": null, "e": 85326, "s": 85209, "text": "NIVEA FOR MEN entertained its customers’ feedback and added products to its line and reformed the existing products." }, { "code": null, "e": 85443, "s": 85326, "text": "NIVEA FOR MEN entertained its customers’ feedback and added products to its line and reformed the existing products." }, { "code": null, "e": 85736, "s": 85443, "text": "Co-branding is now no more a new strategy used by companies for generating higher level of interest and excitement about the products and services. As every single strategy of branding comes with benefits and risks, co-branding is not an exception. Let us see all about co-branding in detail." }, { "code": null, "e": 86078, "s": 85736, "text": "When a company uses multiple brands together to introduce a single product or service, the practice is called Co-branding. It is also called Brand Partnership, piggyback franchising, or combination franchising. There can be two or more than two brands in alliance to achieve an appeal to the consumers that an individual brand could achieve." }, { "code": null, "e": 86400, "s": 86078, "text": "Co-branding provides a way for companies to integrate the marketing forces from each of the brands such that they work cooperatively to associate any of the logos, color schemes, or other brand identifiers to a specific product. The objective of co-branding is to combine strengths of multiple brands for business growth." }, { "code": null, "e": 86452, "s": 86400, "text": "There are various types of co-branding as follows −" }, { "code": null, "e": 86605, "s": 86452, "text": "Ingredient Co-branding − Multiple brands provide distinctive ingredient or component to the carrier brand. For example, Intel chip inside all computers." }, { "code": null, "e": 86758, "s": 86605, "text": "Ingredient Co-branding − Multiple brands provide distinctive ingredient or component to the carrier brand. For example, Intel chip inside all computers." }, { "code": null, "e": 87122, "s": 86758, "text": "Product-Service Co-branding − It is a co-branding between a product and a service. For example, Best Western International, Inc. owns and operates a chain of hotels with state-of-the-art amenities and services to its customers. It runs an exclusive rewards program for Harley Davidson owners. The participating riders get lavish privileged treatment at the hotel." }, { "code": null, "e": 87486, "s": 87122, "text": "Product-Service Co-branding − It is a co-branding between a product and a service. For example, Best Western International, Inc. owns and operates a chain of hotels with state-of-the-art amenities and services to its customers. It runs an exclusive rewards program for Harley Davidson owners. The participating riders get lavish privileged treatment at the hotel." }, { "code": null, "e": 87741, "s": 87486, "text": "Alliance Co-branding − Multiple brand serve the same target audience. For example, Etihad Airways Partners, is a new brand which brings like-minded airlines together to offer customers more choice in flight schedules and enhanced frequent flyer benefits." }, { "code": null, "e": 87996, "s": 87741, "text": "Alliance Co-branding − Multiple brand serve the same target audience. For example, Etihad Airways Partners, is a new brand which brings like-minded airlines together to offer customers more choice in flight schedules and enhanced frequent flyer benefits." }, { "code": null, "e": 88123, "s": 87996, "text": "Supplier-Retailer Co-branding − Starbucks Wi-Fi started from AT&T in the most number of metropolitan cities in USA since 2008." }, { "code": null, "e": 88250, "s": 88123, "text": "Supplier-Retailer Co-branding − Starbucks Wi-Fi started from AT&T in the most number of metropolitan cities in USA since 2008." }, { "code": null, "e": 88329, "s": 88250, "text": "Promotional Co-branding − It is an alliance of a brand with persons or events." }, { "code": null, "e": 88408, "s": 88329, "text": "Promotional Co-branding − It is an alliance of a brand with persons or events." }, { "code": null, "e": 88483, "s": 88408, "text": "There are various situations when companies go for co-branding. They are −" }, { "code": null, "e": 88725, "s": 88483, "text": "When introducing one company's product or services to the loyal consumers of another company. For example, the “Intel Inside” campaign. Within a year of the campaign, Intel started co-branding with around 300 computer manufacturer companies." }, { "code": null, "e": 88967, "s": 88725, "text": "When introducing one company's product or services to the loyal consumers of another company. For example, the “Intel Inside” campaign. Within a year of the campaign, Intel started co-branding with around 300 computer manufacturer companies." }, { "code": null, "e": 89082, "s": 88967, "text": "When a company wants to leverage the effect of one established and affectionate brand for marketing another brand." }, { "code": null, "e": 89197, "s": 89082, "text": "When a company wants to leverage the effect of one established and affectionate brand for marketing another brand." }, { "code": null, "e": 89440, "s": 89197, "text": "When companies want to save costs on branding and other resources in this age of economic competition. For example, the businesses such as fast-food restaurants share the same place of working, counter, menu pamphlets, or sometimes the staff." }, { "code": null, "e": 89683, "s": 89440, "text": "When companies want to save costs on branding and other resources in this age of economic competition. For example, the businesses such as fast-food restaurants share the same place of working, counter, menu pamphlets, or sometimes the staff." }, { "code": null, "e": 89773, "s": 89683, "text": "When one brand is providing complementing products or services that other brand requires." }, { "code": null, "e": 89863, "s": 89773, "text": "When one brand is providing complementing products or services that other brand requires." }, { "code": null, "e": 90016, "s": 89863, "text": "Co-branding comes with inevitable risks. Before the brand managers of brand A go for co-branding with brand B, they must consider the following points −" }, { "code": null, "e": 90203, "s": 90016, "text": "If brand A is well established and generating excellent revenue, brand B would get the benefit of A’s positive perception and experience. In such case, brand A’s perception gets diluted." }, { "code": null, "e": 90390, "s": 90203, "text": "If brand A is well established and generating excellent revenue, brand B would get the benefit of A’s positive perception and experience. In such case, brand A’s perception gets diluted." }, { "code": null, "e": 90601, "s": 90390, "text": "There is a risk of any of the brands A or B underperforming or failing. In such case, the underperforming brand negatively impacts the over-performing brand and destroys its reputation for none of its mistake." }, { "code": null, "e": 90812, "s": 90601, "text": "There is a risk of any of the brands A or B underperforming or failing. In such case, the underperforming brand negatively impacts the over-performing brand and destroys its reputation for none of its mistake." }, { "code": null, "e": 91144, "s": 90812, "text": "If brand B is to some extent depending upon brand A’s equity, then brand B may be taken as weak or secondary.\nBrand A and B should be fit or compatible from the perspective of attributes and benefits. For example, co-branding of ice cream parlor and dry-fruit shop is natural so is co-branding of clothes brand with footwear brand." }, { "code": null, "e": 91254, "s": 91144, "text": "If brand B is to some extent depending upon brand A’s equity, then brand B may be taken as weak or secondary." }, { "code": null, "e": 91476, "s": 91254, "text": "Brand A and B should be fit or compatible from the perspective of attributes and benefits. For example, co-branding of ice cream parlor and dry-fruit shop is natural so is co-branding of clothes brand with footwear brand." }, { "code": null, "e": 91655, "s": 91476, "text": "Brand A and B both should have common core values and corporate philosophies. This is beneficial for both brands and reduces the risk of negative reputation if one of them fails." }, { "code": null, "e": 91834, "s": 91655, "text": "Brand A and B both should have common core values and corporate philosophies. This is beneficial for both brands and reduces the risk of negative reputation if one of them fails." }, { "code": null, "e": 91884, "s": 91834, "text": "Here are basic rough guidelines for co-branding −" }, { "code": null, "e": 91994, "s": 91884, "text": "Know your partner in co-branding. Go for co-branding only with the companies that share complementary values." }, { "code": null, "e": 92104, "s": 91994, "text": "Know your partner in co-branding. Go for co-branding only with the companies that share complementary values." }, { "code": null, "e": 92182, "s": 92104, "text": "Co-brand only if the company has same ethics, core values, and common vision." }, { "code": null, "e": 92260, "s": 92182, "text": "Co-brand only if the company has same ethics, core values, and common vision." }, { "code": null, "e": 92337, "s": 92260, "text": "Choose co-branding only with brands whose products are best-in-class status." }, { "code": null, "e": 92414, "s": 92337, "text": "Choose co-branding only with brands whose products are best-in-class status." }, { "code": null, "e": 92490, "s": 92414, "text": "Co-brand if the partner and company’s brand share the same target audience." }, { "code": null, "e": 92566, "s": 92490, "text": "Co-brand if the partner and company’s brand share the same target audience." }, { "code": null, "e": 92673, "s": 92566, "text": "Co-brand only if the company can retain full review and approval rights on all elements of communications." }, { "code": null, "e": 92780, "s": 92673, "text": "Co-brand only if the company can retain full review and approval rights on all elements of communications." }, { "code": null, "e": 92923, "s": 92780, "text": "These guidelines bring down the opportunities of growth of the company but the good news is, it reduces the risks associated with co-branding." }, { "code": null, "e": 93252, "s": 92923, "text": "Apart from creating additional appeal to the consumers, the objective of co-branding is increasing revenue. The ultimate goal of co-branding is one plus one = more than two. If the co-branding is done using innovative ideas and effective strategies with the right partner, it can prove to be very beneficial for business growth." }, { "code": null, "e": 93275, "s": 93252, "text": "Co-branding helps to −" }, { "code": null, "e": 93371, "s": 93275, "text": "Make the product or service under the brands resistant to imitation by local or private brands." }, { "code": null, "e": 93467, "s": 93371, "text": "Make the product or service under the brands resistant to imitation by local or private brands." }, { "code": null, "e": 93518, "s": 93467, "text": "Combine various perceptions about multiple brands." }, { "code": null, "e": 93569, "s": 93518, "text": "Combine various perceptions about multiple brands." }, { "code": null, "e": 93635, "s": 93569, "text": "Increase the credibility of the product or service in the market." }, { "code": null, "e": 93701, "s": 93635, "text": "Increase the credibility of the product or service in the market." }, { "code": null, "e": 93758, "s": 93701, "text": "Increase revenue of both businesses, if done effectively" }, { "code": null, "e": 93815, "s": 93758, "text": "Increase revenue of both businesses, if done effectively" }, { "code": null, "e": 93931, "s": 93815, "text": "Save costs of the company for launching a new brand, advertising, and promoting the brand through shared resources." }, { "code": null, "e": 94047, "s": 93931, "text": "Save costs of the company for launching a new brand, advertising, and promoting the brand through shared resources." }, { "code": null, "e": 94140, "s": 94047, "text": "Bring benefits from all brands and helps all brands participating in co-branding to prosper." }, { "code": null, "e": 94233, "s": 94140, "text": "Bring benefits from all brands and helps all brands participating in co-branding to prosper." }, { "code": null, "e": 94559, "s": 94233, "text": "For example, Coca Cola, the soft drinks giant has paired itself with McDonalds and made it sure it is associated with the brand that is consumed by millions of consumers around the world. Just by being together, both giants in restaurants and beverage industry respectively are earning billions of dollars revenue every year." }, { "code": null, "e": 94860, "s": 94559, "text": "The consumers follow their favorite celebrity and they wish to look, appear, and conduct the way the celebrity does. The companies grip this nerve of consumer behavior to brand their products with celebrity endorsement. The companies use the success and status of the celebrity to brand its products." }, { "code": null, "e": 94985, "s": 94860, "text": "The product alone cannot achieve consumers’ awareness and recognition as far and wide as a celebrity can help it to achieve." }, { "code": null, "e": 95385, "s": 94985, "text": "In India, Artist Booking India is a celebrity management and celebrity brand endorsement agency powered by B-Town Entertainment Pvt. Ltd. It has a strong network of TV serials, movies, writers, directors, and musicians in Bollywood. It provides solution right from selecting a right celebrity for the brand, applying strategies for optimizing the celebrity’s association with the brand to logistics." }, { "code": null, "e": 95477, "s": 95385, "text": "The contemporary celebrity endorsers can be overused by endorsing too many varied products." }, { "code": null, "e": 95569, "s": 95477, "text": "The contemporary celebrity endorsers can be overused by endorsing too many varied products." }, { "code": null, "e": 95681, "s": 95569, "text": "There must be a reasonable fit or match between the product and the celebrity endorser to appeal the consumers." }, { "code": null, "e": 95793, "s": 95681, "text": "There must be a reasonable fit or match between the product and the celebrity endorser to appeal the consumers." }, { "code": null, "e": 95879, "s": 95793, "text": "Celebrity endorsers can get into controversies, which can affect the brand adversely." }, { "code": null, "e": 95965, "s": 95879, "text": "Celebrity endorsers can get into controversies, which can affect the brand adversely." }, { "code": null, "e": 96052, "s": 95965, "text": "Celebrity can distract the consumer’s focus from the brand by overshadowing the brand." }, { "code": null, "e": 96139, "s": 96052, "text": "Celebrity can distract the consumer’s focus from the brand by overshadowing the brand." }, { "code": null, "e": 96330, "s": 96139, "text": "A number of consumers do not connect with the brand because they think that the endorsing celebrity is doing it just for money and do not necessarily believe in the brand they are endorsing." }, { "code": null, "e": 96521, "s": 96330, "text": "A number of consumers do not connect with the brand because they think that the endorsing celebrity is doing it just for money and do not necessarily believe in the brand they are endorsing." }, { "code": null, "e": 96940, "s": 96521, "text": "Since the idea of branding came into existence and settled in practice, some brands such as Nike, Coca Cola, Nivea, Amazon, etc., have been ruling the marketplace as successful ones. They were novice and had started as ordinary names with some innovative products or services at some point of time. With the efforts required for growing in the contemporary market, these brands became leading, exemplary, and powerful." }, { "code": null, "e": 97056, "s": 96940, "text": "In this chapter, we see what makes a brand successful over a long frame of time and how to asses brand performance." }, { "code": null, "e": 97220, "s": 97056, "text": "Brand launching is not the same as product or service launching. Products change but a brand is to stay. Brand launch is a long-term project unlike product launch." }, { "code": null, "e": 97612, "s": 97220, "text": "When a brand launches a product say P, and advertises for it, the competitors copy it after some time. Since all products go obsolete after some time, the brand chooses to replace the product P with some new product NewP, advocating its benefits and upgrading its quality to the consumer. This NewP often gets the benefit of the previous known product P. This is how a brand comes into life." }, { "code": null, "e": 97974, "s": 97612, "text": "From this point onwards, the products under the brand are sold by brand itself and not by mere advertising. Here, the product name (common noun) becomes a brand name (Proper noun). Over a time, brand gets more unique, builds its way of communication, and develops a rich meaning. Thus, a brand starts with a product and continues growing with multiple products." }, { "code": null, "e": 98076, "s": 97974, "text": "This was all about how a new product is converted to a brand. But launching a new brand is different." }, { "code": null, "e": 98339, "s": 98076, "text": "A successful brand launching needs treating a brand as a large entity than as a product. Right from the start, a new brand is considered as a complete entity in itself endowed with functional and non-functional values and presenting as if it is well-established." }, { "code": null, "e": 98408, "s": 98339, "text": "Take the following steps while launching a new brand in the market −" }, { "code": null, "e": 98495, "s": 98408, "text": "Step 1 − Draft the brand program. Try to get the answers for the following questions −" }, { "code": null, "e": 98593, "s": 98495, "text": "Existence − Why is the brand necessary? What will the consumers miss if the brand does not exist?" }, { "code": null, "e": 98691, "s": 98593, "text": "Existence − Why is the brand necessary? What will the consumers miss if the brand does not exist?" }, { "code": null, "e": 98751, "s": 98691, "text": "Vision − What is brand’s vision in some X product category?" }, { "code": null, "e": 98811, "s": 98751, "text": "Vision − What is brand’s vision in some X product category?" }, { "code": null, "e": 98881, "s": 98811, "text": "Ambition − What does the brand want to change in its consumer’s life?" }, { "code": null, "e": 98951, "s": 98881, "text": "Ambition − What does the brand want to change in its consumer’s life?" }, { "code": null, "e": 99001, "s": 98951, "text": "Values − What will the brand never compromise on?" }, { "code": null, "e": 99051, "s": 99001, "text": "Values − What will the brand never compromise on?" }, { "code": null, "e": 99093, "s": 99051, "text": "Know-How − What are brand’s capabilities?" }, { "code": null, "e": 99135, "s": 99093, "text": "Know-How − What are brand’s capabilities?" }, { "code": null, "e": 99230, "s": 99135, "text": "Territory − Where is the brand providing its lawful benefits? What are its product categories?" }, { "code": null, "e": 99325, "s": 99230, "text": "Territory − Where is the brand providing its lawful benefits? What are its product categories?" }, { "code": null, "e": 99390, "s": 99325, "text": "Style, Tone, and Language − How a brand is going to communicate?" }, { "code": null, "e": 99455, "s": 99390, "text": "Style, Tone, and Language − How a brand is going to communicate?" }, { "code": null, "e": 99533, "s": 99455, "text": "Reflection − What image the brand wants its consumers to render about itself?" }, { "code": null, "e": 99611, "s": 99533, "text": "Reflection − What image the brand wants its consumers to render about itself?" }, { "code": null, "e": 99649, "s": 99611, "text": "Step 2 − Define brand identity prism." }, { "code": null, "e": 99684, "s": 99649, "text": "Step 3 − Create brand positioning." }, { "code": null, "e": 99774, "s": 99684, "text": "Identify potential added values for the brand based on its image, identity, and heritage." }, { "code": null, "e": 99864, "s": 99774, "text": "Identify potential added values for the brand based on its image, identity, and heritage." }, { "code": null, "e": 99929, "s": 99864, "text": "Explore four major scenarios: Why? Against whom? For whom? When?" }, { "code": null, "e": 99994, "s": 99929, "text": "Explore four major scenarios: Why? Against whom? For whom? When?" }, { "code": null, "e": 100110, "s": 99994, "text": "Test the above scenarios, redefine or eliminate them if required. Conduct consumer studies, ideas and formulations." }, { "code": null, "e": 100226, "s": 100110, "text": "Test the above scenarios, redefine or eliminate them if required. Conduct consumer studies, ideas and formulations." }, { "code": null, "e": 100306, "s": 100226, "text": "Conduct strategic evaluation of potential sales and profits in the marketspace." }, { "code": null, "e": 100386, "s": 100306, "text": "Conduct strategic evaluation of potential sales and profits in the marketspace." }, { "code": null, "e": 100600, "s": 100386, "text": "Step 4 − Determine flagship product of the brand. Carefully choose which product or service you think you should introduce as a first campaign. This star product is going to form the brand’s identity subsequently." }, { "code": null, "e": 100807, "s": 100600, "text": "Step 5 − Choose a strong brand name. Choose it by estimating the future changes the brand can undergo. Look for meaningful, short, and easy to pronounce names. Do not choose a deceptive or descriptive name." }, { "code": null, "e": 100901, "s": 100807, "text": "Step 6 − Create brand slogan and jingle that is easy, meaningful, and memorable by consumers." }, { "code": null, "e": 101059, "s": 100901, "text": "Step 7 − Reach out to opinion leaders (people who are influencers) and conduct brand advertisements in various media to create awareness among the consumers." }, { "code": null, "e": 101239, "s": 101059, "text": "Many brands have been with us for a long time and many are still struggling for survival. Why do some brands sustain by escaping the effects of time and why do some brands vanish?" }, { "code": null, "e": 101329, "s": 101239, "text": "There are many reasons why brands start performing low and eventually lead to vanishing −" }, { "code": null, "e": 101397, "s": 101329, "text": "A brand not being able to withstand market changes and competitors." }, { "code": null, "e": 101465, "s": 101397, "text": "A brand not being able to withstand market changes and competitors." }, { "code": null, "e": 101557, "s": 101465, "text": "New cheaper entrants in the market, which destabilize added value of the established brand." }, { "code": null, "e": 101649, "s": 101557, "text": "New cheaper entrants in the market, which destabilize added value of the established brand." }, { "code": null, "e": 101723, "s": 101649, "text": "A brand not able to suffice consumer’s needs, or customized requirements." }, { "code": null, "e": 101797, "s": 101723, "text": "A brand not able to suffice consumer’s needs, or customized requirements." }, { "code": null, "e": 101906, "s": 101797, "text": "A brand not able to attract upcoming generation of consumers all over again when current consumers grow old." }, { "code": null, "e": 102015, "s": 101906, "text": "A brand not able to attract upcoming generation of consumers all over again when current consumers grow old." }, { "code": null, "e": 102078, "s": 102015, "text": "A brand marketing and management team lacking foresightedness." }, { "code": null, "e": 102141, "s": 102078, "text": "A brand marketing and management team lacking foresightedness." }, { "code": null, "e": 102279, "s": 102141, "text": "These are few most common facts why brands start to decline. To last for a long term, the following vital points a brand must adhere to −" }, { "code": null, "e": 102368, "s": 102279, "text": "Keep on innovating on the fronts of product quality, design, and consumer’s convenience." }, { "code": null, "e": 102457, "s": 102368, "text": "Keep on innovating on the fronts of product quality, design, and consumer’s convenience." }, { "code": null, "e": 102490, "s": 102457, "text": "Always keep its reputation good." }, { "code": null, "e": 102523, "s": 102490, "text": "Always keep its reputation good." }, { "code": null, "e": 102681, "s": 102523, "text": "Always remain contemporary with the changes in the consumer’s culture, preferences, economic and technological changes, and new market openings in the world." }, { "code": null, "e": 102839, "s": 102681, "text": "Always remain contemporary with the changes in the consumer’s culture, preferences, economic and technological changes, and new market openings in the world." }, { "code": null, "e": 102891, "s": 102839, "text": "Always keep itself noticeable to the target market." }, { "code": null, "e": 102943, "s": 102891, "text": "Always keep itself noticeable to the target market." }, { "code": null, "e": 103014, "s": 102943, "text": "Work on not to lose its market share for cheap copies of the products." }, { "code": null, "e": 103085, "s": 103014, "text": "Work on not to lose its market share for cheap copies of the products." }, { "code": null, "e": 103139, "s": 103085, "text": "Work on acquiring superior image and then keeping it." }, { "code": null, "e": 103193, "s": 103139, "text": "Work on acquiring superior image and then keeping it." }, { "code": null, "e": 103269, "s": 103193, "text": "Price its products appropriately depending upon the target market’s income." }, { "code": null, "e": 103345, "s": 103269, "text": "Price its products appropriately depending upon the target market’s income." }, { "code": null, "e": 103427, "s": 103345, "text": "Present itself in the quality environment which is as high as its product offers." }, { "code": null, "e": 103509, "s": 103427, "text": "Present itself in the quality environment which is as high as its product offers." }, { "code": null, "e": 103589, "s": 103509, "text": "Control the relationship with the opinion leaders and distribution of products." }, { "code": null, "e": 103669, "s": 103589, "text": "Control the relationship with the opinion leaders and distribution of products." }, { "code": null, "e": 103741, "s": 103669, "text": "Defend its intellectual properties against theft or sneaking intrusion." }, { "code": null, "e": 103813, "s": 103741, "text": "Defend its intellectual properties against theft or sneaking intrusion." }, { "code": null, "e": 104020, "s": 103813, "text": "A brand cannot survive if it does not change according to the market changes. Brand management needs to cater to different branding policies to introduce the product in different countries around the world." }, { "code": null, "e": 104183, "s": 104020, "text": "The market is not the same worldwide. First, the growth takes place in developing countries, then in underdeveloped countries, and finally in developed countries." }, { "code": null, "e": 104426, "s": 104183, "text": "In developing countries such as India, the economic growth rate is fast and there are favorable business conditions. It is also revealed that the customer in developing countries is more brand cautious than that of in the developed countries." }, { "code": null, "e": 104660, "s": 104426, "text": "In developed countries of USA and Europe, the market is matured. There is not much significant growth and innovation taking place. In such matured markets, brand needs to stimulate the new desires and new experiences of the consumer." }, { "code": null, "e": 104885, "s": 104660, "text": "Brand managers need to work by considering changes in the domains of politics, economics, evolution of society, technology, consumer behavior and fads, all of which play an important role while branding in different markets." }, { "code": null, "e": 105064, "s": 104885, "text": "When it comes to brand name changes, some examples flash such as Anderson → Accenture, Datsun → Nissan, Pal → Pedigree, and Phillips → Whirlpool, Backrub → Google, to name a few." }, { "code": null, "e": 105384, "s": 105064, "text": "Brand transfer is a lot more than brand’s name change. A brand’s established name has links with emotional associations, empathy, and preference in its consumers’ mind. The loyalty and trust of the customers cannot be transferred easily to just one entity: the brand name. The brand image is required to be transferred." }, { "code": null, "e": 105439, "s": 105384, "text": "A brand’s name is changed in the following scenarios −" }, { "code": null, "e": 105530, "s": 105439, "text": "When the existing name sounds weak or is not able to establish its position in the market." }, { "code": null, "e": 105621, "s": 105530, "text": "When the existing name sounds weak or is not able to establish its position in the market." }, { "code": null, "e": 105684, "s": 105621, "text": "When a brand wants to present its upgraded product or service." }, { "code": null, "e": 105747, "s": 105684, "text": "When a brand wants to present its upgraded product or service." }, { "code": null, "e": 105805, "s": 105747, "text": "When a brand wants to introduce more clarity in its name." }, { "code": null, "e": 105863, "s": 105805, "text": "When a brand wants to introduce more clarity in its name." }, { "code": null, "e": 105944, "s": 105863, "text": "When a brand needs to distant itself from negating effects of the existing name." }, { "code": null, "e": 106025, "s": 105944, "text": "When a brand needs to distant itself from negating effects of the existing name." }, { "code": null, "e": 106111, "s": 106025, "text": "When a brand wants to get instant recognition in the market while expanding globally." }, { "code": null, "e": 106197, "s": 106111, "text": "When a brand wants to get instant recognition in the market while expanding globally." }, { "code": null, "e": 106260, "s": 106197, "text": "There are few estimations the brand managers need to work on −" }, { "code": null, "e": 106686, "s": 106260, "text": "Estimate and quantify the costs\nIt includes the costs required for changing −\n\nPromotional properties such as banners, hoardings, website ads, business properties such as letterheads and business cards.\nCompany literatures such as white papers, data sheets, and presentations.\nElectronic properties such as website, newsletter, blogs, etc.\nOther in-house properties such as templates, folder names, network node names, etc.\n\n" }, { "code": null, "e": 106718, "s": 106686, "text": "Estimate and quantify the costs" }, { "code": null, "e": 106764, "s": 106718, "text": "It includes the costs required for changing −" }, { "code": null, "e": 106888, "s": 106764, "text": "Promotional properties such as banners, hoardings, website ads, business properties such as letterheads and business cards." }, { "code": null, "e": 107012, "s": 106888, "text": "Promotional properties such as banners, hoardings, website ads, business properties such as letterheads and business cards." }, { "code": null, "e": 107086, "s": 107012, "text": "Company literatures such as white papers, data sheets, and presentations." }, { "code": null, "e": 107160, "s": 107086, "text": "Company literatures such as white papers, data sheets, and presentations." }, { "code": null, "e": 107223, "s": 107160, "text": "Electronic properties such as website, newsletter, blogs, etc." }, { "code": null, "e": 107286, "s": 107223, "text": "Electronic properties such as website, newsletter, blogs, etc." }, { "code": null, "e": 107370, "s": 107286, "text": "Other in-house properties such as templates, folder names, network node names, etc." }, { "code": null, "e": 107454, "s": 107370, "text": "Other in-house properties such as templates, folder names, network node names, etc." }, { "code": null, "e": 107712, "s": 107454, "text": "Judge the benefits and losses\nTry to find out answers for the following questions −\n\nHow long the existing name is in use? How much goodwill has the existing name built?\nHow would it affect the consumers?\nHow would it affect the market share of the brand?\n\n" }, { "code": null, "e": 107742, "s": 107712, "text": "Judge the benefits and losses" }, { "code": null, "e": 107796, "s": 107742, "text": "Try to find out answers for the following questions −" }, { "code": null, "e": 107881, "s": 107796, "text": "How long the existing name is in use? How much goodwill has the existing name built?" }, { "code": null, "e": 107966, "s": 107881, "text": "How long the existing name is in use? How much goodwill has the existing name built?" }, { "code": null, "e": 108001, "s": 107966, "text": "How would it affect the consumers?" }, { "code": null, "e": 108036, "s": 108001, "text": "How would it affect the consumers?" }, { "code": null, "e": 108087, "s": 108036, "text": "How would it affect the market share of the brand?" }, { "code": null, "e": 108138, "s": 108087, "text": "How would it affect the market share of the brand?" }, { "code": null, "e": 108379, "s": 108138, "text": "Analyze target audience and market\n\nConsider the target audience, culture, language, symbols, and preferences.\nConsider the average purchasing frequency of the customer.\nIdentify the characteristics the customer associates with the brand.\n\n" }, { "code": null, "e": 108414, "s": 108379, "text": "Analyze target audience and market" }, { "code": null, "e": 108489, "s": 108414, "text": "Consider the target audience, culture, language, symbols, and preferences." }, { "code": null, "e": 108564, "s": 108489, "text": "Consider the target audience, culture, language, symbols, and preferences." }, { "code": null, "e": 108623, "s": 108564, "text": "Consider the average purchasing frequency of the customer." }, { "code": null, "e": 108682, "s": 108623, "text": "Consider the average purchasing frequency of the customer." }, { "code": null, "e": 108751, "s": 108682, "text": "Identify the characteristics the customer associates with the brand." }, { "code": null, "e": 108820, "s": 108751, "text": "Identify the characteristics the customer associates with the brand." }, { "code": null, "e": 108878, "s": 108820, "text": "To handle actual brand transfer, follow the given steps −" }, { "code": null, "e": 108914, "s": 108878, "text": "Chalk out a plan of brand transfer." }, { "code": null, "e": 108950, "s": 108914, "text": "Chalk out a plan of brand transfer." }, { "code": null, "e": 109053, "s": 108950, "text": "Let every department know, that it is going to be a combined effort of all departments in the company." }, { "code": null, "e": 109156, "s": 109053, "text": "Let every department know, that it is going to be a combined effort of all departments in the company." }, { "code": null, "e": 109236, "s": 109156, "text": "Warn the employees, retailers, opinion leaders and prescribers well in advance." }, { "code": null, "e": 109316, "s": 109236, "text": "Warn the employees, retailers, opinion leaders and prescribers well in advance." }, { "code": null, "e": 109377, "s": 109316, "text": "Communicate clearly to the customers about the brand change." }, { "code": null, "e": 109438, "s": 109377, "text": "Communicate clearly to the customers about the brand change." }, { "code": null, "e": 109502, "s": 109438, "text": "Invest time for all customers to know about the brand transfer." }, { "code": null, "e": 109566, "s": 109502, "text": "Invest time for all customers to know about the brand transfer." }, { "code": null, "e": 109626, "s": 109566, "text": "Keep the transitional period of the brand transfer minimal." }, { "code": null, "e": 109686, "s": 109626, "text": "Keep the transitional period of the brand transfer minimal." }, { "code": null, "e": 109748, "s": 109686, "text": "The following three factors facilitate brand image transfer −" }, { "code": null, "e": 109768, "s": 109748, "text": "Product Resemblance" }, { "code": null, "e": 109985, "s": 109768, "text": "When consumers consider source brand’s product and target brand’s product or product category similar. For example, it is more likely for a pasteurized milk brand to boost a lowcalorie cheese brand than a soap brand." }, { "code": null, "e": 110010, "s": 109985, "text": "Target Group Resemblance" }, { "code": null, "e": 110334, "s": 110010, "text": "If the target brand aims for the same target group as the source brand, there are high chances of target brand succeeding as the initial purchases of a target brand will mainly be made by consumers of the source brand. When the target brand tailors to another target group then initial sales will not be significantly high." }, { "code": null, "e": 110353, "s": 110334, "text": "Family Resemblance" }, { "code": null, "e": 110644, "s": 110353, "text": "Family resemblance means that the look and feel of the source brand and the target brand have to be largely the same. The consumers are perceived by symbols and colors while assessing the brand hence a similar style can transfer their associations with the source brand to the target brand." }, { "code": null, "e": 110789, "s": 110644, "text": "Image transfer may still become successful, provided the marketing communication is clear and aggressive, and advertising campaign is intensive." }, { "code": null, "e": 110997, "s": 110789, "text": "Brand leveraging is the strategy to use the power of an existing brand name to support a company’s entry into a new but related product category by communicating valuable product information to the consumer." }, { "code": null, "e": 111314, "s": 110997, "text": "For example, the manufacturer of tea maker uses its brand name strength to launch tea vending machine. Here, in spite of tea and tea-vending machine belonging to different product categories, there is a strong correlation between the two items that the brand name has a mighty impact on consumers of both categories." }, { "code": null, "e": 111390, "s": 111314, "text": "Brand leveraging is an important form of new product introduction because −" }, { "code": null, "e": 111462, "s": 111390, "text": "Strong brand leveraging provides consumers with a sense of familiarity." }, { "code": null, "e": 111534, "s": 111462, "text": "Strong brand leveraging provides consumers with a sense of familiarity." }, { "code": null, "e": 111619, "s": 111534, "text": "It carries positive brand characteristics and attitudes into a new product category." }, { "code": null, "e": 111704, "s": 111619, "text": "It carries positive brand characteristics and attitudes into a new product category." }, { "code": null, "e": 111818, "s": 111704, "text": "Strong leveraging perceives instant recognition to the brand. Consumers are more likely to try leveraged product." }, { "code": null, "e": 111932, "s": 111818, "text": "Strong leveraging perceives instant recognition to the brand. Consumers are more likely to try leveraged product." }, { "code": null, "e": 112022, "s": 111932, "text": "As the products belong to the different categories, they do not compete for market share." }, { "code": null, "e": 112112, "s": 112022, "text": "As the products belong to the different categories, they do not compete for market share." }, { "code": null, "e": 112206, "s": 112112, "text": "More products mean greater shelf space for the brand and in turn more opportunities for sale." }, { "code": null, "e": 112300, "s": 112206, "text": "More products mean greater shelf space for the brand and in turn more opportunities for sale." }, { "code": null, "e": 112403, "s": 112300, "text": "The cost of introducing a brand-leveraged product is less than introducing an independent new product." }, { "code": null, "e": 112506, "s": 112403, "text": "The cost of introducing a brand-leveraged product is less than introducing an independent new product." }, { "code": null, "e": 112652, "s": 112506, "text": "A full line permits coordination of product offerings, such as bagels and cream cheese, potato chips and ranch dip, peanut butter and jelly, etc." }, { "code": null, "e": 112798, "s": 112652, "text": "A full line permits coordination of product offerings, such as bagels and cream cheese, potato chips and ranch dip, peanut butter and jelly, etc." }, { "code": null, "e": 112894, "s": 112798, "text": "A greater number of products increase efficiency of manufacturing facilities and raw materials." }, { "code": null, "e": 112990, "s": 112894, "text": "A greater number of products increase efficiency of manufacturing facilities and raw materials." }, { "code": null, "e": 113131, "s": 112990, "text": "The brand managers can create a strong brand leveraging, by maintaining the quality of all products in different categories under the brand." }, { "code": null, "e": 113330, "s": 113131, "text": "The brand managers need to decide which products can be leveraged under a brand. It is very important for them to leverage a brand only into related or associated categories of the original product." }, { "code": null, "e": 113436, "s": 113330, "text": "In order to make the best decision for the brand, they need to find answers for the following questions −" }, { "code": null, "e": 113498, "s": 113436, "text": "Is the new product related to the established product family?" }, { "code": null, "e": 113560, "s": 113498, "text": "Is the new product related to the established product family?" }, { "code": null, "e": 113663, "s": 113560, "text": "Does the established brand has characteristics that can be effectively carried on into new categories?" }, { "code": null, "e": 113766, "s": 113663, "text": "Does the established brand has characteristics that can be effectively carried on into new categories?" }, { "code": null, "e": 113816, "s": 113766, "text": "What will be the appropriate leveraging strategy?" }, { "code": null, "e": 113866, "s": 113816, "text": "What will be the appropriate leveraging strategy?" }, { "code": null, "e": 113950, "s": 113866, "text": "What will be the impact on original brand name? Will it be strengthened or diluted?" }, { "code": null, "e": 114034, "s": 113950, "text": "What will be the impact on original brand name? Will it be strengthened or diluted?" }, { "code": null, "e": 114141, "s": 114034, "text": "Does the company have essential facilities to manufacture and distribute a new and differentiated product?" }, { "code": null, "e": 114248, "s": 114141, "text": "Does the company have essential facilities to manufacture and distribute a new and differentiated product?" }, { "code": null, "e": 114331, "s": 114248, "text": "Will sales of the new product cover the cost of product development and marketing?" }, { "code": null, "e": 114414, "s": 114331, "text": "Will sales of the new product cover the cost of product development and marketing?" }, { "code": null, "e": 114507, "s": 114414, "text": "If leveraging fails, what are the policies to revert or to keep original brand’s reputation?" }, { "code": null, "e": 114600, "s": 114507, "text": "If leveraging fails, what are the policies to revert or to keep original brand’s reputation?" }, { "code": null, "e": 114750, "s": 114600, "text": "A brand leveraging strategy can be extremely successful and profitable if it is correctly implemented and provides new products with the right image." }, { "code": null, "e": 115109, "s": 114750, "text": "Brand valuation is an interesting topic in brand management. The brand valuation is not just restricted to acquisitions and mergers but it is also important for the company management to make policies for future, to train the marketing team, to use it for information system, and provide as a reference for product or brand managers to plan their strategies." }, { "code": null, "e": 115331, "s": 115109, "text": "In the entire process of brand development and management, it is essential for the brand managers to assess the progress of brand development. The companies are interested in brand audit as the owner of the organization." }, { "code": null, "e": 115569, "s": 115331, "text": "Brand audit is an assessment of where the brand stands in the market at its present status. It is conducted by the company itself to judge the inclination of the brand. It reveals the loopholes in brand development or management process." }, { "code": null, "e": 115596, "s": 115569, "text": "Brand audit is conducted −" }, { "code": null, "e": 115679, "s": 115596, "text": "When the companies are rebranding, acquiring business, or merging the businesses. " }, { "code": null, "e": 115762, "s": 115679, "text": "When the companies are rebranding, acquiring business, or merging the businesses. " }, { "code": null, "e": 115877, "s": 115762, "text": "When the communication in management team and employees, or interpersonal relations among employees are unhealthy." }, { "code": null, "e": 115992, "s": 115877, "text": "When the communication in management team and employees, or interpersonal relations among employees are unhealthy." }, { "code": null, "e": 116102, "s": 115992, "text": "When brand, the strong foundation of the organization that inspires and empowers the employees is found weak." }, { "code": null, "e": 116212, "s": 116102, "text": "When brand, the strong foundation of the organization that inspires and empowers the employees is found weak." }, { "code": null, "e": 116382, "s": 116212, "text": "The CEO of a company along with his marketing and brand management heads generally conducts brand audit. It can be an in-house team as said or an outside agency on hire." }, { "code": null, "e": 116441, "s": 116382, "text": "There are two categories in which brand auditing is done −" }, { "code": null, "e": 116460, "s": 116441, "text": "Brand positioning " }, { "code": null, "e": 116472, "s": 116460, "text": "Brand value" }, { "code": null, "e": 116503, "s": 116472, "text": "Brand promise or brand essence" }, { "code": null, "e": 116531, "s": 116503, "text": "Culture of the organization" }, { "code": null, "e": 116559, "s": 116531, "text": "Product/service positioning" }, { "code": null, "e": 116571, "s": 116559, "text": "HR policies" }, { "code": null, "e": 116624, "s": 116571, "text": "Corporate identity such as logos, and brand elements" }, { "code": null, "e": 116693, "s": 116624, "text": "Collaterals such as brochures, printed material, trade fair displays" }, { "code": null, "e": 116707, "s": 116693, "text": "Advertisement" }, { "code": null, "e": 116715, "s": 116707, "text": "Website" }, { "code": null, "e": 116748, "s": 116715, "text": "Search Engine Optimization (SEO)" }, { "code": null, "e": 116762, "s": 116748, "text": "Social media " }, { "code": null, "e": 116767, "s": 116762, "text": "News" }, { "code": null, "e": 116784, "s": 116767, "text": "Public Relations" }, { "code": null, "e": 116852, "s": 116784, "text": "Company literature such as white papers, blogs, case studies, books" }, { "code": null, "e": 116878, "s": 116852, "text": "Reviews and testimonials " }, { "code": null, "e": 116885, "s": 116878, "text": "Videos" }, { "code": null, "e": 116909, "s": 116885, "text": "Customer service system" }, { "code": null, "e": 116940, "s": 116909, "text": "Sales procedures, touch points" }, { "code": null, "e": 117114, "s": 116940, "text": "There is little standardization and more opinions in the market about brand equity measurement. Brand equity is measured in both quantitative and qualitative brand research." }, { "code": null, "e": 117214, "s": 117114, "text": "The brand equity performance can be measured by collecting data of brand performance. It includes −" }, { "code": null, "e": 117264, "s": 117214, "text": "Taking face-to-face interviews with focus groups." }, { "code": null, "e": 117319, "s": 117264, "text": "Considering large sample audience to collect the data." }, { "code": null, "e": 117384, "s": 117319, "text": "By analyzing present customers as well as prospective customers." }, { "code": null, "e": 117416, "s": 117384, "text": "By conducting periodic surveys." }, { "code": null, "e": 117486, "s": 117416, "text": "Conducting experiments that examine consumers’ attitude and behavior." }, { "code": null, "e": 117548, "s": 117486, "text": "There are three mainstay drivers or metrics of brand equity −" }, { "code": null, "e": 117683, "s": 117548, "text": "The company management is interested in financial aspect of brand equity to know how profitable the brand is performing in the market." }, { "code": null, "e": 117780, "s": 117683, "text": "Under the financial metrics, the brand managers with marketing team should track the following −" }, { "code": null, "e": 117811, "s": 117780, "text": "Cost for winning new customers" }, { "code": null, "e": 117849, "s": 117811, "text": "Cost for retaining existing customers" }, { "code": null, "e": 117861, "s": 117849, "text": "Growth rate" }, { "code": null, "e": 117887, "s": 117861, "text": "Market share of the brand" }, { "code": null, "e": 117909, "s": 117887, "text": "Marketing investments" }, { "code": null, "e": 117927, "s": 117909, "text": "Price sensitivity" }, { "code": null, "e": 117941, "s": 117927, "text": "Profitability" }, { "code": null, "e": 117949, "s": 117941, "text": "Revenue" }, { "code": null, "e": 118257, "s": 117949, "text": "These are some of the many financial metrics given. By keeping the track of the trends, a brand manager can ensure that the brand is building positive equity. Also, they can use this data to explain how important the brand asset is for the company to bear brand extensions or to determine marketing budgets." }, { "code": null, "e": 118325, "s": 118257, "text": "The strength metrics include measurement of the following aspects −" }, { "code": null, "e": 118341, "s": 118325, "text": "Brand awareness" }, { "code": null, "e": 118357, "s": 118341, "text": "Brand knowledge" }, { "code": null, "e": 118371, "s": 118357, "text": "Brand loyalty" }, { "code": null, "e": 118402, "s": 118371, "text": "Aided and unaided brand recall" }, { "code": null, "e": 118421, "s": 118402, "text": "Buzz in the market" }, { "code": null, "e": 118613, "s": 118421, "text": "It is very important for the brand managers to understand what consumers know, think, and feel about various brands. Under consumer metrics, the brand managers need to measure the following −" }, { "code": null, "e": 118633, "s": 118613, "text": "Consumer sentiments" }, { "code": null, "e": 118653, "s": 118633, "text": "Consumer perception" }, { "code": null, "e": 118685, "s": 118653, "text": "Emotional connection with brand" }, { "code": null, "e": 118709, "s": 118685, "text": "Beliefs about the brand" }, { "code": null, "e": 118751, "s": 118709, "text": "Relevance of brand for the market segment" }, { "code": null, "e": 118821, "s": 118751, "text": "Consumer’s purchasing decision and other driving factors of the brand" }, { "code": null, "e": 118870, "s": 118821, "text": "Consumer’s opinions and feelings about the brand" }, { "code": null, "e": 118912, "s": 118870, "text": "Brand associations in the consumer’s mind" }, { "code": null, "e": 119116, "s": 118912, "text": "It is very difficult to find the right talent in the market. Organizations are always interested in attracting the talented employees thereby reducing the cost of grooming and training the new employees." }, { "code": null, "e": 119357, "s": 119116, "text": "It is the practice of creating and establishing the reputation of an organization as a place to work by associating recruitment and external HR practices with the organization as a brand. It is a way of attracting and keeping employees by −" }, { "code": null, "e": 119374, "s": 119357, "text": "Good pay package" }, { "code": null, "e": 119403, "s": 119374, "text": "Ethical organization culture" }, { "code": null, "e": 119440, "s": 119403, "text": "Comfortable and enjoyable workplace " }, { "code": null, "e": 119481, "s": 119440, "text": "Rewards, perks, appraisals, and benefits" }, { "code": null, "e": 119514, "s": 119481, "text": "Excellent management performance" }, { "code": null, "e": 119727, "s": 119514, "text": "It forms a perception in the employee’s mind about what it would be like to work in the organization. It attracts not only potential employees, but also the specific ones who can fit well within the organization." }, { "code": null, "e": 120000, "s": 119727, "text": "For example, the software products giant Microsoft has provided its Microsoft Careers website. Apart from featuring job opportunities, there is a blog that presents articles about how it would be to work at the company by profiling the experience of the present employees." }, { "code": null, "e": 120288, "s": 120000, "text": "In addition, it provides a separate Facebook page as ‘Women at Microsoft,’ to give a unique insight into the women working at the company. The YouTube video on Microsoft Career features more than 100 videos where potential employees can get to know the aspects of working with Microsoft." }, { "code": null, "e": 120535, "s": 120288, "text": "It is the practice of associating an employee’s behavior and opinions with the image, characteristics, and attributes that the organization wants to project to its external stakeholders. Here, the employee is a small version of a brand ambassador" }, { "code": null, "e": 120769, "s": 120535, "text": "It tries to influence the interactions among employees within the organization as well as among employees and external stakeholders. This way, an organization demonstrates its characteristics it desires to show through its employees." }, { "code": null, "e": 120798, "s": 120769, "text": "Employee branding includes −" }, { "code": null, "e": 120815, "s": 120798, "text": "On-job training " }, { "code": null, "e": 120865, "s": 120815, "text": "Customer service or customer interaction training" }, { "code": null, "e": 120885, "s": 120865, "text": "Company orientation" }, { "code": null, "e": 120937, "s": 120885, "text": "Education programs associated with corporate brands" }, { "code": null, "e": 120968, "s": 120937, "text": "Evaluation and reward programs" }, { "code": null, "e": 121166, "s": 120968, "text": "For example, Cisco Networking Academy, program under Cisco Corporate Social Responsibility, is an IT skills and career building program available to learning institutions and individuals worldwide." }, { "code": null, "e": 121368, "s": 121166, "text": "A poplar CEO of a company can bring in more deal flow and generate more revenue. Brand CEO is the leader who creates a vision for the brand and leads his teams by speaking with actions more than words." }, { "code": null, "e": 121471, "s": 121368, "text": "With high rank in management hierarchy and authority, a CEO can play an instrumental role in branding." }, { "code": null, "e": 121750, "s": 121471, "text": "CEOs are expected to have profiles on LinkedIn, but if they have presence across every prominent social media platform, their focus on reaching consumers directly dilutes. A smart CEO finds out on which social media the target audience spends time and focuses the efforts there." }, { "code": null, "e": 121968, "s": 121750, "text": "It establishes credibility of the brand and helps to bring up CEO’s reputation as an industry expert. It is an opportunity to connect to the audience in person when a CEO is physically in front of the target audience." }, { "code": null, "e": 122159, "s": 121968, "text": "Being an author of the book grants the command on the subject. Writing a book and introducing it among large audience, signing events are excellent opportunities for CEO for brand campaigns." }, { "code": null, "e": 122249, "s": 122159, "text": "When a CEO gets an award as an industry expert, the credibility and reliability elevates." }, { "code": null, "e": 122302, "s": 122249, "text": "Some examples of popular CEO brands are as follows −" }, { "code": null, "e": 122333, "s": 122302, "text": "\n 9 Lectures \n 47 mins\n" }, { "code": null, "e": 122355, "s": 122333, "text": " Aleksandar Cucukovic" }, { "code": null, "e": 122388, "s": 122355, "text": "\n 18 Lectures \n 2 hours \n" }, { "code": null, "e": 122400, "s": 122388, "text": " Rob Cubbon" }, { "code": null, "e": 122433, "s": 122400, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 122455, "s": 122433, "text": " Bernard Kelvin Clive" }, { "code": null, "e": 122488, "s": 122455, "text": "\n 24 Lectures \n 1 hours \n" }, { "code": null, "e": 122502, "s": 122488, "text": " J Aatish Rao" }, { "code": null, "e": 122537, "s": 122502, "text": "\n 31 Lectures \n 2.5 hours \n" }, { "code": null, "e": 122553, "s": 122537, "text": " Being Commerce" }, { "code": null, "e": 122588, "s": 122553, "text": "\n 31 Lectures \n 2.5 hours \n" }, { "code": null, "e": 122604, "s": 122588, "text": " Being Commerce" }, { "code": null, "e": 122611, "s": 122604, "text": " Print" }, { "code": null, "e": 122622, "s": 122611, "text": " Add Notes" } ]
C++ Multithreading
Multithreading is a specialized form of multitasking and a multitasking is the feature that allows your computer to run two or more programs concurrently. In general, there are two types of multitasking: process-based and thread-based. Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Before C++ 11, there is no built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature. This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C++ program using POSIX. POSIX Threads, or Pthreads provides API which are available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris. The following routine is used to create a POSIX thread − #include <pthread.h> pthread_create (thread, attr, start_routine, arg) Here, pthread_create creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code. Here is the description of the parameters − thread An opaque, unique identifier for the new thread returned by the subroutine. attr An opaque attribute object that may be used to set thread attributes. You can specify a thread attributes object, or NULL for the default values. start_routine The C++ routine that the thread will execute once it is created. arg A single argument that may be passed to start_routine. It must be passed by reference as a pointer cast of type void. NULL may be used if no argument is to be passed. The maximum number of threads that may be created by a process is implementation dependent. Once created, threads are peers, and may create other threads. There is no implied hierarchy or dependency between threads. There is following routine which we use to terminate a POSIX thread − #include <pthread.h> pthread_exit (status) Here pthread_exit is used to explicitly exit a thread. Typically, the pthread_exit() routine is called after a thread has completed its work and is no longer required to exist. If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes. Example This simple example code creates 5 threads with the pthread_create() routine. Each thread prints a "Hello World!" message, and then terminates with a call to pthread_exit(). #include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; #define NUM_THREADS 5 void *PrintHello(void *threadid) { long tid; tid = (long)threadid; cout << "Hello World! Thread ID, " << tid << endl; pthread_exit(NULL); } int main () { pthread_t threads[NUM_THREADS]; int rc; int i; for( i = 0; i < NUM_THREADS; i++ ) { cout << "main() : creating thread, " << i << endl; rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i); if (rc) { cout << "Error:unable to create thread," << rc << endl; exit(-1); } } pthread_exit(NULL); } Compile the following program using -lpthread library as follows − $gcc test.cpp -lpthread Now, execute your program which gives the following output − main() : creating thread, 0 main() : creating thread, 1 main() : creating thread, 2 main() : creating thread, 3 main() : creating thread, 4 Hello World! Thread ID, 0 Hello World! Thread ID, 1 Hello World! Thread ID, 2 Hello World! Thread ID, 3 Hello World! Thread ID, 4 This example shows how to pass multiple arguments via a structure. You can pass any data type in a thread callback because it points to void as explained in the following example − #include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; #define NUM_THREADS 5 struct thread_data { int thread_id; char *message; }; void *PrintHello(void *threadarg) { struct thread_data *my_data; my_data = (struct thread_data *) threadarg; cout << "Thread ID : " << my_data->thread_id ; cout << " Message : " << my_data->message << endl; pthread_exit(NULL); } int main () { pthread_t threads[NUM_THREADS]; struct thread_data td[NUM_THREADS]; int rc; int i; for( i = 0; i < NUM_THREADS; i++ ) { cout <<"main() : creating thread, " << i << endl; td[i].thread_id = i; td[i].message = "This is message"; rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]); if (rc) { cout << "Error:unable to create thread," << rc << endl; exit(-1); } } pthread_exit(NULL); } When the above code is compiled and executed, it produces the following result − main() : creating thread, 0 main() : creating thread, 1 main() : creating thread, 2 main() : creating thread, 3 main() : creating thread, 4 Thread ID : 3 Message : This is message Thread ID : 2 Message : This is message Thread ID : 0 Message : This is message Thread ID : 1 Message : This is message Thread ID : 4 Message : This is message There are following two routines which we can use to join or detach threads − pthread_join (threadid, status) pthread_detach (threadid) The pthread_join() subroutine blocks the calling thread until the specified 'threadid' thread terminates. When a thread is created, one of its attributes defines whether it is joinable or detached. Only threads that are created as joinable can be joined. If a thread is created as detached, it can never be joined. This example demonstrates how to wait for thread completions by using the Pthread join routine. #include <iostream> #include <cstdlib> #include <pthread.h> #include <unistd.h> using namespace std; #define NUM_THREADS 5 void *wait(void *t) { int i; long tid; tid = (long)t; sleep(1); cout << "Sleeping in thread " << endl; cout << "Thread with id : " << tid << " ...exiting " << endl; pthread_exit(NULL); } int main () { int rc; int i; pthread_t threads[NUM_THREADS]; pthread_attr_t attr; void *status; // Initialize and set thread joinable pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for( i = 0; i < NUM_THREADS; i++ ) { cout << "main() : creating thread, " << i << endl; rc = pthread_create(&threads[i], &attr, wait, (void *)i ); if (rc) { cout << "Error:unable to create thread," << rc << endl; exit(-1); } } // free attribute and wait for the other threads pthread_attr_destroy(&attr); for( i = 0; i < NUM_THREADS; i++ ) { rc = pthread_join(threads[i], &status); if (rc) { cout << "Error:unable to join," << rc << endl; exit(-1); } cout << "Main: completed thread id :" << i ; cout << " exiting with status :" << status << endl; } cout << "Main: program exiting." << endl; pthread_exit(NULL); } When the above code is compiled and executed, it produces the following result − main() : creating thread, 0 main() : creating thread, 1 main() : creating thread, 2 main() : creating thread, 3 main() : creating thread, 4 Sleeping in thread Thread with id : 0 .... exiting Sleeping in thread Thread with id : 1 .... exiting Sleeping in thread Thread with id : 2 .... exiting Sleeping in thread Thread with id : 3 .... exiting Sleeping in thread Thread with id : 4 .... exiting Main: completed thread id :0 exiting with status :0 Main: completed thread id :1 exiting with status :0 Main: completed thread id :2 exiting with status :0 Main: completed thread id :3 exiting with status :0 Main: completed thread id :4 exiting with status :0 Main: program exiting. 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": 2555, "s": 2318, "text": "Multithreading is a specialized form of multitasking and a multitasking is the feature that allows your computer to run two or more programs concurrently. In general, there are two types of multitasking: process-based and thread-based." }, { "code": null, "e": 2721, "s": 2555, "text": "Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program." }, { "code": null, "e": 2901, "s": 2721, "text": "A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution." }, { "code": null, "e": 3056, "s": 2901, "text": "Before C++ 11, there is no built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature." }, { "code": null, "e": 3328, "s": 3056, "text": "This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C++ program using POSIX. POSIX Threads, or Pthreads provides API which are available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris." }, { "code": null, "e": 3385, "s": 3328, "text": "The following routine is used to create a POSIX thread −" }, { "code": null, "e": 3458, "s": 3385, "text": "#include <pthread.h>\npthread_create (thread, attr, start_routine, arg) \n" }, { "code": null, "e": 3648, "s": 3458, "text": "Here, pthread_create creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code. Here is the description of the parameters −" }, { "code": null, "e": 3655, "s": 3648, "text": "thread" }, { "code": null, "e": 3731, "s": 3655, "text": "An opaque, unique identifier for the new thread returned by the subroutine." }, { "code": null, "e": 3736, "s": 3731, "text": "attr" }, { "code": null, "e": 3882, "s": 3736, "text": "An opaque attribute object that may be used to set thread attributes. You can specify a thread attributes object, or NULL for the default values." }, { "code": null, "e": 3896, "s": 3882, "text": "start_routine" }, { "code": null, "e": 3961, "s": 3896, "text": "The C++ routine that the thread will execute once it is created." }, { "code": null, "e": 3965, "s": 3961, "text": "arg" }, { "code": null, "e": 4132, "s": 3965, "text": "A single argument that may be passed to start_routine. It must be passed by reference as a pointer cast of type void. NULL may be used if no argument is to be passed." }, { "code": null, "e": 4348, "s": 4132, "text": "The maximum number of threads that may be created by a process is implementation dependent. Once created, threads are peers, and may create other threads. There is no implied hierarchy or dependency between threads." }, { "code": null, "e": 4418, "s": 4348, "text": "There is following routine which we use to terminate a POSIX thread −" }, { "code": null, "e": 4463, "s": 4418, "text": "#include <pthread.h>\npthread_exit (status) \n" }, { "code": null, "e": 4640, "s": 4463, "text": "Here pthread_exit is used to explicitly exit a thread. Typically, the pthread_exit() routine is called after a thread has completed its work and is no longer required to exist." }, { "code": null, "e": 4840, "s": 4640, "text": "If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes." }, { "code": null, "e": 4848, "s": 4840, "text": "Example" }, { "code": null, "e": 5023, "s": 4848, "text": "This simple example code creates 5 threads with the pthread_create() routine. Each thread prints a \"Hello World!\" message, and then terminates with a call to pthread_exit(). " }, { "code": null, "e": 5667, "s": 5023, "text": "#include <iostream>\n#include <cstdlib>\n#include <pthread.h>\n\nusing namespace std;\n\n#define NUM_THREADS 5\n\nvoid *PrintHello(void *threadid) {\n long tid;\n tid = (long)threadid;\n cout << \"Hello World! Thread ID, \" << tid << endl;\n pthread_exit(NULL);\n}\n\nint main () {\n pthread_t threads[NUM_THREADS];\n int rc;\n int i;\n \n for( i = 0; i < NUM_THREADS; i++ ) {\n cout << \"main() : creating thread, \" << i << endl;\n rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);\n \n if (rc) {\n cout << \"Error:unable to create thread,\" << rc << endl;\n exit(-1);\n }\n }\n pthread_exit(NULL);\n}" }, { "code": null, "e": 5734, "s": 5667, "text": "Compile the following program using -lpthread library as follows −" }, { "code": null, "e": 5759, "s": 5734, "text": "$gcc test.cpp -lpthread\n" }, { "code": null, "e": 5820, "s": 5759, "text": "Now, execute your program which gives the following output −" }, { "code": null, "e": 6091, "s": 5820, "text": "main() : creating thread, 0\nmain() : creating thread, 1\nmain() : creating thread, 2\nmain() : creating thread, 3\nmain() : creating thread, 4\nHello World! Thread ID, 0\nHello World! Thread ID, 1\nHello World! Thread ID, 2\nHello World! Thread ID, 3\nHello World! Thread ID, 4\n" }, { "code": null, "e": 6272, "s": 6091, "text": "This example shows how to pass multiple arguments via a structure. You can pass any data type in a thread callback because it points to void as explained in the following example −" }, { "code": null, "e": 7180, "s": 6272, "text": "#include <iostream>\n#include <cstdlib>\n#include <pthread.h>\n\nusing namespace std;\n\n#define NUM_THREADS 5\n\nstruct thread_data {\n int thread_id;\n char *message;\n};\n\nvoid *PrintHello(void *threadarg) {\n struct thread_data *my_data;\n my_data = (struct thread_data *) threadarg;\n\n cout << \"Thread ID : \" << my_data->thread_id ;\n cout << \" Message : \" << my_data->message << endl;\n\n pthread_exit(NULL);\n}\n\nint main () {\n pthread_t threads[NUM_THREADS];\n struct thread_data td[NUM_THREADS];\n int rc;\n int i;\n\n for( i = 0; i < NUM_THREADS; i++ ) {\n cout <<\"main() : creating thread, \" << i << endl;\n td[i].thread_id = i;\n td[i].message = \"This is message\";\n rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]);\n \n if (rc) {\n cout << \"Error:unable to create thread,\" << rc << endl;\n exit(-1);\n }\n }\n pthread_exit(NULL);\n}" }, { "code": null, "e": 7261, "s": 7180, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 7602, "s": 7261, "text": "main() : creating thread, 0\nmain() : creating thread, 1\nmain() : creating thread, 2\nmain() : creating thread, 3\nmain() : creating thread, 4\nThread ID : 3 Message : This is message\nThread ID : 2 Message : This is message\nThread ID : 0 Message : This is message\nThread ID : 1 Message : This is message\nThread ID : 4 Message : This is message\n" }, { "code": null, "e": 7680, "s": 7602, "text": "There are following two routines which we can use to join or detach threads −" }, { "code": null, "e": 7741, "s": 7680, "text": "pthread_join (threadid, status) \npthread_detach (threadid) \n" }, { "code": null, "e": 8056, "s": 7741, "text": "The pthread_join() subroutine blocks the calling thread until the specified 'threadid' thread terminates. When a thread is created, one of its attributes defines whether it is joinable or detached. Only threads that are created as joinable can be joined. If a thread is created as detached, it can never be joined." }, { "code": null, "e": 8152, "s": 8056, "text": "This example demonstrates how to wait for thread completions by using the Pthread join routine." }, { "code": null, "e": 9468, "s": 8152, "text": "#include <iostream>\n#include <cstdlib>\n#include <pthread.h>\n#include <unistd.h>\n\nusing namespace std;\n\n#define NUM_THREADS 5\n\nvoid *wait(void *t) {\n int i;\n long tid;\n\n tid = (long)t;\n\n sleep(1);\n cout << \"Sleeping in thread \" << endl;\n cout << \"Thread with id : \" << tid << \" ...exiting \" << endl;\n pthread_exit(NULL);\n}\n\nint main () {\n int rc;\n int i;\n pthread_t threads[NUM_THREADS];\n pthread_attr_t attr;\n void *status;\n\n // Initialize and set thread joinable\n pthread_attr_init(&attr);\n pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\n\n for( i = 0; i < NUM_THREADS; i++ ) {\n cout << \"main() : creating thread, \" << i << endl;\n rc = pthread_create(&threads[i], &attr, wait, (void *)i );\n if (rc) {\n cout << \"Error:unable to create thread,\" << rc << endl;\n exit(-1);\n }\n }\n\n // free attribute and wait for the other threads\n pthread_attr_destroy(&attr);\n for( i = 0; i < NUM_THREADS; i++ ) {\n rc = pthread_join(threads[i], &status);\n if (rc) {\n cout << \"Error:unable to join,\" << rc << endl;\n exit(-1);\n }\n cout << \"Main: completed thread id :\" << i ;\n cout << \" exiting with status :\" << status << endl;\n }\n\n cout << \"Main: program exiting.\" << endl;\n pthread_exit(NULL);\n}" }, { "code": null, "e": 9549, "s": 9468, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 10233, "s": 9549, "text": "main() : creating thread, 0\nmain() : creating thread, 1\nmain() : creating thread, 2\nmain() : creating thread, 3\nmain() : creating thread, 4\nSleeping in thread\nThread with id : 0 .... exiting\nSleeping in thread\nThread with id : 1 .... exiting\nSleeping in thread\nThread with id : 2 .... exiting\nSleeping in thread\nThread with id : 3 .... exiting\nSleeping in thread\nThread with id : 4 .... exiting\nMain: completed thread id :0 exiting with status :0\nMain: completed thread id :1 exiting with status :0\nMain: completed thread id :2 exiting with status :0\nMain: completed thread id :3 exiting with status :0\nMain: completed thread id :4 exiting with status :0\nMain: program exiting.\n" }, { "code": null, "e": 10270, "s": 10233, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 10289, "s": 10270, "text": " Arnab Chakraborty" }, { "code": null, "e": 10321, "s": 10289, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 10344, "s": 10321, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 10380, "s": 10344, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 10397, "s": 10380, "text": " Frahaan Hussain" }, { "code": null, "e": 10432, "s": 10397, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10449, "s": 10432, "text": " Frahaan Hussain" }, { "code": null, "e": 10484, "s": 10449, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 10501, "s": 10484, "text": " Frahaan Hussain" }, { "code": null, "e": 10536, "s": 10501, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10553, "s": 10536, "text": " Frahaan Hussain" }, { "code": null, "e": 10560, "s": 10553, "text": " Print" }, { "code": null, "e": 10571, "s": 10560, "text": " Add Notes" } ]
Dart Programming - toString Method
Returns a string representation of an object. val.toString() Returns a string. void main() { int n = 12; var res = n.toString(); print("New String: ${res}"); } It will produce the following output −. New String: 12 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": 2571, "s": 2525, "text": "Returns a string representation of an object." }, { "code": null, "e": 2587, "s": 2571, "text": "val.toString()\n" }, { "code": null, "e": 2605, "s": 2587, "text": "Returns a string." }, { "code": null, "e": 2701, "s": 2605, "text": "void main() { \n int n = 12; \n var res = n.toString(); \n print(\"New String: ${res}\");\n} " }, { "code": null, "e": 2741, "s": 2701, "text": "It will produce the following output −." }, { "code": null, "e": 2757, "s": 2741, "text": "New String: 12\n" }, { "code": null, "e": 2792, "s": 2757, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2812, "s": 2792, "text": " Sriyank Siddhartha" }, { "code": null, "e": 2845, "s": 2812, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 2865, "s": 2845, "text": " Sriyank Siddhartha" }, { "code": null, "e": 2898, "s": 2865, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 2915, "s": 2898, "text": " Frahaan Hussain" }, { "code": null, "e": 2950, "s": 2915, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 2967, "s": 2950, "text": " Frahaan Hussain" }, { "code": null, "e": 3002, "s": 2967, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3022, "s": 3002, "text": " Pranjal Srivastava" }, { "code": null, "e": 3055, "s": 3022, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 3075, "s": 3055, "text": " Pranjal Srivastava" }, { "code": null, "e": 3082, "s": 3075, "text": " Print" }, { "code": null, "e": 3093, "s": 3082, "text": " Add Notes" } ]
Bell Numbers (Number of ways to Partition a Set) - GeeksforGeeks
16 Apr, 2021 Given a set of n elements, find number of ways of partitioning it. Examples: Input: n = 2 Output: Number of ways = 2 Explanation: Let the set be {1, 2} { {1}, {2} } { {1, 2} } Input: n = 3 Output: Number of ways = 5 Explanation: Let the set be {1, 2, 3} { {1}, {2}, {3} } { {1}, {2, 3} } { {2}, {1, 3} } { {3}, {1, 2} } { {1, 2, 3} }. Solution to above questions is Bell Number. What is a Bell Number? Let S(n, k) be total number of partitions of n elements into k sets. The value of n’th Bell Number is sum of S(n, k) for k = 1 to n. Value of S(n, k) can be defined recursively as, S(n+1, k) = k*S(n, k) + S(n, k-1)How does above recursive formula work? When we add a (n+1)’th element to k partitions, there are two possibilities. 1) It is added as a single element set to existing partitions, i.e, S(n, k-1) 2) It is added to all sets of every partition, i.e., k*S(n, k)S(n, k) is called Stirling numbers of the second kindFirst few Bell numbers are 1, 1, 2, 5, 15, 52, 203, .... A Simple Method to compute n’th Bell Number is to one by one compute S(n, k) for k = 1 to n and return sum of all computed values. Refer this for computation of S(n, k).A Better Method is to use Bell Triangle. Below is a sample Bell Triangle for first few Bell Numbers. 1 1 2 2 3 5 5 7 10 15 15 20 27 37 52 The triangle is constructed using below formula. // If this is first column of current row 'i' If j == 0 // Then copy last entry of previous row // Note that i'th row has i entries Bell(i, j) = Bell(i-1, i-1) // If this is not first column of current row Else // Then this element is sum of previous element // in current row and the element just above the // previous element Bell(i, j) = Bell(i-1, j-1) + Bell(i, j-1) Interpretation Then Bell(n, k) counts the number of partitions of the set {1, 2, ..., n + 1} in which the element k + 1 is the largest element that can be alone in its set.For example, Bell(3, 2) is 3, it is count of number of partitions of {1, 2, 3, 4} in which 3 is the largest singleton element. There are three such partitions: {1}, {2, 4}, {3} {1, 4}, {2}, {3} {1, 2, 4}, {3}. Below is Dynamic Programming based implementation of above recursive formula. C++ Java Python3 C# PHP Javascript // A C++ program to find n'th Bell number#include<iostream>using namespace std; int bellNumber(int n){ int bell[n+1][n+1]; bell[0][0] = 1; for (int i=1; i<=n; i++) { // Explicitly fill for j = 0 bell[i][0] = bell[i-1][i-1]; // Fill for remaining values of j for (int j=1; j<=i; j++) bell[i][j] = bell[i-1][j-1] + bell[i][j-1]; } return bell[n][0];} // Driver programint main(){ for (int n=0; n<=5; n++) cout << "Bell Number " << n << " is " << bellNumber(n) << endl; return 0;} // Java program to find n'th Bell numberimport java.io.*; class GFG{ // Function to find n'th Bell Number static int bellNumber(int n) { int[][] bell = new int[n+1][n+1]; bell[0][0] = 1; for (int i=1; i<=n; i++) { // Explicitly fill for j = 0 bell[i][0] = bell[i-1][i-1]; // Fill for remaining values of j for (int j=1; j<=i; j++) bell[i][j] = bell[i-1][j-1] + bell[i][j-1]; } return bell[n][0]; } // Driver program public static void main (String[] args) { for (int n=0; n<=5; n++) System.out.println("Bell Number "+ n + " is "+bellNumber(n)); }} // This code is contributed by Pramod Kumar # A Python program to find n'th Bell number def bellNumber(n): bell = [[0 for i in range(n+1)] for j in range(n+1)] bell[0][0] = 1 for i in range(1, n+1): # Explicitly fill for j = 0 bell[i][0] = bell[i-1][i-1] # Fill for remaining values of j for j in range(1, i+1): bell[i][j] = bell[i-1][j-1] + bell[i][j-1] return bell[n][0] # Driver programfor n in range(6): print('Bell Number', n, 'is', bellNumber(n)) # This code is contributed by Soumen Ghosh // C# program to find n'th Bell numberusing System; class GFG { // Function to find n'th // Bell Number static int bellNumber(int n) { int[,] bell = new int[n + 1, n + 1]; bell[0, 0] = 1; for (int i = 1; i <= n; i++) { // Explicitly fill for j = 0 bell[i, 0] = bell[i - 1, i - 1]; // Fill for remaining values of j for (int j = 1; j <= i; j++) bell[i, j] = bell[i - 1, j - 1] + bell[i, j - 1]; } return bell[n, 0]; } // Driver Code public static void Main () { for (int n = 0; n <= 5; n++) Console.WriteLine("Bell Number "+ n + " is "+bellNumber(n)); }} // This code is contributed by nitin mittal. <?php// A PHP program to find// n'th Bell number // function that returns// n'th bell numberfunction bellNumber($n){ $bell[0][0] = 1; for ($i = 1; $i <= $n; $i++) { // Explicitly fill for j = 0 $bell[$i][0] = $bell[$i - 1] [$i - 1]; // Fill for remaining // values of j for ($j = 1; $j <= $i; $j++) $bell[$i][$j] = $bell[$i - 1][$j - 1] + $bell[$i][$j - 1]; } return $bell[$n][0];} // Driver Codefor ($n = 0; $n <= 5; $n++)echo("Bell Number " . $n . " is " . bellNumber($n) . "\n"); // This code is contributed by Ajit.?> <script> // Javascript program to find n'th Bell number // Function to find n'th Bell Number function bellNumber(n) { let bell = new Array(n+1); for(let i = 0; i < n + 1; i++) { bell[i] = new Array(n + 1); } bell[0][0] = 1; for (let i=1; i<=n; i++) { // Explicitly fill for j = 0 bell[i][0] = bell[i-1][i-1]; // Fill for remaining values of j for (let j=1; j<=i; j++) bell[i][j] = bell[i-1][j-1] + bell[i][j-1]; } return bell[n][0]; } for (let n=0; n<=5; n++) document.write("Bell Number "+ n + " is "+bellNumber(n) + "</br>"); </script> Output: Bell Number 0 is 1 Bell Number 1 is 1 Bell Number 2 is 2 Bell Number 3 is 5 Bell Number 4 is 15 Bell Number 5 is 52 Time Complexity of above solution is O(n2). We will soon be discussing other more efficient methods of computing Bell Numbers.Another problem that can be solved by Bell Numbers. A number is squarefree if it is not divisible by a perfect square other than 1. For example, 6 is a square free number but 12 is not as it is divisible by 4. Given a squarefree number x, find the number of different multiplicative partitions of x. The number of multiplicative partitions is Bell(n) where n is number of prime factors of x. For example x = 30, there are 3 prime factors of 2, 3 and 5. So the answer is Bell(3) which is 5. The 5 partitions are 1 x 30, 2 x15, 3 x 10, 5 x 6 and 2 x 3 x 5.Exercise: The above implementation causes arithmetic overflow for slightly larger values of n. Extend the above program so that results are computed under modulo 1000000007 to avoid overflows.Reference: https://en.wikipedia.org/wiki/Bell_number https://en.wikipedia.org/wiki/Bell_triangleThis article is contributed by Rajeev Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal jit_t decode2207 subset Dynamic Programming Mathematical Dynamic Programming Mathematical subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Edit Distance | DP-5 Overlapping Subproblems Property in Dynamic Programming | DP-1 Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Program to find GCD or HCF of two numbers Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 24580, "s": 24552, "text": "\n16 Apr, 2021" }, { "code": null, "e": 24659, "s": 24580, "text": "Given a set of n elements, find number of ways of partitioning it. Examples: " }, { "code": null, "e": 25011, "s": 24659, "text": "Input: n = 2\nOutput: Number of ways = 2\nExplanation: Let the set be {1, 2}\n { {1}, {2} } \n { {1, 2} }\n\nInput: n = 3\nOutput: Number of ways = 5\nExplanation: Let the set be {1, 2, 3}\n { {1}, {2}, {3} }\n { {1}, {2, 3} }\n { {2}, {1, 3} }\n { {3}, {1, 2} }\n { {1, 2, 3} }. " }, { "code": null, "e": 25930, "s": 25011, "text": "Solution to above questions is Bell Number. What is a Bell Number? Let S(n, k) be total number of partitions of n elements into k sets. The value of n’th Bell Number is sum of S(n, k) for k = 1 to n. Value of S(n, k) can be defined recursively as, S(n+1, k) = k*S(n, k) + S(n, k-1)How does above recursive formula work? When we add a (n+1)’th element to k partitions, there are two possibilities. 1) It is added as a single element set to existing partitions, i.e, S(n, k-1) 2) It is added to all sets of every partition, i.e., k*S(n, k)S(n, k) is called Stirling numbers of the second kindFirst few Bell numbers are 1, 1, 2, 5, 15, 52, 203, .... A Simple Method to compute n’th Bell Number is to one by one compute S(n, k) for k = 1 to n and return sum of all computed values. Refer this for computation of S(n, k).A Better Method is to use Bell Triangle. Below is a sample Bell Triangle for first few Bell Numbers. " }, { "code": null, "e": 25967, "s": 25930, "text": "1\n1 2\n2 3 5\n5 7 10 15\n15 20 27 37 52" }, { "code": null, "e": 26018, "s": 25967, "text": "The triangle is constructed using below formula. " }, { "code": null, "e": 26414, "s": 26018, "text": "// If this is first column of current row 'i'\nIf j == 0\n // Then copy last entry of previous row\n // Note that i'th row has i entries\n Bell(i, j) = Bell(i-1, i-1) \n\n// If this is not first column of current row\nElse \n // Then this element is sum of previous element \n // in current row and the element just above the\n // previous element\n Bell(i, j) = Bell(i-1, j-1) + Bell(i, j-1)" }, { "code": null, "e": 26746, "s": 26414, "text": "Interpretation Then Bell(n, k) counts the number of partitions of the set {1, 2, ..., n + 1} in which the element k + 1 is the largest element that can be alone in its set.For example, Bell(3, 2) is 3, it is count of number of partitions of {1, 2, 3, 4} in which 3 is the largest singleton element. There are three such partitions:" }, { "code": null, "e": 26809, "s": 26746, "text": " {1}, {2, 4}, {3}\n {1, 4}, {2}, {3}\n {1, 2, 4}, {3}. " }, { "code": null, "e": 26889, "s": 26809, "text": "Below is Dynamic Programming based implementation of above recursive formula. " }, { "code": null, "e": 26893, "s": 26889, "text": "C++" }, { "code": null, "e": 26898, "s": 26893, "text": "Java" }, { "code": null, "e": 26906, "s": 26898, "text": "Python3" }, { "code": null, "e": 26909, "s": 26906, "text": "C#" }, { "code": null, "e": 26913, "s": 26909, "text": "PHP" }, { "code": null, "e": 26924, "s": 26913, "text": "Javascript" }, { "code": "// A C++ program to find n'th Bell number#include<iostream>using namespace std; int bellNumber(int n){ int bell[n+1][n+1]; bell[0][0] = 1; for (int i=1; i<=n; i++) { // Explicitly fill for j = 0 bell[i][0] = bell[i-1][i-1]; // Fill for remaining values of j for (int j=1; j<=i; j++) bell[i][j] = bell[i-1][j-1] + bell[i][j-1]; } return bell[n][0];} // Driver programint main(){ for (int n=0; n<=5; n++) cout << \"Bell Number \" << n << \" is \" << bellNumber(n) << endl; return 0;}", "e": 27462, "s": 26924, "text": null }, { "code": "// Java program to find n'th Bell numberimport java.io.*; class GFG{ // Function to find n'th Bell Number static int bellNumber(int n) { int[][] bell = new int[n+1][n+1]; bell[0][0] = 1; for (int i=1; i<=n; i++) { // Explicitly fill for j = 0 bell[i][0] = bell[i-1][i-1]; // Fill for remaining values of j for (int j=1; j<=i; j++) bell[i][j] = bell[i-1][j-1] + bell[i][j-1]; } return bell[n][0]; } // Driver program public static void main (String[] args) { for (int n=0; n<=5; n++) System.out.println(\"Bell Number \"+ n + \" is \"+bellNumber(n)); }} // This code is contributed by Pramod Kumar", "e": 28249, "s": 27462, "text": null }, { "code": "# A Python program to find n'th Bell number def bellNumber(n): bell = [[0 for i in range(n+1)] for j in range(n+1)] bell[0][0] = 1 for i in range(1, n+1): # Explicitly fill for j = 0 bell[i][0] = bell[i-1][i-1] # Fill for remaining values of j for j in range(1, i+1): bell[i][j] = bell[i-1][j-1] + bell[i][j-1] return bell[n][0] # Driver programfor n in range(6): print('Bell Number', n, 'is', bellNumber(n)) # This code is contributed by Soumen Ghosh", "e": 28759, "s": 28249, "text": null }, { "code": "// C# program to find n'th Bell numberusing System; class GFG { // Function to find n'th // Bell Number static int bellNumber(int n) { int[,] bell = new int[n + 1, n + 1]; bell[0, 0] = 1; for (int i = 1; i <= n; i++) { // Explicitly fill for j = 0 bell[i, 0] = bell[i - 1, i - 1]; // Fill for remaining values of j for (int j = 1; j <= i; j++) bell[i, j] = bell[i - 1, j - 1] + bell[i, j - 1]; } return bell[n, 0]; } // Driver Code public static void Main () { for (int n = 0; n <= 5; n++) Console.WriteLine(\"Bell Number \"+ n + \" is \"+bellNumber(n)); }} // This code is contributed by nitin mittal.", "e": 29632, "s": 28759, "text": null }, { "code": "<?php// A PHP program to find// n'th Bell number // function that returns// n'th bell numberfunction bellNumber($n){ $bell[0][0] = 1; for ($i = 1; $i <= $n; $i++) { // Explicitly fill for j = 0 $bell[$i][0] = $bell[$i - 1] [$i - 1]; // Fill for remaining // values of j for ($j = 1; $j <= $i; $j++) $bell[$i][$j] = $bell[$i - 1][$j - 1] + $bell[$i][$j - 1]; } return $bell[$n][0];} // Driver Codefor ($n = 0; $n <= 5; $n++)echo(\"Bell Number \" . $n . \" is \" . bellNumber($n) . \"\\n\"); // This code is contributed by Ajit.?>", "e": 30293, "s": 29632, "text": null }, { "code": "<script> // Javascript program to find n'th Bell number // Function to find n'th Bell Number function bellNumber(n) { let bell = new Array(n+1); for(let i = 0; i < n + 1; i++) { bell[i] = new Array(n + 1); } bell[0][0] = 1; for (let i=1; i<=n; i++) { // Explicitly fill for j = 0 bell[i][0] = bell[i-1][i-1]; // Fill for remaining values of j for (let j=1; j<=i; j++) bell[i][j] = bell[i-1][j-1] + bell[i][j-1]; } return bell[n][0]; } for (let n=0; n<=5; n++) document.write(\"Bell Number \"+ n + \" is \"+bellNumber(n) + \"</br>\"); </script>", "e": 31042, "s": 30293, "text": null }, { "code": null, "e": 31051, "s": 31042, "text": "Output: " }, { "code": null, "e": 31167, "s": 31051, "text": "Bell Number 0 is 1\nBell Number 1 is 1\nBell Number 2 is 2\nBell Number 3 is 5\nBell Number 4 is 15\nBell Number 5 is 52" }, { "code": null, "e": 32308, "s": 31167, "text": "Time Complexity of above solution is O(n2). We will soon be discussing other more efficient methods of computing Bell Numbers.Another problem that can be solved by Bell Numbers. A number is squarefree if it is not divisible by a perfect square other than 1. For example, 6 is a square free number but 12 is not as it is divisible by 4. Given a squarefree number x, find the number of different multiplicative partitions of x. The number of multiplicative partitions is Bell(n) where n is number of prime factors of x. For example x = 30, there are 3 prime factors of 2, 3 and 5. So the answer is Bell(3) which is 5. The 5 partitions are 1 x 30, 2 x15, 3 x 10, 5 x 6 and 2 x 3 x 5.Exercise: The above implementation causes arithmetic overflow for slightly larger values of n. Extend the above program so that results are computed under modulo 1000000007 to avoid overflows.Reference: https://en.wikipedia.org/wiki/Bell_number https://en.wikipedia.org/wiki/Bell_triangleThis article is contributed by Rajeev Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32321, "s": 32308, "text": "nitin mittal" }, { "code": null, "e": 32327, "s": 32321, "text": "jit_t" }, { "code": null, "e": 32338, "s": 32327, "text": "decode2207" }, { "code": null, "e": 32345, "s": 32338, "text": "subset" }, { "code": null, "e": 32365, "s": 32345, "text": "Dynamic Programming" }, { "code": null, "e": 32378, "s": 32365, "text": "Mathematical" }, { "code": null, "e": 32398, "s": 32378, "text": "Dynamic Programming" }, { "code": null, "e": 32411, "s": 32398, "text": "Mathematical" }, { "code": null, "e": 32418, "s": 32411, "text": "subset" }, { "code": null, "e": 32516, "s": 32418, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32525, "s": 32516, "text": "Comments" }, { "code": null, "e": 32538, "s": 32525, "text": "Old Comments" }, { "code": null, "e": 32569, "s": 32538, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 32602, "s": 32569, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 32670, "s": 32602, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 32691, "s": 32670, "text": "Edit Distance | DP-5" }, { "code": null, "e": 32754, "s": 32691, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" }, { "code": null, "e": 32814, "s": 32754, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32829, "s": 32814, "text": "C++ Data Types" }, { "code": null, "e": 32872, "s": 32829, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 32914, "s": 32872, "text": "Program to find GCD or HCF of two numbers" } ]
Swift - Decision Making
Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general from of a typical decision making structure found in most of the programming languages − Swift 4 provides the following types of decision making statements. Click the following links to check their detail. An if statement consists of a Boolean expression followed by one or more statements. An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. You can use one if or else if statement inside another if or else if statement(s). A switch statement allows a variable to be tested for equality against a list of values. We have covered conditional operator ? : in the previous chapter which can be used to replace if...else statements. It has the following general form − Exp1 ? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. 38 Lectures 1 hours Ashish Sharma 13 Lectures 2 hours Three Millennials 7 Lectures 1 hours Three Millennials 22 Lectures 1 hours Frahaan Hussain 12 Lectures 39 mins Devasena Rajendran 40 Lectures 2.5 hours Grant Klimaytys Print Add Notes Bookmark this page
[ { "code": null, "e": 2570, "s": 2253, "text": "Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false." }, { "code": null, "e": 2684, "s": 2570, "text": "Following is the general from of a typical decision making structure found in most of the programming languages −" }, { "code": null, "e": 2801, "s": 2684, "text": "Swift 4 provides the following types of decision making statements. Click the following links to check their detail." }, { "code": null, "e": 2886, "s": 2801, "text": "An if statement consists of a Boolean expression followed by one or more statements." }, { "code": null, "e": 3002, "s": 2886, "text": "An if statement can be followed by an optional else statement, which executes when the Boolean expression is false." }, { "code": null, "e": 3160, "s": 3002, "text": "An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement." }, { "code": null, "e": 3243, "s": 3160, "text": "You can use one if or else if statement inside another if or else if statement(s)." }, { "code": null, "e": 3332, "s": 3243, "text": "A switch statement allows a variable to be tested for equality against a list of values." }, { "code": null, "e": 3484, "s": 3332, "text": "We have covered conditional operator ? : in the previous chapter which can be used to replace if...else statements. It has the following general form −" }, { "code": null, "e": 3505, "s": 3484, "text": "Exp1 ? Exp2 : Exp3;\n" }, { "code": null, "e": 3592, "s": 3505, "text": "Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon." }, { "code": null, "e": 3844, "s": 3592, "text": "The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression." }, { "code": null, "e": 3877, "s": 3844, "text": "\n 38 Lectures \n 1 hours \n" }, { "code": null, "e": 3892, "s": 3877, "text": " Ashish Sharma" }, { "code": null, "e": 3925, "s": 3892, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 3944, "s": 3925, "text": " Three Millennials" }, { "code": null, "e": 3976, "s": 3944, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 3995, "s": 3976, "text": " Three Millennials" }, { "code": null, "e": 4028, "s": 3995, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 4045, "s": 4028, "text": " Frahaan Hussain" }, { "code": null, "e": 4077, "s": 4045, "text": "\n 12 Lectures \n 39 mins\n" }, { "code": null, "e": 4097, "s": 4077, "text": " Devasena Rajendran" }, { "code": null, "e": 4132, "s": 4097, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4149, "s": 4132, "text": " Grant Klimaytys" }, { "code": null, "e": 4156, "s": 4149, "text": " Print" }, { "code": null, "e": 4167, "s": 4156, "text": " Add Notes" } ]
How to randomly select an item from a tuple in Python?
The choice() function is useful for this purpose. It returns on item randomly selected from any sequence object (tuple in this case) >>> import random >>> t1=(11,'aa',12.50,77,'xyz') >>> item=random.choice(t1) >>> item 11 >>> item=random.choice(t1) >>> item 'xyz'
[ { "code": null, "e": 1195, "s": 1062, "text": "The choice() function is useful for this purpose. It returns on item randomly selected from any sequence object (tuple in this case)" }, { "code": null, "e": 1326, "s": 1195, "text": ">>> import random\n>>> t1=(11,'aa',12.50,77,'xyz')\n>>> item=random.choice(t1)\n>>> item\n11\n>>> item=random.choice(t1)\n>>> item\n'xyz'" } ]
BERT for Text Classification with NO model training | by Mauro Di Pietro | Towards Data Science
Are you struggling to classify text data because you don’t have a labeled dataset? In this article, using BERT and Python, I will explain how to perform a sort of “unsupervised” text classification based on similarity. NLP (Natural Language Processing) is the field of artificial intelligence that studies the interactions between computers and human languages, in particular how to program computers to process and analyze large amounts of natural language data. NLP is often applied for classifying text data. Text classification is the problem of assigning categories to text data according to its content. In order to carry out a classification use case, you need a labeled dataset for machine learning models training. So what happens if you don’t have one? This kind of situation happens in the real world more often than you think. Nowadays, AI is so hyped that firms want to use it even when they don’t have data. In particular, most non-technical people don’t fully get the concept of “target variable” and how it is used in supervised machine learning. So how can you build a classifier when you have text data but no label? In this tutorial, I am going to explain a strategy that applies W2V and BERT to classify text by word vector similarity. I will present some useful Python code that can be easily applied in other similar cases (just copy, paste, run) and walk through every line of code with comments so that you can replicate this example (link to the full code below). github.com I will use the “News category dataset” in which you are provided with news headlines from the year 2012 to 2018 obtained from HuffPost and you are asked to classify them with the right category, therefore this is a multiclass classification problem (link below). www.kaggle.com In particular, I will go through: Setup: import packages, read data. Preprocessing: clean text data. Create Target Clusters: use Word2Vec with gensim to build the target variable. Feature Engineering: Word Embedding with transformers and BERT. Model Design & Testing: assign observations to clusters by Cosine Similarity and evaluate the performance. Explainability: understand how the model produces results. First of all, I need to import the following packages: ## for dataimport jsonimport pandas as pdimport numpy as npfrom sklearn import metrics, manifold## for processingimport reimport nltk## for plottingimport matplotlib.pyplot as pltimport seaborn as sns## for w2vimport gensimimport gensim.downloader as gensim_api## for bertimport transformers The dataset is contained into a json file, so I will first read it into a list of dictionaries with json and then transform it into a pandas Dataframe. lst_dics = []with open('data.json', mode='r', errors='ignore') as json_file: for dic in json_file: lst_dics.append( json.loads(dic) )## print the first onelst_dics[0] The original dataset contains over 30 categories, but for the purposes of this tutorial, I will work with a subset of 3: Entertainment, Politics, and Tech. ## create dtfdtf = pd.DataFrame(lst_dics)## filter categoriesdtf = dtf[ dtf["category"].isin(['ENTERTAINMENT','POLITICS','TECH']) ][["category","headline"]]## rename columnsdtf = dtf.rename(columns={"category":"y", "headline":"text"})## print 5 random rowsdtf.sample(5) As you can see, the dataset includes a target variable as well. I won’t be using it for modeling, just for performance evaluation. So we’ve got some raw text data and we are tasked to classify it into the 3 categories (Entertainment, Politics, Tech) we know nothing about. Here’s what I am planning to do: clean data and embed it into the vector space, create a topic cluster for each category and embed it into the vector space, calculate similarities between every text vector and the topic clusters, then assign it to the closest cluster. That is why I called it “a sort of unsupervised text classification”. It’s a really basic idea, but the execution can be tricky. Now that’s all set, let’s get started. The absolute first step is to preprocess the data: cleaning text, removing stop words, and applying lemmatization. I will write a function and apply it to the whole data set. '''Preprocess a string.:parameter :param text: string - name of column containing text :param lst_stopwords: list - list of stopwords to remove :param flg_stemm: bool - whether stemming is to be applied :param flg_lemm: bool - whether lemmitisation is to be applied:return cleaned text'''def utils_preprocess_text(text, flg_stemm=False, flg_lemm=True, lst_stopwords=None): ## clean (convert to lowercase and remove punctuations and characters and then strip) text = re.sub(r'[^\w\s]', '', str(text).lower().strip()) ## Tokenize (convert from string to list) lst_text = text.split() ## remove Stopwords if lst_stopwords is not None: lst_text = [word for word in lst_text if word not in lst_stopwords] ## Stemming (remove -ing, -ly, ...) if flg_stemm == True: ps = nltk.stem.porter.PorterStemmer() lst_text = [ps.stem(word) for word in lst_text] ## Lemmatisation (convert the word into root word) if flg_lemm == True: lem = nltk.stem.wordnet.WordNetLemmatizer() lst_text = [lem.lemmatize(word) for word in lst_text] ## back to string from list text = " ".join(lst_text) return text That function removes a set of words from the corpus if given. I can create a list of generic stop words for the English vocabulary with nltk (we could edit this list by adding or removing words). lst_stopwords = nltk.corpus.stopwords.words("english")lst_stopwords Now I shall apply the function to the whole dataset and store the result in a new column named “text_clean” that I am going to use as a corpus. dtf["text_clean"] = dtf["text"].apply(lambda x: utils_preprocess_text(x, flg_stemm=False, flg_lemm=True, lst_stopwords=lst_stopwords))dtf.head() We have our preprocessed corpus, consequently the next step is to build the target variable. Basically, we’re here: The objective of this section is to create some keywords which can represent the context of each category. By performing some text analysis, you can easily discover that the 3 most frequent words are “movie”, “trump”, and “apple” (for a detailed text analysis tutorial you can check this article). I’d suggest starting with those keywords. Let’s take the Politics category for instance: the word “trump” can have different meanings, so we need to add keywords to avoid polysemy problems (i.e. “donald”, “republican”, “white house”, “obama”). This task could be carried out manually or you could use the assistance of a pre-trained NLP model. You can load a pre-trained Word Embedding model from genism-data like this: nlp = gensim_api.load("glove-wiki-gigaword-300") The gensim package has a very convenient function that returns the most similar words for any given word into the vocabulary. nlp.most_similar(["obama"], topn=3) I shall use that to create a dictionary of keywords for each category: ## Function to applydef get_similar_words(lst_words, top, nlp): lst_out = lst_words for tupla in nlp.most_similar(lst_words, topn=top): lst_out.append(tupla[0]) return list(set(lst_out))## Create Dictionary {category:[keywords]}dic_clusters = {}dic_clusters["ENTERTAINMENT"] = get_similar_words(['celebrity','cinema','movie','music'], top=30, nlp=nlp)dic_clusters["POLITICS"] = get_similar_words(['gop','clinton','president','obama','republican'] , top=30, nlp=nlp)dic_clusters["TECH"] = get_similar_words(['amazon','android','app','apple','facebook', 'google','tech'], top=30, nlp=nlp)## print somefor k,v in dic_clusters.items(): print(k, ": ", v[0:5], "...", len(v)) Let’s try to visualize those keywords in a 2D space by applying a dimensionality reduction algorithm (i.e. TSNE). We want to make sure that the clusters are well separated from each other. ## word embeddingtot_words = [word for v in dic_clusters.values() for word in v]X = nlp[tot_words] ## pcapca = manifold.TSNE(perplexity=40, n_components=2, init='pca')X = pca.fit_transform(X)## create dtfdtf = pd.DataFrame()for k,v in dic_clusters.items(): size = len(dtf) + len(v) dtf_group = pd.DataFrame(X[len(dtf):size], columns=["x","y"], index=v) dtf_group["cluster"] = k dtf = dtf.append(dtf_group) ## plotfig, ax = plt.subplots()sns.scatterplot(data=dtf, x="x", y="y", hue="cluster", ax=ax)ax.legend().texts[0].set_text(None)ax.set(xlabel=None, ylabel=None, xticks=[], xticklabels=[], yticks=[], yticklabels=[])for i in range(len(dtf)): ax.annotate(dtf.index[i], xy=(dtf["x"].iloc[i],dtf["y"].iloc[i]), xytext=(5,2), textcoords='offset points', ha='right', va='bottom') Cool, they look isolated enough from each other. The Entertainment cluster is closer to the Tech one than the Politics one, which makes sense as words like “apple” and “youtube” can appear in both Tech and Entertainment news. It’s time to embed the corpus we preprocessed and the target clusters we created in the same vector space. Basically, we’re doing this: Yes, I’m using BERT for this. It’s true that you could utilize any Word Embedding model (i.e. Word2Vec, Glove, ...), even the one that we already loaded to define keywords, so why bother to use such a heavy and complex language model? That’s because BERT doesn’t apply a fixed embedding, instead it looks at the entire sentence and then assigns an embedding to each word. Therefore, the vector BERT assigns to a word is a function of the entire sentence, so that a word can have different vectors based on the contexts. I’m going to load the original pre-trained version of BERT with the package transformers and give an example of the dynamic embedding: tokenizer = transformers.BertTokenizer.from_pretrained('bert-base- uncased', do_lower_case=True)nlp = transformers.TFBertModel.from_pretrained('bert-base-uncased') Let’s use the model to convert the string “river bank” into vectors and print the one assigned to the word “bank”: txt = "river bank"## tokenizeidx = tokenizer.encode(txt)print("tokens:", tokenizer.convert_ids_to_tokens(idx))print("ids :", tokenizer.encode(txt))## word embeddingidx = np.array(idx)[None,:]embedding = nlp(idx)print("shape:", embedding[0][0].shape)## vector of the second input wordembedding[0][0][2] If you do the same for the string “financial bank”, you’ll see that the vector assigned to the word “bank” is different because of the context. Please note that the BERT tokenizer inserts special tokens at the beginning and end of sentences and its vector space has a dimension of 768 (to understand better how BERT processes text you can check this article). Having said that, the plan is to use BERT Word Embedding to represent each text with an array (shape: number of tokens x 768) and then summarize each article into a mean vector. So the final feature matrix will be an array with shape: number of documents (or mean vectors) x 768. ## function to applydef utils_bert_embedding(txt, tokenizer, nlp): idx = tokenizer.encode(txt) idx = np.array(idx)[None,:] embedding = nlp(idx) X = np.array(embedding[0][0][1:-1]) return X## create list of news vectorlst_mean_vecs = [utils_bert_embedding(txt, tokenizer, nlp).mean(0) for txt in dtf["text_clean"]]## create the feature matrix (n news x 768)X = np.array(lst_mean_vecs) We can do the same with the keywords in the target clusters. In fact, each label is identified by a list of words that help BERT to understand the context within the clusters. Hence, I’m going to create a dictionary label : cluster mean vector. dic_y = {k:utils_bert_embedding(v, tokenizer, nlp).mean(0) for k,v in dic_clusters.items()} We started with just some text data and 3 strings (“Entertainment”, “Politics”, “Tech”) and now we have a feature matrix and a target variable... ish. Finally, it’s time to build a model that classifies the news based on the similarity to each target cluster. I am going to use Cosine Similarity, a measure of similarity based on the cosine of the angle between two non-zero vectors, which equals the inner product of the same vectors normalized to both have length 1. You can easily use the cosine similarity implementation of scikit-learn, which takes 2 arrays (or vectors) and returns an array of scores (or a single score). In this case, the output is going to be a matrix with shape: number of news x number of labels (3, Entertainment/Politics/Tech). To put it another way, each row will represent an article and contain one similarity score for each target cluster. In order to run the usual evaluation metrics (Accuracy, AUC, Precision, Recall, ...), we have to rescale the scores in each row so that they sum to 1 and decide a category to label the article with. I’m going to choose the one with the highest score, but it could be wise to set some minimum thresholds and leave out predictions with really low scores. #--- Model Algorithm ---### compute cosine similaritiessimilarities = np.array( [metrics.pairwise.cosine_similarity(X, y).T.tolist()[0] for y in dic_y.values()] ).T## adjust and rescalelabels = list(dic_y.keys())for i in range(len(similarities)): ### assign randomly if there is no similarity if sum(similarities[i]) == 0: similarities[i] = [0]*len(labels) similarities[i][np.random.choice(range(len(labels)))] = 1 ### rescale so they sum = 1 similarities[i] = similarities[i] / sum(similarities[i])## classify the label with highest similarity scorepredicted_prob = similaritiespredicted = [labels[np.argmax(pred)] for pred in predicted_prob] Just like in classic supervised use cases, we have an object with predicted probabilities (here they’re adjusted similarity scores) and another with predicted labels. Let’s check how we did: y_test = dtf["y"].valuesclasses = np.unique(y_test)y_test_array = pd.get_dummies(y_test, drop_first=False).values## Accuracy, Precision, Recallaccuracy = metrics.accuracy_score(y_test, predicted)auc = metrics.roc_auc_score(y_test, predicted_prob, multi_class="ovr")print("Accuracy:", round(accuracy,2))print("Auc:", round(auc,2))print("Detail:")print(metrics.classification_report(y_test, predicted)) ## Plot confusion matrixcm = metrics.confusion_matrix(y_test, predicted)fig, ax = plt.subplots()sns.heatmap(cm, annot=True, fmt='d', ax=ax, cmap=plt.cm.Blues, cbar=False)ax.set(xlabel="Pred", ylabel="True", xticklabels=classes, yticklabels=classes, title="Confusion matrix")plt.yticks(rotation=0)fig, ax = plt.subplots(nrows=1, ncols=2)## Plot rocfor i in range(len(classes)): fpr, tpr, thresholds = metrics.roc_curve(y_test_array[:,i], predicted_prob[:,i]) ax[0].plot(fpr, tpr, lw=3, label='{0} (area={1:0.2f})'.format(classes[i], metrics.auc(fpr, tpr)) )ax[0].plot([0,1], [0,1], color='navy', lw=3, linestyle='--')ax[0].set(xlim=[-0.05,1.0], ylim=[0.0,1.05], xlabel='False Positive Rate', ylabel="True Positive Rate (Recall)", title="Receiver operating characteristic")ax[0].legend(loc="lower right")ax[0].grid(True) ## Plot precision-recall curvefor i in range(len(classes)): precision, recall, thresholds = metrics.precision_recall_curve( y_test_array[:,i], predicted_prob[:,i]) ax[1].plot(recall, precision, lw=3, label='{0} (area={1:0.2f})'.format(classes[i], metrics.auc(recall, precision)) )ax[1].set(xlim=[0.0,1.05], ylim=[0.0,1.05], xlabel='Recall', ylabel="Precision", title="Precision-Recall curve")ax[1].legend(loc="best")ax[1].grid(True)plt.show() Okay, I’m the first to say that it’s not the best Accuracy I’ve ever seen. On the other hand, it’s not bad at all considering that we didn’t train any model and we even made up the target variable. The main issue is over 4k Politics observations classified as Entertainment, but these performances can be easily improved by fine-tuning the keywords for those two categories. Let’s try to understand what led our algorithm to classify news with a category instead of the others. Let’s take a random observation from the corpus: i = 7txt_instance = dtf["text_clean"].iloc[i]print("True:", y_test[i], "--> Pred:", predicted[i], "| Similarity:", round(np.max(predicted_prob[i]),2))print(txt_instance) It’s a Politics observation properly classified. Probably, the words “republican” and “clinton” gave BERT the right hint. I will visualize the mean vector of the article in a 2D space and plot the top similarities with the target cluster. ## create embedding Matrixy = np.concatenate([embedding_bert(v, tokenizer, nlp) for v in dic_clusters.values()])X = embedding_bert(txt_instance, tokenizer, nlp).mean(0).reshape(1,-1)M = np.concatenate([y,X])## pcapca = manifold.TSNE(perplexity=40, n_components=2, init='pca')M = pca.fit_transform(M)y, X = M[:len(y)], M[len(y):]## create dtf clustersdtf = pd.DataFrame()for k,v in dic_clusters.items(): size = len(dtf) + len(v) dtf_group = pd.DataFrame(y[len(dtf):size], columns=["x","y"], index=v) dtf_group["cluster"] = k dtf = dtf.append(dtf_group)## plot clustersfig, ax = plt.subplots()sns.scatterplot(data=dtf, x="x", y="y", hue="cluster", ax=ax)ax.legend().texts[0].set_text(None)ax.set(xlabel=None, ylabel=None, xticks=[], xticklabels=[], yticks=[], yticklabels=[])for i in range(len(dtf)): ax.annotate(dtf.index[i], xy=(dtf["x"].iloc[i],dtf["y"].iloc[i]), xytext=(5,2), textcoords='offset points', ha='right', va='bottom')## add txt_instanceax.scatter(x=X[0][0], y=X[0][1], c="red", linewidth=10) ax.annotate("x", xy=(X[0][0],X[0][1]), ha='center', va='center', fontsize=25)## calculate similaritysim_matrix = metrics.pairwise.cosine_similarity(X, y)## add top similarityfor row in range(sim_matrix.shape[0]): ### sorted {keyword:score} dic_sim = {n:sim_matrix[row][n] for n in range(sim_matrix.shape[1])} dic_sim = {k:v for k,v in sorted(dic_sim.items(), key=lambda item:item[1], reverse=True)} ### plot lines for k in dict(list(dic_sim.items())[0:5]).keys(): p1 = [X[row][0], X[row][1]] p2 = [y[k][0], y[k][1]] ax.plot([p1[0],p2[0]], [p1[1],p2[1]], c="red", alpha=0.5)plt.show() Let’s zoom a bit on the cluster of interest: Overall, we can say the mean vector is pretty similar to the Politics cluster. Let’s break down the article into tokens to see which ones “activated” the right cluster. ## create embedding Matrixy = np.concatenate([embedding_bert(v, tokenizer, nlp) for v in dic_clusters.values()])X = embedding_bert(txt_instance, tokenizer, nlp).mean(0).reshape(1,-1)M = np.concatenate([y,X])## pcapca = manifold.TSNE(perplexity=40, n_components=2, init='pca')M = pca.fit_transform(M)y, X = M[:len(y)], M[len(y):]## create dtf clustersdtf = pd.DataFrame()for k,v in dic_clusters.items(): size = len(dtf) + len(v) dtf_group = pd.DataFrame(y[len(dtf):size], columns=["x","y"], index=v) dtf_group["cluster"] = k dtf = dtf.append(dtf_group)## add txt_instancetokens = tokenizer.convert_ids_to_tokens( tokenizer.encode(txt_instance))[1:-1]dtf = pd.DataFrame(X, columns=["x","y"], index=tokens)dtf = dtf[~dtf.index.str.contains("#")]dtf = dtf[dtf.index.str.len() > 1]X = dtf.valuesax.scatter(x=dtf["x"], y=dtf["y"], c="red")for i in range(len(dtf)): ax.annotate(dtf.index[i], xy=(dtf["x"].iloc[i],dtf["y"].iloc[i]), xytext=(5,2), textcoords='offset points', ha='right', va='bottom')## calculate similaritysim_matrix = metrics.pairwise.cosine_similarity(X, y)## add top similarityfor row in range(sim_matrix.shape[0]): ### sorted {keyword:score} dic_sim = {n:sim_matrix[row][n] for n in range(sim_matrix.shape[1])} dic_sim = {k:v for k,v in sorted(dic_sim.items(), key=lambda item:item[1], reverse=True)} ### plot lines for k in dict(list(dic_sim.items())[0:5]).keys(): p1 = [X[row][0], X[row][1]] p2 = [y[k][0], y[k][1]] ax.plot([p1[0],p2[0]], [p1[1],p2[1]], c="red", alpha=0.5)plt.show() As we thought, there are words in the text which are clearly linked to the Politics cluster, but some others are more similar to the Entertainment general context. This article has been a tutorial to demonstrate how to perform text classification when a labeled training set isn't available. I used a pre-trained Word Embedding model to build a set of keywords to contextualize the target variable. Then I transformed those words and the corpus in the same vector space with the pre-trained BERT language model. Finally, I calculated the Cosine Similarity between text and keywords to determine the context of each article and I used that information to label the news. This strategy isn’t the most effective but it’s definitely efficient as it allows you to deliver good results quickly. Moreover, this algorithm can be used as a baseline for a supervised model, once a labeled dataset is obtained. I hope you enjoyed it! Feel free to contact me for questions and feedback or just to share your interesting projects. 👉 Let’s Connect 👈 This article is part of the series NLP with Python, see also:
[ { "code": null, "e": 390, "s": 171, "text": "Are you struggling to classify text data because you don’t have a labeled dataset? In this article, using BERT and Python, I will explain how to perform a sort of “unsupervised” text classification based on similarity." }, { "code": null, "e": 934, "s": 390, "text": "NLP (Natural Language Processing) is the field of artificial intelligence that studies the interactions between computers and human languages, in particular how to program computers to process and analyze large amounts of natural language data. NLP is often applied for classifying text data. Text classification is the problem of assigning categories to text data according to its content. In order to carry out a classification use case, you need a labeled dataset for machine learning models training. So what happens if you don’t have one?" }, { "code": null, "e": 1427, "s": 934, "text": "This kind of situation happens in the real world more often than you think. Nowadays, AI is so hyped that firms want to use it even when they don’t have data. In particular, most non-technical people don’t fully get the concept of “target variable” and how it is used in supervised machine learning. So how can you build a classifier when you have text data but no label? In this tutorial, I am going to explain a strategy that applies W2V and BERT to classify text by word vector similarity." }, { "code": null, "e": 1660, "s": 1427, "text": "I will present some useful Python code that can be easily applied in other similar cases (just copy, paste, run) and walk through every line of code with comments so that you can replicate this example (link to the full code below)." }, { "code": null, "e": 1671, "s": 1660, "text": "github.com" }, { "code": null, "e": 1934, "s": 1671, "text": "I will use the “News category dataset” in which you are provided with news headlines from the year 2012 to 2018 obtained from HuffPost and you are asked to classify them with the right category, therefore this is a multiclass classification problem (link below)." }, { "code": null, "e": 1949, "s": 1934, "text": "www.kaggle.com" }, { "code": null, "e": 1983, "s": 1949, "text": "In particular, I will go through:" }, { "code": null, "e": 2018, "s": 1983, "text": "Setup: import packages, read data." }, { "code": null, "e": 2050, "s": 2018, "text": "Preprocessing: clean text data." }, { "code": null, "e": 2129, "s": 2050, "text": "Create Target Clusters: use Word2Vec with gensim to build the target variable." }, { "code": null, "e": 2193, "s": 2129, "text": "Feature Engineering: Word Embedding with transformers and BERT." }, { "code": null, "e": 2300, "s": 2193, "text": "Model Design & Testing: assign observations to clusters by Cosine Similarity and evaluate the performance." }, { "code": null, "e": 2359, "s": 2300, "text": "Explainability: understand how the model produces results." }, { "code": null, "e": 2414, "s": 2359, "text": "First of all, I need to import the following packages:" }, { "code": null, "e": 2706, "s": 2414, "text": "## for dataimport jsonimport pandas as pdimport numpy as npfrom sklearn import metrics, manifold## for processingimport reimport nltk## for plottingimport matplotlib.pyplot as pltimport seaborn as sns## for w2vimport gensimimport gensim.downloader as gensim_api## for bertimport transformers" }, { "code": null, "e": 2858, "s": 2706, "text": "The dataset is contained into a json file, so I will first read it into a list of dictionaries with json and then transform it into a pandas Dataframe." }, { "code": null, "e": 3035, "s": 2858, "text": "lst_dics = []with open('data.json', mode='r', errors='ignore') as json_file: for dic in json_file: lst_dics.append( json.loads(dic) )## print the first onelst_dics[0]" }, { "code": null, "e": 3191, "s": 3035, "text": "The original dataset contains over 30 categories, but for the purposes of this tutorial, I will work with a subset of 3: Entertainment, Politics, and Tech." }, { "code": null, "e": 3468, "s": 3191, "text": "## create dtfdtf = pd.DataFrame(lst_dics)## filter categoriesdtf = dtf[ dtf[\"category\"].isin(['ENTERTAINMENT','POLITICS','TECH']) ][[\"category\",\"headline\"]]## rename columnsdtf = dtf.rename(columns={\"category\":\"y\", \"headline\":\"text\"})## print 5 random rowsdtf.sample(5)" }, { "code": null, "e": 3599, "s": 3468, "text": "As you can see, the dataset includes a target variable as well. I won’t be using it for modeling, just for performance evaluation." }, { "code": null, "e": 3774, "s": 3599, "text": "So we’ve got some raw text data and we are tasked to classify it into the 3 categories (Entertainment, Politics, Tech) we know nothing about. Here’s what I am planning to do:" }, { "code": null, "e": 3821, "s": 3774, "text": "clean data and embed it into the vector space," }, { "code": null, "e": 3898, "s": 3821, "text": "create a topic cluster for each category and embed it into the vector space," }, { "code": null, "e": 4010, "s": 3898, "text": "calculate similarities between every text vector and the topic clusters, then assign it to the closest cluster." }, { "code": null, "e": 4139, "s": 4010, "text": "That is why I called it “a sort of unsupervised text classification”. It’s a really basic idea, but the execution can be tricky." }, { "code": null, "e": 4178, "s": 4139, "text": "Now that’s all set, let’s get started." }, { "code": null, "e": 4353, "s": 4178, "text": "The absolute first step is to preprocess the data: cleaning text, removing stop words, and applying lemmatization. I will write a function and apply it to the whole data set." }, { "code": null, "e": 5608, "s": 4353, "text": "'''Preprocess a string.:parameter :param text: string - name of column containing text :param lst_stopwords: list - list of stopwords to remove :param flg_stemm: bool - whether stemming is to be applied :param flg_lemm: bool - whether lemmitisation is to be applied:return cleaned text'''def utils_preprocess_text(text, flg_stemm=False, flg_lemm=True, lst_stopwords=None): ## clean (convert to lowercase and remove punctuations and characters and then strip) text = re.sub(r'[^\\w\\s]', '', str(text).lower().strip()) ## Tokenize (convert from string to list) lst_text = text.split() ## remove Stopwords if lst_stopwords is not None: lst_text = [word for word in lst_text if word not in lst_stopwords] ## Stemming (remove -ing, -ly, ...) if flg_stemm == True: ps = nltk.stem.porter.PorterStemmer() lst_text = [ps.stem(word) for word in lst_text] ## Lemmatisation (convert the word into root word) if flg_lemm == True: lem = nltk.stem.wordnet.WordNetLemmatizer() lst_text = [lem.lemmatize(word) for word in lst_text] ## back to string from list text = \" \".join(lst_text) return text" }, { "code": null, "e": 5805, "s": 5608, "text": "That function removes a set of words from the corpus if given. I can create a list of generic stop words for the English vocabulary with nltk (we could edit this list by adding or removing words)." }, { "code": null, "e": 5873, "s": 5805, "text": "lst_stopwords = nltk.corpus.stopwords.words(\"english\")lst_stopwords" }, { "code": null, "e": 6017, "s": 5873, "text": "Now I shall apply the function to the whole dataset and store the result in a new column named “text_clean” that I am going to use as a corpus." }, { "code": null, "e": 6182, "s": 6017, "text": "dtf[\"text_clean\"] = dtf[\"text\"].apply(lambda x: utils_preprocess_text(x, flg_stemm=False, flg_lemm=True, lst_stopwords=lst_stopwords))dtf.head()" }, { "code": null, "e": 6298, "s": 6182, "text": "We have our preprocessed corpus, consequently the next step is to build the target variable. Basically, we’re here:" }, { "code": null, "e": 6638, "s": 6298, "text": "The objective of this section is to create some keywords which can represent the context of each category. By performing some text analysis, you can easily discover that the 3 most frequent words are “movie”, “trump”, and “apple” (for a detailed text analysis tutorial you can check this article). I’d suggest starting with those keywords." }, { "code": null, "e": 7016, "s": 6638, "text": "Let’s take the Politics category for instance: the word “trump” can have different meanings, so we need to add keywords to avoid polysemy problems (i.e. “donald”, “republican”, “white house”, “obama”). This task could be carried out manually or you could use the assistance of a pre-trained NLP model. You can load a pre-trained Word Embedding model from genism-data like this:" }, { "code": null, "e": 7065, "s": 7016, "text": "nlp = gensim_api.load(\"glove-wiki-gigaword-300\")" }, { "code": null, "e": 7191, "s": 7065, "text": "The gensim package has a very convenient function that returns the most similar words for any given word into the vocabulary." }, { "code": null, "e": 7227, "s": 7191, "text": "nlp.most_similar([\"obama\"], topn=3)" }, { "code": null, "e": 7298, "s": 7227, "text": "I shall use that to create a dictionary of keywords for each category:" }, { "code": null, "e": 8059, "s": 7298, "text": "## Function to applydef get_similar_words(lst_words, top, nlp): lst_out = lst_words for tupla in nlp.most_similar(lst_words, topn=top): lst_out.append(tupla[0]) return list(set(lst_out))## Create Dictionary {category:[keywords]}dic_clusters = {}dic_clusters[\"ENTERTAINMENT\"] = get_similar_words(['celebrity','cinema','movie','music'], top=30, nlp=nlp)dic_clusters[\"POLITICS\"] = get_similar_words(['gop','clinton','president','obama','republican'] , top=30, nlp=nlp)dic_clusters[\"TECH\"] = get_similar_words(['amazon','android','app','apple','facebook', 'google','tech'], top=30, nlp=nlp)## print somefor k,v in dic_clusters.items(): print(k, \": \", v[0:5], \"...\", len(v))" }, { "code": null, "e": 8248, "s": 8059, "text": "Let’s try to visualize those keywords in a 2D space by applying a dimensionality reduction algorithm (i.e. TSNE). We want to make sure that the clusters are well separated from each other." }, { "code": null, "e": 9136, "s": 8248, "text": "## word embeddingtot_words = [word for v in dic_clusters.values() for word in v]X = nlp[tot_words] ## pcapca = manifold.TSNE(perplexity=40, n_components=2, init='pca')X = pca.fit_transform(X)## create dtfdtf = pd.DataFrame()for k,v in dic_clusters.items(): size = len(dtf) + len(v) dtf_group = pd.DataFrame(X[len(dtf):size], columns=[\"x\",\"y\"], index=v) dtf_group[\"cluster\"] = k dtf = dtf.append(dtf_group) ## plotfig, ax = plt.subplots()sns.scatterplot(data=dtf, x=\"x\", y=\"y\", hue=\"cluster\", ax=ax)ax.legend().texts[0].set_text(None)ax.set(xlabel=None, ylabel=None, xticks=[], xticklabels=[], yticks=[], yticklabels=[])for i in range(len(dtf)): ax.annotate(dtf.index[i], xy=(dtf[\"x\"].iloc[i],dtf[\"y\"].iloc[i]), xytext=(5,2), textcoords='offset points', ha='right', va='bottom')" }, { "code": null, "e": 9362, "s": 9136, "text": "Cool, they look isolated enough from each other. The Entertainment cluster is closer to the Tech one than the Politics one, which makes sense as words like “apple” and “youtube” can appear in both Tech and Entertainment news." }, { "code": null, "e": 9498, "s": 9362, "text": "It’s time to embed the corpus we preprocessed and the target clusters we created in the same vector space. Basically, we’re doing this:" }, { "code": null, "e": 10018, "s": 9498, "text": "Yes, I’m using BERT for this. It’s true that you could utilize any Word Embedding model (i.e. Word2Vec, Glove, ...), even the one that we already loaded to define keywords, so why bother to use such a heavy and complex language model? That’s because BERT doesn’t apply a fixed embedding, instead it looks at the entire sentence and then assigns an embedding to each word. Therefore, the vector BERT assigns to a word is a function of the entire sentence, so that a word can have different vectors based on the contexts." }, { "code": null, "e": 10153, "s": 10018, "text": "I’m going to load the original pre-trained version of BERT with the package transformers and give an example of the dynamic embedding:" }, { "code": null, "e": 10328, "s": 10153, "text": "tokenizer = transformers.BertTokenizer.from_pretrained('bert-base- uncased', do_lower_case=True)nlp = transformers.TFBertModel.from_pretrained('bert-base-uncased')" }, { "code": null, "e": 10443, "s": 10328, "text": "Let’s use the model to convert the string “river bank” into vectors and print the one assigned to the word “bank”:" }, { "code": null, "e": 10747, "s": 10443, "text": "txt = \"river bank\"## tokenizeidx = tokenizer.encode(txt)print(\"tokens:\", tokenizer.convert_ids_to_tokens(idx))print(\"ids :\", tokenizer.encode(txt))## word embeddingidx = np.array(idx)[None,:]embedding = nlp(idx)print(\"shape:\", embedding[0][0].shape)## vector of the second input wordembedding[0][0][2]" }, { "code": null, "e": 11107, "s": 10747, "text": "If you do the same for the string “financial bank”, you’ll see that the vector assigned to the word “bank” is different because of the context. Please note that the BERT tokenizer inserts special tokens at the beginning and end of sentences and its vector space has a dimension of 768 (to understand better how BERT processes text you can check this article)." }, { "code": null, "e": 11285, "s": 11107, "text": "Having said that, the plan is to use BERT Word Embedding to represent each text with an array (shape: number of tokens x 768) and then summarize each article into a mean vector." }, { "code": null, "e": 11387, "s": 11285, "text": "So the final feature matrix will be an array with shape: number of documents (or mean vectors) x 768." }, { "code": null, "e": 11805, "s": 11387, "text": "## function to applydef utils_bert_embedding(txt, tokenizer, nlp): idx = tokenizer.encode(txt) idx = np.array(idx)[None,:] embedding = nlp(idx) X = np.array(embedding[0][0][1:-1]) return X## create list of news vectorlst_mean_vecs = [utils_bert_embedding(txt, tokenizer, nlp).mean(0) for txt in dtf[\"text_clean\"]]## create the feature matrix (n news x 768)X = np.array(lst_mean_vecs)" }, { "code": null, "e": 12050, "s": 11805, "text": "We can do the same with the keywords in the target clusters. In fact, each label is identified by a list of words that help BERT to understand the context within the clusters. Hence, I’m going to create a dictionary label : cluster mean vector." }, { "code": null, "e": 12150, "s": 12050, "text": "dic_y = {k:utils_bert_embedding(v, tokenizer, nlp).mean(0) for k,v in dic_clusters.items()}" }, { "code": null, "e": 12301, "s": 12150, "text": "We started with just some text data and 3 strings (“Entertainment”, “Politics”, “Tech”) and now we have a feature matrix and a target variable... ish." }, { "code": null, "e": 12410, "s": 12301, "text": "Finally, it’s time to build a model that classifies the news based on the similarity to each target cluster." }, { "code": null, "e": 13023, "s": 12410, "text": "I am going to use Cosine Similarity, a measure of similarity based on the cosine of the angle between two non-zero vectors, which equals the inner product of the same vectors normalized to both have length 1. You can easily use the cosine similarity implementation of scikit-learn, which takes 2 arrays (or vectors) and returns an array of scores (or a single score). In this case, the output is going to be a matrix with shape: number of news x number of labels (3, Entertainment/Politics/Tech). To put it another way, each row will represent an article and contain one similarity score for each target cluster." }, { "code": null, "e": 13376, "s": 13023, "text": "In order to run the usual evaluation metrics (Accuracy, AUC, Precision, Recall, ...), we have to rescale the scores in each row so that they sum to 1 and decide a category to label the article with. I’m going to choose the one with the highest score, but it could be wise to set some minimum thresholds and leave out predictions with really low scores." }, { "code": null, "e": 14079, "s": 13376, "text": "#--- Model Algorithm ---### compute cosine similaritiessimilarities = np.array( [metrics.pairwise.cosine_similarity(X, y).T.tolist()[0] for y in dic_y.values()] ).T## adjust and rescalelabels = list(dic_y.keys())for i in range(len(similarities)): ### assign randomly if there is no similarity if sum(similarities[i]) == 0: similarities[i] = [0]*len(labels) similarities[i][np.random.choice(range(len(labels)))] = 1 ### rescale so they sum = 1 similarities[i] = similarities[i] / sum(similarities[i])## classify the label with highest similarity scorepredicted_prob = similaritiespredicted = [labels[np.argmax(pred)] for pred in predicted_prob]" }, { "code": null, "e": 14270, "s": 14079, "text": "Just like in classic supervised use cases, we have an object with predicted probabilities (here they’re adjusted similarity scores) and another with predicted labels. Let’s check how we did:" }, { "code": null, "e": 16203, "s": 14270, "text": "y_test = dtf[\"y\"].valuesclasses = np.unique(y_test)y_test_array = pd.get_dummies(y_test, drop_first=False).values## Accuracy, Precision, Recallaccuracy = metrics.accuracy_score(y_test, predicted)auc = metrics.roc_auc_score(y_test, predicted_prob, multi_class=\"ovr\")print(\"Accuracy:\", round(accuracy,2))print(\"Auc:\", round(auc,2))print(\"Detail:\")print(metrics.classification_report(y_test, predicted)) ## Plot confusion matrixcm = metrics.confusion_matrix(y_test, predicted)fig, ax = plt.subplots()sns.heatmap(cm, annot=True, fmt='d', ax=ax, cmap=plt.cm.Blues, cbar=False)ax.set(xlabel=\"Pred\", ylabel=\"True\", xticklabels=classes, yticklabels=classes, title=\"Confusion matrix\")plt.yticks(rotation=0)fig, ax = plt.subplots(nrows=1, ncols=2)## Plot rocfor i in range(len(classes)): fpr, tpr, thresholds = metrics.roc_curve(y_test_array[:,i], predicted_prob[:,i]) ax[0].plot(fpr, tpr, lw=3, label='{0} (area={1:0.2f})'.format(classes[i], metrics.auc(fpr, tpr)) )ax[0].plot([0,1], [0,1], color='navy', lw=3, linestyle='--')ax[0].set(xlim=[-0.05,1.0], ylim=[0.0,1.05], xlabel='False Positive Rate', ylabel=\"True Positive Rate (Recall)\", title=\"Receiver operating characteristic\")ax[0].legend(loc=\"lower right\")ax[0].grid(True) ## Plot precision-recall curvefor i in range(len(classes)): precision, recall, thresholds = metrics.precision_recall_curve( y_test_array[:,i], predicted_prob[:,i]) ax[1].plot(recall, precision, lw=3, label='{0} (area={1:0.2f})'.format(classes[i], metrics.auc(recall, precision)) )ax[1].set(xlim=[0.0,1.05], ylim=[0.0,1.05], xlabel='Recall', ylabel=\"Precision\", title=\"Precision-Recall curve\")ax[1].legend(loc=\"best\")ax[1].grid(True)plt.show()" }, { "code": null, "e": 16578, "s": 16203, "text": "Okay, I’m the first to say that it’s not the best Accuracy I’ve ever seen. On the other hand, it’s not bad at all considering that we didn’t train any model and we even made up the target variable. The main issue is over 4k Politics observations classified as Entertainment, but these performances can be easily improved by fine-tuning the keywords for those two categories." }, { "code": null, "e": 16730, "s": 16578, "text": "Let’s try to understand what led our algorithm to classify news with a category instead of the others. Let’s take a random observation from the corpus:" }, { "code": null, "e": 16906, "s": 16730, "text": "i = 7txt_instance = dtf[\"text_clean\"].iloc[i]print(\"True:\", y_test[i], \"--> Pred:\", predicted[i], \"| Similarity:\", round(np.max(predicted_prob[i]),2))print(txt_instance)" }, { "code": null, "e": 17145, "s": 16906, "text": "It’s a Politics observation properly classified. Probably, the words “republican” and “clinton” gave BERT the right hint. I will visualize the mean vector of the article in a 2D space and plot the top similarities with the target cluster." }, { "code": null, "e": 18957, "s": 17145, "text": "## create embedding Matrixy = np.concatenate([embedding_bert(v, tokenizer, nlp) for v in dic_clusters.values()])X = embedding_bert(txt_instance, tokenizer, nlp).mean(0).reshape(1,-1)M = np.concatenate([y,X])## pcapca = manifold.TSNE(perplexity=40, n_components=2, init='pca')M = pca.fit_transform(M)y, X = M[:len(y)], M[len(y):]## create dtf clustersdtf = pd.DataFrame()for k,v in dic_clusters.items(): size = len(dtf) + len(v) dtf_group = pd.DataFrame(y[len(dtf):size], columns=[\"x\",\"y\"], index=v) dtf_group[\"cluster\"] = k dtf = dtf.append(dtf_group)## plot clustersfig, ax = plt.subplots()sns.scatterplot(data=dtf, x=\"x\", y=\"y\", hue=\"cluster\", ax=ax)ax.legend().texts[0].set_text(None)ax.set(xlabel=None, ylabel=None, xticks=[], xticklabels=[], yticks=[], yticklabels=[])for i in range(len(dtf)): ax.annotate(dtf.index[i], xy=(dtf[\"x\"].iloc[i],dtf[\"y\"].iloc[i]), xytext=(5,2), textcoords='offset points', ha='right', va='bottom')## add txt_instanceax.scatter(x=X[0][0], y=X[0][1], c=\"red\", linewidth=10) ax.annotate(\"x\", xy=(X[0][0],X[0][1]), ha='center', va='center', fontsize=25)## calculate similaritysim_matrix = metrics.pairwise.cosine_similarity(X, y)## add top similarityfor row in range(sim_matrix.shape[0]): ### sorted {keyword:score} dic_sim = {n:sim_matrix[row][n] for n in range(sim_matrix.shape[1])} dic_sim = {k:v for k,v in sorted(dic_sim.items(), key=lambda item:item[1], reverse=True)} ### plot lines for k in dict(list(dic_sim.items())[0:5]).keys(): p1 = [X[row][0], X[row][1]] p2 = [y[k][0], y[k][1]] ax.plot([p1[0],p2[0]], [p1[1],p2[1]], c=\"red\", alpha=0.5)plt.show()" }, { "code": null, "e": 19002, "s": 18957, "text": "Let’s zoom a bit on the cluster of interest:" }, { "code": null, "e": 19171, "s": 19002, "text": "Overall, we can say the mean vector is pretty similar to the Politics cluster. Let’s break down the article into tokens to see which ones “activated” the right cluster." }, { "code": null, "e": 20884, "s": 19171, "text": "## create embedding Matrixy = np.concatenate([embedding_bert(v, tokenizer, nlp) for v in dic_clusters.values()])X = embedding_bert(txt_instance, tokenizer, nlp).mean(0).reshape(1,-1)M = np.concatenate([y,X])## pcapca = manifold.TSNE(perplexity=40, n_components=2, init='pca')M = pca.fit_transform(M)y, X = M[:len(y)], M[len(y):]## create dtf clustersdtf = pd.DataFrame()for k,v in dic_clusters.items(): size = len(dtf) + len(v) dtf_group = pd.DataFrame(y[len(dtf):size], columns=[\"x\",\"y\"], index=v) dtf_group[\"cluster\"] = k dtf = dtf.append(dtf_group)## add txt_instancetokens = tokenizer.convert_ids_to_tokens( tokenizer.encode(txt_instance))[1:-1]dtf = pd.DataFrame(X, columns=[\"x\",\"y\"], index=tokens)dtf = dtf[~dtf.index.str.contains(\"#\")]dtf = dtf[dtf.index.str.len() > 1]X = dtf.valuesax.scatter(x=dtf[\"x\"], y=dtf[\"y\"], c=\"red\")for i in range(len(dtf)): ax.annotate(dtf.index[i], xy=(dtf[\"x\"].iloc[i],dtf[\"y\"].iloc[i]), xytext=(5,2), textcoords='offset points', ha='right', va='bottom')## calculate similaritysim_matrix = metrics.pairwise.cosine_similarity(X, y)## add top similarityfor row in range(sim_matrix.shape[0]): ### sorted {keyword:score} dic_sim = {n:sim_matrix[row][n] for n in range(sim_matrix.shape[1])} dic_sim = {k:v for k,v in sorted(dic_sim.items(), key=lambda item:item[1], reverse=True)} ### plot lines for k in dict(list(dic_sim.items())[0:5]).keys(): p1 = [X[row][0], X[row][1]] p2 = [y[k][0], y[k][1]] ax.plot([p1[0],p2[0]], [p1[1],p2[1]], c=\"red\", alpha=0.5)plt.show()" }, { "code": null, "e": 21048, "s": 20884, "text": "As we thought, there are words in the text which are clearly linked to the Politics cluster, but some others are more similar to the Entertainment general context." }, { "code": null, "e": 21176, "s": 21048, "text": "This article has been a tutorial to demonstrate how to perform text classification when a labeled training set isn't available." }, { "code": null, "e": 21554, "s": 21176, "text": "I used a pre-trained Word Embedding model to build a set of keywords to contextualize the target variable. Then I transformed those words and the corpus in the same vector space with the pre-trained BERT language model. Finally, I calculated the Cosine Similarity between text and keywords to determine the context of each article and I used that information to label the news." }, { "code": null, "e": 21784, "s": 21554, "text": "This strategy isn’t the most effective but it’s definitely efficient as it allows you to deliver good results quickly. Moreover, this algorithm can be used as a baseline for a supervised model, once a labeled dataset is obtained." }, { "code": null, "e": 21902, "s": 21784, "text": "I hope you enjoyed it! Feel free to contact me for questions and feedback or just to share your interesting projects." }, { "code": null, "e": 21920, "s": 21902, "text": "👉 Let’s Connect 👈" } ]
Assembly - Macros
Writing a macro is another way of ensuring modular programming in assembly language. A macro is a sequence of instructions, assigned by a name and could be used anywhere in the program. A macro is a sequence of instructions, assigned by a name and could be used anywhere in the program. In NASM, macros are defined with %macro and %endmacro directives. In NASM, macros are defined with %macro and %endmacro directives. The macro begins with the %macro directive and ends with the %endmacro directive. The macro begins with the %macro directive and ends with the %endmacro directive. The Syntax for macro definition − %macro macro_name number_of_params <macro body> %endmacro Where, number_of_params specifies the number parameters, macro_name specifies the name of the macro. The macro is invoked by using the macro name along with the necessary parameters. When you need to use some sequence of instructions many times in a program, you can put those instructions in a macro and use it instead of writing the instructions all the time. For example, a very common need for programs is to write a string of characters in the screen. For displaying a string of characters, you need the following sequence of instructions − mov edx,len ;message length mov ecx,msg ;message to write mov ebx,1 ;file descriptor (stdout) mov eax,4 ;system call number (sys_write) int 0x80 ;call kernel In the above example of displaying a character string, the registers EAX, EBX, ECX and EDX have been used by the INT 80H function call. So, each time you need to display on screen, you need to save these registers on the stack, invoke INT 80H and then restore the original value of the registers from the stack. So, it could be useful to write two macros for saving and restoring data. We have observed that, some instructions like IMUL, IDIV, INT, etc., need some of the information to be stored in some particular registers and even return values in some specific register(s). If the program was already using those registers for keeping important data, then the existing data from these registers should be saved in the stack and restored after the instruction is executed. Following example shows defining and using macros − ; A macro with two parameters ; Implements the write system call %macro write_string 2 mov eax, 4 mov ebx, 1 mov ecx, %1 mov edx, %2 int 80h %endmacro section .text global _start ;must be declared for using gcc _start: ;tell linker entry point write_string msg1, len1 write_string msg2, len2 write_string msg3, len3 mov eax,1 ;system call number (sys_exit) int 0x80 ;call kernel section .data msg1 db 'Hello, programmers!',0xA,0xD len1 equ $ - msg1 msg2 db 'Welcome to the world of,', 0xA,0xD len2 equ $- msg2 msg3 db 'Linux assembly programming! ' len3 equ $- msg3 When the above code is compiled and executed, it produces the following result − Hello, programmers! Welcome to the world of, Linux assembly programming! 46 Lectures 2 hours Frahaan Hussain 23 Lectures 12 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2170, "s": 2085, "text": "Writing a macro is another way of ensuring modular programming in assembly language." }, { "code": null, "e": 2271, "s": 2170, "text": "A macro is a sequence of instructions, assigned by a name and could be used anywhere in the program." }, { "code": null, "e": 2372, "s": 2271, "text": "A macro is a sequence of instructions, assigned by a name and could be used anywhere in the program." }, { "code": null, "e": 2438, "s": 2372, "text": "In NASM, macros are defined with %macro and %endmacro directives." }, { "code": null, "e": 2504, "s": 2438, "text": "In NASM, macros are defined with %macro and %endmacro directives." }, { "code": null, "e": 2586, "s": 2504, "text": "The macro begins with the %macro directive and ends with the %endmacro directive." }, { "code": null, "e": 2668, "s": 2586, "text": "The macro begins with the %macro directive and ends with the %endmacro directive." }, { "code": null, "e": 2702, "s": 2668, "text": "The Syntax for macro definition −" }, { "code": null, "e": 2762, "s": 2702, "text": "%macro macro_name number_of_params\n<macro body>\n%endmacro\n" }, { "code": null, "e": 2863, "s": 2762, "text": "Where, number_of_params specifies the number parameters, macro_name specifies the name of the macro." }, { "code": null, "e": 3124, "s": 2863, "text": "The macro is invoked by using the macro name along with the necessary parameters. When you need to use some sequence of instructions many times in a program, you can put those instructions in a macro and use it instead of writing the instructions all the time." }, { "code": null, "e": 3308, "s": 3124, "text": "For example, a very common need for programs is to write a string of characters in the screen. For displaying a string of characters, you need the following sequence of instructions −" }, { "code": null, "e": 3493, "s": 3308, "text": "mov\tedx,len\t ;message length\nmov\tecx,msg\t ;message to write\nmov\tebx,1 ;file descriptor (stdout)\nmov\teax,4 ;system call number (sys_write)\nint\t0x80 ;call kernel" }, { "code": null, "e": 3879, "s": 3493, "text": "In the above example of displaying a character string, the registers EAX, EBX, ECX and EDX have been used by the INT 80H function call. So, each time you need to display on screen, you need to save these registers on the stack, invoke INT 80H and then restore the original value of the registers from the stack. So, it could be useful to write two macros for saving and restoring data." }, { "code": null, "e": 4270, "s": 3879, "text": "We have observed that, some instructions like IMUL, IDIV, INT, etc., need some of the information to be stored in some particular registers and even return values in some specific register(s). If the program was already using those registers for keeping important data, then the existing data from these registers should be saved in the stack and restored after the instruction is executed." }, { "code": null, "e": 4322, "s": 4270, "text": "Following example shows defining and using macros −" }, { "code": null, "e": 5052, "s": 4322, "text": "; A macro with two parameters\n; Implements the write system call\n %macro write_string 2 \n mov eax, 4\n mov ebx, 1\n mov ecx, %1\n mov edx, %2\n int 80h\n %endmacro\n \nsection\t.text\n global _start ;must be declared for using gcc\n\t\n_start: ;tell linker entry point\n write_string msg1, len1 \n write_string msg2, len2 \n write_string msg3, len3 \n\t\n mov eax,1 ;system call number (sys_exit)\n int 0x80 ;call kernel\n\nsection\t.data\nmsg1 db\t'Hello, programmers!',0xA,0xD \t\nlen1 equ $ - msg1\t\t\t\n\nmsg2 db 'Welcome to the world of,', 0xA,0xD \nlen2 equ $- msg2 \n\nmsg3 db 'Linux assembly programming! '\nlen3 equ $- msg3" }, { "code": null, "e": 5133, "s": 5052, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5207, "s": 5133, "text": "Hello, programmers!\nWelcome to the world of,\nLinux assembly programming!\n" }, { "code": null, "e": 5240, "s": 5207, "text": "\n 46 Lectures \n 2 hours \n" }, { "code": null, "e": 5257, "s": 5240, "text": " Frahaan Hussain" }, { "code": null, "e": 5291, "s": 5257, "text": "\n 23 Lectures \n 12 hours \n" }, { "code": null, "e": 5299, "s": 5291, "text": " Uplatz" }, { "code": null, "e": 5306, "s": 5299, "text": " Print" }, { "code": null, "e": 5317, "s": 5306, "text": " Add Notes" } ]
Batch Script - Recursive Functions
The ability to completely encapsulate the body of a function by keeping variable changes local to the function and invisible to the caller. We can now have the ability to call a function recursively making sure each level of recursion works with its own set of variables even though variable names are being reused. Following example shows how recursive functions can be used. The example shows how to calculate a Fibonacci number recursively. The recursion stops when the Fibonacci algorism reaches a number greater or equal to a given input number. The example starts with the numbers 0 and 1, the :myFibo function calls itself recursively to calculate the next Fibonacci number until it finds the Fibonacci number greater or equal to 1000000000. The first argument of the myFibo function is the name of the variable to store the output in. This variable must be initialized to the Fibonacci number to start with and will be used as current Fibonacci number when calling the function and will be set to the subsequent Fibonacci number when the function returns. @echo off set "fst = 0" set "fib = 1" set "limit = 1000000000" call:myFibo fib,%fst%,%limit% echo.The next Fibonacci number greater or equal %limit% is %fib%. echo.&pause&goto:eof :myFibo -- calculate recursively :myFibo -- calculate recursively the next Fibonacci number greater or equal to a limit SETLOCAL set /a "Number1 = %~1" set /a "Number2 = %~2" set /a "Limit = %~3" set /a "NumberN = Number1 + Number2" if /i %NumberN% LSS %Limit% call:myFibo NumberN,%Number1%,%Limit% (ENDLOCAL IF "%~1" NEQ "" SET "%~1 = %NumberN%" )goto:eof The above command produces the following output. The next Fibonacci number greater or equal 1000000000 is 1134903170. Print Add Notes Bookmark this page
[ { "code": null, "e": 2485, "s": 2169, "text": "The ability to completely encapsulate the body of a function by keeping variable changes local to the function and invisible to the caller. We can now have the ability to call a function recursively making sure each level of recursion works with its own set of variables even though variable names are being reused." }, { "code": null, "e": 2546, "s": 2485, "text": "Following example shows how recursive functions can be used." }, { "code": null, "e": 2918, "s": 2546, "text": "The example shows how to calculate a Fibonacci number recursively. The recursion stops when the Fibonacci algorism reaches a number greater or equal to a given input number. The example starts with the numbers 0 and 1, the :myFibo function calls itself recursively to calculate the next Fibonacci number until it finds the Fibonacci number greater or equal to 1000000000." }, { "code": null, "e": 3233, "s": 2918, "text": "The first argument of the myFibo function is the name of the variable to store the output in. This variable must be initialized to the Fibonacci number to start with and will be used as current Fibonacci number when calling the function and will be set to the subsequent Fibonacci number when the function returns." }, { "code": null, "e": 3774, "s": 3233, "text": "@echo off\nset \"fst = 0\"\nset \"fib = 1\"\nset \"limit = 1000000000\"\ncall:myFibo fib,%fst%,%limit%\necho.The next Fibonacci number greater or equal %limit% is %fib%.\necho.&pause&goto:eof\n:myFibo -- calculate recursively\n:myFibo -- calculate recursively the next Fibonacci number greater or equal to a limit\nSETLOCAL\nset /a \"Number1 = %~1\"\nset /a \"Number2 = %~2\"\nset /a \"Limit = %~3\"\nset /a \"NumberN = Number1 + Number2\"\n\nif /i %NumberN% LSS %Limit% call:myFibo NumberN,%Number1%,%Limit%\n(ENDLOCAL\n IF \"%~1\" NEQ \"\" SET \"%~1 = %NumberN%\"\n)goto:eof" }, { "code": null, "e": 3823, "s": 3774, "text": "The above command produces the following output." }, { "code": null, "e": 3893, "s": 3823, "text": "The next Fibonacci number greater or equal 1000000000 is 1134903170.\n" }, { "code": null, "e": 3900, "s": 3893, "text": " Print" }, { "code": null, "e": 3911, "s": 3900, "text": " Add Notes" } ]
Longest Bitonic subsequence | Practice | GeeksforGeeks
Given an array of positive integers. Find the maximum length of Bitonic subsequence. A subsequence of array is called Bitonic if it is first increasing, then decreasing. Example 1: Input: nums = [1, 2, 5, 3, 2] Output: 5 Explanation: The sequence {1, 2, 5} is increasing and the sequence {3, 2} is decreasing so merging both we will get length 5. Example 2: Input: nums = [1, 11, 2, 10, 4, 5, 2, 1] Output: 6 Explanation: The bitonic sequence {1, 2, 10, 4, 2, 1} has length 6. Your Task: You don't need to read or print anything. Your task is to complete the function LongestBitonicSequence() which takes the array nums[] as input parameter and returns the maximum length of bitonic subsequence. Expected Time Complexity: O(n2) Expected Space Complexity: O(n) Constraints: 1 ≤ length of array ≤ 200 1 ≤ arr[i] ≤ 1000000 0 aayushrawat2 weeks ago C++ Solution The idea here is to calculate the Longest Increasing Subsequence and Longest Decreasing Subsequence separately. After that, we will iterate through them and will get the maximum length by adding lis[i] and lds[i]; int LongestBitonicSequence(vector<int>nums) { // code here int len = nums.size(); vector<int> lis(len,1); vector<int> lds(len,1); for(int i=1;i<len;i++){ for(int j=0;j<i;j++){ if(nums[j]<nums[i] && lis[i]<=lis[j]){ lis[i] = lis[j]+1; } } } for(int i = len-2;i>=0;i--){ for(int j = len-1;j>i;j--){ if(nums[j]<nums[i] && lds[i]<=lds[j] ){ lds[i] = lds[j]+1; } } } //We are subtracting -1 here because the last number in LIS and LDS will be same, and we //do not want to count it twice. 5 in this case. int maxV = 0; for(int i=0;i<len;i++){ maxV = max(maxV , lis[i]+lds[i]-1); } return maxV; } 0 madhukartemba This comment was deleted. +2 madhukartemba2 weeks ago JAVA SOLUTION: class Solution { public int LongestBitonicSequence(int[] arr) { int n = arr.length; int dp_left[] = new int[n]; int dp_right[] = new int[n]; int ans = 1; for(int i=0; i<n; i++) { int max_len = 0; for(int j=0; j<i; j++) { if(arr[j]<arr[i]) { max_len = Math.max(dp_left[j], max_len); } } dp_left[i] = max_len + 1; ans = Math.max(ans, dp_left[i]); } for(int i=n-1; i>=0; i--) { int max_len = 0; for(int j=i+1; j<n; j++) { if(arr[j]<arr[i]) { max_len = Math.max(dp_right[j], max_len); } } dp_right[i] = max_len + 1; ans = Math.max(ans, dp_right[i]); } for(int i=0; i<n; i++) { for(int j=i+1; j<n; j++) { if(arr[j]<arr[i]) { ans = Math.max(dp_left[i]+dp_right[j], ans); } } } return ans; } } 0 vishalkumar13july3 weeks ago int LongestBitonicSequence(vector<int>nums){ // code here int n=nums.size(); // int i,j; int *lis=new int[n]; for( i=0;i<n;i++){ lis[i]=1; } for(i=1;i<n;i++){ for(j=0;j<i;j++){ if(nums[j]<nums[i] && lis[i]<lis[j]+1) lis[i]=lis[j]+1; } } int *lds=new int[n]; for(i=0;i<n;i++){ lds[i]=1; } for(i=n-2;i>=0;i--){ for(j=n-1;j>i;j--){ if(nums[j]<nums[i] && lds[i]<lds[j]+1) lds[i]=lds[j]+1; } } int max=lis[0]+lds[0]-1; for(i=1;i<n;i++){ if(lis[i]+lds[i]-1 > max) max=lis[i]+lds[i]-1; } delete [] lis; delete [] lds; return max;} 0 himanshukug19cs3 months ago java solution // Code here int n=nums.length; int ans=Integer.MIN_VALUE; int[] ic = new int[n]; int[] dc = new int[n]; ic[0]=1; dc[n-1]=1; for(int i=1;i<n;i++){ ic[i]=1; for(int j=0;j<i;j++){ if(nums[i]>nums[j]) ic[i]=Math.max(ic[i],1+ic[j]); } } for(int i=n-2;i>=0;i--){ dc[i]=1; for(int j=n-1;j>i;j--){ if(nums[j]<nums[i]) dc[i]=Math.max(dc[i],dc[j]+1); } } for(int i=0;i<n;i++){ ans=Math.max(ans,ic[i]+dc[i]-1); } return ans; } 0 baibhavrajputt3 months ago Java DP solution class Solution { public int LongestBitonicSequence(int[] nums) { // Code here int n = nums.length; int lis[] = new int[n]; int lds[] = new int[n]; lis[0] = 1; lds[n-1] = 1; for(int i=1 ; i<n ; i++){ lis[i] = 1; for(int j=0 ; j<i ; j++){ if(nums[i] > nums[j]) lis[i] = Math.max(lis[i] , lis[j] + 1); } } for(int i=n-2 ; i>=0 ; i--){ lds[i] = 1; for(int j=n-1 ; j>i ; j--){ if(nums[i] > nums[j]) lds[i] = Math.max(lds[i] , lds[j] + 1); } } int lbs =0; for(int i=0 ; i<n ; i++){ lbs = Math.max(lbs , lis[i]+lds[i]-1); } return lbs; } } 0 aaishuagarwal3 months ago int LongestBitonicSequence(vector<int>nums){ // code here int n=nums.size(); int lis[n],lds[n]; lis[0]=1; for(int i=1;i<n;i++) { lis[i]=1; for(int j=0;j<i;j++) { if(nums[j]<nums[i]) { lis[i]=max(lis[i],lis[j]+1); } } } lds[n-1]=1; for(int i=n-2;i>=0;i--) { lds[i]=1; for(int j=n-1;j>i;j--) { if(nums[j]<nums[i]) { lds[i]=max(lds[i],lds[j]+1); } } } for(int i=0;i<n;i++) lis[i]+=lds[i]; int m=INT_MIN; for(int i=0;i<n;i++) { m=max(m,lis[i]); } return m-1;} 0 amishasahu3283 months ago class Solution{ public: int LongestBitonicSequence(vector<int>nums) { // code here int n = nums.size(); int lis[n], lds[n]; lis[0] = 1; lds[n-1] = 1; for(int i = 1; i < n; i++) { lis[i] = 1; for(int j = 0; j < i; j++) { if(nums[j] < nums[i]) lis[i] = max(lis[i], lis[j]+1); } } for(int i = n-2; i >= 0; i--) { lds[i] = 1; for(int j = n-1; j > i; j--) { if(nums[j] < nums[i]) lds[i] = max(lds[i], lds[j]+1); } } int ans = 0; for(int i = 0; i < n; i++) { ans = max(ans, lis[i]+lds[i]-1); } return ans; } }; 0 taiphanvan24034 months ago int Binotic_subsequence(int a[], int n){int* ListIncre = new int[n];int* ListDecre = new int[n];ListIncre[0] = 1;for (int i = 1; i < n; i++){ ListIncre[i] = 1; for (int j = 0; j < i; j++) { if (a[j]<a[i] && ListIncre[j] + 1>ListIncre[i]) ListIncre[i] = ListIncre[j] + 1; }}ListDecre[n - 1] = 1;for (int i = n - 2; i >= 0; i--){ ListDecre[i] = 1; for (int j = n - 1; j > i; j--) { if (a[j]<a[i] && ListDecre[j]+1>ListDecre[i]) ListDecre[i] = ListDecre[j] + 1; }}int Max = ListIncre[0] + ListDecre[0];for (int i = 1; i < n; i++) Max = max(Max, ListIncre[i] + ListDecre[i]);return Max - 1;}int main(){int a[] = { 12, 11, 40, 5, 3, 1 };int n = sizeof(a) / 4;cout<<Binotic_subsequence(a, n);} 0 sparshrastogi14 months ago #Python code def LongestBitonicSequence(self, nums): # Code here l = len(nums) f = [1]*l b = [1]*l for i in range(l-1): for j in range(i+1,l): if nums[i]<nums[j]: f[j] = max(f[j], f[i]+1) if nums[l-i-1]<nums[l-j-1]: b[l-j-1] = max(b[l-i-1]+1, b[l-j-1]) res = 0 for i in range(l): res = max(res, f[i]+b[i]-1) return res 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": 411, "s": 238, "text": "Given an array of positive integers. Find the maximum length of Bitonic subsequence. \nA subsequence of array is called Bitonic if it is first increasing, then decreasing.\n " }, { "code": null, "e": 422, "s": 411, "text": "Example 1:" }, { "code": null, "e": 591, "s": 422, "text": "Input: nums = [1, 2, 5, 3, 2]\nOutput: 5\nExplanation: The sequence {1, 2, 5} is\nincreasing and the sequence {3, 2} is \ndecreasing so merging both we will get \nlength 5.\n" }, { "code": null, "e": 602, "s": 591, "text": "Example 2:" }, { "code": null, "e": 723, "s": 602, "text": "Input: nums = [1, 11, 2, 10, 4, 5, 2, 1]\nOutput: 6\nExplanation: The bitonic sequence \n{1, 2, 10, 4, 2, 1} has length 6.\n" }, { "code": null, "e": 946, "s": 725, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function LongestBitonicSequence() which takes the array nums[] as input parameter and returns the maximum length of bitonic subsequence.\n " }, { "code": null, "e": 1012, "s": 946, "text": "Expected Time Complexity: O(n2)\nExpected Space Complexity: O(n)\n " }, { "code": null, "e": 1072, "s": 1012, "text": "Constraints:\n1 ≤ length of array ≤ 200\n1 ≤ arr[i] ≤ 1000000" }, { "code": null, "e": 1074, "s": 1072, "text": "0" }, { "code": null, "e": 1097, "s": 1074, "text": "aayushrawat2 weeks ago" }, { "code": null, "e": 1111, "s": 1097, "text": "C++ Solution " }, { "code": null, "e": 1325, "s": 1111, "text": "The idea here is to calculate the Longest Increasing Subsequence and Longest Decreasing Subsequence separately. After that, we will iterate through them and will get the maximum length by adding lis[i] and lds[i];" }, { "code": null, "e": 2054, "s": 1327, "text": "\tint LongestBitonicSequence(vector<int>nums)\n\t{\n\t // code here\n int len = nums.size();\n vector<int> lis(len,1);\n vector<int> lds(len,1);\n for(int i=1;i<len;i++){\n for(int j=0;j<i;j++){\n if(nums[j]<nums[i] && lis[i]<=lis[j]){\n lis[i] = lis[j]+1;\n }\n }\n }\n for(int i = len-2;i>=0;i--){\n for(int j = len-1;j>i;j--){\n if(nums[j]<nums[i] && lds[i]<=lds[j] ){\n lds[i] = lds[j]+1;\n }\n }\n }\n //We are subtracting -1 here because the last number in LIS and LDS will be same, and we\n //do not want to count it twice. 5 in this case.\n int maxV = 0;\n for(int i=0;i<len;i++){\n maxV = max(maxV , lis[i]+lds[i]-1);\n }\n return maxV;\n\n\t}" }, { "code": null, "e": 2056, "s": 2054, "text": "0" }, { "code": null, "e": 2070, "s": 2056, "text": "madhukartemba" }, { "code": null, "e": 2096, "s": 2070, "text": "This comment was deleted." }, { "code": null, "e": 2099, "s": 2096, "text": "+2" }, { "code": null, "e": 2124, "s": 2099, "text": "madhukartemba2 weeks ago" }, { "code": null, "e": 2139, "s": 2124, "text": "JAVA SOLUTION:" }, { "code": null, "e": 3467, "s": 2139, "text": "class Solution\n{\n public int LongestBitonicSequence(int[] arr)\n {\n int n = arr.length;\n int dp_left[] = new int[n];\n int dp_right[] = new int[n];\n \n int ans = 1;\n \n for(int i=0; i<n; i++)\n {\n int max_len = 0;\n for(int j=0; j<i; j++)\n {\n if(arr[j]<arr[i])\n {\n max_len = Math.max(dp_left[j], max_len);\n }\n }\n \n dp_left[i] = max_len + 1;\n ans = Math.max(ans, dp_left[i]);\n }\n \n \n for(int i=n-1; i>=0; i--)\n {\n int max_len = 0;\n \n for(int j=i+1; j<n; j++)\n {\n if(arr[j]<arr[i])\n {\n max_len = Math.max(dp_right[j], max_len);\n }\n }\n \n dp_right[i] = max_len + 1;\n ans = Math.max(ans, dp_right[i]);\n \n }\n \n \n for(int i=0; i<n; i++)\n {\n for(int j=i+1; j<n; j++)\n {\n if(arr[j]<arr[i])\n {\n ans = Math.max(dp_left[i]+dp_right[j], ans);\n }\n }\n }\n \n \n return ans;\n \n }\n}" }, { "code": null, "e": 3469, "s": 3467, "text": "0" }, { "code": null, "e": 3498, "s": 3469, "text": "vishalkumar13july3 weeks ago" }, { "code": null, "e": 4193, "s": 3498, "text": "int LongestBitonicSequence(vector<int>nums){ // code here int n=nums.size(); // int i,j; int *lis=new int[n]; for( i=0;i<n;i++){ lis[i]=1; } for(i=1;i<n;i++){ for(j=0;j<i;j++){ if(nums[j]<nums[i] && lis[i]<lis[j]+1) lis[i]=lis[j]+1; } } int *lds=new int[n]; for(i=0;i<n;i++){ lds[i]=1; } for(i=n-2;i>=0;i--){ for(j=n-1;j>i;j--){ if(nums[j]<nums[i] && lds[i]<lds[j]+1) lds[i]=lds[j]+1; } } int max=lis[0]+lds[0]-1; for(i=1;i<n;i++){ if(lis[i]+lds[i]-1 > max) max=lis[i]+lds[i]-1; } delete [] lis; delete [] lds; return max;}" }, { "code": null, "e": 4195, "s": 4193, "text": "0" }, { "code": null, "e": 4223, "s": 4195, "text": "himanshukug19cs3 months ago" }, { "code": null, "e": 4237, "s": 4223, "text": "java solution" }, { "code": null, "e": 4875, "s": 4237, "text": " // Code here int n=nums.length; int ans=Integer.MIN_VALUE; int[] ic = new int[n]; int[] dc = new int[n]; ic[0]=1; dc[n-1]=1; for(int i=1;i<n;i++){ ic[i]=1; for(int j=0;j<i;j++){ if(nums[i]>nums[j]) ic[i]=Math.max(ic[i],1+ic[j]); } } for(int i=n-2;i>=0;i--){ dc[i]=1; for(int j=n-1;j>i;j--){ if(nums[j]<nums[i]) dc[i]=Math.max(dc[i],dc[j]+1); } } for(int i=0;i<n;i++){ ans=Math.max(ans,ic[i]+dc[i]-1); } return ans; }" }, { "code": null, "e": 4877, "s": 4875, "text": "0" }, { "code": null, "e": 4904, "s": 4877, "text": "baibhavrajputt3 months ago" }, { "code": null, "e": 4921, "s": 4904, "text": "Java DP solution" }, { "code": null, "e": 5818, "s": 4921, "text": "class Solution\n{\n public int LongestBitonicSequence(int[] nums)\n {\n // Code here\n int n = nums.length;\n \n int lis[] = new int[n];\n int lds[] = new int[n];\n \n lis[0] = 1;\n lds[n-1] = 1;\n \n for(int i=1 ; i<n ; i++){\n lis[i] = 1;\n for(int j=0 ; j<i ; j++){\n \n if(nums[i] > nums[j])\n lis[i] = Math.max(lis[i] , lis[j] + 1);\n }\n }\n \n \n for(int i=n-2 ; i>=0 ; i--){\n lds[i] = 1;\n for(int j=n-1 ; j>i ; j--){\n \n if(nums[i] > nums[j])\n lds[i] = Math.max(lds[i] , lds[j] + 1);\n }\n }\n \n int lbs =0;\n for(int i=0 ; i<n ; i++){\n lbs = Math.max(lbs , lis[i]+lds[i]-1);\n }\n return lbs;\n }\n}" }, { "code": null, "e": 5820, "s": 5818, "text": "0" }, { "code": null, "e": 5846, "s": 5820, "text": "aaishuagarwal3 months ago" }, { "code": null, "e": 6508, "s": 5846, "text": " int LongestBitonicSequence(vector<int>nums){ // code here int n=nums.size(); int lis[n],lds[n]; lis[0]=1; for(int i=1;i<n;i++) { lis[i]=1; for(int j=0;j<i;j++) { if(nums[j]<nums[i]) { lis[i]=max(lis[i],lis[j]+1); } } } lds[n-1]=1; for(int i=n-2;i>=0;i--) { lds[i]=1; for(int j=n-1;j>i;j--) { if(nums[j]<nums[i]) { lds[i]=max(lds[i],lds[j]+1); } } } for(int i=0;i<n;i++) lis[i]+=lds[i]; int m=INT_MIN; for(int i=0;i<n;i++) { m=max(m,lis[i]); } return m-1;}" }, { "code": null, "e": 6510, "s": 6508, "text": "0" }, { "code": null, "e": 6536, "s": 6510, "text": "amishasahu3283 months ago" }, { "code": null, "e": 7295, "s": 6536, "text": "class Solution{\n\tpublic:\n\t\n\tint LongestBitonicSequence(vector<int>nums)\n\t{\n\t // code here\n\t int n = nums.size();\n\t int lis[n], lds[n];\n\t \n\t lis[0] = 1;\n\t lds[n-1] = 1;\n\t \n\t for(int i = 1; i < n; i++)\n\t {\n\t lis[i] = 1;\n\t for(int j = 0; j < i; j++)\n\t {\n\t if(nums[j] < nums[i])\n\t lis[i] = max(lis[i], lis[j]+1);\n\t }\n\t }\n\t for(int i = n-2; i >= 0; i--)\n\t {\n\t lds[i] = 1;\n\t for(int j = n-1; j > i; j--)\n\t {\n\t if(nums[j] < nums[i])\n\t lds[i] = max(lds[i], lds[j]+1);\n\t }\n\t }\n\t \n\t int ans = 0;\n\t for(int i = 0; i < n; i++)\n\t {\n\t ans = max(ans, lis[i]+lds[i]-1);\n\t }\n\t \n\t return ans;\n\t}\n};" }, { "code": null, "e": 7297, "s": 7295, "text": "0" }, { "code": null, "e": 7324, "s": 7297, "text": "taiphanvan24034 months ago" }, { "code": null, "e": 8014, "s": 7324, "text": "int Binotic_subsequence(int a[], int n){int* ListIncre = new int[n];int* ListDecre = new int[n];ListIncre[0] = 1;for (int i = 1; i < n; i++){ ListIncre[i] = 1; for (int j = 0; j < i; j++) { if (a[j]<a[i] && ListIncre[j] + 1>ListIncre[i]) ListIncre[i] = ListIncre[j] + 1; }}ListDecre[n - 1] = 1;for (int i = n - 2; i >= 0; i--){ ListDecre[i] = 1; for (int j = n - 1; j > i; j--) { if (a[j]<a[i] && ListDecre[j]+1>ListDecre[i]) ListDecre[i] = ListDecre[j] + 1; }}int Max = ListIncre[0] + ListDecre[0];for (int i = 1; i < n; i++) Max = max(Max, ListIncre[i] + ListDecre[i]);return Max - 1;}int main(){int a[] = { 12, 11, 40, 5, 3, 1 };int n = sizeof(a) / 4;cout<<Binotic_subsequence(a, n);}" }, { "code": null, "e": 8016, "s": 8014, "text": "0" }, { "code": null, "e": 8043, "s": 8016, "text": "sparshrastogi14 months ago" }, { "code": null, "e": 8056, "s": 8043, "text": "#Python code" }, { "code": null, "e": 8410, "s": 8056, "text": "def LongestBitonicSequence(self, nums): # Code here l = len(nums) f = [1]*l b = [1]*l for i in range(l-1): for j in range(i+1,l): if nums[i]<nums[j]: f[j] = max(f[j], f[i]+1) if nums[l-i-1]<nums[l-j-1]: b[l-j-1] = max(b[l-i-1]+1, b[l-j-1]) res = 0 for i in range(l): res = max(res, f[i]+b[i]-1) return res" }, { "code": null, "e": 8556, "s": 8410, "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": 8592, "s": 8556, "text": " Login to access your submissions. " }, { "code": null, "e": 8602, "s": 8592, "text": "\nProblem\n" }, { "code": null, "e": 8612, "s": 8602, "text": "\nContest\n" }, { "code": null, "e": 8675, "s": 8612, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8823, "s": 8675, "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": 9031, "s": 8823, "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": 9137, "s": 9031, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Monitoring Python Applications with Elastic APM | by Jimit Dholakia | Towards Data Science
Elastic APM is an application performance monitoring system built on the Elastic Stack. It allows you to monitor software services and applications in real-time, by collecting detailed performance information on response time for incoming requests, database queries, calls to caches, external HTTP requests, and more. This makes it easy to pinpoint and fix performance problems quickly. Elastic APM also automatically collects unhandled errors and exceptions. Errors are grouped based primarily on the stacktrace, so you can identify new errors as they appear and keep an eye on how many times specific errors happen. -Elastic This article consists of three parts: Monitoring Flask / Flask-RESTPlus ApplicationsMonitoring FastAPI ApplicationsMonitoring Python Applications Monitoring Flask / Flask-RESTPlus Applications Monitoring FastAPI Applications Monitoring Python Applications Elastic APM has built-in support for Flask. Since Flask RESTPlus and Flask-RESTful are extensions for Flask, the same steps apply for Flask-RESTPlus as well as Flask-RESTful. Install Elastic APM agent using pip: pip install elastic-apm[flask] Let’s first import the required packages: from flask import Flaskfrom elasticapm.contrib.flask import ElasticAPMimport elasticapm Now, let's create an instance of Flask, which will be our WSGI application. app = Flask(__name__) We can initialize the APM agent by using either environment variables or in our application code itself. In this article, we will initialize the APM agent in our code itself. To create an instance of Elastic APM agent, we need the following parameters: server_url → The URL of the Elastic APM service_name → Name of the application environment → The environment in which the application is running e.g. dev, qa or prod server_url = 'http://localhost:8200'service_name = 'DemoFlask'environment = 'dev' Next, we will initialize the APM Agent. We need to pass the Flask instance app as the first argument for initializing the APM agent, along with the parameters that we defined above. apm = ElasticAPM(app, server_url=server_url, service_name=service_name, environment=environment) Our APM agent is now ready. Now, let’s open Kibana (e.g. http://localhost:5601/) to see the logged data. Open the Kibana dashboard and go to the APM tab. You can see our service DemoFlask listed there. Click on the service name and go to Metrics, where you can track the CPU and Memory Usage. In the transactions tab, you can see the visualization related to each request your application receives, such as Transaction duration and Requests per minute. You can also view the list of all the endpoints along with their average duration. Click on a transaction to see more details for the transaction. You can also add additional information about the transaction by using labels. elasticapm.label(platform='DemoPlatform') To add default labels to all transactions, we can use Flask’s app.before_request decorator. @app.before_requestdef apm_log(): elasticapm.label(platform = 'DemoPlatform', application = 'DemoApplication') The information of the labels will be visible in the metadata tab in the trace sample of the transaction. Note that, by default, the transaction and error data will be recorded only when the application is not in debug mode. Sample code can be found from the link mentioned in the Resources section. To monitor FastAPI/Starlette Applications properly using Elastic APM, you need to use Python 3.7+ Install the Elastic APM agent using pip: pip install elastic-apm First, let’s import the required packages: import uvicornfrom fastapi import FastAPIfrom elasticapm.contrib.starlette import make_apm_client, ElasticAPM Next, we will create an APM client using the SERVICE_NAME , SERVER_URL and ENVIRONMENT. Also, we will specify the global labels at the same time using GLOBAL_LABELS. apm_config = { 'SERVICE_NAME': 'DemoFastAPI', 'SERVER_URL': 'http://localhost:8200', 'ENVIRONMENT': 'dev', 'GLOBAL_LABELS': 'platform=DemoPlatform, application=DemoApplication'}apm = make_apm_client(apm_config) Now, let’s initialize the Elastic APM agent. app = FastAPI()app.add_middleware(ElasticAPM, client=apm) The FastAPI application is now ready to send the logs to Elastic Server. Sample code can be found from the link mentioned in the Resources section. We can create an Elastic APM Client to monitor Python applications that do not use a framework (e.g. Flask, Django or FastAPI). An example of these applications could be schedulable code. Install Elastic APM agent using pip: pip install elastic-apm First, we will create an Elastic APM Client from elasticapm import Clientimport elasticapmclient = Client( {'SERVICE_NAME': 'DemoPython', 'SERVER_URL': 'http://localhost:8200', 'ENVIRONMENT': 'dev'}) For frameworks like Flask and FastAPI, Elastic APM automatically instruments the application and also begins and ends the transactions. However, for Python applications that do not use such frameworks, we need to manually instrument the application and also begin and end the transactions. To automatically instrument your application to capture HTTP requests, database queries, etc., add the following line elasticapm.instrumentation.control.instrument() To begin a transaction, use begin_transaction method with the appropriate transaction type as the parameter. For example, client.begin_transaction('schedule') To complete a transaction, use the end_transaction method which takes two arguments viz. transaction name and result. For example, client.end_transaction('demo-transaction', 'success') Sample code for monitoring Python application can be found from the link mentioned in the Resources section. All the code snippets of this article are available on my GitHub page. https://www.elastic.co/guide/en/apm/agent/python/current/configuration.html https://www.elastic.co/guide/en/apm/agent/python/current/flask-support.html https://www.elastic.co/guide/en/apm/get-started/7.4/metadata.html https://www.elastic.co/guide/en/apm/agent/python/current/starlette-support.html LinkedIn: https://www.linkedin.com/in/jimit105/GitHub: https://github.com/jimit105Twitter: https://twitter.com/jimit105
[ { "code": null, "e": 558, "s": 171, "text": "Elastic APM is an application performance monitoring system built on the Elastic Stack. It allows you to monitor software services and applications in real-time, by collecting detailed performance information on response time for incoming requests, database queries, calls to caches, external HTTP requests, and more. This makes it easy to pinpoint and fix performance problems quickly." }, { "code": null, "e": 789, "s": 558, "text": "Elastic APM also automatically collects unhandled errors and exceptions. Errors are grouped based primarily on the stacktrace, so you can identify new errors as they appear and keep an eye on how many times specific errors happen." }, { "code": null, "e": 798, "s": 789, "text": "-Elastic" }, { "code": null, "e": 836, "s": 798, "text": "This article consists of three parts:" }, { "code": null, "e": 944, "s": 836, "text": "Monitoring Flask / Flask-RESTPlus ApplicationsMonitoring FastAPI ApplicationsMonitoring Python Applications" }, { "code": null, "e": 991, "s": 944, "text": "Monitoring Flask / Flask-RESTPlus Applications" }, { "code": null, "e": 1023, "s": 991, "text": "Monitoring FastAPI Applications" }, { "code": null, "e": 1054, "s": 1023, "text": "Monitoring Python Applications" }, { "code": null, "e": 1229, "s": 1054, "text": "Elastic APM has built-in support for Flask. Since Flask RESTPlus and Flask-RESTful are extensions for Flask, the same steps apply for Flask-RESTPlus as well as Flask-RESTful." }, { "code": null, "e": 1266, "s": 1229, "text": "Install Elastic APM agent using pip:" }, { "code": null, "e": 1297, "s": 1266, "text": "pip install elastic-apm[flask]" }, { "code": null, "e": 1339, "s": 1297, "text": "Let’s first import the required packages:" }, { "code": null, "e": 1427, "s": 1339, "text": "from flask import Flaskfrom elasticapm.contrib.flask import ElasticAPMimport elasticapm" }, { "code": null, "e": 1503, "s": 1427, "text": "Now, let's create an instance of Flask, which will be our WSGI application." }, { "code": null, "e": 1525, "s": 1503, "text": "app = Flask(__name__)" }, { "code": null, "e": 1700, "s": 1525, "text": "We can initialize the APM agent by using either environment variables or in our application code itself. In this article, we will initialize the APM agent in our code itself." }, { "code": null, "e": 1778, "s": 1700, "text": "To create an instance of Elastic APM agent, we need the following parameters:" }, { "code": null, "e": 1818, "s": 1778, "text": "server_url → The URL of the Elastic APM" }, { "code": null, "e": 1857, "s": 1818, "text": "service_name → Name of the application" }, { "code": null, "e": 1944, "s": 1857, "text": "environment → The environment in which the application is running e.g. dev, qa or prod" }, { "code": null, "e": 2026, "s": 1944, "text": "server_url = 'http://localhost:8200'service_name = 'DemoFlask'environment = 'dev'" }, { "code": null, "e": 2208, "s": 2026, "text": "Next, we will initialize the APM Agent. We need to pass the Flask instance app as the first argument for initializing the APM agent, along with the parameters that we defined above." }, { "code": null, "e": 2305, "s": 2208, "text": "apm = ElasticAPM(app, server_url=server_url, service_name=service_name, environment=environment)" }, { "code": null, "e": 2333, "s": 2305, "text": "Our APM agent is now ready." }, { "code": null, "e": 2410, "s": 2333, "text": "Now, let’s open Kibana (e.g. http://localhost:5601/) to see the logged data." }, { "code": null, "e": 2507, "s": 2410, "text": "Open the Kibana dashboard and go to the APM tab. You can see our service DemoFlask listed there." }, { "code": null, "e": 2598, "s": 2507, "text": "Click on the service name and go to Metrics, where you can track the CPU and Memory Usage." }, { "code": null, "e": 2758, "s": 2598, "text": "In the transactions tab, you can see the visualization related to each request your application receives, such as Transaction duration and Requests per minute." }, { "code": null, "e": 2841, "s": 2758, "text": "You can also view the list of all the endpoints along with their average duration." }, { "code": null, "e": 2905, "s": 2841, "text": "Click on a transaction to see more details for the transaction." }, { "code": null, "e": 2984, "s": 2905, "text": "You can also add additional information about the transaction by using labels." }, { "code": null, "e": 3026, "s": 2984, "text": "elasticapm.label(platform='DemoPlatform')" }, { "code": null, "e": 3118, "s": 3026, "text": "To add default labels to all transactions, we can use Flask’s app.before_request decorator." }, { "code": null, "e": 3273, "s": 3118, "text": "@app.before_requestdef apm_log(): elasticapm.label(platform = 'DemoPlatform', application = 'DemoApplication')" }, { "code": null, "e": 3379, "s": 3273, "text": "The information of the labels will be visible in the metadata tab in the trace sample of the transaction." }, { "code": null, "e": 3498, "s": 3379, "text": "Note that, by default, the transaction and error data will be recorded only when the application is not in debug mode." }, { "code": null, "e": 3573, "s": 3498, "text": "Sample code can be found from the link mentioned in the Resources section." }, { "code": null, "e": 3671, "s": 3573, "text": "To monitor FastAPI/Starlette Applications properly using Elastic APM, you need to use Python 3.7+" }, { "code": null, "e": 3712, "s": 3671, "text": "Install the Elastic APM agent using pip:" }, { "code": null, "e": 3736, "s": 3712, "text": "pip install elastic-apm" }, { "code": null, "e": 3779, "s": 3736, "text": "First, let’s import the required packages:" }, { "code": null, "e": 3889, "s": 3779, "text": "import uvicornfrom fastapi import FastAPIfrom elasticapm.contrib.starlette import make_apm_client, ElasticAPM" }, { "code": null, "e": 4055, "s": 3889, "text": "Next, we will create an APM client using the SERVICE_NAME , SERVER_URL and ENVIRONMENT. Also, we will specify the global labels at the same time using GLOBAL_LABELS." }, { "code": null, "e": 4266, "s": 4055, "text": "apm_config = { 'SERVICE_NAME': 'DemoFastAPI', 'SERVER_URL': 'http://localhost:8200', 'ENVIRONMENT': 'dev', 'GLOBAL_LABELS': 'platform=DemoPlatform, application=DemoApplication'}apm = make_apm_client(apm_config)" }, { "code": null, "e": 4311, "s": 4266, "text": "Now, let’s initialize the Elastic APM agent." }, { "code": null, "e": 4369, "s": 4311, "text": "app = FastAPI()app.add_middleware(ElasticAPM, client=apm)" }, { "code": null, "e": 4442, "s": 4369, "text": "The FastAPI application is now ready to send the logs to Elastic Server." }, { "code": null, "e": 4517, "s": 4442, "text": "Sample code can be found from the link mentioned in the Resources section." }, { "code": null, "e": 4705, "s": 4517, "text": "We can create an Elastic APM Client to monitor Python applications that do not use a framework (e.g. Flask, Django or FastAPI). An example of these applications could be schedulable code." }, { "code": null, "e": 4742, "s": 4705, "text": "Install Elastic APM agent using pip:" }, { "code": null, "e": 4766, "s": 4742, "text": "pip install elastic-apm" }, { "code": null, "e": 4810, "s": 4766, "text": "First, we will create an Elastic APM Client" }, { "code": null, "e": 4977, "s": 4810, "text": "from elasticapm import Clientimport elasticapmclient = Client( {'SERVICE_NAME': 'DemoPython', 'SERVER_URL': 'http://localhost:8200', 'ENVIRONMENT': 'dev'})" }, { "code": null, "e": 5113, "s": 4977, "text": "For frameworks like Flask and FastAPI, Elastic APM automatically instruments the application and also begins and ends the transactions." }, { "code": null, "e": 5267, "s": 5113, "text": "However, for Python applications that do not use such frameworks, we need to manually instrument the application and also begin and end the transactions." }, { "code": null, "e": 5385, "s": 5267, "text": "To automatically instrument your application to capture HTTP requests, database queries, etc., add the following line" }, { "code": null, "e": 5433, "s": 5385, "text": "elasticapm.instrumentation.control.instrument()" }, { "code": null, "e": 5542, "s": 5433, "text": "To begin a transaction, use begin_transaction method with the appropriate transaction type as the parameter." }, { "code": null, "e": 5555, "s": 5542, "text": "For example," }, { "code": null, "e": 5592, "s": 5555, "text": "client.begin_transaction('schedule')" }, { "code": null, "e": 5710, "s": 5592, "text": "To complete a transaction, use the end_transaction method which takes two arguments viz. transaction name and result." }, { "code": null, "e": 5723, "s": 5710, "text": "For example," }, { "code": null, "e": 5777, "s": 5723, "text": "client.end_transaction('demo-transaction', 'success')" }, { "code": null, "e": 5886, "s": 5777, "text": "Sample code for monitoring Python application can be found from the link mentioned in the Resources section." }, { "code": null, "e": 5957, "s": 5886, "text": "All the code snippets of this article are available on my GitHub page." }, { "code": null, "e": 6033, "s": 5957, "text": "https://www.elastic.co/guide/en/apm/agent/python/current/configuration.html" }, { "code": null, "e": 6109, "s": 6033, "text": "https://www.elastic.co/guide/en/apm/agent/python/current/flask-support.html" }, { "code": null, "e": 6175, "s": 6109, "text": "https://www.elastic.co/guide/en/apm/get-started/7.4/metadata.html" }, { "code": null, "e": 6255, "s": 6175, "text": "https://www.elastic.co/guide/en/apm/agent/python/current/starlette-support.html" } ]
Socket.IO - Event Handling
Sockets work based on events. There are some reserved events, which can be accessed using the socket object on the server side. These are − Connect Message Disconnect Reconnect Ping Join and Leave. The client-side socket object also provides us with some reserved events, which are − Connect Connect_error Connect_timeout Reconnect, etc. Now, let us see an example to handle events using SocketIO library. In the Hello World example, we used the connection and disconnection events to log when a user connected and left. Now we will be using the message event to pass message from the server to the client. To do this, modify the io.on ('connection', function(socket)) as shown below –var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile('E:/test/index.html'); }); io.on('connection', function(socket){ console.log('A user connected'); // Send a message after a timeout of 4seconds setTimeout(function(){ socket.send('Sent a message 4seconds after connection!'); }, 4000); socket.on('disconnect', function () { console.log('A user disconnected'); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); }); This will send an event called message(built in) to our client, four seconds after the client connects. The send function on socket object associates the 'message' event. Now, we need to handle this event on our client side, to do so, replace the contents of the index.html page with the following − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); socket.on('message', function(data){document.write(data)}); </script> <body>Hello world</body> </html> We are now handling the 'message' event on the client. When you go to the page in your browser now, you will be presented with the following screenshot. After 4 seconds pass and the server sends the message event, our client will handle it and produce the following output − Note − We sent a string of text here; we can also send an object in any event. Message was a built-in event provided by the API, but is of not much use in a real application, as we need to be able to differentiate between events. To allow this, Socket.IO provides us the ability to create custom events. You can create and fire custom events using the socket.emit function. Following code emits an event called testerEvent − var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile('E:/test/index.html'); }); io.on('connection', function(socket){ console.log('A user connected'); // Send a message when setTimeout(function(){ // Sending an object when emmiting an event socket.emit('testerEvent', { description: 'A custom event named testerEvent!'}); }, 4000); socket.on('disconnect', function () { console.log('A user disconnected'); }); }); http.listen(3000, function(){ console.log('listening on localhost:3000'); }); To handle this custom event on client we need a listener that listens for the event testerEvent. The following code handles this event on the client − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); socket.on('testerEvent', function(data){document.write(data.description)}); </script> <body>Hello world</body> </html> This will work in the same way as our previous example, with the event being testerEvent in this case. When you open your browser and go to localhost:3000, you'l be greeted with − Hello world After four seconds, this event will be fired and the browser will have the text changed to − A custom event named testerEvent! We can also emit events from the client. To emit an event from your client, use the emit function on the socket object. <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); socket.emit('clientEvent', 'Sent an event from the client!'); </script> <body>Hello world</body> </html> To handle these events, use the on function on the socket object on your server. var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile('E:/test/index.html'); }); io.on('connection', function(socket){ socket.on('clientEvent', function(data){ console.log(data); }); }); http.listen(3000, function(){ console.log('listening on localhost:3000'); }); So, now if we go to localhost:3000, we will get a custom event called clientEvent fired. This event will be handled on the server by logging − Sent an event from the client! 35 Lectures 2.5 hours Nicholas Lever Print Add Notes Bookmark this page
[ { "code": null, "e": 1993, "s": 1865, "text": "Sockets work based on events. There are some reserved events, which can be accessed using the socket object on the server side." }, { "code": null, "e": 2005, "s": 1993, "text": "These are −" }, { "code": null, "e": 2013, "s": 2005, "text": "Connect" }, { "code": null, "e": 2021, "s": 2013, "text": "Message" }, { "code": null, "e": 2032, "s": 2021, "text": "Disconnect" }, { "code": null, "e": 2042, "s": 2032, "text": "Reconnect" }, { "code": null, "e": 2047, "s": 2042, "text": "Ping" }, { "code": null, "e": 2056, "s": 2047, "text": "Join and" }, { "code": null, "e": 2063, "s": 2056, "text": "Leave." }, { "code": null, "e": 2149, "s": 2063, "text": "The client-side socket object also provides us with some reserved events, which are −" }, { "code": null, "e": 2157, "s": 2149, "text": "Connect" }, { "code": null, "e": 2171, "s": 2157, "text": "Connect_error" }, { "code": null, "e": 2187, "s": 2171, "text": "Connect_timeout" }, { "code": null, "e": 2203, "s": 2187, "text": "Reconnect, etc." }, { "code": null, "e": 2271, "s": 2203, "text": "Now, let us see an example to handle events using SocketIO library." }, { "code": null, "e": 3133, "s": 2271, "text": "In the Hello World example, we used the connection and disconnection events to\nlog when a user connected and left. Now we will be using the message event to\npass message from the server to the client. To do this, modify the io.on\n('connection', function(socket)) as shown below –var app =\nrequire('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');\n});\n \nio.on('connection', function(socket){\n console.log('A user connected');\n \n // Send a message after a timeout of 4seconds\n setTimeout(function(){\n socket.send('Sent a message 4seconds after connection!');\n }, 4000);\n socket.on('disconnect', function () {\n console.log('A user disconnected');\n });\n});\nhttp.listen(3000, function(){\n console.log('listening on *:3000');\n});" }, { "code": null, "e": 3304, "s": 3133, "text": "This will send an event called message(built in) to our client, four seconds after the client connects. The send function on socket object associates the 'message' event." }, { "code": null, "e": 3433, "s": 3304, "text": "Now, we need to handle this event on our client side, to do so, replace the contents of the index.html page with the following −" }, { "code": null, "e": 3702, "s": 3433, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n socket.on('message', function(data){document.write(data)});\n </script>\n <body>Hello world</body>\n</html>" }, { "code": null, "e": 3855, "s": 3702, "text": "We are now handling the 'message' event on the client. When you go to the page in your browser now, you will be presented with the following screenshot." }, { "code": null, "e": 3977, "s": 3855, "text": "After 4 seconds pass and the server sends the message event, our client will handle it and produce the following output −" }, { "code": null, "e": 4056, "s": 3977, "text": "Note − We sent a string of text here; we can also send an object in any event." }, { "code": null, "e": 4207, "s": 4056, "text": "Message was a built-in event provided by the API, but is of not much use in a real application, as we need to be able to differentiate between events." }, { "code": null, "e": 4402, "s": 4207, "text": "To allow this, Socket.IO provides us the ability to create custom events. You can create and fire custom events using the socket.emit function. Following code emits an event called testerEvent −" }, { "code": null, "e": 5043, "s": 4402, "text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');\n});\n \nio.on('connection', function(socket){\n console.log('A user connected');\n // Send a message when\n setTimeout(function(){\n // Sending an object when emmiting an event\n socket.emit('testerEvent', { description: 'A custom event named testerEvent!'});\n }, 4000);\n socket.on('disconnect', function () {\n console.log('A user disconnected');\n });\n});\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});" }, { "code": null, "e": 5194, "s": 5043, "text": "To handle this custom event on client we need a listener that listens for the event testerEvent. The following code handles this event on the client −" }, { "code": null, "e": 5479, "s": 5194, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n socket.on('testerEvent', function(data){document.write(data.description)});\n </script>\n <body>Hello world</body>\n</html>" }, { "code": null, "e": 5659, "s": 5479, "text": "This will work in the same way as our previous example, with the event being testerEvent in this case. When you open your browser and go to localhost:3000, you'l be greeted with −" }, { "code": null, "e": 5672, "s": 5659, "text": "Hello world\n" }, { "code": null, "e": 5765, "s": 5672, "text": "After four seconds, this event will be fired and the browser will have the text changed to −" }, { "code": null, "e": 5800, "s": 5765, "text": "A custom event named testerEvent!\n" }, { "code": null, "e": 5920, "s": 5800, "text": "We can also emit events from the client. To emit an event from your client, use the emit function on the socket object." }, { "code": null, "e": 6191, "s": 5920, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n socket.emit('clientEvent', 'Sent an event from the client!');\n </script>\n <body>Hello world</body>\n</html>" }, { "code": null, "e": 6272, "s": 6191, "text": "To handle these events, use the on function on the socket object on your server." }, { "code": null, "e": 6658, "s": 6272, "text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');\n});\nio.on('connection', function(socket){\n socket.on('clientEvent', function(data){\n console.log(data);\n });\n});\n\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});" }, { "code": null, "e": 6801, "s": 6658, "text": "So, now if we go to localhost:3000, we will get a custom event called clientEvent fired. This event will be handled on the server by logging −" }, { "code": null, "e": 6833, "s": 6801, "text": "Sent an event from the client!\n" }, { "code": null, "e": 6868, "s": 6833, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6884, "s": 6868, "text": " Nicholas Lever" }, { "code": null, "e": 6891, "s": 6884, "text": " Print" }, { "code": null, "e": 6902, "s": 6891, "text": " Add Notes" } ]
One-Step Predictions with LSTM: Forecasting Hotel Revenues | by Michael Grogan | Towards Data Science
Note: This is an update to my previous article Forecasting Average Daily Rate Trends for Hotels Using LSTM. I since recognised a couple of technical errors in the original analysis, and decided to write a new article to address these and expand my prior analysis. The purpose of using an LSTM model in this instance is to forecast ADR (average daily rate) for a hotel. ADR is calculated as follows: ADR = Revenue ÷ sold rooms In this example, the average ADR for customers per week is calculated and formulated into a time series. The LSTM model is then used to forecast this metric on a week-by-week basis. The original study by Antonio, Almeida and Nunes (2019) can be found here. Using pandas, the average ADR is calculated per week. Here is a plot of the weekly ADR trend. Note that the Jupyter Notebook for this example is available at the end of this article. As with any neural network, the data needs to be scaled for proper interpretation by the network, a process known as normalization. MinMaxScaler is used for this purpose. However, this comes with a caveat. Scaling must be done after the data has been split into training, validation and test sets — with each being scaled separately. A common mistake when first using the LSTM (I made this mistake myself) is to first normalize the data before splitting the data. The reason this is erroneous is that the normalization technique will use data from the validation and test sets as a reference point when scaling the data as a whole. This will inadvertently influence the values of the training data, essentially resulting in data leakage from the validation and test sets. In this regard, 100 data points are split into training and validation sets, with the last 15 data points being held as test data for comparison with the LSTM predictions. train_size = int(len(df) * 0.8)val_size = len(df) - train_sizetrain, val = df[0:train_size,:], df[train_size:len(df),:] A dataset matrix is formed: def create_dataset(df, previous=1): dataX, dataY = [], [] for i in range(len(df)-previous-1): a = df[i:(i+previous), 0] dataX.append(a) dataY.append(df[i + previous, 0]) return np.array(dataX), np.array(dataY) At this point, the training data can be scaled as follows: scaler = MinMaxScaler(feature_range=(0, 1))train = scaler.fit_transform(train)train Here is a sample of the output: array([[0.35915778], [0.42256282], [0.53159902],... [0.0236608 ], [0.11987636], [0.48651694]]) Similarly, the validation data is scaled in the same way: val = scaler.fit_transform(val)val A “lookback period” defines how many previous timesteps are used in order to predict the subsequent timestep. In this regard, we are using a one-step prediction model. The lookback period is set to 5 in this instance. This means that we are using the time steps at t-4, t-3, t-2, t-1, and t to predict the value at time t+1. # Lookback periodlookback = 5X_train, Y_train = create_dataset(train, lookback)X_val, Y_val = create_dataset(val, lookback) Note that the selection of the lookback period is quite an arbitrary process. In this instance, a lookback window of 5 was shown to demonstrate the best predictive performance on the test set. However, another option could be to use the number of lags as indicated by PACF to set the size of the lookback window, as described at Data Science Stack Exchange. Let’s take a look at the normalized window for X_train. array([[0.35915778, 0.42256282, 0.53159902, 0.6084246 , 0.63902841], [0.42256282, 0.53159902, 0.6084246 , 0.63902841, 0.70858066], [0.53159902, 0.6084246 , 0.63902841, 0.70858066, 0.75574219],... Here are the first three entries. We can see that the five time steps immediately prior to the one we are trying to predict move in a stepwise motion. For instance, the first entry shows 0.63902841 at time t. In the second entry, this value now moves backwards to time t-1. Let’s give an example applicable to this situation. For a hotel that wishes to predict the ADR value in week 26 for instance, the hotel will use this model to make the prediction in the prior week using data for weeks 21, 22, 23, 24, and 25. Now, the input is reshaped into a [samples, time steps, features] format. # reshape input to be [samples, time steps, features]X_train = np.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1]))X_val = np.reshape(X_val, (X_val.shape[0], 1, X_val.shape[1])) In this case, the shape of the input is [74, 1, 1]. 74 samples are present in the training data, the model is operating on a time step of 1, and 1 feature is being used in the model, i.e. a lagged version of the time series. An LSTM model is defined as follows: # Generate LSTM networkmodel = tf.keras.Sequential()model.add(LSTM(4, input_shape=(1, lookback)))model.add(Dense(1))model.compile(loss='mean_squared_error', optimizer='adam')history=model.fit(X_train, Y_train, validation_split=0.2, epochs=100, batch_size=1, verbose=2) An LSTM model is created with 4 neurons. The mean squared error is being used as the loss function — given that we are dealing with a regression problem. Additionally, the adam optimizer is used, with training done over 100 epochs with a validation split of 20%. Here is a visual overview of the training and validation loss: # list all data in historyprint(history.history.keys())# summarize history for accuracyplt.plot(history.history['loss'])plt.plot(history.history['val_loss'])plt.title('model loss')plt.ylabel('loss')plt.xlabel('epoch')plt.legend(['train', 'val'], loc='upper left')plt.show() We can see that after an initial increase in the validation loss, the loss starts to decrease after about 10 epochs. Now, the predictions are converted back to the original scale: # Convert predictions back to normal valuestrainpred = scaler.inverse_transform(trainpred)Y_train = scaler.inverse_transform([Y_train])valpred = scaler.inverse_transform(valpred)Y_val = scaler.inverse_transform([Y_val])predictions = valpred The root mean squared error is calculated on the training and validation set: # calculate RMSEtrainScore = math.sqrt(mean_squared_error(Y_train[0], trainpred[:,0]))print('Train Score: %.2f RMSE' % (trainScore))valScore = math.sqrt(mean_squared_error(Y_val[0], valpred[:,0]))print('Validation Score: %.2f RMSE' % (valScore)) The obtained RMSE values are as follows: Train error: 3.88 RMSE Validation error: 8.78 RMSE With a mean ADR value of 69.99 across the validation set, the validation error is quite small in comparison (roughly 12% of the mean value), indicating that the model has done a good job at forecasting ADR values. Here is a plot of the forecasted versus actual ADR values across the training and validation set. # Plot all predictionsinversetransform, =plt.plot(scaler.inverse_transform(df))trainpred, =plt.plot(scaler.inverse_transform(trainpredPlot))valpred, =plt.plot(scaler.inverse_transform(valpredPlot))plt.xlabel('Number of weeks')plt.ylabel('Cancellations')plt.title("Predicted vs. Actual Weekly ADR")plt.show() We can see that the LSTM model is generally capturing the directional oscillations of the time series. However, during periods of extreme spikes in ADR, e.g. week 60, the model seems to perform less well. However, in order to fully determine whether the model has predictive power — it will now be used to predict the last 15 time steps in the series, i.e. the test data. Xnew = np.array([tseries.iloc[95:100],tseries.iloc[96:101],tseries.iloc[97:102],tseries.iloc[98:103],tseries.iloc[99:104],tseries.iloc[100:105],tseries.iloc[101:106],tseries.iloc[102:107],tseries.iloc[103:108],tseries.iloc[104:109],tseries.iloc[105:110],tseries.iloc[106:111],tseries.iloc[107:112],tseries.iloc[108:113],tseries.iloc[109:114]]) In this example, Xnew uses the previous five time steps to predict at time t+1. For instance, weeks 95 to 100 are used to predict the ADR value for week 101, then weeks 96 to 101 are used to predict week 102, and so on. The above graph illustrates the LSTM predictions versus the actual ADR values in the test set — the last 15 points in the series. The obtained RMSE and MAE (mean absolute error) values are as follows: MAE: -27.65 RMSE: 31.91 The RMSE error for the test set is significantly higher than that for the validation set — which would be expected since we are working with unseen data. However, with a mean ADR value of 160 across the test set, the RMSE error is approximately 20% of the size of the mean value, indicating that the LSTM does still have reasonably strong predictive power in determining the value of the next timestep. Ideally, one would like to use a significantly larger data sample to validate whether the LSTM would retain predictive power across new data. Additionally, as illustrated in this Reddit thread, LSTMs can be prone to overfitting depending on the size of the data sample. In this regard, a larger data sample is needed to validate if this model would work in a real-world scenario. However, the preliminary results in this case look promising. In this example, you have seen: How to properly format data to work with an LSTM model Building of a one-step LSTM predictive model Interpretation of RMSE and MAE values to determine model accuracy Many thanks for reading, and any feedback or questions are greatly appreciated. You can find the Jupyter Notebook for this example here. Additionally, I also highly recommend this tutorial by Machine Learning Mastery, which was used as a guideline for designing the LSTM model used in this example. Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice in any way. The author has no relationship with any third-parties mentioned in this article.
[ { "code": null, "e": 436, "s": 172, "text": "Note: This is an update to my previous article Forecasting Average Daily Rate Trends for Hotels Using LSTM. I since recognised a couple of technical errors in the original analysis, and decided to write a new article to address these and expand my prior analysis." }, { "code": null, "e": 541, "s": 436, "text": "The purpose of using an LSTM model in this instance is to forecast ADR (average daily rate) for a hotel." }, { "code": null, "e": 571, "s": 541, "text": "ADR is calculated as follows:" }, { "code": null, "e": 598, "s": 571, "text": "ADR = Revenue ÷ sold rooms" }, { "code": null, "e": 780, "s": 598, "text": "In this example, the average ADR for customers per week is calculated and formulated into a time series. The LSTM model is then used to forecast this metric on a week-by-week basis." }, { "code": null, "e": 855, "s": 780, "text": "The original study by Antonio, Almeida and Nunes (2019) can be found here." }, { "code": null, "e": 949, "s": 855, "text": "Using pandas, the average ADR is calculated per week. Here is a plot of the weekly ADR trend." }, { "code": null, "e": 1038, "s": 949, "text": "Note that the Jupyter Notebook for this example is available at the end of this article." }, { "code": null, "e": 1209, "s": 1038, "text": "As with any neural network, the data needs to be scaled for proper interpretation by the network, a process known as normalization. MinMaxScaler is used for this purpose." }, { "code": null, "e": 1502, "s": 1209, "text": "However, this comes with a caveat. Scaling must be done after the data has been split into training, validation and test sets — with each being scaled separately. A common mistake when first using the LSTM (I made this mistake myself) is to first normalize the data before splitting the data." }, { "code": null, "e": 1810, "s": 1502, "text": "The reason this is erroneous is that the normalization technique will use data from the validation and test sets as a reference point when scaling the data as a whole. This will inadvertently influence the values of the training data, essentially resulting in data leakage from the validation and test sets." }, { "code": null, "e": 1982, "s": 1810, "text": "In this regard, 100 data points are split into training and validation sets, with the last 15 data points being held as test data for comparison with the LSTM predictions." }, { "code": null, "e": 2102, "s": 1982, "text": "train_size = int(len(df) * 0.8)val_size = len(df) - train_sizetrain, val = df[0:train_size,:], df[train_size:len(df),:]" }, { "code": null, "e": 2130, "s": 2102, "text": "A dataset matrix is formed:" }, { "code": null, "e": 2370, "s": 2130, "text": "def create_dataset(df, previous=1): dataX, dataY = [], [] for i in range(len(df)-previous-1): a = df[i:(i+previous), 0] dataX.append(a) dataY.append(df[i + previous, 0]) return np.array(dataX), np.array(dataY)" }, { "code": null, "e": 2429, "s": 2370, "text": "At this point, the training data can be scaled as follows:" }, { "code": null, "e": 2513, "s": 2429, "text": "scaler = MinMaxScaler(feature_range=(0, 1))train = scaler.fit_transform(train)train" }, { "code": null, "e": 2545, "s": 2513, "text": "Here is a sample of the output:" }, { "code": null, "e": 2670, "s": 2545, "text": "array([[0.35915778], [0.42256282], [0.53159902],... [0.0236608 ], [0.11987636], [0.48651694]])" }, { "code": null, "e": 2728, "s": 2670, "text": "Similarly, the validation data is scaled in the same way:" }, { "code": null, "e": 2763, "s": 2728, "text": "val = scaler.fit_transform(val)val" }, { "code": null, "e": 2931, "s": 2763, "text": "A “lookback period” defines how many previous timesteps are used in order to predict the subsequent timestep. In this regard, we are using a one-step prediction model." }, { "code": null, "e": 3088, "s": 2931, "text": "The lookback period is set to 5 in this instance. This means that we are using the time steps at t-4, t-3, t-2, t-1, and t to predict the value at time t+1." }, { "code": null, "e": 3212, "s": 3088, "text": "# Lookback periodlookback = 5X_train, Y_train = create_dataset(train, lookback)X_val, Y_val = create_dataset(val, lookback)" }, { "code": null, "e": 3570, "s": 3212, "text": "Note that the selection of the lookback period is quite an arbitrary process. In this instance, a lookback window of 5 was shown to demonstrate the best predictive performance on the test set. However, another option could be to use the number of lags as indicated by PACF to set the size of the lookback window, as described at Data Science Stack Exchange." }, { "code": null, "e": 3626, "s": 3570, "text": "Let’s take a look at the normalized window for X_train." }, { "code": null, "e": 3834, "s": 3626, "text": "array([[0.35915778, 0.42256282, 0.53159902, 0.6084246 , 0.63902841], [0.42256282, 0.53159902, 0.6084246 , 0.63902841, 0.70858066], [0.53159902, 0.6084246 , 0.63902841, 0.70858066, 0.75574219],..." }, { "code": null, "e": 3985, "s": 3834, "text": "Here are the first three entries. We can see that the five time steps immediately prior to the one we are trying to predict move in a stepwise motion." }, { "code": null, "e": 4108, "s": 3985, "text": "For instance, the first entry shows 0.63902841 at time t. In the second entry, this value now moves backwards to time t-1." }, { "code": null, "e": 4350, "s": 4108, "text": "Let’s give an example applicable to this situation. For a hotel that wishes to predict the ADR value in week 26 for instance, the hotel will use this model to make the prediction in the prior week using data for weeks 21, 22, 23, 24, and 25." }, { "code": null, "e": 4424, "s": 4350, "text": "Now, the input is reshaped into a [samples, time steps, features] format." }, { "code": null, "e": 4610, "s": 4424, "text": "# reshape input to be [samples, time steps, features]X_train = np.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1]))X_val = np.reshape(X_val, (X_val.shape[0], 1, X_val.shape[1]))" }, { "code": null, "e": 4662, "s": 4610, "text": "In this case, the shape of the input is [74, 1, 1]." }, { "code": null, "e": 4835, "s": 4662, "text": "74 samples are present in the training data, the model is operating on a time step of 1, and 1 feature is being used in the model, i.e. a lagged version of the time series." }, { "code": null, "e": 4872, "s": 4835, "text": "An LSTM model is defined as follows:" }, { "code": null, "e": 5141, "s": 4872, "text": "# Generate LSTM networkmodel = tf.keras.Sequential()model.add(LSTM(4, input_shape=(1, lookback)))model.add(Dense(1))model.compile(loss='mean_squared_error', optimizer='adam')history=model.fit(X_train, Y_train, validation_split=0.2, epochs=100, batch_size=1, verbose=2)" }, { "code": null, "e": 5404, "s": 5141, "text": "An LSTM model is created with 4 neurons. The mean squared error is being used as the loss function — given that we are dealing with a regression problem. Additionally, the adam optimizer is used, with training done over 100 epochs with a validation split of 20%." }, { "code": null, "e": 5467, "s": 5404, "text": "Here is a visual overview of the training and validation loss:" }, { "code": null, "e": 5741, "s": 5467, "text": "# list all data in historyprint(history.history.keys())# summarize history for accuracyplt.plot(history.history['loss'])plt.plot(history.history['val_loss'])plt.title('model loss')plt.ylabel('loss')plt.xlabel('epoch')plt.legend(['train', 'val'], loc='upper left')plt.show()" }, { "code": null, "e": 5858, "s": 5741, "text": "We can see that after an initial increase in the validation loss, the loss starts to decrease after about 10 epochs." }, { "code": null, "e": 5921, "s": 5858, "text": "Now, the predictions are converted back to the original scale:" }, { "code": null, "e": 6162, "s": 5921, "text": "# Convert predictions back to normal valuestrainpred = scaler.inverse_transform(trainpred)Y_train = scaler.inverse_transform([Y_train])valpred = scaler.inverse_transform(valpred)Y_val = scaler.inverse_transform([Y_val])predictions = valpred" }, { "code": null, "e": 6240, "s": 6162, "text": "The root mean squared error is calculated on the training and validation set:" }, { "code": null, "e": 6486, "s": 6240, "text": "# calculate RMSEtrainScore = math.sqrt(mean_squared_error(Y_train[0], trainpred[:,0]))print('Train Score: %.2f RMSE' % (trainScore))valScore = math.sqrt(mean_squared_error(Y_val[0], valpred[:,0]))print('Validation Score: %.2f RMSE' % (valScore))" }, { "code": null, "e": 6527, "s": 6486, "text": "The obtained RMSE values are as follows:" }, { "code": null, "e": 6550, "s": 6527, "text": "Train error: 3.88 RMSE" }, { "code": null, "e": 6578, "s": 6550, "text": "Validation error: 8.78 RMSE" }, { "code": null, "e": 6792, "s": 6578, "text": "With a mean ADR value of 69.99 across the validation set, the validation error is quite small in comparison (roughly 12% of the mean value), indicating that the model has done a good job at forecasting ADR values." }, { "code": null, "e": 6890, "s": 6792, "text": "Here is a plot of the forecasted versus actual ADR values across the training and validation set." }, { "code": null, "e": 7198, "s": 6890, "text": "# Plot all predictionsinversetransform, =plt.plot(scaler.inverse_transform(df))trainpred, =plt.plot(scaler.inverse_transform(trainpredPlot))valpred, =plt.plot(scaler.inverse_transform(valpredPlot))plt.xlabel('Number of weeks')plt.ylabel('Cancellations')plt.title(\"Predicted vs. Actual Weekly ADR\")plt.show()" }, { "code": null, "e": 7403, "s": 7198, "text": "We can see that the LSTM model is generally capturing the directional oscillations of the time series. However, during periods of extreme spikes in ADR, e.g. week 60, the model seems to perform less well." }, { "code": null, "e": 7570, "s": 7403, "text": "However, in order to fully determine whether the model has predictive power — it will now be used to predict the last 15 time steps in the series, i.e. the test data." }, { "code": null, "e": 7914, "s": 7570, "text": "Xnew = np.array([tseries.iloc[95:100],tseries.iloc[96:101],tseries.iloc[97:102],tseries.iloc[98:103],tseries.iloc[99:104],tseries.iloc[100:105],tseries.iloc[101:106],tseries.iloc[102:107],tseries.iloc[103:108],tseries.iloc[104:109],tseries.iloc[105:110],tseries.iloc[106:111],tseries.iloc[107:112],tseries.iloc[108:113],tseries.iloc[109:114]])" }, { "code": null, "e": 8134, "s": 7914, "text": "In this example, Xnew uses the previous five time steps to predict at time t+1. For instance, weeks 95 to 100 are used to predict the ADR value for week 101, then weeks 96 to 101 are used to predict week 102, and so on." }, { "code": null, "e": 8264, "s": 8134, "text": "The above graph illustrates the LSTM predictions versus the actual ADR values in the test set — the last 15 points in the series." }, { "code": null, "e": 8335, "s": 8264, "text": "The obtained RMSE and MAE (mean absolute error) values are as follows:" }, { "code": null, "e": 8347, "s": 8335, "text": "MAE: -27.65" }, { "code": null, "e": 8359, "s": 8347, "text": "RMSE: 31.91" }, { "code": null, "e": 8513, "s": 8359, "text": "The RMSE error for the test set is significantly higher than that for the validation set — which would be expected since we are working with unseen data." }, { "code": null, "e": 8762, "s": 8513, "text": "However, with a mean ADR value of 160 across the test set, the RMSE error is approximately 20% of the size of the mean value, indicating that the LSTM does still have reasonably strong predictive power in determining the value of the next timestep." }, { "code": null, "e": 9032, "s": 8762, "text": "Ideally, one would like to use a significantly larger data sample to validate whether the LSTM would retain predictive power across new data. Additionally, as illustrated in this Reddit thread, LSTMs can be prone to overfitting depending on the size of the data sample." }, { "code": null, "e": 9204, "s": 9032, "text": "In this regard, a larger data sample is needed to validate if this model would work in a real-world scenario. However, the preliminary results in this case look promising." }, { "code": null, "e": 9236, "s": 9204, "text": "In this example, you have seen:" }, { "code": null, "e": 9291, "s": 9236, "text": "How to properly format data to work with an LSTM model" }, { "code": null, "e": 9336, "s": 9291, "text": "Building of a one-step LSTM predictive model" }, { "code": null, "e": 9402, "s": 9336, "text": "Interpretation of RMSE and MAE values to determine model accuracy" }, { "code": null, "e": 9539, "s": 9402, "text": "Many thanks for reading, and any feedback or questions are greatly appreciated. You can find the Jupyter Notebook for this example here." }, { "code": null, "e": 9701, "s": 9539, "text": "Additionally, I also highly recommend this tutorial by Machine Learning Mastery, which was used as a guideline for designing the LSTM model used in this example." } ]
JavaScript TypeError - "X" is not a constructor - GeeksforGeeks
24 Jul, 2020 This JavaScript exception is not a constructor that occurs if code tries to use an object or a variable as a constructor, which is not a constructor. Message: TypeError: Object doesn't support this action (Edge) TypeError: "x" is not a constructor TypeError: Math is not a constructor TypeError: JSON is not a constructor TypeError: Symbol is not a constructor TypeError: Reflect is not a constructor TypeError: Intl is not a constructor TypeError: Atomics is not a constructor Error Type: TypeError Cause of Error: Somewhere the code is trying to use an object or a variable as a constructor, which is not a constructor. Example 1: In this example, the variable(‘var2’) which is a string, is used as a constructor, So the error has occurred. HTML <!DOCTYPE html><html><head> <title>Type Error</title></head><body> <script> var var2 = "This is string"; document.write(new var2()); </script></body></html> Output(In Edge console): TypeError: Object doesn't support this action Example 2: In this example, Math is used as a constructor, So the error has occurred. HTML <!DOCTYPE html><html><head> <title>Type Error</title></head><body> <script> document.write(new Math()); </script></body></html> Output(In Edge console): TypeError: Object doesn't support this action JavaScript-Errors JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to filter object array based on attributes? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25300, "s": 25272, "text": "\n24 Jul, 2020" }, { "code": null, "e": 25450, "s": 25300, "text": "This JavaScript exception is not a constructor that occurs if code tries to use an object or a variable as a constructor, which is not a constructor." }, { "code": null, "e": 25459, "s": 25450, "text": "Message:" }, { "code": null, "e": 25781, "s": 25459, "text": "TypeError: Object doesn't support this action (Edge)\nTypeError: \"x\" is not a constructor\n\nTypeError: Math is not a constructor\nTypeError: JSON is not a constructor\nTypeError: Symbol is not a constructor\nTypeError: Reflect is not a constructor\nTypeError: Intl is not a constructor\nTypeError: Atomics is not a constructor\n\n" }, { "code": null, "e": 25793, "s": 25781, "text": "Error Type:" }, { "code": null, "e": 25804, "s": 25793, "text": "TypeError\n" }, { "code": null, "e": 25926, "s": 25804, "text": "Cause of Error: Somewhere the code is trying to use an object or a variable as a constructor, which is not a constructor." }, { "code": null, "e": 26047, "s": 25926, "text": "Example 1: In this example, the variable(‘var2’) which is a string, is used as a constructor, So the error has occurred." }, { "code": null, "e": 26052, "s": 26047, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Type Error</title></head><body> <script> var var2 = \"This is string\"; document.write(new var2()); </script></body></html>", "e": 26224, "s": 26052, "text": null }, { "code": null, "e": 26249, "s": 26224, "text": "Output(In Edge console):" }, { "code": null, "e": 26296, "s": 26249, "text": "TypeError: Object doesn't support this action\n" }, { "code": null, "e": 26382, "s": 26296, "text": "Example 2: In this example, Math is used as a constructor, So the error has occurred." }, { "code": null, "e": 26387, "s": 26382, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Type Error</title></head><body> <script> document.write(new Math()); </script></body></html>", "e": 26527, "s": 26387, "text": null }, { "code": null, "e": 26552, "s": 26527, "text": "Output(In Edge console):" }, { "code": null, "e": 26599, "s": 26552, "text": "TypeError: Object doesn't support this action\n" }, { "code": null, "e": 26617, "s": 26599, "text": "JavaScript-Errors" }, { "code": null, "e": 26628, "s": 26617, "text": "JavaScript" }, { "code": null, "e": 26645, "s": 26628, "text": "Web Technologies" }, { "code": null, "e": 26743, "s": 26645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26752, "s": 26743, "text": "Comments" }, { "code": null, "e": 26765, "s": 26752, "text": "Old Comments" }, { "code": null, "e": 26826, "s": 26765, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26867, "s": 26826, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26921, "s": 26867, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 26961, "s": 26921, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27009, "s": 26961, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 27051, "s": 27009, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27084, "s": 27051, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27127, "s": 27084, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27189, "s": 27127, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Formatting dynamic json array JavaScript
Let’s say, we have an array of objects like this − const arr = [ {"name1": "firstString"}, {"name2": "secondString"}, {"name3": "thirdString"}, {"name4": "fourthString"}, {"name5": "fifthString"}, {"name6": "sixthString"}, ]; We are required to write a function that takes one such array of objects and returns an object with all the properties listed in that object. So, let’s write the code for this function. It can be done through the Array reduce method − const arr = [ {"name1": "firstString"}, {"name2": "secondString"}, {"name3": "thirdString"}, {"name4": "fourthString"}, {"name5": "fifthString"}, {"name6": "sixthString"}, ]; const reduceArray = arr => { return arr.reduce((acc, val) => { Object.assign(acc, val); return acc; }, {}); }; The output in the console will be − { name1: 'firstString', name2: 'secondString', name3: 'thirdString', name4: 'fourthString', name5: 'fifthString', name6: 'sixthString' }
[ { "code": null, "e": 1113, "s": 1062, "text": "Let’s say, we have an array of objects like this −" }, { "code": null, "e": 1306, "s": 1113, "text": "const arr = [\n {\"name1\": \"firstString\"},\n {\"name2\": \"secondString\"},\n {\"name3\": \"thirdString\"},\n {\"name4\": \"fourthString\"},\n {\"name5\": \"fifthString\"},\n {\"name6\": \"sixthString\"},\n];" }, { "code": null, "e": 1448, "s": 1306, "text": "We are required to write a function that takes one such array of objects and returns an object\nwith all the properties listed in that object." }, { "code": null, "e": 1541, "s": 1448, "text": "So, let’s write the code for this function. It can be done through the Array reduce method −" }, { "code": null, "e": 1863, "s": 1541, "text": "const arr = [\n {\"name1\": \"firstString\"},\n {\"name2\": \"secondString\"},\n {\"name3\": \"thirdString\"},\n {\"name4\": \"fourthString\"},\n {\"name5\": \"fifthString\"},\n {\"name6\": \"sixthString\"},\n];\nconst reduceArray = arr => {\n return arr.reduce((acc, val) => {\n Object.assign(acc, val);\n return acc;\n }, {});\n};" }, { "code": null, "e": 1899, "s": 1863, "text": "The output in the console will be −" }, { "code": null, "e": 2054, "s": 1899, "text": "{\n name1: 'firstString',\n name2: 'secondString',\n name3: 'thirdString',\n name4: 'fourthString',\n name5: 'fifthString',\n name6: 'sixthString'\n}" } ]
Binary Literals and Digit Separators in C# - GeeksforGeeks
30 Apr, 2019 The fixed values are called as Literal. Literal is a value which is used by the variables. Before C# 7.0 six types of literals are available that are an integer, Floating-point, Character, String, Null, Boolean literals. In C# 7.0 there is one more literal is added which is known as Binary Literal. The binary literal is used to store the binary value in a variable. And the binary literal is represented by 0b. Binary literals are mainly used for bitmasks. Example: var num = 0b10001 Here when the compiler sees 0b in the variable value, then it automatically treated this num as a binary literal. If you try to run this on the compilers below C# 7.0, then the compiler will throw an error because this feature is introduced in C# 7.0 so, it will only work on C# 7.0 and above compilers. Example: // C# program to illustrate the // concept of binary literals.using System; class GFG { // Main method static public void Main() { // Creating binary literals // by prefixing with 0b var num1 = 0b1001; var num2 = 0b01000011; Console.WriteLine("Value of Num1 is: " + num1); Console.WriteLine("Value of Num2 is: " + num2); Console.WriteLine("Char value of Num2 is: {0}", Convert.ToChar(num2)); }} Value of Num1 is: 9 Value of Num2 is: 67 Char value of Num2 is: C The concept of digit separator is introduced in C# 7.0. With the help of digit separator, you can separate the large number into small parts which makes your code more readable. Underscore(_) is used as a digit separator. When you use digit separator in your code they are simply ignored by the compiler, so the compiler does not print digit separators in the output like as shown in the below example. Example: // C# program to illustrate the // concept of digit separators.using System; class GFG { // Main method static public void Main() { // Without Using digit separators long x = 100000022200000202; long z = 10000000020; Console.WriteLine("X: {0}", x); Console.WriteLine("Z: {0}", z); // Using digit separators long num1 = 1_00_10_00_00_00; var num2 = 0b_010_000_000_000_000_000_000_000_000; long num3 = 1_00_00_00_00_00_00; var num4 = 0b_1_1000_0000_1000_0000_0011_0000_0000_1000_0001; Console.WriteLine("Num1: {0}", num1); Console.WriteLine("Num2: {0}", num2); Console.WriteLine("Num3: {0}", num3); Console.WriteLine("Num4: {0}", num4); }} X: 100000022200000202 Z: 10000000020 Num1: 1000110000000000 Num2: 33554432 Num3: 1000000000000000000 Num4: 103213629569 CSharp-7.0 C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Method Overriding Destructors in C# Difference between Ref and Out keywords in C# C# | Delegates C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# Introduction to .NET Framework C# | Abstract Classes HashSet in C# with Examples
[ { "code": null, "e": 23890, "s": 23862, "text": "\n30 Apr, 2019" }, { "code": null, "e": 24349, "s": 23890, "text": "The fixed values are called as Literal. Literal is a value which is used by the variables. Before C# 7.0 six types of literals are available that are an integer, Floating-point, Character, String, Null, Boolean literals. In C# 7.0 there is one more literal is added which is known as Binary Literal. The binary literal is used to store the binary value in a variable. And the binary literal is represented by 0b. Binary literals are mainly used for bitmasks." }, { "code": null, "e": 24358, "s": 24349, "text": "Example:" }, { "code": null, "e": 24376, "s": 24358, "text": "var num = 0b10001" }, { "code": null, "e": 24680, "s": 24376, "text": "Here when the compiler sees 0b in the variable value, then it automatically treated this num as a binary literal. If you try to run this on the compilers below C# 7.0, then the compiler will throw an error because this feature is introduced in C# 7.0 so, it will only work on C# 7.0 and above compilers." }, { "code": null, "e": 24689, "s": 24680, "text": "Example:" }, { "code": "// C# program to illustrate the // concept of binary literals.using System; class GFG { // Main method static public void Main() { // Creating binary literals // by prefixing with 0b var num1 = 0b1001; var num2 = 0b01000011; Console.WriteLine(\"Value of Num1 is: \" + num1); Console.WriteLine(\"Value of Num2 is: \" + num2); Console.WriteLine(\"Char value of Num2 is: {0}\", Convert.ToChar(num2)); }}", "e": 25185, "s": 24689, "text": null }, { "code": null, "e": 25252, "s": 25185, "text": "Value of Num1 is: 9\nValue of Num2 is: 67\nChar value of Num2 is: C\n" }, { "code": null, "e": 25655, "s": 25252, "text": "The concept of digit separator is introduced in C# 7.0. With the help of digit separator, you can separate the large number into small parts which makes your code more readable. Underscore(_) is used as a digit separator. When you use digit separator in your code they are simply ignored by the compiler, so the compiler does not print digit separators in the output like as shown in the below example." }, { "code": null, "e": 25664, "s": 25655, "text": "Example:" }, { "code": "// C# program to illustrate the // concept of digit separators.using System; class GFG { // Main method static public void Main() { // Without Using digit separators long x = 100000022200000202; long z = 10000000020; Console.WriteLine(\"X: {0}\", x); Console.WriteLine(\"Z: {0}\", z); // Using digit separators long num1 = 1_00_10_00_00_00; var num2 = 0b_010_000_000_000_000_000_000_000_000; long num3 = 1_00_00_00_00_00_00; var num4 = 0b_1_1000_0000_1000_0000_0011_0000_0000_1000_0001; Console.WriteLine(\"Num1: {0}\", num1); Console.WriteLine(\"Num2: {0}\", num2); Console.WriteLine(\"Num3: {0}\", num3); Console.WriteLine(\"Num4: {0}\", num4); }}", "e": 26423, "s": 25664, "text": null }, { "code": null, "e": 26544, "s": 26423, "text": "X: 100000022200000202\nZ: 10000000020\nNum1: 1000110000000000\nNum2: 33554432\nNum3: 1000000000000000000\nNum4: 103213629569\n" }, { "code": null, "e": 26555, "s": 26544, "text": "CSharp-7.0" }, { "code": null, "e": 26558, "s": 26555, "text": "C#" }, { "code": null, "e": 26656, "s": 26558, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26684, "s": 26656, "text": "C# Dictionary with examples" }, { "code": null, "e": 26707, "s": 26684, "text": "C# | Method Overriding" }, { "code": null, "e": 26725, "s": 26707, "text": "Destructors in C#" }, { "code": null, "e": 26771, "s": 26725, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 26786, "s": 26771, "text": "C# | Delegates" }, { "code": null, "e": 26826, "s": 26786, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 26849, "s": 26826, "text": "Extension Method in C#" }, { "code": null, "e": 26880, "s": 26849, "text": "Introduction to .NET Framework" }, { "code": null, "e": 26902, "s": 26880, "text": "C# | Abstract Classes" } ]
SQL Query to Exclude Null Values - GeeksforGeeks
23 Sep, 2021 In this article, we will look at how to exclude Null Values from the table using a SQL query. A null value indicates no value. It means that the column value is absent in a row. A null value is not the same as a blank space or a zero value. A zero value is an integer and a blank space is a character while a null value is the one that has been left blank. To exclude the null values from a table we have to create a table with null values. So, let us create a table. Step 1: Creating table Syntax: CREATE TABLE table_name ( column1 datatype, column2 datatype, column3 datatype, ....); Query: CREATE TABLE Student(Name varchar(40), Department varchar(30),Roll_No int, ); Using the above query student table is created in our database. The student table has three fields Name, Department, and Roll Number of a student. To insert values in the table we have to use the INSERT query. Output: Step 2: Insert Data into the Table Syntax: INSERT INTO table_name VALUES (value1, value2, value3, ...); Query: INSERT INTO Student VALUES ('Rahul Sharma','Electronics',15), ('Soha Shaikh','Computer Science',NULL), ('Vivek Rao',NULL,31), ('Sonali Rane','Electronics',20); Using the above query we have added the data to our table. We used the NULL keyword to insert NULL values. Output: Step 3: View Table Data We can print the data in the table using the SELECT query as below. Syntax: SELECT * FROM table_name Query: SELECT * FROM Student The output will show the table with all the fields because we used ‘*’ in the query. It means that select all fields within the table. Output: Step 4: Exclude Null Values To exclude the null values from the table we need to use IS NOT NULL operator with the WHERE clause. WHERE Clause:The WHERE clause is used to filter the records.It will extract those records that fulfill the condition.It can be used with SELECT, UPDATE, DELETE queries. The WHERE clause is used to filter the records. It will extract those records that fulfill the condition. It can be used with SELECT, UPDATE, DELETE queries. IS NOT NULL Operator: This operator is used to test for non-empty values. This operator is used to test for non-empty values. Syntax: SELECT column_names FROM table_name WHERE column_name IS NOT NULL; Query: SELECT * FROM Student WHERE Name IS NOT NULL AND Department IS NOT NULL AND Roll_No IS NOT NULL; To exclude the null values from all the columns we used AND operator. AND operator shows the record if all the conditions are true. Output: Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Update Multiple Columns in Single Update Statement in SQL? How to Alter Multiple Columns at Once in SQL Server? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL | Subquery SQL Query to Convert VARCHAR to INT SQL | Date functions SQL - SELECT from Multiple Tables with MS SQL Server SQL Query to Insert Multiple Rows
[ { "code": null, "e": 24292, "s": 24264, "text": "\n23 Sep, 2021" }, { "code": null, "e": 24388, "s": 24292, "text": "In this article, we will look at how to exclude Null Values from the table using a SQL query. " }, { "code": null, "e": 24651, "s": 24388, "text": "A null value indicates no value. It means that the column value is absent in a row. A null value is not the same as a blank space or a zero value. A zero value is an integer and a blank space is a character while a null value is the one that has been left blank." }, { "code": null, "e": 24762, "s": 24651, "text": "To exclude the null values from a table we have to create a table with null values. So, let us create a table." }, { "code": null, "e": 24785, "s": 24762, "text": "Step 1: Creating table" }, { "code": null, "e": 24793, "s": 24785, "text": "Syntax:" }, { "code": null, "e": 24891, "s": 24793, "text": "CREATE TABLE table_name (\n column1 datatype,\n column2 datatype,\n column3 datatype,\n ....);" }, { "code": null, "e": 24898, "s": 24891, "text": "Query:" }, { "code": null, "e": 24976, "s": 24898, "text": "CREATE TABLE Student(Name varchar(40),\nDepartment varchar(30),Roll_No int, );" }, { "code": null, "e": 25186, "s": 24976, "text": "Using the above query student table is created in our database. The student table has three fields Name, Department, and Roll Number of a student. To insert values in the table we have to use the INSERT query." }, { "code": null, "e": 25194, "s": 25186, "text": "Output:" }, { "code": null, "e": 25230, "s": 25194, "text": "Step 2: Insert Data into the Table" }, { "code": null, "e": 25238, "s": 25230, "text": "Syntax:" }, { "code": null, "e": 25299, "s": 25238, "text": "INSERT INTO table_name\nVALUES (value1, value2, value3, ...);" }, { "code": null, "e": 25306, "s": 25299, "text": "Query:" }, { "code": null, "e": 25484, "s": 25306, "text": "INSERT INTO Student\nVALUES ('Rahul Sharma','Electronics',15),\n ('Soha Shaikh','Computer Science',NULL),\n ('Vivek Rao',NULL,31),\n ('Sonali Rane','Electronics',20);" }, { "code": null, "e": 25591, "s": 25484, "text": "Using the above query we have added the data to our table. We used the NULL keyword to insert NULL values." }, { "code": null, "e": 25599, "s": 25591, "text": "Output:" }, { "code": null, "e": 25623, "s": 25599, "text": "Step 3: View Table Data" }, { "code": null, "e": 25691, "s": 25623, "text": "We can print the data in the table using the SELECT query as below." }, { "code": null, "e": 25699, "s": 25691, "text": "Syntax:" }, { "code": null, "e": 25724, "s": 25699, "text": "SELECT * FROM table_name" }, { "code": null, "e": 25731, "s": 25724, "text": "Query:" }, { "code": null, "e": 25753, "s": 25731, "text": "SELECT * FROM Student" }, { "code": null, "e": 25888, "s": 25753, "text": "The output will show the table with all the fields because we used ‘*’ in the query. It means that select all fields within the table." }, { "code": null, "e": 25896, "s": 25888, "text": "Output:" }, { "code": null, "e": 25924, "s": 25896, "text": "Step 4: Exclude Null Values" }, { "code": null, "e": 26025, "s": 25924, "text": "To exclude the null values from the table we need to use IS NOT NULL operator with the WHERE clause." }, { "code": null, "e": 26194, "s": 26025, "text": "WHERE Clause:The WHERE clause is used to filter the records.It will extract those records that fulfill the condition.It can be used with SELECT, UPDATE, DELETE queries." }, { "code": null, "e": 26242, "s": 26194, "text": "The WHERE clause is used to filter the records." }, { "code": null, "e": 26300, "s": 26242, "text": "It will extract those records that fulfill the condition." }, { "code": null, "e": 26352, "s": 26300, "text": "It can be used with SELECT, UPDATE, DELETE queries." }, { "code": null, "e": 26426, "s": 26352, "text": "IS NOT NULL Operator: This operator is used to test for non-empty values." }, { "code": null, "e": 26478, "s": 26426, "text": "This operator is used to test for non-empty values." }, { "code": null, "e": 26486, "s": 26478, "text": "Syntax:" }, { "code": null, "e": 26554, "s": 26486, "text": "SELECT column_names\n FROM table_name\nWHERE column_name IS NOT NULL;" }, { "code": null, "e": 26561, "s": 26554, "text": "Query:" }, { "code": null, "e": 26658, "s": 26561, "text": "SELECT * FROM Student\nWHERE Name IS NOT NULL\nAND Department IS NOT NULL\nAND Roll_No IS NOT NULL;" }, { "code": null, "e": 26790, "s": 26658, "text": "To exclude the null values from all the columns we used AND operator. AND operator shows the record if all the conditions are true." }, { "code": null, "e": 26798, "s": 26790, "text": "Output:" }, { "code": null, "e": 26805, "s": 26798, "text": "Picked" }, { "code": null, "e": 26815, "s": 26805, "text": "SQL-Query" }, { "code": null, "e": 26826, "s": 26815, "text": "SQL-Server" }, { "code": null, "e": 26830, "s": 26826, "text": "SQL" }, { "code": null, "e": 26834, "s": 26830, "text": "SQL" }, { "code": null, "e": 26932, "s": 26834, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26941, "s": 26932, "text": "Comments" }, { "code": null, "e": 26954, "s": 26941, "text": "Old Comments" }, { "code": null, "e": 27020, "s": 26954, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27073, "s": 27020, "text": "How to Alter Multiple Columns at Once in SQL Server?" }, { "code": null, "e": 27105, "s": 27073, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27183, "s": 27105, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27200, "s": 27183, "text": "SQL using Python" }, { "code": null, "e": 27215, "s": 27200, "text": "SQL | Subquery" }, { "code": null, "e": 27251, "s": 27215, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27272, "s": 27251, "text": "SQL | Date functions" }, { "code": null, "e": 27325, "s": 27272, "text": "SQL - SELECT from Multiple Tables with MS SQL Server" } ]
PHP Callbacks/Callables
Callback is a pseudo-type in PHP. With PHP 5.4, Callable type hint has been introduced, which is similar to Callback. When some object is identified as callable, it means that it can be used as a function that can be called. A callable can be a built-in or user defined function or a method inside any class. The is_callable() function can be used to verify if the identifier is a callable or not. PHP has call_user_function() that accepts a function's name as a parameter. Following example shows a built-in function is a callable. Live Demo <?php var_dump (is_callable("abs")); ?> This will produce following result − bool(true) In following example a user defined function is tested for being callable. Live Demo <?php function myfunction(){ echo "Hello World"; } echo is_callable("myfunction") . "\n"; call_user_func("myfunction") ?> This will produce following result − 1 Hello World To pass a object method as a callable, the object itself and its method are passed as two elements in an array Live Demo <?php class myclass{ function mymethod(){ echo "This is a callable" . "\n"; } } $obj=new myclass(); call_user_func(array($obj, "mymethod")); //array passed in literal form call_user_func([$obj, "mymethod"]); ?> This will produce following result − This is a callable This is a callable Static method in a class can also be passed as callable. Instead of object, name of the class should be first element in array parameter Live Demo <?php class myclass{ static function mymethod(){ echo "This is a callable" . "\n"; } } $obj=new myclass(); call_user_func(array("myclass", "mymethod")); //using scope resolution operator call_user_func("myclass::mymethod"); ?> This will produce following result − This is a callable This is a callable
[ { "code": null, "e": 1371, "s": 1062, "text": "Callback is a pseudo-type in PHP. With PHP 5.4, Callable type hint has been introduced, which is similar to Callback. When some object is identified as callable, it means that it can be used as a function that can be called. A callable can be a built-in or user defined function or a method inside any class." }, { "code": null, "e": 1536, "s": 1371, "text": "The is_callable() function can be used to verify if the identifier is a callable or not. PHP has call_user_function() that accepts a function's name as a parameter." }, { "code": null, "e": 1595, "s": 1536, "text": "Following example shows a built-in function is a callable." }, { "code": null, "e": 1606, "s": 1595, "text": " Live Demo" }, { "code": null, "e": 1646, "s": 1606, "text": "<?php\nvar_dump (is_callable(\"abs\"));\n?>" }, { "code": null, "e": 1683, "s": 1646, "text": "This will produce following result −" }, { "code": null, "e": 1694, "s": 1683, "text": "bool(true)" }, { "code": null, "e": 1769, "s": 1694, "text": "In following example a user defined function is tested for being callable." }, { "code": null, "e": 1780, "s": 1769, "text": " Live Demo" }, { "code": null, "e": 1905, "s": 1780, "text": "<?php\nfunction myfunction(){\n echo \"Hello World\";\n}\necho is_callable(\"myfunction\") . \"\\n\";\ncall_user_func(\"myfunction\")\n?>" }, { "code": null, "e": 1942, "s": 1905, "text": "This will produce following result −" }, { "code": null, "e": 1956, "s": 1942, "text": "1\nHello World" }, { "code": null, "e": 2067, "s": 1956, "text": "To pass a object method as a callable, the object itself and its method are passed as two elements in an array" }, { "code": null, "e": 2078, "s": 2067, "text": " Live Demo" }, { "code": null, "e": 2301, "s": 2078, "text": "<?php\nclass myclass{\n function mymethod(){\n echo \"This is a callable\" . \"\\n\";\n }\n}\n$obj=new myclass();\ncall_user_func(array($obj, \"mymethod\"));\n//array passed in literal form\ncall_user_func([$obj, \"mymethod\"]);\n?>" }, { "code": null, "e": 2338, "s": 2301, "text": "This will produce following result −" }, { "code": null, "e": 2376, "s": 2338, "text": "This is a callable\nThis is a callable" }, { "code": null, "e": 2513, "s": 2376, "text": "Static method in a class can also be passed as callable. Instead of object, name of the class should be first element in array parameter" }, { "code": null, "e": 2524, "s": 2513, "text": " Live Demo" }, { "code": null, "e": 2763, "s": 2524, "text": "<?php\nclass myclass{\n static function mymethod(){\n echo \"This is a callable\" . \"\\n\";\n }\n}\n$obj=new myclass();\ncall_user_func(array(\"myclass\", \"mymethod\"));\n//using scope resolution operator\ncall_user_func(\"myclass::mymethod\");\n?>" }, { "code": null, "e": 2800, "s": 2763, "text": "This will produce following result −" }, { "code": null, "e": 2838, "s": 2800, "text": "This is a callable\nThis is a callable" } ]
BeautifulSoup - Search by text inside a tag - GeeksforGeeks
15 Mar, 2021 Prerequisites: Beautifulsoup Beautifulsoup is a powerful python module used for web scraping. This article discusses how a specific text can be searched inside a given tag. Import module Pass the URL Request page Specify the tag to be searched For Search by text inside tag we need to check condition to with help of string function. The string function will return the text inside a tag. When we will navigate tag then we will check the condition with the text. Return text We will see search text inside a tag by two method. This method uses for loop for to search for the text. Example Python3 from bs4 import BeautifulSoupimport requests # sample web pagesample_web_page = 'https://www.geeksforgeeks.org/caching-page-tables/' # call get method to request that pagepage = requests.get(sample_web_page) # with the help of beautifulSoup and html parser create soupsoup = BeautifulSoup(page.content, "html.parser") child_soup = soup.find_all('strong') text = 'page table base register (PTBR)' # we will search the tag with in which text is same as given textfor i in child_soup: if(i.string == text): print(i) Output <strong>page table base register (PTBR)</strong> It is a one liner alternative of the above example. Example Python3 from bs4 import BeautifulSoupimport requests # sample web pagesample_web_page = 'https://www.geeksforgeeks.org/caching-page-tables/' # call get method to request that pagepage = requests.get(sample_web_page) # with the help of beautifulSoup and html parser create soupsoup = BeautifulSoup(page.content, "html.parser") text = 'CS Theory Course' # Search by text with the help of lambda functiongfg = soup.find_all(lambda tag: tag.name == "strong" and text in tag.text) print(gfg) Output [<strong>CS Theory Course</strong>] Picked Python BeautifulSoup Python bs4-Exercises 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": 24292, "s": 24264, "text": "\n15 Mar, 2021" }, { "code": null, "e": 24321, "s": 24292, "text": "Prerequisites: Beautifulsoup" }, { "code": null, "e": 24465, "s": 24321, "text": "Beautifulsoup is a powerful python module used for web scraping. This article discusses how a specific text can be searched inside a given tag." }, { "code": null, "e": 24479, "s": 24465, "text": "Import module" }, { "code": null, "e": 24492, "s": 24479, "text": "Pass the URL" }, { "code": null, "e": 24505, "s": 24492, "text": "Request page" }, { "code": null, "e": 24536, "s": 24505, "text": "Specify the tag to be searched" }, { "code": null, "e": 24626, "s": 24536, "text": "For Search by text inside tag we need to check condition to with help of string function." }, { "code": null, "e": 24681, "s": 24626, "text": "The string function will return the text inside a tag." }, { "code": null, "e": 24755, "s": 24681, "text": "When we will navigate tag then we will check the condition with the text." }, { "code": null, "e": 24767, "s": 24755, "text": "Return text" }, { "code": null, "e": 24819, "s": 24767, "text": "We will see search text inside a tag by two method." }, { "code": null, "e": 24873, "s": 24819, "text": "This method uses for loop for to search for the text." }, { "code": null, "e": 24881, "s": 24873, "text": "Example" }, { "code": null, "e": 24889, "s": 24881, "text": "Python3" }, { "code": "from bs4 import BeautifulSoupimport requests # sample web pagesample_web_page = 'https://www.geeksforgeeks.org/caching-page-tables/' # call get method to request that pagepage = requests.get(sample_web_page) # with the help of beautifulSoup and html parser create soupsoup = BeautifulSoup(page.content, \"html.parser\") child_soup = soup.find_all('strong') text = 'page table base register (PTBR)' # we will search the tag with in which text is same as given textfor i in child_soup: if(i.string == text): print(i)", "e": 25418, "s": 24889, "text": null }, { "code": null, "e": 25425, "s": 25418, "text": "Output" }, { "code": null, "e": 25474, "s": 25425, "text": "<strong>page table base register (PTBR)</strong>" }, { "code": null, "e": 25526, "s": 25474, "text": "It is a one liner alternative of the above example." }, { "code": null, "e": 25534, "s": 25526, "text": "Example" }, { "code": null, "e": 25542, "s": 25534, "text": "Python3" }, { "code": "from bs4 import BeautifulSoupimport requests # sample web pagesample_web_page = 'https://www.geeksforgeeks.org/caching-page-tables/' # call get method to request that pagepage = requests.get(sample_web_page) # with the help of beautifulSoup and html parser create soupsoup = BeautifulSoup(page.content, \"html.parser\") text = 'CS Theory Course' # Search by text with the help of lambda functiongfg = soup.find_all(lambda tag: tag.name == \"strong\" and text in tag.text) print(gfg)", "e": 26027, "s": 25542, "text": null }, { "code": null, "e": 26034, "s": 26027, "text": "Output" }, { "code": null, "e": 26070, "s": 26034, "text": "[<strong>CS Theory Course</strong>]" }, { "code": null, "e": 26077, "s": 26070, "text": "Picked" }, { "code": null, "e": 26098, "s": 26077, "text": "Python BeautifulSoup" }, { "code": null, "e": 26119, "s": 26098, "text": "Python bs4-Exercises" }, { "code": null, "e": 26126, "s": 26119, "text": "Python" }, { "code": null, "e": 26224, "s": 26126, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26256, "s": 26224, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26298, "s": 26256, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26354, "s": 26298, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26396, "s": 26354, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26451, "s": 26396, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26482, "s": 26451, "text": "Python | os.path.join() method" }, { "code": null, "e": 26504, "s": 26482, "text": "Defaultdict in Python" }, { "code": null, "e": 26533, "s": 26504, "text": "Create a directory in Python" }, { "code": null, "e": 26572, "s": 26533, "text": "Python | Get unique values from a list" } ]
Performing distinct on multiple fields in MongoDB?
You can use $group operator along with aggregate framework to perform distinct on multiple fields. Let us first create a collection with documents − > db.distinctOnMultipleFieldsDemo.insertOne( ... { ... "StudentFirstName" : "Chris", ... "StudentAge" : 21, ... "StudentCountryName": "US" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2e518b64f4b851c3a13d7") } > db.distinctOnMultipleFieldsDemo.insertOne( ... { ... "StudentFirstName" : "Robert", ... "StudentAge" : 21, ... "StudentCountryName": "AUS" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2e518b64f4b851c3a13d8") } > db.distinctOnMultipleFieldsDemo.insertOne( ... { ... "StudentFirstName" : "Chris", ... "StudentAge" : 22, ... "StudentCountryName": "UK" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2e518b64f4b851c3a13d9") } > db.distinctOnMultipleFieldsDemo.insertOne( ... { ... "StudentFirstName" : "David", ... "StudentAge" : 24, ... "StudentCountryName": "AUS" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2e518b64f4b851c3a13da") } Following is the query to display all documents from a collection with the help of find() method − > db.distinctOnMultipleFieldsDemo.find().pretty(); This will produce the following output − { "_id" : ObjectId("5cd2e518b64f4b851c3a13d7"), "StudentFirstName" : "Chris", "StudentAge" : 21, "StudentCountryName" : "US" } { "_id" : ObjectId("5cd2e518b64f4b851c3a13d8"), "StudentFirstName" : "Robert", "StudentAge" : 21, "StudentCountryName" : "AUS" } { "_id" : ObjectId("5cd2e518b64f4b851c3a13d9"), "StudentFirstName" : "Chris", "StudentAge" : 22, "StudentCountryName" : "UK" } { "_id" : ObjectId("5cd2e518b64f4b851c3a13da"), "StudentFirstName" : "David", "StudentAge" : 24, "StudentCountryName" : "AUS" } Following is the query to perform distinct on multiple fields in MongoDB − > db.distinctOnMultipleFieldsDemo.aggregate([ ... { ... $group: ... { ... _id:0, ... StudentFirstName: {$addToSet: '$StudentFirstName'}, ... StudentAge: {$addToSet: '$StudentAge'}, ... StudentCountryName: {$addToSet: '$StudentCountryName'}, ... }} ... ]); This will produce the following output − { "_id" : 0, "StudentFirstName" : [ "David", "Robert", "Chris" ], "StudentAge" : [ 24, 22, 21 ], "StudentCountryName" : [ "UK", "AUS", "US" ] }
[ { "code": null, "e": 1211, "s": 1062, "text": "You can use $group operator along with aggregate framework to perform distinct on multiple fields. Let us first create a collection with documents −" }, { "code": null, "e": 2258, "s": 1211, "text": "> db.distinctOnMultipleFieldsDemo.insertOne(\n... {\n... \"StudentFirstName\" : \"Chris\",\n... \"StudentAge\" : 21,\n... \"StudentCountryName\": \"US\"\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd2e518b64f4b851c3a13d7\")\n}\n> db.distinctOnMultipleFieldsDemo.insertOne(\n... {\n... \"StudentFirstName\" : \"Robert\",\n... \"StudentAge\" : 21,\n... \"StudentCountryName\": \"AUS\"\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd2e518b64f4b851c3a13d8\")\n}\n> db.distinctOnMultipleFieldsDemo.insertOne(\n... {\n... \"StudentFirstName\" : \"Chris\",\n... \"StudentAge\" : 22,\n... \"StudentCountryName\": \"UK\"\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd2e518b64f4b851c3a13d9\")\n}\n> db.distinctOnMultipleFieldsDemo.insertOne(\n... {\n... \"StudentFirstName\" : \"David\",\n... \"StudentAge\" : 24,\n... \"StudentCountryName\": \"AUS\"\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd2e518b64f4b851c3a13da\")\n}" }, { "code": null, "e": 2357, "s": 2258, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2408, "s": 2357, "text": "> db.distinctOnMultipleFieldsDemo.find().pretty();" }, { "code": null, "e": 2449, "s": 2408, "text": "This will produce the following output −" }, { "code": null, "e": 3008, "s": 2449, "text": "{\n \"_id\" : ObjectId(\"5cd2e518b64f4b851c3a13d7\"),\n \"StudentFirstName\" : \"Chris\",\n \"StudentAge\" : 21,\n \"StudentCountryName\" : \"US\"\n}\n{\n \"_id\" : ObjectId(\"5cd2e518b64f4b851c3a13d8\"),\n \"StudentFirstName\" : \"Robert\",\n \"StudentAge\" : 21,\n \"StudentCountryName\" : \"AUS\"\n}\n{\n \"_id\" : ObjectId(\"5cd2e518b64f4b851c3a13d9\"),\n \"StudentFirstName\" : \"Chris\",\n \"StudentAge\" : 22,\n \"StudentCountryName\" : \"UK\"\n}\n{\n \"_id\" : ObjectId(\"5cd2e518b64f4b851c3a13da\"),\n \"StudentFirstName\" : \"David\",\n \"StudentAge\" : 24,\n \"StudentCountryName\" : \"AUS\"\n}" }, { "code": null, "e": 3083, "s": 3008, "text": "Following is the query to perform distinct on multiple fields in MongoDB −" }, { "code": null, "e": 3393, "s": 3083, "text": "> db.distinctOnMultipleFieldsDemo.aggregate([\n... {\n... $group:\n... {\n... _id:0,\n... StudentFirstName: {$addToSet: '$StudentFirstName'},\n... StudentAge: {$addToSet: '$StudentAge'},\n... StudentCountryName: {$addToSet: '$StudentCountryName'},\n... }}\n... ]);" }, { "code": null, "e": 3434, "s": 3393, "text": "This will produce the following output −" }, { "code": null, "e": 3578, "s": 3434, "text": "{ \"_id\" : 0, \"StudentFirstName\" : [ \"David\", \"Robert\", \"Chris\" ], \"StudentAge\" : [ 24, 22, 21 ], \"StudentCountryName\" : [ \"UK\", \"AUS\", \"US\" ] }" } ]
Character.isWhitespace() method in Java with examples
06 Dec, 2018 The java.lang.Character.isWhitespace() is an inbuilt method in a java that determines if the specified character (Unicode code point) is white space according to Java. A character is a Java whitespace character if and only if it satisfies one of the following criteria: It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space (‘\u00A0’, ‘\u2007’, ‘\u202F’). It is ‘\t’, U+0009 HORIZONTAL TABULATION. It is ‘\n’, U+000A LINE FEED. It is ‘\u000B’, U+000B VERTICAL TABULATION. It is ‘\f’, U+000C FORM FEED. It is ‘\r’, U+000D CARRIAGE RETURN. It is ‘\u001C’, U+001C FILE SEPARATOR. It is ‘\u001D’, U+001D GROUP SEPARATOR. It is ‘\u001E’, U+001E RECORD SEPARATOR. It is ‘\u001F’, U+001F UNIT SEPARATOR. Syntax: public static boolean isWhitespace(datatype character) Parameters: The function accepts one mandatory parameter character. This parameter can be of datatype int or char. It specifies the character to be tested. Return value: This method returns true if the character is a Java whitespace character, false otherwise. Below programs illustrate the Character.isWhitespace(char ch) method: Program 1: // Java program to illustrate the Character.isWhitespace()// method when the passed parameter is a characterimport java.lang.*; public class gfg { public static void main(String[] args) { // create 2 char primitives c1, c2 char c1 = '*', c2 = '\f'; boolean b1 = Character.isWhitespace(c1); boolean b2 = Character.isWhitespace(c2); String str1 = "c1 is a Java whitespace character is " + b1; String str2 = "c2 is a Java whitespace character is " + b2; // print b1, b2 values System.out.println(str1); System.out.println(str2); }} Output: c1 is a Java whitespace character is false c2 is a Java whitespace character is true Program 2: // Java program to demonstrate the Character.isWhitespace()// method when the passed parameter is a characterimport java.lang.*; public class gfg { public static void main(String[] args) { // create 2 char primitives c1, c2 char c1 = '/', c2 = '\f'; boolean b1 = Character.isWhitespace(c1); boolean b2 = Character.isWhitespace(c2); String str1 = "c1 is a Java whitespace character is " + b1; String str2 = "c2 is a Java whitespace character is " + b2; // print b1, b2 values System.out.println(str1); System.out.println(str2); }} Output: c1 is a Java whitespace character is false c2 is a Java whitespace character is true Program 3: When the parameter is of type int. // Java program to demonstrate the// Character.isWhitespace()// method when the passed parameter// is a characterimport java.lang.*; public class gfg { public static void main(String[] args) { // create 2 int primitives c1, c2 int c1 = 0x451c, c2 = 0x4abc; boolean b1 = Character.isWhitespace(c1); boolean b2 = Character.isWhitespace(c2); String str1 = "c1 represents Java whitespace character is " + b1; String str2 = "c2 represents Java whitespace character is " + b2; // print b1, b2 values System.out.println(str1); System.out.println(str2); }} Output: c1 represents Java whitespace character is false c2 represents Java whitespace character is false Program 4: When the parameter is of type int. // Java program to demonstrate the Character.isWhitespace()// method when the passed parameter is a characterimport java.lang.*; public class gfg { public static void main(String[] args) { // create 2 int primitives c1, c2 int c1 = 0x001c, c2 = 0x1bbc; boolean b1 = Character.isWhitespace(c1); boolean b2 = Character.isWhitespace(c2); String str1 = "c1 represents Java whitespace character is " + b1; String str2 = "c2 represents Java whitespace character is " + b2; // print b1, b2 values System.out.println(str1); System.out.println(str2); }} Output: c1 represents Java whitespace character is true c2 represents Java whitespace character is false Java-Character Java-Functions Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Multidimensional Arrays in Java Stream In Java Singleton Class in Java Set in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Dec, 2018" }, { "code": null, "e": 324, "s": 54, "text": "The java.lang.Character.isWhitespace() is an inbuilt method in a java that determines if the specified character (Unicode code point) is white space according to Java. A character is a Java whitespace character if and only if it satisfies one of the following criteria:" }, { "code": null, "e": 483, "s": 324, "text": "It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space (‘\\u00A0’, ‘\\u2007’, ‘\\u202F’)." }, { "code": null, "e": 525, "s": 483, "text": "It is ‘\\t’, U+0009 HORIZONTAL TABULATION." }, { "code": null, "e": 555, "s": 525, "text": "It is ‘\\n’, U+000A LINE FEED." }, { "code": null, "e": 599, "s": 555, "text": "It is ‘\\u000B’, U+000B VERTICAL TABULATION." }, { "code": null, "e": 629, "s": 599, "text": "It is ‘\\f’, U+000C FORM FEED." }, { "code": null, "e": 665, "s": 629, "text": "It is ‘\\r’, U+000D CARRIAGE RETURN." }, { "code": null, "e": 704, "s": 665, "text": "It is ‘\\u001C’, U+001C FILE SEPARATOR." }, { "code": null, "e": 744, "s": 704, "text": "It is ‘\\u001D’, U+001D GROUP SEPARATOR." }, { "code": null, "e": 785, "s": 744, "text": "It is ‘\\u001E’, U+001E RECORD SEPARATOR." }, { "code": null, "e": 824, "s": 785, "text": "It is ‘\\u001F’, U+001F UNIT SEPARATOR." }, { "code": null, "e": 832, "s": 824, "text": "Syntax:" }, { "code": null, "e": 888, "s": 832, "text": "public static boolean isWhitespace(datatype character)\n" }, { "code": null, "e": 1044, "s": 888, "text": "Parameters: The function accepts one mandatory parameter character. This parameter can be of datatype int or char. It specifies the character to be tested." }, { "code": null, "e": 1149, "s": 1044, "text": "Return value: This method returns true if the character is a Java whitespace character, false otherwise." }, { "code": null, "e": 1219, "s": 1149, "text": "Below programs illustrate the Character.isWhitespace(char ch) method:" }, { "code": null, "e": 1230, "s": 1219, "text": "Program 1:" }, { "code": "// Java program to illustrate the Character.isWhitespace()// method when the passed parameter is a characterimport java.lang.*; public class gfg { public static void main(String[] args) { // create 2 char primitives c1, c2 char c1 = '*', c2 = '\\f'; boolean b1 = Character.isWhitespace(c1); boolean b2 = Character.isWhitespace(c2); String str1 = \"c1 is a Java whitespace character is \" + b1; String str2 = \"c2 is a Java whitespace character is \" + b2; // print b1, b2 values System.out.println(str1); System.out.println(str2); }}", "e": 1842, "s": 1230, "text": null }, { "code": null, "e": 1850, "s": 1842, "text": "Output:" }, { "code": null, "e": 1936, "s": 1850, "text": "c1 is a Java whitespace character is false\nc2 is a Java whitespace character is true\n" }, { "code": null, "e": 1947, "s": 1936, "text": "Program 2:" }, { "code": "// Java program to demonstrate the Character.isWhitespace()// method when the passed parameter is a characterimport java.lang.*; public class gfg { public static void main(String[] args) { // create 2 char primitives c1, c2 char c1 = '/', c2 = '\\f'; boolean b1 = Character.isWhitespace(c1); boolean b2 = Character.isWhitespace(c2); String str1 = \"c1 is a Java whitespace character is \" + b1; String str2 = \"c2 is a Java whitespace character is \" + b2; // print b1, b2 values System.out.println(str1); System.out.println(str2); }}", "e": 2560, "s": 1947, "text": null }, { "code": null, "e": 2568, "s": 2560, "text": "Output:" }, { "code": null, "e": 2654, "s": 2568, "text": "c1 is a Java whitespace character is false\nc2 is a Java whitespace character is true\n" }, { "code": null, "e": 2700, "s": 2654, "text": "Program 3: When the parameter is of type int." }, { "code": "// Java program to demonstrate the// Character.isWhitespace()// method when the passed parameter// is a characterimport java.lang.*; public class gfg { public static void main(String[] args) { // create 2 int primitives c1, c2 int c1 = 0x451c, c2 = 0x4abc; boolean b1 = Character.isWhitespace(c1); boolean b2 = Character.isWhitespace(c2); String str1 = \"c1 represents Java whitespace character is \" + b1; String str2 = \"c2 represents Java whitespace character is \" + b2; // print b1, b2 values System.out.println(str1); System.out.println(str2); }}", "e": 3332, "s": 2700, "text": null }, { "code": null, "e": 3340, "s": 3332, "text": "Output:" }, { "code": null, "e": 3439, "s": 3340, "text": "c1 represents Java whitespace character is false\nc2 represents Java whitespace character is false\n" }, { "code": null, "e": 3485, "s": 3439, "text": "Program 4: When the parameter is of type int." }, { "code": "// Java program to demonstrate the Character.isWhitespace()// method when the passed parameter is a characterimport java.lang.*; public class gfg { public static void main(String[] args) { // create 2 int primitives c1, c2 int c1 = 0x001c, c2 = 0x1bbc; boolean b1 = Character.isWhitespace(c1); boolean b2 = Character.isWhitespace(c2); String str1 = \"c1 represents Java whitespace character is \" + b1; String str2 = \"c2 represents Java whitespace character is \" + b2; // print b1, b2 values System.out.println(str1); System.out.println(str2); }}", "e": 4113, "s": 3485, "text": null }, { "code": null, "e": 4121, "s": 4113, "text": "Output:" }, { "code": null, "e": 4219, "s": 4121, "text": "c1 represents Java whitespace character is true\nc2 represents Java whitespace character is false\n" }, { "code": null, "e": 4234, "s": 4219, "text": "Java-Character" }, { "code": null, "e": 4249, "s": 4234, "text": "Java-Functions" }, { "code": null, "e": 4267, "s": 4249, "text": "Java-lang package" }, { "code": null, "e": 4272, "s": 4267, "text": "Java" }, { "code": null, "e": 4277, "s": 4272, "text": "Java" }, { "code": null, "e": 4375, "s": 4277, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4426, "s": 4375, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4457, "s": 4426, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4476, "s": 4457, "text": "Interfaces in Java" }, { "code": null, "e": 4506, "s": 4476, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4524, "s": 4506, "text": "ArrayList in Java" }, { "code": null, "e": 4544, "s": 4524, "text": "Collections in Java" }, { "code": null, "e": 4576, "s": 4544, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 4591, "s": 4576, "text": "Stream In Java" }, { "code": null, "e": 4615, "s": 4591, "text": "Singleton Class in Java" } ]
What is use of %n in printf() ?
09 Oct, 2019 In C printf(), %n is a special format specifier which instead of printing something causes printf() to load the variable pointed by the corresponding argument with a value equal to the number of characters that have been printed by printf() before the occurrence of %n. #include<stdio.h> int main(){ int c; printf("geeks for %ngeeks ", &c); printf("%d", c); getchar(); return 0;} The above program prints “geeks for geeks 10”. The first printf() prints “geeks for geeks”. The second printf() prints 10 as there are 10 characters printed (the 10 characters are “geeks for “) before %n in first printf() and c is set to 10 by first printf(). Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-Input and Output Quiz C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Oct, 2019" }, { "code": null, "e": 322, "s": 52, "text": "In C printf(), %n is a special format specifier which instead of printing something causes printf() to load the variable pointed by the corresponding argument with a value equal to the number of characters that have been printed by printf() before the occurrence of %n." }, { "code": "#include<stdio.h> int main(){ int c; printf(\"geeks for %ngeeks \", &c); printf(\"%d\", c); getchar(); return 0;}", "e": 438, "s": 322, "text": null }, { "code": null, "e": 698, "s": 438, "text": "The above program prints “geeks for geeks 10”. The first printf() prints “geeks for geeks”. The second printf() prints 10 as there are 10 characters printed (the 10 characters are “geeks for “) before %n in first printf() and c is set to 10 by first printf()." }, { "code": null, "e": 823, "s": 698, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 847, "s": 823, "text": "C-Input and Output Quiz" }, { "code": null, "e": 858, "s": 847, "text": "C Language" } ]
jQuery UI Dialog title Option
12 Jan, 2021 The article explains the title option which is used to set the title in the dialog box. By default, its value is null. Syntax: $( ".selector" ).dialog({ title : "title" }); Approach: First, add jQuery UI scripts needed for your project. <link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel=”stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script> Example: HTML <!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script src= "https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <script> $(function () { $("#gfg").dialog({ autoOpen: false, title: "GeeksforGeeks" }); $("#geeks").click(function () { $("#gfg").dialog("open"); }); }); </script></head> <body> <div id="gfg"> Jquery UI| resizable dialog option </div> <button id="geeks">Open Dialog</button></body> </html> Output: jQuery-UI HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jan, 2021" }, { "code": null, "e": 147, "s": 28, "text": "The article explains the title option which is used to set the title in the dialog box. By default, its value is null." }, { "code": null, "e": 155, "s": 147, "text": "Syntax:" }, { "code": null, "e": 205, "s": 155, "text": "$( \".selector\" ).dialog({\n title : \"title\"\n});" }, { "code": null, "e": 269, "s": 205, "text": "Approach: First, add jQuery UI scripts needed for your project." }, { "code": null, "e": 508, "s": 269, "text": "<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel=”stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>" }, { "code": null, "e": 517, "s": 508, "text": "Example:" }, { "code": null, "e": 522, "s": 517, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link href=\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\"> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"></script> <script src= \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <script> $(function () { $(\"#gfg\").dialog({ autoOpen: false, title: \"GeeksforGeeks\" }); $(\"#geeks\").click(function () { $(\"#gfg\").dialog(\"open\"); }); }); </script></head> <body> <div id=\"gfg\"> Jquery UI| resizable dialog option </div> <button id=\"geeks\">Open Dialog</button></body> </html>", "e": 1276, "s": 522, "text": null }, { "code": null, "e": 1284, "s": 1276, "text": "Output:" }, { "code": null, "e": 1294, "s": 1284, "text": "jQuery-UI" }, { "code": null, "e": 1299, "s": 1294, "text": "HTML" }, { "code": null, "e": 1306, "s": 1299, "text": "JQuery" }, { "code": null, "e": 1323, "s": 1306, "text": "Web Technologies" }, { "code": null, "e": 1328, "s": 1323, "text": "HTML" } ]
JavaScript URIError | Malformed URI Sequence
19 Aug, 2020 This JavaScript exception malformed URI sequence occurs if the encoding or decoding of URI is unsuccessful. Message: URIError: The URI to be encoded contains invalid character (Edge) URIError: malformed URI sequence (Firefox) URIError: URI malformed (Chrome) Error Type: URIError Cause of the Error: This error is thrown as somewhere in the code, the URI encoding or decoding is unsuccessful. Example 1: In this example, the value passed is not acceptable, therefore the error has occurred. HTML <script> // Error here encodeURI('\uD810');</script> Output: URIError: URI malformed Example 2: In this example, the value passed is not acceptable, therefore the error has occurred. HTML <script> // Error here decodeURIComponent('%E0%B4%A'); </script> Output: URIError: URI malformed JavaScript-Errors JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Aug, 2020" }, { "code": null, "e": 136, "s": 28, "text": "This JavaScript exception malformed URI sequence occurs if the encoding or decoding of URI is unsuccessful." }, { "code": null, "e": 145, "s": 136, "text": "Message:" }, { "code": null, "e": 288, "s": 145, "text": "URIError: The URI to be encoded contains invalid character (Edge)\nURIError: malformed URI sequence (Firefox)\nURIError: URI malformed (Chrome)\n" }, { "code": null, "e": 300, "s": 288, "text": "Error Type:" }, { "code": null, "e": 310, "s": 300, "text": "URIError\n" }, { "code": null, "e": 423, "s": 310, "text": "Cause of the Error: This error is thrown as somewhere in the code, the URI encoding or decoding is unsuccessful." }, { "code": null, "e": 521, "s": 423, "text": "Example 1: In this example, the value passed is not acceptable, therefore the error has occurred." }, { "code": null, "e": 526, "s": 521, "text": "HTML" }, { "code": "<script> // Error here encodeURI('\\uD810');</script>", "e": 581, "s": 526, "text": null }, { "code": null, "e": 589, "s": 581, "text": "Output:" }, { "code": null, "e": 613, "s": 589, "text": "URIError: URI malformed" }, { "code": null, "e": 711, "s": 613, "text": "Example 2: In this example, the value passed is not acceptable, therefore the error has occurred." }, { "code": null, "e": 716, "s": 711, "text": "HTML" }, { "code": "<script> // Error here decodeURIComponent('%E0%B4%A'); </script>", "e": 783, "s": 716, "text": null }, { "code": null, "e": 791, "s": 783, "text": "Output:" }, { "code": null, "e": 815, "s": 791, "text": "URIError: URI malformed" }, { "code": null, "e": 833, "s": 815, "text": "JavaScript-Errors" }, { "code": null, "e": 844, "s": 833, "text": "JavaScript" }, { "code": null, "e": 861, "s": 844, "text": "Web Technologies" } ]
Find Duplicates of array using bit array
08 Jul, 2022 You have an array of N numbers, where N is at most 32,000. The array may have duplicate entries and you do not know what N is. With only 4 Kilobytes of memory available, how would print all duplicate elements in the array ?. Examples: Input : arr[] = {1, 5, 1, 10, 12, 10} Output : 1 10 1 and 10 appear more than once in given array. Input : arr[] = {50, 40, 50} Output : 50 Asked In: Amazon We have 4 Kilobytes of memory which means we can address up to 8 * 4 * 210 bits. Note that 32 * 210 bits is greater than 32000. We can create a bit with 32000 bits, where each bit represents one integer. Note: If you need to create a bit with more than 32000 bits, then you can create easily more and more than 32000; Using this bit vector, we can then iterate through the array, flagging each element v by setting bit v to 1. When we come across a duplicate element, we print it. Below is the implementation of the idea. Implementation: C++ Java Python3 C# Javascript // C++ program to print all Duplicates in array#include <bits/stdc++.h>using namespace std; // A class to represent an array of bits using// array of integersclass BitArray{ int *arr; public: BitArray() {} // Constructor BitArray(int n) { // Divide by 32. To store n bits, we need // n/32 + 1 integers (Assuming int is stored // using 32 bits) arr = new int[(n >> 5) + 1]; } // Get value of a bit at given position bool get(int pos) { // Divide by 32 to find position of // integer. int index = (pos >> 5); // Now find bit number in arr[index] int bitNo = (pos & 0x1F); // Find value of given bit number in // arr[index] return (arr[index] & (1 << bitNo)) != 0; } // Sets a bit at given position void set(int pos) { // Find index of bit position int index = (pos >> 5); // Set bit number in arr[index] int bitNo = (pos & 0x1F); arr[index] |= (1 << bitNo); } // Main function to print all Duplicates void checkDuplicates(int arr[], int n) { // create a bit with 32000 bits BitArray ba = BitArray(320000); // Traverse array elements for (int i = 0; i < n; i++) { // Index in bit array int num = arr[i]; // If num is already present in bit array if (ba.get(num)) cout << num << " "; // Else insert num else ba.set(num); } }}; // Driver codeint main(){ int arr[] = {1, 5, 1, 10, 12, 10}; int n = sizeof(arr) / sizeof(arr[0]); BitArray obj = BitArray(); obj.checkDuplicates(arr, n); return 0;} // This code is contributed by// sanjeev2552 // Java program to print all Duplicates in arrayimport java.util.*;import java.lang.*;import java.io.*; // A class to represent array of bits using// array of integersclass BitArray{ int[] arr; // Constructor public BitArray(int n) { // Divide by 32. To store n bits, we need // n/32 + 1 integers (Assuming int is stored // using 32 bits) arr = new int[(n>>5) + 1]; } // Get value of a bit at given position boolean get(int pos) { // Divide by 32 to find position of // integer. int index = (pos >> 5); // Now find bit number in arr[index] int bitNo = (pos & 0x1F); // Find value of given bit number in // arr[index] return (arr[index] & (1 << bitNo)) != 0; } // Sets a bit at given position void set(int pos) { // Find index of bit position int index = (pos >> 5); // Set bit number in arr[index] int bitNo = (pos & 0x1F); arr[index] |= (1 << bitNo); } // Main function to print all Duplicates static void checkDuplicates(int[] arr) { // create a bit with 32000 bits BitArray ba = new BitArray(320000); // Traverse array elements for (int i=0; i<arr.length; i++) { // Index in bit array int num = arr[i] - 1; // If num is already present in bit array if (ba.get(num)) System.out.print(num +" "); // Else insert num else ba.set(num); } } // Driver code public static void main(String[] args) throws java.lang.Exception { int[] arr = {1, 5, 1, 10, 12, 10}; checkDuplicates(arr); }} # Python3 program to print all Duplicates in array # A class to represent array of bits using# array of integersclass BitArray: # Constructor def __init__(self, n): # Divide by 32. To store n bits, we need # n/32 + 1 integers (Assuming int is stored # using 32 bits) self.arr = [0] * ((n >> 5) + 1) # Get value of a bit at given position def get(self, pos): # Divide by 32 to find position of # integer. self.index = pos >> 5 # Now find bit number in arr[index] self.bitNo = pos & 0x1F # Find value of given bit number in # arr[index] return (self.arr[self.index] & (1 << self.bitNo)) != 0 # Sets a bit at given position def set(self, pos): # Find index of bit position self.index = pos >> 5 # Set bit number in arr[index] self.bitNo = pos & 0x1F self.arr[self.index] |= (1 << self.bitNo) # Main function to print all Duplicatesdef checkDuplicates(arr): # create a bit with 32000 bits ba = BitArray(320000) # Traverse array elements for i in range(len(arr)): # Index in bit array num = arr[i] # If num is already present in bit array if ba.get(num): print(num, end = " ") # Else insert num else: ba.set(num) # Driver Codeif __name__ == "__main__": arr = [1, 5, 1, 10, 12, 10] checkDuplicates(arr) # This code is contributed by# sanjeev2552 // C# program to print all Duplicates in array // A class to represent array of bits using// array of integersusing System; class BitArray{ int[] arr; // Constructor public BitArray(int n) { // Divide by 32. To store n bits, we need // n/32 + 1 integers (Assuming int is stored // using 32 bits) arr = new int[(int)(n >> 5) + 1]; } // Get value of a bit at given position bool get(int pos) { // Divide by 32 to find position of // integer. int index = (pos >> 5); // Now find bit number in arr[index] int bitNo = (pos & 0x1F); // Find value of given bit number in // arr[index] return (arr[index] & (1 << bitNo)) != 0; } // Sets a bit at given position void set(int pos) { // Find index of bit position int index = (pos >> 5); // Set bit number in arr[index] int bitNo = (pos & 0x1F); arr[index] |= (1 << bitNo); } // Main function to print all Duplicates static void checkDuplicates(int[] arr) { // create a bit with 32000 bits BitArray ba = new BitArray(320000); // Traverse array elements for (int i = 0; i < arr.Length; i++) { // Index in bit array int num = arr[i]; // If num is already present in bit array if (ba.get(num)) Console.Write(num + " "); // Else insert num else ba.set(num); } } // Driver code public static void Main() { int[] arr = {1, 5, 1, 10, 12, 10}; checkDuplicates(arr); }} // This code is contributed by Rajput-Ji // JavaScript program to print all Duplicates in array // A class to represent array of bits using// array of integers class BitArray { // Constructor constructor(n) { // Divide by 32. To store n bits, we need // n/32 + 1 integers (Assuming int is stored // using 32 bits) this.arr = new Array((n >> 5) + 1); } // Get value of a bit at given position get(pos) { // Divide by 32 to find position of // integer. var index = (pos >> 5); // Now find bit number in arr[index] var bitNo = (pos & 0x1F); // Find value of given bit number in // arr[index] var arrCopy = this.arr return (arrCopy[index] & (1 << bitNo)) != 0; } // Sets a bit at given position set(pos) { // Find index of bit position var index = (pos >> 5); // Set bit number in arr[index] var bitNo = (pos & 0x1F); var arr1 = this.arr; arr1[index] = arr1[index] | (1 << bitNo); this.arr = arr1; }} // Main function to print all Duplicatesfunction checkDuplicates(arr){ // create a bit with 32000 bits var ba = new BitArray(320000); // Traverse array elements for (var i = 0; i < arr.length; i++) { // Index in bit array var num = arr[i]; // If num is already present in bit array if (ba.get(num)) console.log(num); // Else insert num else ba.set(num); }} // Driver codevar a = [ 1, 5, 1, 10, 12, 10 ];checkDuplicates(a); // This code is contributed by phasing17. 1 10 This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Rajput-Ji sanjeev2552 raghavgehlot682 phasing17 hardikkoriintern Arrays Bit Magic Arrays Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 278, "s": 52, "text": "You have an array of N numbers, where N is at most 32,000. The array may have duplicate entries and you do not know what N is. With only 4 Kilobytes of memory available, how would print all duplicate elements in the array ?. " }, { "code": null, "e": 288, "s": 278, "text": "Examples:" }, { "code": null, "e": 429, "s": 288, "text": "Input : arr[] = {1, 5, 1, 10, 12, 10}\nOutput : 1 10\n1 and 10 appear more than once in given\narray.\n\nInput : arr[] = {50, 40, 50}\nOutput : 50" }, { "code": null, "e": 447, "s": 429, "text": "Asked In: Amazon " }, { "code": null, "e": 970, "s": 447, "text": "We have 4 Kilobytes of memory which means we can address up to 8 * 4 * 210 bits. Note that 32 * 210 bits is greater than 32000. We can create a bit with 32000 bits, where each bit represents one integer. Note: If you need to create a bit with more than 32000 bits, then you can create easily more and more than 32000; Using this bit vector, we can then iterate through the array, flagging each element v by setting bit v to 1. When we come across a duplicate element, we print it. Below is the implementation of the idea. " }, { "code": null, "e": 986, "s": 970, "text": "Implementation:" }, { "code": null, "e": 990, "s": 986, "text": "C++" }, { "code": null, "e": 995, "s": 990, "text": "Java" }, { "code": null, "e": 1003, "s": 995, "text": "Python3" }, { "code": null, "e": 1006, "s": 1003, "text": "C#" }, { "code": null, "e": 1017, "s": 1006, "text": "Javascript" }, { "code": "// C++ program to print all Duplicates in array#include <bits/stdc++.h>using namespace std; // A class to represent an array of bits using// array of integersclass BitArray{ int *arr; public: BitArray() {} // Constructor BitArray(int n) { // Divide by 32. To store n bits, we need // n/32 + 1 integers (Assuming int is stored // using 32 bits) arr = new int[(n >> 5) + 1]; } // Get value of a bit at given position bool get(int pos) { // Divide by 32 to find position of // integer. int index = (pos >> 5); // Now find bit number in arr[index] int bitNo = (pos & 0x1F); // Find value of given bit number in // arr[index] return (arr[index] & (1 << bitNo)) != 0; } // Sets a bit at given position void set(int pos) { // Find index of bit position int index = (pos >> 5); // Set bit number in arr[index] int bitNo = (pos & 0x1F); arr[index] |= (1 << bitNo); } // Main function to print all Duplicates void checkDuplicates(int arr[], int n) { // create a bit with 32000 bits BitArray ba = BitArray(320000); // Traverse array elements for (int i = 0; i < n; i++) { // Index in bit array int num = arr[i]; // If num is already present in bit array if (ba.get(num)) cout << num << \" \"; // Else insert num else ba.set(num); } }}; // Driver codeint main(){ int arr[] = {1, 5, 1, 10, 12, 10}; int n = sizeof(arr) / sizeof(arr[0]); BitArray obj = BitArray(); obj.checkDuplicates(arr, n); return 0;} // This code is contributed by// sanjeev2552", "e": 2791, "s": 1017, "text": null }, { "code": "// Java program to print all Duplicates in arrayimport java.util.*;import java.lang.*;import java.io.*; // A class to represent array of bits using// array of integersclass BitArray{ int[] arr; // Constructor public BitArray(int n) { // Divide by 32. To store n bits, we need // n/32 + 1 integers (Assuming int is stored // using 32 bits) arr = new int[(n>>5) + 1]; } // Get value of a bit at given position boolean get(int pos) { // Divide by 32 to find position of // integer. int index = (pos >> 5); // Now find bit number in arr[index] int bitNo = (pos & 0x1F); // Find value of given bit number in // arr[index] return (arr[index] & (1 << bitNo)) != 0; } // Sets a bit at given position void set(int pos) { // Find index of bit position int index = (pos >> 5); // Set bit number in arr[index] int bitNo = (pos & 0x1F); arr[index] |= (1 << bitNo); } // Main function to print all Duplicates static void checkDuplicates(int[] arr) { // create a bit with 32000 bits BitArray ba = new BitArray(320000); // Traverse array elements for (int i=0; i<arr.length; i++) { // Index in bit array int num = arr[i] - 1; // If num is already present in bit array if (ba.get(num)) System.out.print(num +\" \"); // Else insert num else ba.set(num); } } // Driver code public static void main(String[] args) throws java.lang.Exception { int[] arr = {1, 5, 1, 10, 12, 10}; checkDuplicates(arr); }}", "e": 4548, "s": 2791, "text": null }, { "code": "# Python3 program to print all Duplicates in array # A class to represent array of bits using# array of integersclass BitArray: # Constructor def __init__(self, n): # Divide by 32. To store n bits, we need # n/32 + 1 integers (Assuming int is stored # using 32 bits) self.arr = [0] * ((n >> 5) + 1) # Get value of a bit at given position def get(self, pos): # Divide by 32 to find position of # integer. self.index = pos >> 5 # Now find bit number in arr[index] self.bitNo = pos & 0x1F # Find value of given bit number in # arr[index] return (self.arr[self.index] & (1 << self.bitNo)) != 0 # Sets a bit at given position def set(self, pos): # Find index of bit position self.index = pos >> 5 # Set bit number in arr[index] self.bitNo = pos & 0x1F self.arr[self.index] |= (1 << self.bitNo) # Main function to print all Duplicatesdef checkDuplicates(arr): # create a bit with 32000 bits ba = BitArray(320000) # Traverse array elements for i in range(len(arr)): # Index in bit array num = arr[i] # If num is already present in bit array if ba.get(num): print(num, end = \" \") # Else insert num else: ba.set(num) # Driver Codeif __name__ == \"__main__\": arr = [1, 5, 1, 10, 12, 10] checkDuplicates(arr) # This code is contributed by# sanjeev2552", "e": 6039, "s": 4548, "text": null }, { "code": "// C# program to print all Duplicates in array // A class to represent array of bits using// array of integersusing System; class BitArray{ int[] arr; // Constructor public BitArray(int n) { // Divide by 32. To store n bits, we need // n/32 + 1 integers (Assuming int is stored // using 32 bits) arr = new int[(int)(n >> 5) + 1]; } // Get value of a bit at given position bool get(int pos) { // Divide by 32 to find position of // integer. int index = (pos >> 5); // Now find bit number in arr[index] int bitNo = (pos & 0x1F); // Find value of given bit number in // arr[index] return (arr[index] & (1 << bitNo)) != 0; } // Sets a bit at given position void set(int pos) { // Find index of bit position int index = (pos >> 5); // Set bit number in arr[index] int bitNo = (pos & 0x1F); arr[index] |= (1 << bitNo); } // Main function to print all Duplicates static void checkDuplicates(int[] arr) { // create a bit with 32000 bits BitArray ba = new BitArray(320000); // Traverse array elements for (int i = 0; i < arr.Length; i++) { // Index in bit array int num = arr[i]; // If num is already present in bit array if (ba.get(num)) Console.Write(num + \" \"); // Else insert num else ba.set(num); } } // Driver code public static void Main() { int[] arr = {1, 5, 1, 10, 12, 10}; checkDuplicates(arr); }} // This code is contributed by Rajput-Ji", "e": 7726, "s": 6039, "text": null }, { "code": "// JavaScript program to print all Duplicates in array // A class to represent array of bits using// array of integers class BitArray { // Constructor constructor(n) { // Divide by 32. To store n bits, we need // n/32 + 1 integers (Assuming int is stored // using 32 bits) this.arr = new Array((n >> 5) + 1); } // Get value of a bit at given position get(pos) { // Divide by 32 to find position of // integer. var index = (pos >> 5); // Now find bit number in arr[index] var bitNo = (pos & 0x1F); // Find value of given bit number in // arr[index] var arrCopy = this.arr return (arrCopy[index] & (1 << bitNo)) != 0; } // Sets a bit at given position set(pos) { // Find index of bit position var index = (pos >> 5); // Set bit number in arr[index] var bitNo = (pos & 0x1F); var arr1 = this.arr; arr1[index] = arr1[index] | (1 << bitNo); this.arr = arr1; }} // Main function to print all Duplicatesfunction checkDuplicates(arr){ // create a bit with 32000 bits var ba = new BitArray(320000); // Traverse array elements for (var i = 0; i < arr.length; i++) { // Index in bit array var num = arr[i]; // If num is already present in bit array if (ba.get(num)) console.log(num); // Else insert num else ba.set(num); }} // Driver codevar a = [ 1, 5, 1, 10, 12, 10 ];checkDuplicates(a); // This code is contributed by phasing17.", "e": 9360, "s": 7726, "text": null }, { "code": null, "e": 9366, "s": 9360, "text": "1 10 " }, { "code": null, "e": 9793, "s": 9366, "text": "This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 9803, "s": 9793, "text": "Rajput-Ji" }, { "code": null, "e": 9815, "s": 9803, "text": "sanjeev2552" }, { "code": null, "e": 9831, "s": 9815, "text": "raghavgehlot682" }, { "code": null, "e": 9841, "s": 9831, "text": "phasing17" }, { "code": null, "e": 9858, "s": 9841, "text": "hardikkoriintern" }, { "code": null, "e": 9865, "s": 9858, "text": "Arrays" }, { "code": null, "e": 9875, "s": 9865, "text": "Bit Magic" }, { "code": null, "e": 9882, "s": 9875, "text": "Arrays" }, { "code": null, "e": 9892, "s": 9882, "text": "Bit Magic" } ]
pstree Command in Linux with Examples
03 Jun, 2020 Pstree command in Linux that shows the running processes as a tree which is a more convenient way to display the processes hierarchy and makes the output more visually appealing. The root of the tree is either init or the process with the given pid. Pstree can also be installed in other Unix systems. Syntax: pstree [options] [pid or username] 1. To display process tree pstree It produces process-related information in output. 2. To include command line arguments in output pstree -a We do this by using the “-a” command line option. This command now displays command line options for some processes. 3. To display PIDs pstree -p To display PIDs for each process name, we use “-p” option. 4. To force pstree to expand identical subtrees in output. pstree -c By default, the pstree command merges identical branches by putting them in square brackets and prefixing them with the repetition count. But we can also force the tool to expand identical trees, by using the “-c” command-line option. 5. To sort processes pstree -n If we want to sort processes with the same ancestor by PID instead of by name i.e. numeric sort, we use “-n” option. 6. To see who is the owner/user of a process pstree -u If we want to find out the owner of a process in parenthesis, use the “-u” option. 7. To highlight the current process or any other process pstree -h To highlight the current process and its ancestors use “-h” option. It highlights the specified process (by name/pid) 8. To show process group IDs in output pstree -g We can see that process group IDs are shown as decimal numbers in parentheses after each process name. 9. To make pstree display process tree specific to a user. pstree khushi It we want to display all process trees rooted at processes owned by a specific user, for this, we have to pass the name of that user as input to the command. 10. To display version information. pstree -V When we want to display version information we use “-V” option. linux-command Linux-system-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples Introduction to Linux Operating System chown command in Linux with Examples chmod command in Linux with examples SED command in Linux | Set 2 nohup Command in Linux with Examples Array Basics in Shell Scripting | Set 1 How to Permanently Disable Swap in Linux? mv command in Linux with examples
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jun, 2020" }, { "code": null, "e": 356, "s": 54, "text": "Pstree command in Linux that shows the running processes as a tree which is a more convenient way to display the processes hierarchy and makes the output more visually appealing. The root of the tree is either init or the process with the given pid. Pstree can also be installed in other Unix systems." }, { "code": null, "e": 364, "s": 356, "text": "Syntax:" }, { "code": null, "e": 399, "s": 364, "text": "pstree [options] [pid or username]" }, { "code": null, "e": 426, "s": 399, "text": "1. To display process tree" }, { "code": null, "e": 433, "s": 426, "text": "pstree" }, { "code": null, "e": 484, "s": 433, "text": "It produces process-related information in output." }, { "code": null, "e": 531, "s": 484, "text": "2. To include command line arguments in output" }, { "code": null, "e": 541, "s": 531, "text": "pstree -a" }, { "code": null, "e": 658, "s": 541, "text": "We do this by using the “-a” command line option. This command now displays command line options for some processes." }, { "code": null, "e": 677, "s": 658, "text": "3. To display PIDs" }, { "code": null, "e": 687, "s": 677, "text": "pstree -p" }, { "code": null, "e": 746, "s": 687, "text": "To display PIDs for each process name, we use “-p” option." }, { "code": null, "e": 805, "s": 746, "text": "4. To force pstree to expand identical subtrees in output." }, { "code": null, "e": 815, "s": 805, "text": "pstree -c" }, { "code": null, "e": 1050, "s": 815, "text": "By default, the pstree command merges identical branches by putting them in square brackets and prefixing them with the repetition count. But we can also force the tool to expand identical trees, by using the “-c” command-line option." }, { "code": null, "e": 1071, "s": 1050, "text": "5. To sort processes" }, { "code": null, "e": 1081, "s": 1071, "text": "pstree -n" }, { "code": null, "e": 1198, "s": 1081, "text": "If we want to sort processes with the same ancestor by PID instead of by name i.e. numeric sort, we use “-n” option." }, { "code": null, "e": 1243, "s": 1198, "text": "6. To see who is the owner/user of a process" }, { "code": null, "e": 1253, "s": 1243, "text": "pstree -u" }, { "code": null, "e": 1336, "s": 1253, "text": "If we want to find out the owner of a process in parenthesis, use the “-u” option." }, { "code": null, "e": 1393, "s": 1336, "text": "7. To highlight the current process or any other process" }, { "code": null, "e": 1403, "s": 1393, "text": "pstree -h" }, { "code": null, "e": 1521, "s": 1403, "text": "To highlight the current process and its ancestors use “-h” option. It highlights the specified process (by name/pid)" }, { "code": null, "e": 1560, "s": 1521, "text": "8. To show process group IDs in output" }, { "code": null, "e": 1570, "s": 1560, "text": "pstree -g" }, { "code": null, "e": 1673, "s": 1570, "text": "We can see that process group IDs are shown as decimal numbers in parentheses after each process name." }, { "code": null, "e": 1732, "s": 1673, "text": "9. To make pstree display process tree specific to a user." }, { "code": null, "e": 1746, "s": 1732, "text": "pstree khushi" }, { "code": null, "e": 1905, "s": 1746, "text": "It we want to display all process trees rooted at processes owned by a specific user, for this, we have to pass the name of that user as input to the command." }, { "code": null, "e": 1941, "s": 1905, "text": "10. To display version information." }, { "code": null, "e": 1951, "s": 1941, "text": "pstree -V" }, { "code": null, "e": 2015, "s": 1951, "text": "When we want to display version information we use “-V” option." }, { "code": null, "e": 2029, "s": 2015, "text": "linux-command" }, { "code": null, "e": 2051, "s": 2029, "text": "Linux-system-commands" }, { "code": null, "e": 2062, "s": 2051, "text": "Linux-Unix" }, { "code": null, "e": 2160, "s": 2062, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2186, "s": 2160, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2221, "s": 2186, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2260, "s": 2221, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 2297, "s": 2260, "text": "chown command in Linux with Examples" }, { "code": null, "e": 2334, "s": 2297, "text": "chmod command in Linux with examples" }, { "code": null, "e": 2363, "s": 2334, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 2400, "s": 2363, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 2440, "s": 2400, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 2482, "s": 2440, "text": "How to Permanently Disable Swap in Linux?" } ]
ROUND() Function in SQL Server
30 Dec, 2020 ROUND() function :This function in SQL Server is used to round off a specified number to a specified decimal places. Features : This function is used to round off a specified number to a specified decimal places. This function accepts only all type of numbers i.e., positive, negative, zero. This function accepts fraction numbers. This function always returns the number after rounded to the specified decimal places. Syntax : ROUND(number, decimals, operation) Parameter :This method accepts three parameters as given below : number : Specified number to be rounded off. decimals : Specified number of decimal places up to which the given number is to be rounded. operation : This is optional parameter. If it’s value is 0, it rounds the result to the number of decimal. If another value than 0, it truncates the result to the number of decimals. Default value is 0 Returns :It returns the number after rounded to the specified places. Example-1 :Getting a rounded number up to next two decimal places. SELECT ROUND(12.3456, 2); Output : 12.3500 Example-2 :Getting the number to the next two decimal places with the operational parameter 1 which says only to truncate the specified number (-23.456) to the given decimal places i, e., 2. SELECT ROUND(12.3456, 2, 1); Output : 12.3400 Example-3 :Using ROUND() function with a variable and getting the rounded number to -2 decimal place. DECLARE @Parameter_Value FLOAT; SET @Parameter_Value = -2; SELECT ROUND(123.4567, @Parameter_Value); Output : 100.0000 Example-4 : Getting the rounded number to the zero number of decimal places. SELECT ROUND(123.467, 0); Output : 123.000 Example-5 :Using ROUND() function with variables and getting the rounded number to the 2 decimal places. DECLARE @Number_Value FLOAT; DECLARE @Decimals_Value INT; SET @Number_Value = -23.456; SET @Decimals_Value = 2; SELECT ROUND(@Number_Value, @Decimals_Value); Output : -23.460000000000001 Example-6 :Getting the number to the next two decimal places with the operational parameter 1 which says only to truncate the specified number (-23.456) to the given decimal places i.e., 2. SELECT ROUND(-23.456, 2, 1); Output : -23.450 Application :This function is used to return the number after rounded to the specified places. DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Dec, 2020" }, { "code": null, "e": 145, "s": 28, "text": "ROUND() function :This function in SQL Server is used to round off a specified number to a specified decimal places." }, { "code": null, "e": 156, "s": 145, "text": "Features :" }, { "code": null, "e": 241, "s": 156, "text": "This function is used to round off a specified number to a specified decimal places." }, { "code": null, "e": 320, "s": 241, "text": "This function accepts only all type of numbers i.e., positive, negative, zero." }, { "code": null, "e": 360, "s": 320, "text": "This function accepts fraction numbers." }, { "code": null, "e": 447, "s": 360, "text": "This function always returns the number after rounded to the specified decimal places." }, { "code": null, "e": 456, "s": 447, "text": "Syntax :" }, { "code": null, "e": 491, "s": 456, "text": "ROUND(number, decimals, operation)" }, { "code": null, "e": 556, "s": 491, "text": "Parameter :This method accepts three parameters as given below :" }, { "code": null, "e": 601, "s": 556, "text": "number : Specified number to be rounded off." }, { "code": null, "e": 694, "s": 601, "text": "decimals : Specified number of decimal places up to which the given number is to be rounded." }, { "code": null, "e": 896, "s": 694, "text": "operation : This is optional parameter. If it’s value is 0, it rounds the result to the number of decimal. If another value than 0, it truncates the result to the number of decimals. Default value is 0" }, { "code": null, "e": 966, "s": 896, "text": "Returns :It returns the number after rounded to the specified places." }, { "code": null, "e": 1033, "s": 966, "text": "Example-1 :Getting a rounded number up to next two decimal places." }, { "code": null, "e": 1059, "s": 1033, "text": "SELECT ROUND(12.3456, 2);" }, { "code": null, "e": 1068, "s": 1059, "text": "Output :" }, { "code": null, "e": 1076, "s": 1068, "text": "12.3500" }, { "code": null, "e": 1267, "s": 1076, "text": "Example-2 :Getting the number to the next two decimal places with the operational parameter 1 which says only to truncate the specified number (-23.456) to the given decimal places i, e., 2." }, { "code": null, "e": 1296, "s": 1267, "text": "SELECT ROUND(12.3456, 2, 1);" }, { "code": null, "e": 1305, "s": 1296, "text": "Output :" }, { "code": null, "e": 1313, "s": 1305, "text": "12.3400" }, { "code": null, "e": 1415, "s": 1313, "text": "Example-3 :Using ROUND() function with a variable and getting the rounded number to -2 decimal place." }, { "code": null, "e": 1517, "s": 1415, "text": "DECLARE @Parameter_Value FLOAT;\nSET @Parameter_Value = -2;\nSELECT ROUND(123.4567, @Parameter_Value);\n" }, { "code": null, "e": 1526, "s": 1517, "text": "Output :" }, { "code": null, "e": 1535, "s": 1526, "text": "100.0000" }, { "code": null, "e": 1547, "s": 1535, "text": "Example-4 :" }, { "code": null, "e": 1612, "s": 1547, "text": "Getting the rounded number to the zero number of decimal places." }, { "code": null, "e": 1638, "s": 1612, "text": "SELECT ROUND(123.467, 0);" }, { "code": null, "e": 1647, "s": 1638, "text": "Output :" }, { "code": null, "e": 1655, "s": 1647, "text": "123.000" }, { "code": null, "e": 1760, "s": 1655, "text": "Example-5 :Using ROUND() function with variables and getting the rounded number to the 2 decimal places." }, { "code": null, "e": 1919, "s": 1760, "text": "DECLARE @Number_Value FLOAT;\nDECLARE @Decimals_Value INT;\nSET @Number_Value = -23.456;\nSET @Decimals_Value = 2;\nSELECT ROUND(@Number_Value, @Decimals_Value);\n" }, { "code": null, "e": 1928, "s": 1919, "text": "Output :" }, { "code": null, "e": 1948, "s": 1928, "text": "-23.460000000000001" }, { "code": null, "e": 2138, "s": 1948, "text": "Example-6 :Getting the number to the next two decimal places with the operational parameter 1 which says only to truncate the specified number (-23.456) to the given decimal places i.e., 2." }, { "code": null, "e": 2167, "s": 2138, "text": "SELECT ROUND(-23.456, 2, 1);" }, { "code": null, "e": 2176, "s": 2167, "text": "Output :" }, { "code": null, "e": 2184, "s": 2176, "text": "-23.450" }, { "code": null, "e": 2279, "s": 2184, "text": "Application :This function is used to return the number after rounded to the specified places." }, { "code": null, "e": 2288, "s": 2279, "text": "DBMS-SQL" }, { "code": null, "e": 2299, "s": 2288, "text": "SQL-Server" }, { "code": null, "e": 2303, "s": 2299, "text": "SQL" }, { "code": null, "e": 2307, "s": 2303, "text": "SQL" } ]
Double factorial - GeeksforGeeks
29 Apr, 2021 Double factorial of a non-negative integer n, is the product of all the integers from 1 to n that have the same parity (odd or even) as n. It is also called as semifactorial of a number and is denoted by !!. For example, double factorial of 9 is 9*7*5*3*1 which is 945. Note that, a consequence of this definition is 0!! = 1.Examples: Input: 6 Output: 48 Note that 6*4*2 = 48 Input: 7 Output: 105 Note that 7*5*3 = 105 For even n, the double factorial is:For odd n, the double factorial is: Recursive Solution: Double factorial can be calculated using following recursive formula. n!! = n * (n-2)!! n!! = 1 if n = 0 or n = 1 Following is the implementation of double factorial. C++ Java Python3 C# PHP Javascript #include<stdio.h> // function to find double factorial of given numberunsigned int doublefactorial(unsigned int n){ if (n == 0 || n==1) return 1; return n*doublefactorial(n-2);} int main(){ printf("Double factorial is %d", doublefactorial(5)); return 0;} import java.io.*; class GFG { // function to find double factorial // of given number static long doublefactorial(long n) { if (n == 0 || n==1) return 1; return n * doublefactorial(n - 2); } // Driver code static public void main (String[] args) { System.out.println("Double factorial" + " is " + doublefactorial(5)); }} // This code is contributed by anuj_67. # function to find double# factorial of given numberdef doublefactorial(n): if (n == 0 or n == 1): return 1; return n * doublefactorial(n - 2); # Driver Codeprint("Double factorial is", doublefactorial(5)); # This code is contributed# by Smitha using System; class GFG { // function to find double factorial // of given number static uint doublefactorial(uint n) { if (n == 0 || n==1) return 1; return n * doublefactorial(n - 2); } // Driver code static public void Main () { Console.WriteLine("Double factorial" + " is " + doublefactorial(5)); }} // This code is contributed by anuj_67. <?php// PHP code for// Double factorial // function return// double factorialfunction doublefactorial($n){ if ($n == 0 || $n==1) return 1; return $n * doublefactorial($n - 2);} // Driver Code echo "Double factorial is ", doublefactorial(5); // This code is contributed by Ajit.?> <script>// Javascript program to find double factorial of given number // function to find double factorial // of given number function doublefactorial(n) { if (n == 0 || n==1) return 1; return n * doublefactorial(n - 2); } // Driver code document.write("Double factorial" + " is " + doublefactorial(5)); // This code is contributed by susmitakundugoaldanga. </script> Output: Double factorial is 15 Iterative Solution: Double factorial can also be calculated iteratively as recursion can be costly for large numbers. C++ Java Python3 C# PHP Javascript #include<stdio.h> // function to find double factorial of given numberunsigned int doublefactorial(unsigned int n){ int res = 1; for (int i=n; i>=0; i=i-2) { if (i==0 || i==1) return res; else res *= i; }} int main(){ printf("Double factorial is %d", doublefactorial(5)); return 0;} // Java Program to find double factorial// of given numberimport java .io.*; class GFG { // function to find double factorial // of given number static int doublefactorial(int n) { int res = 1; for (int i = n; i >= 0; i = i-2) { if (i == 0 || i == 1) return res; else res *= i; } return res; } // Driver code public static void main(String[] args) { System.out.println("Double factorial" + " is " + doublefactorial(5)); }} // This code is Contributed by Anuj_67 # Python3 Program to find double# factorial of given number # Function to find double# factorial of given numberdef doublefactorial(n): res = 1; for i in range(n, -1, -2): if(i == 0 or i == 1): return res; else: res *= i; # Driver Codeprint("Double factorial is", doublefactorial(5)); # This code is contributed by mits // C# Program to find double factorial// of given numberusing System; class GFG { // function to find double factorial // of given number static int doublefactorial(int n) { int res = 1; for (int i = n; i >= 0; i = i-2) { if (i == 0 || i == 1) return res; else res *= i; } return res; } // Driver code static void Main() { Console.Write("Double factorial" + " is " + doublefactorial(5)); }} // This code is Contributed by Anuj_67 <?php // function to find double// factorial of given numberfunction doublefactorial( $n){ $res = 1; for ($i = $n; $i >= 0; $i = $i - 2) { if ($i == 0 or $i == 1) return $res; else $res *= $i; }} // Driver Code echo "Double factorial is ", doublefactorial(5); // This code is contributed by anuj_67.?> <script> // Javascript Program to find // double factorial of given number // function to find double factorial // of given number function doublefactorial(n) { let res = 1; for (let i = n; i >= 0; i = i-2) { if (i == 0 || i == 1) return res; else res *= i; } return res; } document.write("Double factorial" + " is " + doublefactorial(5)); </script> Output: Double factorial is 15 Time complexity of the above solutions is O(n).Important Points : Double factorial and factorial are related using below formula. Double factorial and factorial are related using below formula. Note : n!! means double factorial. If n is even, i.e., n = 2k n!! = 2kk! Else (n = 2k + 1) n!! = (2k)! / 2kk! 2.Double factorial is frequently used in combinatorics. Refer wiki for list of applications. An example application is count of perfect matchings of a complete graph Kn+1 for odd n. References: https://en.wikipedia.org/wiki/Double_factorialThis article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t vt_m Smitha Dinesh Semwal Mithun Kumar susmitakundugoaldanga divyesh072019 factorial Mathematical Mathematical factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Algorithm to solve Rubik's Cube Modular multiplicative inverse Program to print prime numbers from 1 to N. Program to multiply two matrices Count ways to reach the n'th stair Fizz Buzz Implementation Program to convert a given number to words Check if a number is Palindrome Find first and last digits of a number Generate all permutation of a set in Python
[ { "code": null, "e": 24716, "s": 24688, "text": "\n29 Apr, 2021" }, { "code": null, "e": 25053, "s": 24716, "text": "Double factorial of a non-negative integer n, is the product of all the integers from 1 to n that have the same parity (odd or even) as n. It is also called as semifactorial of a number and is denoted by !!. For example, double factorial of 9 is 9*7*5*3*1 which is 945. Note that, a consequence of this definition is 0!! = 1.Examples: " }, { "code": null, "e": 25138, "s": 25053, "text": "Input: 6\nOutput: 48\nNote that 6*4*2 = 48\n\nInput: 7\nOutput: 105\nNote that 7*5*3 = 105" }, { "code": null, "e": 25211, "s": 25138, "text": "For even n, the double factorial is:For odd n, the double factorial is: " }, { "code": null, "e": 25303, "s": 25211, "text": "Recursive Solution: Double factorial can be calculated using following recursive formula. " }, { "code": null, "e": 25352, "s": 25303, "text": " n!! = n * (n-2)!!\n n!! = 1 if n = 0 or n = 1 " }, { "code": null, "e": 25407, "s": 25352, "text": "Following is the implementation of double factorial. " }, { "code": null, "e": 25411, "s": 25407, "text": "C++" }, { "code": null, "e": 25416, "s": 25411, "text": "Java" }, { "code": null, "e": 25424, "s": 25416, "text": "Python3" }, { "code": null, "e": 25427, "s": 25424, "text": "C#" }, { "code": null, "e": 25431, "s": 25427, "text": "PHP" }, { "code": null, "e": 25442, "s": 25431, "text": "Javascript" }, { "code": "#include<stdio.h> // function to find double factorial of given numberunsigned int doublefactorial(unsigned int n){ if (n == 0 || n==1) return 1; return n*doublefactorial(n-2);} int main(){ printf(\"Double factorial is %d\", doublefactorial(5)); return 0;}", "e": 25716, "s": 25442, "text": null }, { "code": "import java.io.*; class GFG { // function to find double factorial // of given number static long doublefactorial(long n) { if (n == 0 || n==1) return 1; return n * doublefactorial(n - 2); } // Driver code static public void main (String[] args) { System.out.println(\"Double factorial\" + \" is \" + doublefactorial(5)); }} // This code is contributed by anuj_67.", "e": 26162, "s": 25716, "text": null }, { "code": "# function to find double# factorial of given numberdef doublefactorial(n): if (n == 0 or n == 1): return 1; return n * doublefactorial(n - 2); # Driver Codeprint(\"Double factorial is\", doublefactorial(5)); # This code is contributed# by Smitha", "e": 26427, "s": 26162, "text": null }, { "code": "using System; class GFG { // function to find double factorial // of given number static uint doublefactorial(uint n) { if (n == 0 || n==1) return 1; return n * doublefactorial(n - 2); } // Driver code static public void Main () { Console.WriteLine(\"Double factorial\" + \" is \" + doublefactorial(5)); }} // This code is contributed by anuj_67.", "e": 26856, "s": 26427, "text": null }, { "code": "<?php// PHP code for// Double factorial // function return// double factorialfunction doublefactorial($n){ if ($n == 0 || $n==1) return 1; return $n * doublefactorial($n - 2);} // Driver Code echo \"Double factorial is \", doublefactorial(5); // This code is contributed by Ajit.?>", "e": 27163, "s": 26856, "text": null }, { "code": "<script>// Javascript program to find double factorial of given number // function to find double factorial // of given number function doublefactorial(n) { if (n == 0 || n==1) return 1; return n * doublefactorial(n - 2); } // Driver code document.write(\"Double factorial\" + \" is \" + doublefactorial(5)); // This code is contributed by susmitakundugoaldanga. </script>", "e": 27617, "s": 27163, "text": null }, { "code": null, "e": 27627, "s": 27617, "text": "Output: " }, { "code": null, "e": 27650, "s": 27627, "text": "Double factorial is 15" }, { "code": null, "e": 27770, "s": 27650, "text": "Iterative Solution: Double factorial can also be calculated iteratively as recursion can be costly for large numbers. " }, { "code": null, "e": 27774, "s": 27770, "text": "C++" }, { "code": null, "e": 27779, "s": 27774, "text": "Java" }, { "code": null, "e": 27787, "s": 27779, "text": "Python3" }, { "code": null, "e": 27790, "s": 27787, "text": "C#" }, { "code": null, "e": 27794, "s": 27790, "text": "PHP" }, { "code": null, "e": 27805, "s": 27794, "text": "Javascript" }, { "code": "#include<stdio.h> // function to find double factorial of given numberunsigned int doublefactorial(unsigned int n){ int res = 1; for (int i=n; i>=0; i=i-2) { if (i==0 || i==1) return res; else res *= i; }} int main(){ printf(\"Double factorial is %d\", doublefactorial(5)); return 0;}", "e": 28144, "s": 27805, "text": null }, { "code": "// Java Program to find double factorial// of given numberimport java .io.*; class GFG { // function to find double factorial // of given number static int doublefactorial(int n) { int res = 1; for (int i = n; i >= 0; i = i-2) { if (i == 0 || i == 1) return res; else res *= i; } return res; } // Driver code public static void main(String[] args) { System.out.println(\"Double factorial\" + \" is \" + doublefactorial(5)); }} // This code is Contributed by Anuj_67", "e": 28754, "s": 28144, "text": null }, { "code": "# Python3 Program to find double# factorial of given number # Function to find double# factorial of given numberdef doublefactorial(n): res = 1; for i in range(n, -1, -2): if(i == 0 or i == 1): return res; else: res *= i; # Driver Codeprint(\"Double factorial is\", doublefactorial(5)); # This code is contributed by mits", "e": 29127, "s": 28754, "text": null }, { "code": "// C# Program to find double factorial// of given numberusing System; class GFG { // function to find double factorial // of given number static int doublefactorial(int n) { int res = 1; for (int i = n; i >= 0; i = i-2) { if (i == 0 || i == 1) return res; else res *= i; } return res; } // Driver code static void Main() { Console.Write(\"Double factorial\" + \" is \" + doublefactorial(5)); }} // This code is Contributed by Anuj_67", "e": 29705, "s": 29127, "text": null }, { "code": "<?php // function to find double// factorial of given numberfunction doublefactorial( $n){ $res = 1; for ($i = $n; $i >= 0; $i = $i - 2) { if ($i == 0 or $i == 1) return $res; else $res *= $i; }} // Driver Code echo \"Double factorial is \", doublefactorial(5); // This code is contributed by anuj_67.?>", "e": 30068, "s": 29705, "text": null }, { "code": "<script> // Javascript Program to find // double factorial of given number // function to find double factorial // of given number function doublefactorial(n) { let res = 1; for (let i = n; i >= 0; i = i-2) { if (i == 0 || i == 1) return res; else res *= i; } return res; } document.write(\"Double factorial\" + \" is \" + doublefactorial(5)); </script>", "e": 30557, "s": 30068, "text": null }, { "code": null, "e": 30567, "s": 30557, "text": "Output: " }, { "code": null, "e": 30590, "s": 30567, "text": "Double factorial is 15" }, { "code": null, "e": 30658, "s": 30590, "text": "Time complexity of the above solutions is O(n).Important Points : " }, { "code": null, "e": 30724, "s": 30658, "text": "Double factorial and factorial are related using below formula. " }, { "code": null, "e": 30790, "s": 30724, "text": "Double factorial and factorial are related using below formula. " }, { "code": null, "e": 30908, "s": 30790, "text": "Note : n!! means double factorial.\nIf n is even, i.e., n = 2k\n n!! = 2kk!\nElse (n = 2k + 1)\n n!! = (2k)! / 2kk! \n" }, { "code": null, "e": 31092, "s": 30908, "text": "2.Double factorial is frequently used in combinatorics. Refer wiki for list of applications. An example application is count of perfect matchings of a complete graph Kn+1 for odd n. " }, { "code": null, "e": 31571, "s": 31092, "text": "References: https://en.wikipedia.org/wiki/Double_factorialThis article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31577, "s": 31571, "text": "jit_t" }, { "code": null, "e": 31582, "s": 31577, "text": "vt_m" }, { "code": null, "e": 31603, "s": 31582, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 31616, "s": 31603, "text": "Mithun Kumar" }, { "code": null, "e": 31638, "s": 31616, "text": "susmitakundugoaldanga" }, { "code": null, "e": 31652, "s": 31638, "text": "divyesh072019" }, { "code": null, "e": 31662, "s": 31652, "text": "factorial" }, { "code": null, "e": 31675, "s": 31662, "text": "Mathematical" }, { "code": null, "e": 31688, "s": 31675, "text": "Mathematical" }, { "code": null, "e": 31698, "s": 31688, "text": "factorial" }, { "code": null, "e": 31796, "s": 31698, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31805, "s": 31796, "text": "Comments" }, { "code": null, "e": 31818, "s": 31805, "text": "Old Comments" }, { "code": null, "e": 31850, "s": 31818, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 31881, "s": 31850, "text": "Modular multiplicative inverse" }, { "code": null, "e": 31925, "s": 31881, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 31958, "s": 31925, "text": "Program to multiply two matrices" }, { "code": null, "e": 31993, "s": 31958, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 32018, "s": 31993, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 32061, "s": 32018, "text": "Program to convert a given number to words" }, { "code": null, "e": 32093, "s": 32061, "text": "Check if a number is Palindrome" }, { "code": null, "e": 32132, "s": 32093, "text": "Find first and last digits of a number" } ]
QTP - Descriptive Programming
QTP scripts can execute only if the objects are present in the Object Repository. The descriptions of the Objects are created using Descriptive programming − When the testers want to perform an operation on an object that is not present in the object repository When the testers want to perform an operation on an object that is not present in the object repository When objects in the application are very dynamic in nature. When objects in the application are very dynamic in nature. When the Object Repository grows big, it results in poor Performance as the size of the Object Repository increases. When the Object Repository grows big, it results in poor Performance as the size of the Object Repository increases. When the framework is built, such that it has been decided not to use Object Repository at all. When the framework is built, such that it has been decided not to use Object Repository at all. When testers want to perform an action on the application at run-time without having the knowledge of object's unique properties. When testers want to perform an action on the application at run-time without having the knowledge of object's unique properties. There are two ways to scripting using Descriptive Programming technique. They are − Description Objects Description Strings Script is developed using Description Objects that depend upon the properties used and their corresponding values. Then, these descriptions are used to build the script. 'Creating a description object Set btncalc = Description.Create() 'Add descriptions and properties btncalc("type").value = "Button" btncalc("name").value = "calculate" btncalc("html tag").value = "INPUT" ' Use the same to script it Browser("Math Calc").Page("Num Calculator").WebButton(btncalc).Click The description of the objects is developed using the properties and values as strings as shown below. Browser("Math Calc").Page("Num Calculator").WebButton("html tag:=INPUT","type:=Button","name:=calculate").Click QTP provides the ChildObjects method, which enables us to create a collection of objects. The parent objects precedes ChildObjects. Dim oDesc Set oDesc = Description.Create oDesc("micclass").value = "Link" 'Find all the Links Set obj = Browser("Math Calc").Page("Math Calc").ChildObjects(oDesc) Dim i 'obj.Count value has the number of links in the page For i = 0 to obj.Count - 1 'get the name of all the links in the page x = obj(i).GetROProperty("innerhtml") print x Next Descriptive programming is used to write the script based on ordinal identifiers, which will enable QTP to act on those objects when two or more objects have the same properties. ' Using Location Dim Obj Set Obj = Browser("title:=.*google.*").Page("micclass:=Page") Obj.WebEdit("name:=Test","location:=0").Set "ABC" Obj.WebEdit("name:=Test","location:=1").Set "123" ' Index Obj.WebEdit("name:=Test","index:=0").Set "1123" Obj.WebEdit("name:=Test","index:=1").Set "2222" ' Creation Time Browser("creationtime:=0").Sync Browser("creationtime:=1").Sync Browser("creationtime:=2").Sync 108 Lectures 8 hours Pavan Lalwani Print Add Notes Bookmark this page
[ { "code": null, "e": 2280, "s": 2122, "text": "QTP scripts can execute only if the objects are present in the Object Repository. The descriptions of the Objects are created using Descriptive programming −" }, { "code": null, "e": 2384, "s": 2280, "text": "When the testers want to perform an operation on an object that is not present in the object repository" }, { "code": null, "e": 2488, "s": 2384, "text": "When the testers want to perform an operation on an object that is not present in the object repository" }, { "code": null, "e": 2548, "s": 2488, "text": "When objects in the application are very dynamic in nature." }, { "code": null, "e": 2608, "s": 2548, "text": "When objects in the application are very dynamic in nature." }, { "code": null, "e": 2725, "s": 2608, "text": "When the Object Repository grows big, it results in poor Performance as the size of the Object Repository increases." }, { "code": null, "e": 2842, "s": 2725, "text": "When the Object Repository grows big, it results in poor Performance as the size of the Object Repository increases." }, { "code": null, "e": 2938, "s": 2842, "text": "When the framework is built, such that it has been decided not to use Object Repository at all." }, { "code": null, "e": 3034, "s": 2938, "text": "When the framework is built, such that it has been decided not to use Object Repository at all." }, { "code": null, "e": 3164, "s": 3034, "text": "When testers want to perform an action on the application at run-time without having the knowledge of object's unique properties." }, { "code": null, "e": 3294, "s": 3164, "text": "When testers want to perform an action on the application at run-time without having the knowledge of object's unique properties." }, { "code": null, "e": 3378, "s": 3294, "text": "There are two ways to scripting using Descriptive Programming technique. They are −" }, { "code": null, "e": 3398, "s": 3378, "text": "Description Objects" }, { "code": null, "e": 3418, "s": 3398, "text": "Description Strings" }, { "code": null, "e": 3588, "s": 3418, "text": "Script is developed using Description Objects that depend upon the properties used and their corresponding values. Then, these descriptions are used to build the script." }, { "code": null, "e": 3891, "s": 3588, "text": "'Creating a description object\nSet btncalc = Description.Create()\n\n'Add descriptions and properties\nbtncalc(\"type\").value = \"Button\"\nbtncalc(\"name\").value = \"calculate\"\nbtncalc(\"html tag\").value = \"INPUT\"\n\n' Use the same to script it\nBrowser(\"Math Calc\").Page(\"Num Calculator\").WebButton(btncalc).Click" }, { "code": null, "e": 3994, "s": 3891, "text": "The description of the objects is developed using the properties and values as strings as shown below." }, { "code": null, "e": 4108, "s": 3994, "text": "Browser(\"Math Calc\").Page(\"Num Calculator\").WebButton(\"html \ntag:=INPUT\",\"type:=Button\",\"name:=calculate\").Click\n" }, { "code": null, "e": 4240, "s": 4108, "text": "QTP provides the ChildObjects method, which enables us to create a collection of objects. The parent objects precedes ChildObjects." }, { "code": null, "e": 4602, "s": 4240, "text": "Dim oDesc\nSet oDesc = Description.Create\noDesc(\"micclass\").value = \"Link\"\n\n'Find all the Links\nSet obj = Browser(\"Math Calc\").Page(\"Math Calc\").ChildObjects(oDesc)\n\nDim i\n'obj.Count value has the number of links in the page\n\nFor i = 0 to obj.Count - 1\t \n 'get the name of all the links in the page\t\t\t\n x = obj(i).GetROProperty(\"innerhtml\") \n print x \nNext" }, { "code": null, "e": 4781, "s": 4602, "text": "Descriptive programming is used to write the script based on ordinal identifiers, which will enable QTP to act on those objects when two or more objects have the same properties." }, { "code": null, "e": 5188, "s": 4781, "text": "' Using Location\nDim Obj\nSet Obj = Browser(\"title:=.*google.*\").Page(\"micclass:=Page\")\nObj.WebEdit(\"name:=Test\",\"location:=0\").Set \"ABC\"\nObj.WebEdit(\"name:=Test\",\"location:=1\").Set \"123\"\n \n' Index\nObj.WebEdit(\"name:=Test\",\"index:=0\").Set \"1123\"\nObj.WebEdit(\"name:=Test\",\"index:=1\").Set \"2222\"\n \n' Creation Time\nBrowser(\"creationtime:=0\").Sync\nBrowser(\"creationtime:=1\").Sync\nBrowser(\"creationtime:=2\").Sync" }, { "code": null, "e": 5222, "s": 5188, "text": "\n 108 Lectures \n 8 hours \n" }, { "code": null, "e": 5237, "s": 5222, "text": " Pavan Lalwani" }, { "code": null, "e": 5244, "s": 5237, "text": " Print" }, { "code": null, "e": 5255, "s": 5244, "text": " Add Notes" } ]
C# program to get the last element from an array
Firstly, set an array − string[] str = new string[]{ "Java", "HTML", "jQuery", "JavaScript", "Bootstrap" }; To get the value of the last element, get the length and display the following value − str[str.Length - 1] The above returns the last element. Here is the complete code − Live Demo using System; public class Demo { public static void Main() { string[] str = new string[] { "Java", "HTML", "jQuery", "JavaScript", "Bootstrap" }; Console.WriteLine("Array..."); foreach(string res in str) { Console.WriteLine(res); } Console.WriteLine("Last element: "+str[str.Length - 1]); } } Array... Java HTML jQuery JavaScript Bootstrap Last element: Bootstrap
[ { "code": null, "e": 1086, "s": 1062, "text": "Firstly, set an array −" }, { "code": null, "e": 1185, "s": 1086, "text": "string[] str = new string[]{\n \"Java\",\n \"HTML\",\n \"jQuery\",\n \"JavaScript\",\n \"Bootstrap\"\n};" }, { "code": null, "e": 1272, "s": 1185, "text": "To get the value of the last element, get the length and display the following value −" }, { "code": null, "e": 1292, "s": 1272, "text": "str[str.Length - 1]" }, { "code": null, "e": 1328, "s": 1292, "text": "The above returns the last element." }, { "code": null, "e": 1356, "s": 1328, "text": "Here is the complete code −" }, { "code": null, "e": 1367, "s": 1356, "text": " Live Demo" }, { "code": null, "e": 1758, "s": 1367, "text": "using System;\n\npublic class Demo {\n public static void Main() {\n string[] str = new string[] {\n \"Java\",\n \"HTML\",\n \"jQuery\",\n \"JavaScript\",\n \"Bootstrap\"\n };\n Console.WriteLine(\"Array...\");\n foreach(string res in str) {\n Console.WriteLine(res);\n }\n Console.WriteLine(\"Last element: \"+str[str.Length - 1]);\n }\n}" }, { "code": null, "e": 1829, "s": 1758, "text": "Array...\nJava\nHTML\njQuery\nJavaScript\nBootstrap\nLast element: Bootstrap" } ]
Arduino - Compound Operators
Assume variable A holds 10 and variable B holds 20 then − void loop () { int a = 10,b = 20 int c = 0; a++; a--; b += a; b -= a; b *= a; b /= a; a %= b; a |= b; a &= b; } a = 11 a = 9 b = 30 b = 10 b = 200 b = 2 a = 0 a = 0 a = 30 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 2928, "s": 2870, "text": "Assume variable A holds 10 and variable B holds 20 then −" }, { "code": null, "e": 3077, "s": 2928, "text": "void loop () {\n int a = 10,b = 20\n int c = 0;\n \n a++;\n a--;\n b += a;\n b -= a;\n b *= a;\n b /= a;\n a %= b;\n a |= b;\n a &= b;\n}" }, { "code": null, "e": 3138, "s": 3077, "text": "a = 11\na = 9\nb = 30\nb = 10\nb = 200\nb = 2\na = 0\na = 0\na = 30\n" }, { "code": null, "e": 3173, "s": 3138, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3184, "s": 3173, "text": " Amit Rana" }, { "code": null, "e": 3217, "s": 3184, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 3228, "s": 3217, "text": " Amit Rana" }, { "code": null, "e": 3261, "s": 3228, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3274, "s": 3261, "text": " Ashraf Said" }, { "code": null, "e": 3309, "s": 3274, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3322, "s": 3309, "text": " Ashraf Said" }, { "code": null, "e": 3354, "s": 3322, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 3367, "s": 3354, "text": " Ashraf Said" }, { "code": null, "e": 3398, "s": 3367, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 3411, "s": 3398, "text": " Ashraf Said" }, { "code": null, "e": 3418, "s": 3411, "text": " Print" }, { "code": null, "e": 3429, "s": 3418, "text": " Add Notes" } ]
Farthest distance of a Node from each Node of a Tree - GeeksforGeeks
15 Jun, 2021 Given a Tree, the task is to find the farthest node from each node to another node in the given tree. Examples Input: Output: 2 3 3 3 4 4 4 Explanation: Maximum Distance from Node 1 : 2 (Nodes {5, 6, 7} are at a distance 2) Maximum Distance from Node 2 : 3 (Nodes {6, 7} are at a distance 3) Maximum Distance from Node 3 : 3 (Nodes {5, 6, 7} are at a distance 3) Maximum Distance from Node 4 : 3 (Node {5} is at a distance 3) Maximum Distance from Node 5 : 4 (Nodes {6, 7} are at a distance 4) Maximum Distance from Node 6 : 4 (Node {5} is at a distance 4) Maximum Distance from Node 7 : 4 (Node {5} is at a distance 4) Input: Output : 3 2 3 3 2 3 Approach: Follow the steps below to solve the problem: Calculate the height of each node of the tree (Assuming the leaf nodes are at height 1) using DFS This gives the maximum distance from a Node to all Nodes present in its Subtree. Store these heights. Now, perform DFS to calculate the maximum distance of a Node from all its ancestors. Store these distances. For each node, print the maximum of the two distances calculated. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; #define maxN 100001 // Adjacency List to store the graphvector<int> adj[maxN]; // Stores the height of each nodeint height[maxN]; // Stores the maximum distance of a// node from its ancestorsint dist[maxN]; // Function to add edge between// two verticesvoid addEdge(int u, int v){ // Insert edge from u to v adj[u].push_back(v); // Insert edge from v to u adj[v].push_back(u);} // Function to calculate height of// each Nodevoid dfs1(int cur, int par){ // Iterate in the adjacency // list of the current node for (auto u : adj[cur]) { if (u != par) { // Dfs for child node dfs1(u, cur); // Calculate height of nodes height[cur] = max(height[cur], height[u]); } } // Increase height height[cur] += 1;} // Function to calculate the maximum// distance of a node from its ancestorvoid dfs2(int cur, int par){ int max1 = 0; int max2 = 0; // Iterate in the adjacency // list of the current node for (auto u : adj[cur]) { if (u != par) { // Find two children // with maximum heights if (height[u] >= max1) { max2 = max1; max1 = height[u]; } else if (height[u] > max2) { max2 = height[u]; } } } int sum = 0; for (auto u : adj[cur]) { if (u != par) { // Calculate the maximum distance // with ancestor for every node sum = ((max1 == height[u]) ? max2 : max1); if (max1 == height[u]) dist[u] = 1 + max(1 + max2, dist[cur]); else dist[u] = 1 + max(1 + max1, dist[cur]); // Calculating for children dfs2(u, cur); } }} // Driver Codeint main(){ int n = 6; addEdge(1, 2); addEdge(2, 3); addEdge(2, 4); addEdge(2, 5); addEdge(5, 6); // Calculate height of // nodes of the tree dfs1(1, 0); // Calculate the maximum // distance with ancestors dfs2(1, 0); // Print the maximum of the two // distances from each node for (int i = 1; i <= n; i++) cout << (max(dist[i], height[i]) - 1) << " "; return 0;} // Java program to implement// the above approachimport java.util.*; class GFG{ static final int maxN = 100001; // Adjacency List to store the graph@SuppressWarnings("unchecked")static Vector<Integer> []adj = new Vector[maxN]; // Stores the height of each nodestatic int []height = new int[maxN]; // Stores the maximum distance of a// node from its ancestorsstatic int []dist = new int[maxN]; // Function to add edge between// two verticesstatic void addEdge(int u, int v){ // Insert edge from u to v adj[u].add(v); // Insert edge from v to u adj[v].add(u);} // Function to calculate height of// each Nodestatic void dfs1(int cur, int par){ // Iterate in the adjacency // list of the current node for(int u : adj[cur]) { if (u != par) { // Dfs for child node dfs1(u, cur); // Calculate height of nodes height[cur] = Math.max(height[cur], height[u]); } } // Increase height height[cur] += 1;} // Function to calculate the maximum// distance of a node from its ancestorstatic void dfs2(int cur, int par){ int max1 = 0; int max2 = 0; // Iterate in the adjacency // list of the current node for(int u : adj[cur]) { if (u != par) { // Find two children // with maximum heights if (height[u] >= max1) { max2 = max1; max1 = height[u]; } else if (height[u] > max2) { max2 = height[u]; } } } int sum = 0; for(int u : adj[cur]) { if (u != par) { // Calculate the maximum distance // with ancestor for every node sum = ((max1 == height[u]) ? max2 : max1); if (max1 == height[u]) dist[u] = 1 + Math.max(1 + max2, dist[cur]); else dist[u] = 1 + Math.max(1 + max1, dist[cur]); // Calculating for children dfs2(u, cur); } }} // Driver Codepublic static void main(String[] args){ int n = 6; for(int i = 0; i < adj.length; i++) adj[i] = new Vector<Integer>(); addEdge(1, 2); addEdge(2, 3); addEdge(2, 4); addEdge(2, 5); addEdge(5, 6); // Calculate height of // nodes of the tree dfs1(1, 0); // Calculate the maximum // distance with ancestors dfs2(1, 0); // Print the maximum of the two // distances from each node for(int i = 1; i <= n; i++) System.out.print((Math.max(dist[i], height[i]) - 1) + " ");}} // This code is contributed by 29AjayKumar # Python3 program to implement# the above approachmaxN = 100001 # Adjacency List to store the graphadj = [[] for i in range(maxN)] # Stores the height of each nodeheight = [0 for i in range(maxN)] # Stores the maximum distance of a# node from its ancestorsdist = [0 for i in range(maxN)] # Function to add edge between# two verticesdef addEdge(u, v): # Insert edge from u to v adj[u].append(v) # Insert edge from v to u adj[v].append(u) # Function to calculate height of# each Nodedef dfs1(cur, par): # Iterate in the adjacency # list of the current node for u in adj[cur]: if (u != par): # Dfs for child node dfs1(u, cur) # Calculate height of nodes height[cur] = max(height[cur], height[u]) # Increase height height[cur] += 1 # Function to calculate the maximum# distance of a node from its ancestordef dfs2(cur, par): max1 = 0 max2 = 0 # Iterate in the adjacency # list of the current node for u in adj[cur]: if (u != par): # Find two children # with maximum heights if (height[u] >= max1): max2 = max1 max1 = height[u] elif (height[u] > max2): max2 = height[u] sum = 0 for u in adj[cur]: if (u != par): # Calculate the maximum distance # with ancestor for every node sum = (max2 if (max1 == height[u]) else max1) if (max1 == height[u]): dist[u] = 1 + max(1 + max2, dist[cur]) else: dist[u] = 1 + max(1 + max1, dist[cur]) # Calculating for children dfs2(u, cur) # Driver Codeif __name__=="__main__": n = 6 addEdge(1, 2) addEdge(2, 3) addEdge(2, 4) addEdge(2, 5) addEdge(5, 6) # Calculate height of # nodes of the tree dfs1(1, 0) # Calculate the maximum # distance with ancestors dfs2(1, 0) # Print the maximum of the two # distances from each node for i in range(1, n + 1): print(max(dist[i], height[i]) - 1, end = ' ') # This code is contributed by rutvik_56 // C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ static readonly int maxN = 100001; // Adjacency List to store the graphstatic List<int> []adj = new List<int>[maxN]; // Stores the height of each nodestatic int []height = new int[maxN]; // Stores the maximum distance of a// node from its ancestorsstatic int []dist = new int[maxN]; // Function to add edge between// two verticesstatic void addEdge(int u, int v){ // Insert edge from u to v adj[u].Add(v); // Insert edge from v to u adj[v].Add(u);} // Function to calculate height of// each Nodestatic void dfs1(int cur, int par){ // Iterate in the adjacency // list of the current node foreach(int u in adj[cur]) { if (u != par) { // Dfs for child node dfs1(u, cur); // Calculate height of nodes height[cur] = Math.Max(height[cur], height[u]); } } // Increase height height[cur] += 1;} // Function to calculate the maximum// distance of a node from its ancestorstatic void dfs2(int cur, int par){ int max1 = 0; int max2 = 0; // Iterate in the adjacency // list of the current node foreach(int u in adj[cur]) { if (u != par) { // Find two children // with maximum heights if (height[u] >= max1) { max2 = max1; max1 = height[u]; } else if (height[u] > max2) { max2 = height[u]; } } } int sum = 0; foreach(int u in adj[cur]) { if (u != par) { // Calculate the maximum distance // with ancestor for every node sum = ((max1 == height[u]) ? max2 : max1); if (max1 == height[u]) dist[u] = 1 + Math.Max(1 + max2, dist[cur]); else dist[u] = 1 + Math.Max(1 + max1, dist[cur]); // Calculating for children dfs2(u, cur); } }} // Driver Codepublic static void Main(String[] args){ int n = 6; for(int i = 0; i < adj.Length; i++) adj[i] = new List<int>(); addEdge(1, 2); addEdge(2, 3); addEdge(2, 4); addEdge(2, 5); addEdge(5, 6); // Calculate height of // nodes of the tree dfs1(1, 0); // Calculate the maximum // distance with ancestors dfs2(1, 0); // Print the maximum of the two // distances from each node for(int i = 1; i <= n; i++) Console.Write((Math.Max(dist[i], height[i]) - 1) + " ");}} // This code is contributed by Rohit_ranjan <script> // JavaScript program to implement the above approach let maxN = 100001; // Adjacency List to store the graph let adj = new Array(maxN); adj.fill(0); // Stores the height of each node let height = new Array(maxN); height.fill(0); // Stores the maximum distance of a // node from its ancestors let dist = new Array(maxN); dist.fill(0); // Function to add edge between // two vertices function addEdge(u, v) { // Insert edge from u to v adj[u].push(v); // Insert edge from v to u adj[v].push(u); } // Function to calculate height of // each Node function dfs1(cur, par) { // Iterate in the adjacency // list of the current node for(let u = 0; u < adj[cur].length; u++) { if (adj[cur][u] != par) { // Dfs for child node dfs1(adj[cur][u], cur); // Calculate height of nodes height[cur] = Math.max(height[cur], height[adj[cur][u]]); } } // Increase height height[cur] += 1; } // Function to calculate the maximum // distance of a node from its ancestor function dfs2(cur, par) { let max1 = 0; let max2 = 0; // Iterate in the adjacency // list of the current node for(let u = 0; u < adj[cur].length; u++) { if (adj[cur][u] != par) { // Find two children // with maximum heights if (height[adj[cur][u]] >= max1) { max2 = max1; max1 = height[adj[cur][u]]; } else if (height[adj[cur][u]] > max2) { max2 = height[adj[cur][u]]; } } } let sum = 0; for(let u = 0; u < adj[cur].length; u++) { if (adj[cur][u] != par) { // Calculate the maximum distance // with ancestor for every node sum = ((max1 == height[adj[cur][u]]) ? max2 : max1); if (max1 == height[adj[cur][u]]) dist[adj[cur][u]] = 1 + Math.max(1 + max2, dist[cur]); else dist[adj[cur][u]] = 1 + Math.max(1 + max1, dist[cur]); // Calculating for children dfs2(adj[cur][u], cur); } } } let n = 6; for(let i = 0; i < adj.length; i++) adj[i] = []; addEdge(1, 2); addEdge(2, 3); addEdge(2, 4); addEdge(2, 5); addEdge(5, 6); // Calculate height of // nodes of the tree dfs1(1, 0); // Calculate the maximum // distance with ancestors dfs2(1, 0); // Print the maximum of the two // distances from each node for(let i = 1; i <= n; i++) document.write((Math.max(dist[i], height[i]) - 1) + " "); </script> 3 2 3 3 2 3 Time Complexity: O(V+E) Auxiliary Space: O(N) 29AjayKumar Rohit_ranjan rutvik_56 mukesh07 DFS Tree Traversals Trees Dynamic Programming Recursion Searching Tree Searching Dynamic Programming Recursion DFS Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Longest Palindromic Substring | Set 1 Matrix Chain Multiplication | DP-8 Write a program to print all permutations of a given string Program for Tower of Hanoi Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Sum of the digits of a given number
[ { "code": null, "e": 25108, "s": 25080, "text": "\n15 Jun, 2021" }, { "code": null, "e": 25210, "s": 25108, "text": "Given a Tree, the task is to find the farthest node from each node to another node in the given tree." }, { "code": null, "e": 25221, "s": 25210, "text": "Examples " }, { "code": null, "e": 25229, "s": 25221, "text": "Input: " }, { "code": null, "e": 25731, "s": 25229, "text": "Output: 2 3 3 3 4 4 4 Explanation: Maximum Distance from Node 1 : 2 (Nodes {5, 6, 7} are at a distance 2) Maximum Distance from Node 2 : 3 (Nodes {6, 7} are at a distance 3) Maximum Distance from Node 3 : 3 (Nodes {5, 6, 7} are at a distance 3) Maximum Distance from Node 4 : 3 (Node {5} is at a distance 3) Maximum Distance from Node 5 : 4 (Nodes {6, 7} are at a distance 4) Maximum Distance from Node 6 : 4 (Node {5} is at a distance 4) Maximum Distance from Node 7 : 4 (Node {5} is at a distance 4)" }, { "code": null, "e": 25739, "s": 25731, "text": "Input: " }, { "code": null, "e": 25762, "s": 25739, "text": "Output : 3 2 3 3 2 3 " }, { "code": null, "e": 25773, "s": 25762, "text": "Approach: " }, { "code": null, "e": 25819, "s": 25773, "text": "Follow the steps below to solve the problem: " }, { "code": null, "e": 25917, "s": 25819, "text": "Calculate the height of each node of the tree (Assuming the leaf nodes are at height 1) using DFS" }, { "code": null, "e": 26019, "s": 25917, "text": "This gives the maximum distance from a Node to all Nodes present in its Subtree. Store these heights." }, { "code": null, "e": 26127, "s": 26019, "text": "Now, perform DFS to calculate the maximum distance of a Node from all its ancestors. Store these distances." }, { "code": null, "e": 26193, "s": 26127, "text": "For each node, print the maximum of the two distances calculated." }, { "code": null, "e": 26244, "s": 26193, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26248, "s": 26244, "text": "C++" }, { "code": null, "e": 26253, "s": 26248, "text": "Java" }, { "code": null, "e": 26261, "s": 26253, "text": "Python3" }, { "code": null, "e": 26264, "s": 26261, "text": "C#" }, { "code": null, "e": 26275, "s": 26264, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; #define maxN 100001 // Adjacency List to store the graphvector<int> adj[maxN]; // Stores the height of each nodeint height[maxN]; // Stores the maximum distance of a// node from its ancestorsint dist[maxN]; // Function to add edge between// two verticesvoid addEdge(int u, int v){ // Insert edge from u to v adj[u].push_back(v); // Insert edge from v to u adj[v].push_back(u);} // Function to calculate height of// each Nodevoid dfs1(int cur, int par){ // Iterate in the adjacency // list of the current node for (auto u : adj[cur]) { if (u != par) { // Dfs for child node dfs1(u, cur); // Calculate height of nodes height[cur] = max(height[cur], height[u]); } } // Increase height height[cur] += 1;} // Function to calculate the maximum// distance of a node from its ancestorvoid dfs2(int cur, int par){ int max1 = 0; int max2 = 0; // Iterate in the adjacency // list of the current node for (auto u : adj[cur]) { if (u != par) { // Find two children // with maximum heights if (height[u] >= max1) { max2 = max1; max1 = height[u]; } else if (height[u] > max2) { max2 = height[u]; } } } int sum = 0; for (auto u : adj[cur]) { if (u != par) { // Calculate the maximum distance // with ancestor for every node sum = ((max1 == height[u]) ? max2 : max1); if (max1 == height[u]) dist[u] = 1 + max(1 + max2, dist[cur]); else dist[u] = 1 + max(1 + max1, dist[cur]); // Calculating for children dfs2(u, cur); } }} // Driver Codeint main(){ int n = 6; addEdge(1, 2); addEdge(2, 3); addEdge(2, 4); addEdge(2, 5); addEdge(5, 6); // Calculate height of // nodes of the tree dfs1(1, 0); // Calculate the maximum // distance with ancestors dfs2(1, 0); // Print the maximum of the two // distances from each node for (int i = 1; i <= n; i++) cout << (max(dist[i], height[i]) - 1) << \" \"; return 0;}", "e": 28639, "s": 26275, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG{ static final int maxN = 100001; // Adjacency List to store the graph@SuppressWarnings(\"unchecked\")static Vector<Integer> []adj = new Vector[maxN]; // Stores the height of each nodestatic int []height = new int[maxN]; // Stores the maximum distance of a// node from its ancestorsstatic int []dist = new int[maxN]; // Function to add edge between// two verticesstatic void addEdge(int u, int v){ // Insert edge from u to v adj[u].add(v); // Insert edge from v to u adj[v].add(u);} // Function to calculate height of// each Nodestatic void dfs1(int cur, int par){ // Iterate in the adjacency // list of the current node for(int u : adj[cur]) { if (u != par) { // Dfs for child node dfs1(u, cur); // Calculate height of nodes height[cur] = Math.max(height[cur], height[u]); } } // Increase height height[cur] += 1;} // Function to calculate the maximum// distance of a node from its ancestorstatic void dfs2(int cur, int par){ int max1 = 0; int max2 = 0; // Iterate in the adjacency // list of the current node for(int u : adj[cur]) { if (u != par) { // Find two children // with maximum heights if (height[u] >= max1) { max2 = max1; max1 = height[u]; } else if (height[u] > max2) { max2 = height[u]; } } } int sum = 0; for(int u : adj[cur]) { if (u != par) { // Calculate the maximum distance // with ancestor for every node sum = ((max1 == height[u]) ? max2 : max1); if (max1 == height[u]) dist[u] = 1 + Math.max(1 + max2, dist[cur]); else dist[u] = 1 + Math.max(1 + max1, dist[cur]); // Calculating for children dfs2(u, cur); } }} // Driver Codepublic static void main(String[] args){ int n = 6; for(int i = 0; i < adj.length; i++) adj[i] = new Vector<Integer>(); addEdge(1, 2); addEdge(2, 3); addEdge(2, 4); addEdge(2, 5); addEdge(5, 6); // Calculate height of // nodes of the tree dfs1(1, 0); // Calculate the maximum // distance with ancestors dfs2(1, 0); // Print the maximum of the two // distances from each node for(int i = 1; i <= n; i++) System.out.print((Math.max(dist[i], height[i]) - 1) + \" \");}} // This code is contributed by 29AjayKumar", "e": 31474, "s": 28639, "text": null }, { "code": "# Python3 program to implement# the above approachmaxN = 100001 # Adjacency List to store the graphadj = [[] for i in range(maxN)] # Stores the height of each nodeheight = [0 for i in range(maxN)] # Stores the maximum distance of a# node from its ancestorsdist = [0 for i in range(maxN)] # Function to add edge between# two verticesdef addEdge(u, v): # Insert edge from u to v adj[u].append(v) # Insert edge from v to u adj[v].append(u) # Function to calculate height of# each Nodedef dfs1(cur, par): # Iterate in the adjacency # list of the current node for u in adj[cur]: if (u != par): # Dfs for child node dfs1(u, cur) # Calculate height of nodes height[cur] = max(height[cur], height[u]) # Increase height height[cur] += 1 # Function to calculate the maximum# distance of a node from its ancestordef dfs2(cur, par): max1 = 0 max2 = 0 # Iterate in the adjacency # list of the current node for u in adj[cur]: if (u != par): # Find two children # with maximum heights if (height[u] >= max1): max2 = max1 max1 = height[u] elif (height[u] > max2): max2 = height[u] sum = 0 for u in adj[cur]: if (u != par): # Calculate the maximum distance # with ancestor for every node sum = (max2 if (max1 == height[u]) else max1) if (max1 == height[u]): dist[u] = 1 + max(1 + max2, dist[cur]) else: dist[u] = 1 + max(1 + max1, dist[cur]) # Calculating for children dfs2(u, cur) # Driver Codeif __name__==\"__main__\": n = 6 addEdge(1, 2) addEdge(2, 3) addEdge(2, 4) addEdge(2, 5) addEdge(5, 6) # Calculate height of # nodes of the tree dfs1(1, 0) # Calculate the maximum # distance with ancestors dfs2(1, 0) # Print the maximum of the two # distances from each node for i in range(1, n + 1): print(max(dist[i], height[i]) - 1, end = ' ') # This code is contributed by rutvik_56", "e": 33707, "s": 31474, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ static readonly int maxN = 100001; // Adjacency List to store the graphstatic List<int> []adj = new List<int>[maxN]; // Stores the height of each nodestatic int []height = new int[maxN]; // Stores the maximum distance of a// node from its ancestorsstatic int []dist = new int[maxN]; // Function to add edge between// two verticesstatic void addEdge(int u, int v){ // Insert edge from u to v adj[u].Add(v); // Insert edge from v to u adj[v].Add(u);} // Function to calculate height of// each Nodestatic void dfs1(int cur, int par){ // Iterate in the adjacency // list of the current node foreach(int u in adj[cur]) { if (u != par) { // Dfs for child node dfs1(u, cur); // Calculate height of nodes height[cur] = Math.Max(height[cur], height[u]); } } // Increase height height[cur] += 1;} // Function to calculate the maximum// distance of a node from its ancestorstatic void dfs2(int cur, int par){ int max1 = 0; int max2 = 0; // Iterate in the adjacency // list of the current node foreach(int u in adj[cur]) { if (u != par) { // Find two children // with maximum heights if (height[u] >= max1) { max2 = max1; max1 = height[u]; } else if (height[u] > max2) { max2 = height[u]; } } } int sum = 0; foreach(int u in adj[cur]) { if (u != par) { // Calculate the maximum distance // with ancestor for every node sum = ((max1 == height[u]) ? max2 : max1); if (max1 == height[u]) dist[u] = 1 + Math.Max(1 + max2, dist[cur]); else dist[u] = 1 + Math.Max(1 + max1, dist[cur]); // Calculating for children dfs2(u, cur); } }} // Driver Codepublic static void Main(String[] args){ int n = 6; for(int i = 0; i < adj.Length; i++) adj[i] = new List<int>(); addEdge(1, 2); addEdge(2, 3); addEdge(2, 4); addEdge(2, 5); addEdge(5, 6); // Calculate height of // nodes of the tree dfs1(1, 0); // Calculate the maximum // distance with ancestors dfs2(1, 0); // Print the maximum of the two // distances from each node for(int i = 1; i <= n; i++) Console.Write((Math.Max(dist[i], height[i]) - 1) + \" \");}} // This code is contributed by Rohit_ranjan", "e": 36543, "s": 33707, "text": null }, { "code": "<script> // JavaScript program to implement the above approach let maxN = 100001; // Adjacency List to store the graph let adj = new Array(maxN); adj.fill(0); // Stores the height of each node let height = new Array(maxN); height.fill(0); // Stores the maximum distance of a // node from its ancestors let dist = new Array(maxN); dist.fill(0); // Function to add edge between // two vertices function addEdge(u, v) { // Insert edge from u to v adj[u].push(v); // Insert edge from v to u adj[v].push(u); } // Function to calculate height of // each Node function dfs1(cur, par) { // Iterate in the adjacency // list of the current node for(let u = 0; u < adj[cur].length; u++) { if (adj[cur][u] != par) { // Dfs for child node dfs1(adj[cur][u], cur); // Calculate height of nodes height[cur] = Math.max(height[cur], height[adj[cur][u]]); } } // Increase height height[cur] += 1; } // Function to calculate the maximum // distance of a node from its ancestor function dfs2(cur, par) { let max1 = 0; let max2 = 0; // Iterate in the adjacency // list of the current node for(let u = 0; u < adj[cur].length; u++) { if (adj[cur][u] != par) { // Find two children // with maximum heights if (height[adj[cur][u]] >= max1) { max2 = max1; max1 = height[adj[cur][u]]; } else if (height[adj[cur][u]] > max2) { max2 = height[adj[cur][u]]; } } } let sum = 0; for(let u = 0; u < adj[cur].length; u++) { if (adj[cur][u] != par) { // Calculate the maximum distance // with ancestor for every node sum = ((max1 == height[adj[cur][u]]) ? max2 : max1); if (max1 == height[adj[cur][u]]) dist[adj[cur][u]] = 1 + Math.max(1 + max2, dist[cur]); else dist[adj[cur][u]] = 1 + Math.max(1 + max1, dist[cur]); // Calculating for children dfs2(adj[cur][u], cur); } } } let n = 6; for(let i = 0; i < adj.length; i++) adj[i] = []; addEdge(1, 2); addEdge(2, 3); addEdge(2, 4); addEdge(2, 5); addEdge(5, 6); // Calculate height of // nodes of the tree dfs1(1, 0); // Calculate the maximum // distance with ancestors dfs2(1, 0); // Print the maximum of the two // distances from each node for(let i = 1; i <= n; i++) document.write((Math.max(dist[i], height[i]) - 1) + \" \"); </script>", "e": 39692, "s": 36543, "text": null }, { "code": null, "e": 39704, "s": 39692, "text": "3 2 3 3 2 3" }, { "code": null, "e": 39753, "s": 39706, "text": "Time Complexity: O(V+E) Auxiliary Space: O(N) " }, { "code": null, "e": 39765, "s": 39753, "text": "29AjayKumar" }, { "code": null, "e": 39778, "s": 39765, "text": "Rohit_ranjan" }, { "code": null, "e": 39788, "s": 39778, "text": "rutvik_56" }, { "code": null, "e": 39797, "s": 39788, "text": "mukesh07" }, { "code": null, "e": 39801, "s": 39797, "text": "DFS" }, { "code": null, "e": 39817, "s": 39801, "text": "Tree Traversals" }, { "code": null, "e": 39823, "s": 39817, "text": "Trees" }, { "code": null, "e": 39843, "s": 39823, "text": "Dynamic Programming" }, { "code": null, "e": 39853, "s": 39843, "text": "Recursion" }, { "code": null, "e": 39863, "s": 39853, "text": "Searching" }, { "code": null, "e": 39868, "s": 39863, "text": "Tree" }, { "code": null, "e": 39878, "s": 39868, "text": "Searching" }, { "code": null, "e": 39898, "s": 39878, "text": "Dynamic Programming" }, { "code": null, "e": 39908, "s": 39898, "text": "Recursion" }, { "code": null, "e": 39912, "s": 39908, "text": "DFS" }, { "code": null, "e": 39917, "s": 39912, "text": "Tree" }, { "code": null, "e": 40015, "s": 39917, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40046, "s": 40015, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 40079, "s": 40046, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 40147, "s": 40079, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 40185, "s": 40147, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 40220, "s": 40185, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 40280, "s": 40220, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 40307, "s": 40280, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 40392, "s": 40307, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 40402, "s": 40392, "text": "Recursion" } ]
Using R to Visualise Data on Aviation Tragedies in the US since 1948 | by Hamza Bendemra, Ph.D. | Towards Data Science
In this post, I look at a dataset sourced from the NTSB Aviation Accident Database which contains information about civil aviation accidents. A dataset is available on Kaggle also. This Exploratory Data Analysis (EDA) aims to perform an initial exploration of the data and get an initial look at relationships between the various variables present in the dataset. My aim is to also show how a simple understanding of Data Analysis and Wrangling in R coupled with domain knowledge can provide a better understanding of relationships between variables in a dataset. The R Markdown file can found in this GitHub repo. First, a quick intro of the dataset I’ll be exploring. The dataset features 81,013 observations of 31 variables which are related to aviation accidents recorded. ## [1] 81013 31 Variables provide information on a variety of topics including date and location of observations, model and type of aircraft, information on the sustained injuries to passengers and to the aircraft, and the reported weather conditions at the time. ## [1] "Event.Id" "Investigation.Type" ## [3] "Accident.Number" "Event.Date" ## [5] "Location" "Country" ## [7] "Latitude" "Longitude" ## [9] "Airport.Code" "Airport.Name" ## [11] "Injury.Severity" "Aircraft.Damage" ## [13] "Aircraft.Category" "Registration.Number" ## [15] "Make" "Model" ## [17] "Amateur.Built" "Number.of.Engines" ## [19] "Engine.Type" "FAR.Description" ## [21] "Schedule" "Purpose.of.Flight" ## [23] "Air.Carrier" "Total.Fatal.Injuries" ## [25] "Total.Serious.Injuries" "Total.Minor.Injuries" ## [27] "Total.Uninjured" "Weather.Condition" ## [29] "Broad.Phase.of.Flight" "Report.Status" ## [31] "Publication.Date" Since this an NTSB database from the United States, the majority of accidents (over 94%) in this databased are observations in the US. Hence, I will be focusing on the accidents that took place in the US in this analysis. After removing international observations the new dataframe now features 76,188 observations. ## [1] 76188 31 Some data wrangling was necessary of course (details of which can be found in the R Markdown file in the GitHub repo). For instance, the listed location names (city, state) was separated into two variables: one for the city and one for the state, for each observation. The variable related to the observation’s event date was broken down into the observation’s event date by day, month, and year to investigate if there are any correlations between number of accidents and particular periods within a year. More data wrangling was necessary to Also, a better way of displaying data related to total fatalities for a given observation was to group number of fatalities in buckets (or bands). This will give us a better representation of the distribution of fatalities across the observations in the dataset. In this section, I will create univariate plots for variables of interest. Let’s plots frequency histograms for the year, month, and weekday of accidents in the dataset. The majority of the observations in the dataframe are from after the early 1980s onwards. So let’s generate a plot from 1980 to 2017. The number of accidents has overall decreased by approx. 47% between 1982 and 2017 from approx. 3400 observations to approx. 1600 observations. Next, let’s look at observations distribution by months of the year. The highest number of accidents in the dataset for a given year take place during northern hemisphere summer time (Jun-Jul-Aug). This is also likely to be correlated with the increased numbers of flights during the summer holiday period. And finally, let’s look at the observations distribution by day of the week. The highest frequency of accidents in a given week take place during the weekend (Sat-Sun). Again ,this is also likely to be correlated with the increased numbers of flights during the summer holiday period. The next variable of interest relates to the Total Fatal Injuries for each observation in the dataset. This is quantified by the number of people fatally injured for each recorded observation. Let’s group the number of fatalities in buckets as shown in the plot below. Note the use of the Log10 scale for the y-axis in the plot below. The bulk of the recorded accidents have a number of fatalities <10 while some observations are displaying numbers of fatalities >100. Next, I look at the aircraft engine types recorded in the dataset. I’ve abbreviate engine type names to improve labelling of the x-axis. Note the use of the Log10 scale for the y-axis in the plot below. According to the plots above, the bulk of engine types in the reported accidents are Reciprocating engine types which were prevalent in commercial aircraft, particularly in aircraft built during the 20th century. Recent aircraft, like the Airbus A380 or the Boeing 787 Dreamliner rely on Jet engines (e.g. TurboFan, TurboProp). Next, I look at the weather conditions recorded in the dataset. Two key aviation weather conditions to be familiar with here: VMC which means that conditions are such that pilots have sufficient visibility to fly the aircraft maintaining visual separation from terrain and other aircraft. IMC which means weather conditions require pilots to fly primarily by reference to instruments. The bulk of accidents in the dataset take place during VMC weather conditions, which are great conditions for flying as VMC requires greater visibility and cloud clearance than IMC. I imagine this would go against most people’s intuition when it comes to the relationship between weather conditions and aviation accidents. Pilots are indeed well trained to fly in all sorts of weather conditions, relying solely on the avionics instruments at their disposal. Next, let’s look at the phases of flight for the recorded accidents in the dataset. According to the plot, the bulk of accidents took place during landing or take-off. It is well known in the industry that these are high-risk — often referred to as “critical phases of flight”. Let’s look at the relationship between pairs of variables that could show interesting relationship. The bulk of the distribution has a total fatal injuries under 10, let’s zoom in on that portion of the data. The R function geom_jitter was used to amplify the visualisation of the data points. According to the plot, the bulk of the data for fatalities under 10 is with the engine type reciprocating engine type. The first plot shows that the Turbo-Fan engine has more outliers with higher number of fatalities than other engines. This is likely correlated to the use of Turbo-Fan engines use on large commercial aircraft. As previously noted ,weather conditions do not show a particularly strong relationship with total fatal injuries. The bulk of the distribution is associate with VMC weather conditions. However, that is likely to the fact that the vast majority of flights are flown in VMC conditions. Let’s look at the relationship of Phase of Flight and Total Fatal Injuries The plots show that Take-Off and Approach are associated with outliers with high number of fatalities. As previously noted, these two phases of flight are often referred to as “critical phases of flight” for that particular reason. Let’s look at the relationship of Event Date and Total Fatal Injuries. We’ll focus on the bulk of the distribution with fatalities of less than 10. There doesn’t seem to be any specific month or weekday showing a particularly high frequency of accidents. The plots indicates that there is higher frequency of recorded observations for certain combinations of weather and phases of flight — for example, IMC flying conditions while during “cruise” or “approach” phases of flight. The plots indicates that there is a higher frequency of recorded observations for Northern summer months during Landing and Take-off. Across all months, the heat map also shows that the Take-off and Landing register the highest number of observations. Plotting the Latitude vs Longitude of the accidents essentially gives us the map of the US. The plots also indicates that the coastal states are more heavily impacted compared to mid-western states and most of Alaska. This can be explained by the volume of flight to/from destinations those areas of the US. A sad chart however as it shows that the vast majority of US States suffered an aviation tragedy between 1948 and 2017. Now let’s look at multivariate plots. The distribution of accident months across latitude and longitude is fairly spread across the US, with a slightly higher prevalence of observations during the winter in southern states like Florida. Let’s now look at latitude vs longitude add layer for the weather condition. Weather condition VMC seems to be quite consistent except for patches of primarily IMC conditions for certain discrete areas of the mid-west. Let’s now look at the relationship of Broad Phase of Flight vs Month by Weather Conditions. I decided to leave the observations with “unkown” weather conditions as there is what I perceive to be non-negligible number of observations, particularly for the “Cruise”phase of flight. When looking at the relationship between Broad Phase of Flight vs Month and Weather Condition, we can see that accident primarily take place during VMC weather condition. However, for certain months of the year such as December an January, IMC conditions are a non-negligible portion of the observations, particularly during Approach and Cruise phases of flight. Next, let’s look at Total Fatal Injuries vs Broad Phases of Flight by Weather Condition. I decided to focus on total fatal injuries of less than 40 to highlight the bulk of the distribution of recorded fatal injuries. IMC weather conditions are associated with accidents during “Cruise” and “Approach” phases of flight with higher frequencies than in VMC weather conditions. This plot is interesting as it shows how certain engines have become prevalent in different time periods. For instance, Turbo-Jet and Turbo-Fan powered aircraft show a higher number of fatalities in later years whereas reciprocating engines show a distribution of fatalities in earlier years, this corresponds to the increasingly use of jet engines in modern aircraft. I hope you enjoyed this EDA and learned a few things about aviation along the way. I hope that this post also shows the power of simple data visualisations with ggplot2 in R. This skills is particularly useful when exploring a dataset in the initial phase of the data science pipeline. I certainly enjoyed this fun little study done over the weekend.
[ { "code": null, "e": 353, "s": 172, "text": "In this post, I look at a dataset sourced from the NTSB Aviation Accident Database which contains information about civil aviation accidents. A dataset is available on Kaggle also." }, { "code": null, "e": 536, "s": 353, "text": "This Exploratory Data Analysis (EDA) aims to perform an initial exploration of the data and get an initial look at relationships between the various variables present in the dataset." }, { "code": null, "e": 787, "s": 536, "text": "My aim is to also show how a simple understanding of Data Analysis and Wrangling in R coupled with domain knowledge can provide a better understanding of relationships between variables in a dataset. The R Markdown file can found in this GitHub repo." }, { "code": null, "e": 949, "s": 787, "text": "First, a quick intro of the dataset I’ll be exploring. The dataset features 81,013 observations of 31 variables which are related to aviation accidents recorded." }, { "code": null, "e": 965, "s": 949, "text": "## [1] 81013 31" }, { "code": null, "e": 1213, "s": 965, "text": "Variables provide information on a variety of topics including date and location of observations, model and type of aircraft, information on the sustained injuries to passengers and to the aircraft, and the reported weather conditions at the time." }, { "code": null, "e": 1847, "s": 1213, "text": "## [1] \"Event.Id\" \"Investigation.Type\" ## [3] \"Accident.Number\" \"Event.Date\" ## [5] \"Location\" \"Country\" ## [7] \"Latitude\" \"Longitude\" ## [9] \"Airport.Code\" \"Airport.Name\" ## [11] \"Injury.Severity\" \"Aircraft.Damage\" ## [13] \"Aircraft.Category\" \"Registration.Number\" ## [15] \"Make\" \"Model\" ## [17] \"Amateur.Built\" \"Number.of.Engines\" ## [19] \"Engine.Type\" \"FAR.Description\" ## [21] \"Schedule\" \"Purpose.of.Flight\" ## [23] \"Air.Carrier\" \"Total.Fatal.Injuries\" ## [25] \"Total.Serious.Injuries\" \"Total.Minor.Injuries\" ## [27] \"Total.Uninjured\" \"Weather.Condition\" ## [29] \"Broad.Phase.of.Flight\" \"Report.Status\" ## [31] \"Publication.Date\"" }, { "code": null, "e": 2163, "s": 1847, "text": "Since this an NTSB database from the United States, the majority of accidents (over 94%) in this databased are observations in the US. Hence, I will be focusing on the accidents that took place in the US in this analysis. After removing international observations the new dataframe now features 76,188 observations." }, { "code": null, "e": 2179, "s": 2163, "text": "## [1] 76188 31" }, { "code": null, "e": 2448, "s": 2179, "text": "Some data wrangling was necessary of course (details of which can be found in the R Markdown file in the GitHub repo). For instance, the listed location names (city, state) was separated into two variables: one for the city and one for the state, for each observation." }, { "code": null, "e": 2723, "s": 2448, "text": "The variable related to the observation’s event date was broken down into the observation’s event date by day, month, and year to investigate if there are any correlations between number of accidents and particular periods within a year. More data wrangling was necessary to" }, { "code": null, "e": 2986, "s": 2723, "text": "Also, a better way of displaying data related to total fatalities for a given observation was to group number of fatalities in buckets (or bands). This will give us a better representation of the distribution of fatalities across the observations in the dataset." }, { "code": null, "e": 3061, "s": 2986, "text": "In this section, I will create univariate plots for variables of interest." }, { "code": null, "e": 3290, "s": 3061, "text": "Let’s plots frequency histograms for the year, month, and weekday of accidents in the dataset. The majority of the observations in the dataframe are from after the early 1980s onwards. So let’s generate a plot from 1980 to 2017." }, { "code": null, "e": 3434, "s": 3290, "text": "The number of accidents has overall decreased by approx. 47% between 1982 and 2017 from approx. 3400 observations to approx. 1600 observations." }, { "code": null, "e": 3503, "s": 3434, "text": "Next, let’s look at observations distribution by months of the year." }, { "code": null, "e": 3741, "s": 3503, "text": "The highest number of accidents in the dataset for a given year take place during northern hemisphere summer time (Jun-Jul-Aug). This is also likely to be correlated with the increased numbers of flights during the summer holiday period." }, { "code": null, "e": 3818, "s": 3741, "text": "And finally, let’s look at the observations distribution by day of the week." }, { "code": null, "e": 4026, "s": 3818, "text": "The highest frequency of accidents in a given week take place during the weekend (Sat-Sun). Again ,this is also likely to be correlated with the increased numbers of flights during the summer holiday period." }, { "code": null, "e": 4361, "s": 4026, "text": "The next variable of interest relates to the Total Fatal Injuries for each observation in the dataset. This is quantified by the number of people fatally injured for each recorded observation. Let’s group the number of fatalities in buckets as shown in the plot below. Note the use of the Log10 scale for the y-axis in the plot below." }, { "code": null, "e": 4495, "s": 4361, "text": "The bulk of the recorded accidents have a number of fatalities <10 while some observations are displaying numbers of fatalities >100." }, { "code": null, "e": 4698, "s": 4495, "text": "Next, I look at the aircraft engine types recorded in the dataset. I’ve abbreviate engine type names to improve labelling of the x-axis. Note the use of the Log10 scale for the y-axis in the plot below." }, { "code": null, "e": 5026, "s": 4698, "text": "According to the plots above, the bulk of engine types in the reported accidents are Reciprocating engine types which were prevalent in commercial aircraft, particularly in aircraft built during the 20th century. Recent aircraft, like the Airbus A380 or the Boeing 787 Dreamliner rely on Jet engines (e.g. TurboFan, TurboProp)." }, { "code": null, "e": 5411, "s": 5026, "text": "Next, I look at the weather conditions recorded in the dataset. Two key aviation weather conditions to be familiar with here: VMC which means that conditions are such that pilots have sufficient visibility to fly the aircraft maintaining visual separation from terrain and other aircraft. IMC which means weather conditions require pilots to fly primarily by reference to instruments." }, { "code": null, "e": 5593, "s": 5411, "text": "The bulk of accidents in the dataset take place during VMC weather conditions, which are great conditions for flying as VMC requires greater visibility and cloud clearance than IMC." }, { "code": null, "e": 5870, "s": 5593, "text": "I imagine this would go against most people’s intuition when it comes to the relationship between weather conditions and aviation accidents. Pilots are indeed well trained to fly in all sorts of weather conditions, relying solely on the avionics instruments at their disposal." }, { "code": null, "e": 6148, "s": 5870, "text": "Next, let’s look at the phases of flight for the recorded accidents in the dataset. According to the plot, the bulk of accidents took place during landing or take-off. It is well known in the industry that these are high-risk — often referred to as “critical phases of flight”." }, { "code": null, "e": 6248, "s": 6148, "text": "Let’s look at the relationship between pairs of variables that could show interesting relationship." }, { "code": null, "e": 6442, "s": 6248, "text": "The bulk of the distribution has a total fatal injuries under 10, let’s zoom in on that portion of the data. The R function geom_jitter was used to amplify the visualisation of the data points." }, { "code": null, "e": 6771, "s": 6442, "text": "According to the plot, the bulk of the data for fatalities under 10 is with the engine type reciprocating engine type. The first plot shows that the Turbo-Fan engine has more outliers with higher number of fatalities than other engines. This is likely correlated to the use of Turbo-Fan engines use on large commercial aircraft." }, { "code": null, "e": 7055, "s": 6771, "text": "As previously noted ,weather conditions do not show a particularly strong relationship with total fatal injuries. The bulk of the distribution is associate with VMC weather conditions. However, that is likely to the fact that the vast majority of flights are flown in VMC conditions." }, { "code": null, "e": 7130, "s": 7055, "text": "Let’s look at the relationship of Phase of Flight and Total Fatal Injuries" }, { "code": null, "e": 7362, "s": 7130, "text": "The plots show that Take-Off and Approach are associated with outliers with high number of fatalities. As previously noted, these two phases of flight are often referred to as “critical phases of flight” for that particular reason." }, { "code": null, "e": 7617, "s": 7362, "text": "Let’s look at the relationship of Event Date and Total Fatal Injuries. We’ll focus on the bulk of the distribution with fatalities of less than 10. There doesn’t seem to be any specific month or weekday showing a particularly high frequency of accidents." }, { "code": null, "e": 7841, "s": 7617, "text": "The plots indicates that there is higher frequency of recorded observations for certain combinations of weather and phases of flight — for example, IMC flying conditions while during “cruise” or “approach” phases of flight." }, { "code": null, "e": 8093, "s": 7841, "text": "The plots indicates that there is a higher frequency of recorded observations for Northern summer months during Landing and Take-off. Across all months, the heat map also shows that the Take-off and Landing register the highest number of observations." }, { "code": null, "e": 8521, "s": 8093, "text": "Plotting the Latitude vs Longitude of the accidents essentially gives us the map of the US. The plots also indicates that the coastal states are more heavily impacted compared to mid-western states and most of Alaska. This can be explained by the volume of flight to/from destinations those areas of the US. A sad chart however as it shows that the vast majority of US States suffered an aviation tragedy between 1948 and 2017." }, { "code": null, "e": 8559, "s": 8521, "text": "Now let’s look at multivariate plots." }, { "code": null, "e": 8758, "s": 8559, "text": "The distribution of accident months across latitude and longitude is fairly spread across the US, with a slightly higher prevalence of observations during the winter in southern states like Florida." }, { "code": null, "e": 8835, "s": 8758, "text": "Let’s now look at latitude vs longitude add layer for the weather condition." }, { "code": null, "e": 8977, "s": 8835, "text": "Weather condition VMC seems to be quite consistent except for patches of primarily IMC conditions for certain discrete areas of the mid-west." }, { "code": null, "e": 9257, "s": 8977, "text": "Let’s now look at the relationship of Broad Phase of Flight vs Month by Weather Conditions. I decided to leave the observations with “unkown” weather conditions as there is what I perceive to be non-negligible number of observations, particularly for the “Cruise”phase of flight." }, { "code": null, "e": 9620, "s": 9257, "text": "When looking at the relationship between Broad Phase of Flight vs Month and Weather Condition, we can see that accident primarily take place during VMC weather condition. However, for certain months of the year such as December an January, IMC conditions are a non-negligible portion of the observations, particularly during Approach and Cruise phases of flight." }, { "code": null, "e": 9838, "s": 9620, "text": "Next, let’s look at Total Fatal Injuries vs Broad Phases of Flight by Weather Condition. I decided to focus on total fatal injuries of less than 40 to highlight the bulk of the distribution of recorded fatal injuries." }, { "code": null, "e": 9995, "s": 9838, "text": "IMC weather conditions are associated with accidents during “Cruise” and “Approach” phases of flight with higher frequencies than in VMC weather conditions." }, { "code": null, "e": 10364, "s": 9995, "text": "This plot is interesting as it shows how certain engines have become prevalent in different time periods. For instance, Turbo-Jet and Turbo-Fan powered aircraft show a higher number of fatalities in later years whereas reciprocating engines show a distribution of fatalities in earlier years, this corresponds to the increasingly use of jet engines in modern aircraft." } ]
How to rethrow InnerException without losing stack trace in C#?
In c#, the throw is a keyword and it is useful to throw an exception manually during the execution of the program and we can handle those thrown exceptions using try−catch blocks based on our requirements. By using throw keyword in the catch block, we can re-throw an exception that is handled in the catch block. The re-throwing an exception is useful when we want to pass an exception to the caller to handle it in a way they want. Following is the example of re−throwing an exception to the caller using throw keyword with try-catch blocks in c#. class Program{ static void Main(string[] args){ try{ Method2(); } catch (System.Exception ex){ System.Console.WriteLine($"{ex.StackTrace.ToString()} {ex.Message}"); } Console.ReadLine(); } static void Method2(){ try{ Method1(); } catch (System.Exception){ throw; } } static void Method1(){ try{ throw new NullReferenceException("Null Exception error"); } catch (System.Exception){ throw; } } } This is how we can re-throw an exception to the caller using throw keyword in catch block based on our requirements. at DemoApplication.Program.Method1() in C:\Users\Koushik\Desktop\Questions\ConsoleApp\Program.cs:line 49 at DemoApplication.Program.Method2() in C:\Users\Koushik\Desktop\Questions\ConsoleApp\Program.cs:line 37 at DemoApplication.Program.Main(String[] args) in C:\Users\Koushik\Desktop\Questions\ConsoleApp\Program.cs:line 24 Null Exception error
[ { "code": null, "e": 1268, "s": 1062, "text": "In c#, the throw is a keyword and it is useful to throw an exception manually during the execution of the program and we can handle those thrown exceptions using try−catch blocks based on our requirements." }, { "code": null, "e": 1496, "s": 1268, "text": "By using throw keyword in the catch block, we can re-throw an exception that is handled in the catch block. The re-throwing an exception is useful when we want to pass an exception to the caller to handle it in a way they want." }, { "code": null, "e": 1612, "s": 1496, "text": "Following is the example of re−throwing an exception to the caller using throw keyword with try-catch blocks in c#." }, { "code": null, "e": 2156, "s": 1612, "text": "class Program{\n static void Main(string[] args){\n try{\n Method2();\n }\n catch (System.Exception ex){\n System.Console.WriteLine($\"{ex.StackTrace.ToString()} {ex.Message}\");\n }\n Console.ReadLine();\n }\n static void Method2(){\n try{\n Method1();\n }\n catch (System.Exception){\n throw;\n }\n }\n static void Method1(){\n try{\n throw new NullReferenceException(\"Null Exception error\");\n }\n catch (System.Exception){\n throw;\n }\n }\n}" }, { "code": null, "e": 2273, "s": 2156, "text": "This is how we can re-throw an exception to the caller using throw keyword in catch block based on our requirements." }, { "code": null, "e": 2619, "s": 2273, "text": "at DemoApplication.Program.Method1() in C:\\Users\\Koushik\\Desktop\\Questions\\ConsoleApp\\Program.cs:line 49\nat DemoApplication.Program.Method2() in C:\\Users\\Koushik\\Desktop\\Questions\\ConsoleApp\\Program.cs:line 37\nat DemoApplication.Program.Main(String[] args) in C:\\Users\\Koushik\\Desktop\\Questions\\ConsoleApp\\Program.cs:line 24 Null Exception error" } ]
Dart Programming - Enumeration
An enumeration is used for defining named constant values. An enumerated type is declared using the enum keyword. enum enum_name { enumeration list } Where, The enum_name specifies the enumeration type name The enumeration list is a comma-separated list of identifiers Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0. enum Status { none, running, stopped, paused } enum Status { none, running, stopped, paused } void main() { print(Status.values); Status.values.forEach((v) => print('value: $v, index: ${v.index}')); print('running: ${Status.running}, ${Status.running.index}'); print('running index: ${Status.values[1]}'); } It will produce the following output − [Status.none, Status.running, Status.stopped, Status.paused] value: Status.none, index: 0 value: Status.running, index: 1 value: Status.stopped, index: 2 value: Status.paused, index: 3 running: Status.running, 1 running index: Status.running 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": 2639, "s": 2525, "text": "An enumeration is used for defining named constant values. An enumerated type is declared using the enum keyword." }, { "code": null, "e": 2682, "s": 2639, "text": "enum enum_name { \n enumeration list \n}\n" }, { "code": null, "e": 2689, "s": 2682, "text": "Where," }, { "code": null, "e": 2739, "s": 2689, "text": "The enum_name specifies the enumeration type name" }, { "code": null, "e": 2801, "s": 2739, "text": "The enumeration list is a comma-separated list of identifiers" }, { "code": null, "e": 2980, "s": 2801, "text": "Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0." }, { "code": null, "e": 3044, "s": 2980, "text": "enum Status { \n none, \n running, \n stopped, \n paused \n}" }, { "code": null, "e": 3340, "s": 3044, "text": "enum Status { \n none, \n running, \n stopped, \n paused \n} \nvoid main() { \n print(Status.values); \n Status.values.forEach((v) => print('value: $v, index: ${v.index}'));\n print('running: ${Status.running}, ${Status.running.index}'); \n print('running index: ${Status.values[1]}'); \n}" }, { "code": null, "e": 3379, "s": 3340, "text": "It will produce the following output −" }, { "code": null, "e": 3629, "s": 3379, "text": "[Status.none, Status.running, Status.stopped, Status.paused] \nvalue: Status.none, index: 0 \nvalue: Status.running, index: 1 \nvalue: Status.stopped, index: 2 \nvalue: Status.paused, index: 3 \nrunning: Status.running, 1 \nrunning index: Status.running \n" }, { "code": null, "e": 3664, "s": 3629, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3684, "s": 3664, "text": " Sriyank Siddhartha" }, { "code": null, "e": 3717, "s": 3684, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 3737, "s": 3717, "text": " Sriyank Siddhartha" }, { "code": null, "e": 3770, "s": 3737, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 3787, "s": 3770, "text": " Frahaan Hussain" }, { "code": null, "e": 3822, "s": 3787, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 3839, "s": 3822, "text": " Frahaan Hussain" }, { "code": null, "e": 3874, "s": 3839, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3894, "s": 3874, "text": " Pranjal Srivastava" }, { "code": null, "e": 3927, "s": 3894, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 3947, "s": 3927, "text": " Pranjal Srivastava" }, { "code": null, "e": 3954, "s": 3947, "text": " Print" }, { "code": null, "e": 3965, "s": 3954, "text": " Add Notes" } ]
C# program to concat two or more Lists
Set three lists − // three lists var list1 = new List<int>{3, 4}; var list2 = new List<int>{1, 2, 3}; var list3 = new List<int>{2, 5, 6}; Now, use the Concat mthod to concat the above lists − var res1 = list1.Concat(list2); var res2 = res1.Concat(list3); Here is the complete code − Live Demo using System.Collections.Generic; using System.Linq; using System; public class Demo { public static void Main() { // three lists var list1 = new List<int>{3, 4}; var list2 = new List<int>{1, 2, 3}; var list3 = new List<int>{2, 5, 6}; // concat var res1 = list1.Concat(list2); var res2 = res1.Concat(list3); foreach(int i in res2) { Console.WriteLine(i); } } } 3 4 1 2 3 2 5 6
[ { "code": null, "e": 1080, "s": 1062, "text": "Set three lists −" }, { "code": null, "e": 1200, "s": 1080, "text": "// three lists\nvar list1 = new List<int>{3, 4};\nvar list2 = new List<int>{1, 2, 3};\nvar list3 = new List<int>{2, 5, 6};" }, { "code": null, "e": 1254, "s": 1200, "text": "Now, use the Concat mthod to concat the above lists −" }, { "code": null, "e": 1317, "s": 1254, "text": "var res1 = list1.Concat(list2);\nvar res2 = res1.Concat(list3);" }, { "code": null, "e": 1345, "s": 1317, "text": "Here is the complete code −" }, { "code": null, "e": 1356, "s": 1345, "text": " Live Demo" }, { "code": null, "e": 1790, "s": 1356, "text": "using System.Collections.Generic;\nusing System.Linq;\nusing System;\n\npublic class Demo {\n public static void Main() {\n\n // three lists\n var list1 = new List<int>{3, 4};\n var list2 = new List<int>{1, 2, 3};\n var list3 = new List<int>{2, 5, 6};\n\n // concat\n var res1 = list1.Concat(list2);\n var res2 = res1.Concat(list3);\n\n foreach(int i in res2) {\n Console.WriteLine(i);\n }\n }\n}" }, { "code": null, "e": 1806, "s": 1790, "text": "3\n4\n1\n2\n3\n2\n5\n6" } ]
Check if mirror image of a number is same if displayed in seven segment display - GeeksforGeeks
05 May, 2021 Given a positive number n. The task is to check if the mirror image of the number is equal to given number or not if displayed on Seven Line Segment. A mirror image of a number is a reflected duplication of the number that appears almost identical but is reversed in the direction perpendicular to the mirror surface.Examples: Input : n = 101 Output: Yes Mirror image of 101 is 101 on seven line segment. So, print "Yes". Input : n = 020 Output : No Observe each digit when displayed on seven line segment, only digit 0, 1, 8 remain same in their mirror image. So, for a number to be equal to its mirror image, it should contain only 0, 1, 8 digits. Also, observe, for two number to be equal their corresponding position digit should be same. Therefore, mirror image should also contain the same digit on their corresponding digit position. So, the number should also be a palindrome.Below is implementation of this approach: C++ Java Python3 C# PHP Javascript // C++ Program to check if mirror image of a number is// same if displayed in seven segment display#include <bits/stdc++.h>using namespace std; // Return "Yes", if the mirror image of number// is same as the given number// Else return "No"string checkEqual(string S){ // Checking if the number contain only 0, 1, 8. for (int i = 0; i < S.size(); i++) { if (S[i] != '1' && S[i] != '0' && S[i] != '8') { return "No"; } } int start = 0, end = S.size() - 1; // Checking if the number is palindrome or not. while (start < end) { // If corresponding index is not equal. if (S[start] != S[end]) { return "No"; } start++; end--; } return "Yes";}int main(){ string S = "101"; cout << checkEqual(S) << endl; return 0;} // Java Program to check if// mirror image of a number// is same if displayed in// seven segment displayimport java.io.*; class GFG{ // Return "Yes", if the// mirror image of number// is same as the given// number Else return "No"static String checkEqual(String S){ // Checking if the number // contain only 0, 1, 8. for (int i = 0; i < S.length(); i++) { if (S.charAt(i) != '1' && S.charAt(i) != '0' && S.charAt(i) != '8') { return "No"; } } int start = 0, end = S.length() - 1; // Checking if the number // is palindrome or not. while (start < end) { // If corresponding // index is not equal. if (S.charAt(start) != S.charAt(end)) { return "No"; } start++; end--; } return "Yes";} // Driver Codepublic static void main (String[] args){ String S = "101"; System.out.println(checkEqual(S));}} // This code is contributed// by anuj_67. # Python3 Program to check if mirror# image of a number is same if displayed# in seven segment display # Return "Yes", if the mirror image# of number is same as the given number# Else return "No"def checkEqual(S): # Checking if the number contain # only 0, 1, 8. for i in range(len(S)): if (S[i] != '1' and S[i] != '0' and S[i] != '8'): return "No"; start = 0; end = len(S) - 1; # Checking if the number is # palindrome or not. while (start < end): # If corresponding index is not equal. if (S[start] != S[end]): return "No"; start += 1; end -= 1; return "Yes"; # Driver CodeS = "101";print(checkEqual(S)); # This code is contributed by mits // C# Program to check if mirror image// of a number is same if displayed in// seven segment displayusing System; class GFG{ // Return "Yes", if the mirror image// of number is same as the given// number Else return "No"static string checkEqual(string S){ // Checking if the number // contain only 0, 1, 8. for (int i = 0; i < S.Length; i++) { if (S[i] != '1' && S[i] != '0' && S[i] != '8') { return "No"; } } int start = 0, end = S.Length - 1; // Checking if the number is // palindrome or not. while (start < end) { // If corresponding index is not equal. if (S[start] != S[end]) { return "No"; } start++; end--; } return "Yes";} // Driver Codepublic static void Main(){ string S = "101"; Console.WriteLine(checkEqual(S));}} // This code is contributed// by mits <?php// PHP Program to check if mirror image// of a number is same if displayed in// seven segment display // Return "Yes", if the mirror image// of number is same as the given number// Else return "No"function checkEqual($S){ // Checking if the number contain // only 0, 1, 8. for ($i = 0; $i < strlen($S); $i++) { if ($S[$i] != '1' && $S[$i] != '0' && $S[$i] != '8') { return "No"; } } $start = 0; $end = strlen($S) - 1; // Checking if the number is // palindrome or not. while ($start < $end) { // If corresponding index is not equal. if ($S[$start] != $S[$end]) { return "No"; } $start++; $end--; } return "Yes";} // Driver Code$S = "101";echo checkEqual($S); // This code is contributed by ajit?> <script> // Javascript Program to check if mirror image of a number is// same if displayed in seven segment display // Return "Yes", if the mirror image of number// is same as the given number// Else return "No"function checkEqual(S){ // Checking if the number contain only 0, 1, 8. for (var i = 0; i < S.length; i++) { if (S[i] != '1' && S[i] != '0' && S[i] != '8') { return "No"; } } var start = 0, end = S.length - 1; // Checking if the number is palindrome or not. while (start < end) { // If corresponding index is not equal. if (S[start] != S[end]) { return "No"; } start++; end--; } return "Yes";} var S = "101";document.write( checkEqual(S)); </script> Output Yes vt_m Mithun Kumar jit_t ManasChhabra2 rutvik_56 number-digits palindrome Mathematical Mathematical palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find GCD or HCF of two numbers Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Program for factorial of a number Operators in C / C++ Sieve of Eratosthenes Euclidean algorithms (Basic and Extended) Program for Decimal to Binary Conversion
[ { "code": null, "e": 24924, "s": 24896, "text": "\n05 May, 2021" }, { "code": null, "e": 25253, "s": 24924, "text": "Given a positive number n. The task is to check if the mirror image of the number is equal to given number or not if displayed on Seven Line Segment. A mirror image of a number is a reflected duplication of the number that appears almost identical but is reversed in the direction perpendicular to the mirror surface.Examples: " }, { "code": null, "e": 25377, "s": 25253, "text": "Input : n = 101\nOutput: Yes\nMirror image of 101 is 101 on seven line segment. So, print \"Yes\".\n\nInput : n = 020\nOutput : No" }, { "code": null, "e": 25857, "s": 25379, "text": "Observe each digit when displayed on seven line segment, only digit 0, 1, 8 remain same in their mirror image. So, for a number to be equal to its mirror image, it should contain only 0, 1, 8 digits. Also, observe, for two number to be equal their corresponding position digit should be same. Therefore, mirror image should also contain the same digit on their corresponding digit position. So, the number should also be a palindrome.Below is implementation of this approach: " }, { "code": null, "e": 25861, "s": 25857, "text": "C++" }, { "code": null, "e": 25866, "s": 25861, "text": "Java" }, { "code": null, "e": 25874, "s": 25866, "text": "Python3" }, { "code": null, "e": 25877, "s": 25874, "text": "C#" }, { "code": null, "e": 25881, "s": 25877, "text": "PHP" }, { "code": null, "e": 25892, "s": 25881, "text": "Javascript" }, { "code": "// C++ Program to check if mirror image of a number is// same if displayed in seven segment display#include <bits/stdc++.h>using namespace std; // Return \"Yes\", if the mirror image of number// is same as the given number// Else return \"No\"string checkEqual(string S){ // Checking if the number contain only 0, 1, 8. for (int i = 0; i < S.size(); i++) { if (S[i] != '1' && S[i] != '0' && S[i] != '8') { return \"No\"; } } int start = 0, end = S.size() - 1; // Checking if the number is palindrome or not. while (start < end) { // If corresponding index is not equal. if (S[start] != S[end]) { return \"No\"; } start++; end--; } return \"Yes\";}int main(){ string S = \"101\"; cout << checkEqual(S) << endl; return 0;}", "e": 26711, "s": 25892, "text": null }, { "code": "// Java Program to check if// mirror image of a number// is same if displayed in// seven segment displayimport java.io.*; class GFG{ // Return \"Yes\", if the// mirror image of number// is same as the given// number Else return \"No\"static String checkEqual(String S){ // Checking if the number // contain only 0, 1, 8. for (int i = 0; i < S.length(); i++) { if (S.charAt(i) != '1' && S.charAt(i) != '0' && S.charAt(i) != '8') { return \"No\"; } } int start = 0, end = S.length() - 1; // Checking if the number // is palindrome or not. while (start < end) { // If corresponding // index is not equal. if (S.charAt(start) != S.charAt(end)) { return \"No\"; } start++; end--; } return \"Yes\";} // Driver Codepublic static void main (String[] args){ String S = \"101\"; System.out.println(checkEqual(S));}} // This code is contributed// by anuj_67.", "e": 27743, "s": 26711, "text": null }, { "code": "# Python3 Program to check if mirror# image of a number is same if displayed# in seven segment display # Return \"Yes\", if the mirror image# of number is same as the given number# Else return \"No\"def checkEqual(S): # Checking if the number contain # only 0, 1, 8. for i in range(len(S)): if (S[i] != '1' and S[i] != '0' and S[i] != '8'): return \"No\"; start = 0; end = len(S) - 1; # Checking if the number is # palindrome or not. while (start < end): # If corresponding index is not equal. if (S[start] != S[end]): return \"No\"; start += 1; end -= 1; return \"Yes\"; # Driver CodeS = \"101\";print(checkEqual(S)); # This code is contributed by mits", "e": 28506, "s": 27743, "text": null }, { "code": "// C# Program to check if mirror image// of a number is same if displayed in// seven segment displayusing System; class GFG{ // Return \"Yes\", if the mirror image// of number is same as the given// number Else return \"No\"static string checkEqual(string S){ // Checking if the number // contain only 0, 1, 8. for (int i = 0; i < S.Length; i++) { if (S[i] != '1' && S[i] != '0' && S[i] != '8') { return \"No\"; } } int start = 0, end = S.Length - 1; // Checking if the number is // palindrome or not. while (start < end) { // If corresponding index is not equal. if (S[start] != S[end]) { return \"No\"; } start++; end--; } return \"Yes\";} // Driver Codepublic static void Main(){ string S = \"101\"; Console.WriteLine(checkEqual(S));}} // This code is contributed// by mits", "e": 29441, "s": 28506, "text": null }, { "code": "<?php// PHP Program to check if mirror image// of a number is same if displayed in// seven segment display // Return \"Yes\", if the mirror image// of number is same as the given number// Else return \"No\"function checkEqual($S){ // Checking if the number contain // only 0, 1, 8. for ($i = 0; $i < strlen($S); $i++) { if ($S[$i] != '1' && $S[$i] != '0' && $S[$i] != '8') { return \"No\"; } } $start = 0; $end = strlen($S) - 1; // Checking if the number is // palindrome or not. while ($start < $end) { // If corresponding index is not equal. if ($S[$start] != $S[$end]) { return \"No\"; } $start++; $end--; } return \"Yes\";} // Driver Code$S = \"101\";echo checkEqual($S); // This code is contributed by ajit?>", "e": 30304, "s": 29441, "text": null }, { "code": "<script> // Javascript Program to check if mirror image of a number is// same if displayed in seven segment display // Return \"Yes\", if the mirror image of number// is same as the given number// Else return \"No\"function checkEqual(S){ // Checking if the number contain only 0, 1, 8. for (var i = 0; i < S.length; i++) { if (S[i] != '1' && S[i] != '0' && S[i] != '8') { return \"No\"; } } var start = 0, end = S.length - 1; // Checking if the number is palindrome or not. while (start < end) { // If corresponding index is not equal. if (S[start] != S[end]) { return \"No\"; } start++; end--; } return \"Yes\";} var S = \"101\";document.write( checkEqual(S)); </script>", "e": 31065, "s": 30304, "text": null }, { "code": null, "e": 31074, "s": 31065, "text": "Output " }, { "code": null, "e": 31078, "s": 31074, "text": "Yes" }, { "code": null, "e": 31085, "s": 31080, "text": "vt_m" }, { "code": null, "e": 31098, "s": 31085, "text": "Mithun Kumar" }, { "code": null, "e": 31104, "s": 31098, "text": "jit_t" }, { "code": null, "e": 31118, "s": 31104, "text": "ManasChhabra2" }, { "code": null, "e": 31128, "s": 31118, "text": "rutvik_56" }, { "code": null, "e": 31142, "s": 31128, "text": "number-digits" }, { "code": null, "e": 31153, "s": 31142, "text": "palindrome" }, { "code": null, "e": 31166, "s": 31153, "text": "Mathematical" }, { "code": null, "e": 31179, "s": 31166, "text": "Mathematical" }, { "code": null, "e": 31190, "s": 31179, "text": "palindrome" }, { "code": null, "e": 31288, "s": 31190, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31297, "s": 31288, "text": "Comments" }, { "code": null, "e": 31310, "s": 31297, "text": "Old Comments" }, { "code": null, "e": 31352, "s": 31310, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 31376, "s": 31352, "text": "Merge two sorted arrays" }, { "code": null, "e": 31419, "s": 31376, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 31433, "s": 31419, "text": "Prime Numbers" }, { "code": null, "e": 31482, "s": 31433, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 31516, "s": 31482, "text": "Program for factorial of a number" }, { "code": null, "e": 31537, "s": 31516, "text": "Operators in C / C++" }, { "code": null, "e": 31559, "s": 31537, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 31601, "s": 31559, "text": "Euclidean algorithms (Basic and Extended)" } ]
Edit your videos AUTOMATICALLY with this Python code! | by Favio Vázquez | Towards Data Science
The time has come! I’m creating courses for amazing companies like Business Science and Ciencia y Datos and I’m editing videos is a pain in the a**!! The software I’ll present you here is by the great Carykh. The goal of the system is to edit the annoying silences in videos, the error we make, and almost every piece of something you’d like. It won’t transform your video into a beautiful video, but at least it will allow you to save hours and hours of listening to yourself failing. If you are not a video creator, but you consume videos on the internet this can help you watch them faster. I remember when I was studying and I watched a lot of Stanford and MIT videos, it took me hours and a lot of the time the professor wasn’t even speaking. So this can help with that too. I tested the system on MatrixDS one of the best tools for launching a terminal and a Jupyter notebook for free and in seconds. So you can reproduce that there. The first thing you need to do is to clone the repo: github.com git clone https://github.com/carykh/jumpcutter.git Then install the requirements: cd jumpcutterpip install --user -r requirements.txt You’ll also need ffmpeg. If you are in Ubuntu: sudo apt updatesudo apt install ffmpeg If you are in MatrixDS you’ll need to be root so: sudo suapt install ffmpeg Now the fun part! I created a simple video to test this out. Here you can see the original video: What I did in MatrixDS was upload the video in the same folder of the cloned repo. And then after running this command: python3 jumpcutter.py --input_file auto_2.mp4 --sounded_speed 1 --silent_speed 999999 --frame_margin 2 I had my video edited in seconds. SECONDS!! You can see the result here: THIS IS JUST AWESOME :) Right now there’s no much documentation about the software but the code is open source so you can go to the repo and see everything. The basic command is python jumpcutter.py --input_file path/to/file.mp4 You can play with this options: optional arguments: -h, --help show this help message and exit --input_file INPUT_FILE the video file you want modified --url URL A youtube url to download and process --output_file OUTPUT_FILE the output file. (optional. if not included, it'll just modify the input file name) --silent_threshold SILENT_THRESHOLD the volume amount that frames' audio needs to surpass to be consider "sounded". It ranges from 0 (silence) to 1 (max volume) --sounded_speed SOUNDED_SPEED the speed that sounded (spoken) frames should be played at. Typically 1. --silent_speed SILENT_SPEED the speed that silent frames should be played at. 999999 for jumpcutting. --frame_margin FRAME_MARGIN some silent frames adjacent to sounded frames are included to provide context. How many frames on either the side of speech should be included? That's this variable. --sample_rate SAMPLE_RATE sample rate of the input and output videos --frame_rate FRAME_RATE frame rate of the input and output videos. optional... I try to find it out myself, but it doesn't always work. --frame_quality FRAME_QUALITY quality of frames to be extracted from input video. 1 is highest, 31 is lowest, 3 is the default. Yes! You can even pass a YouTube video link and it will download the original and also change the video creating a new one. For that the command will look like this: python3 jumpcutter.py --url https://youtu.be/2MjlMpEzDA8 --sounded_speed 1 --silent_speed 999999 --frame_margin 2 --frame_rate 3 And that’s it. Lovely work. Btw, the code are just 203 lines of code! The power of Python these days amazes me. Thanks for reading this. If you have any questions please write me here: www.linkedin.com Have fun learning :)
[ { "code": null, "e": 381, "s": 172, "text": "The time has come! I’m creating courses for amazing companies like Business Science and Ciencia y Datos and I’m editing videos is a pain in the a**!! The software I’ll present you here is by the great Carykh." }, { "code": null, "e": 515, "s": 381, "text": "The goal of the system is to edit the annoying silences in videos, the error we make, and almost every piece of something you’d like." }, { "code": null, "e": 658, "s": 515, "text": "It won’t transform your video into a beautiful video, but at least it will allow you to save hours and hours of listening to yourself failing." }, { "code": null, "e": 952, "s": 658, "text": "If you are not a video creator, but you consume videos on the internet this can help you watch them faster. I remember when I was studying and I watched a lot of Stanford and MIT videos, it took me hours and a lot of the time the professor wasn’t even speaking. So this can help with that too." }, { "code": null, "e": 1112, "s": 952, "text": "I tested the system on MatrixDS one of the best tools for launching a terminal and a Jupyter notebook for free and in seconds. So you can reproduce that there." }, { "code": null, "e": 1165, "s": 1112, "text": "The first thing you need to do is to clone the repo:" }, { "code": null, "e": 1176, "s": 1165, "text": "github.com" }, { "code": null, "e": 1227, "s": 1176, "text": "git clone https://github.com/carykh/jumpcutter.git" }, { "code": null, "e": 1258, "s": 1227, "text": "Then install the requirements:" }, { "code": null, "e": 1310, "s": 1258, "text": "cd jumpcutterpip install --user -r requirements.txt" }, { "code": null, "e": 1357, "s": 1310, "text": "You’ll also need ffmpeg. If you are in Ubuntu:" }, { "code": null, "e": 1396, "s": 1357, "text": "sudo apt updatesudo apt install ffmpeg" }, { "code": null, "e": 1446, "s": 1396, "text": "If you are in MatrixDS you’ll need to be root so:" }, { "code": null, "e": 1472, "s": 1446, "text": "sudo suapt install ffmpeg" }, { "code": null, "e": 1570, "s": 1472, "text": "Now the fun part! I created a simple video to test this out. Here you can see the original video:" }, { "code": null, "e": 1690, "s": 1570, "text": "What I did in MatrixDS was upload the video in the same folder of the cloned repo. And then after running this command:" }, { "code": null, "e": 1793, "s": 1690, "text": "python3 jumpcutter.py --input_file auto_2.mp4 --sounded_speed 1 --silent_speed 999999 --frame_margin 2" }, { "code": null, "e": 1837, "s": 1793, "text": "I had my video edited in seconds. SECONDS!!" }, { "code": null, "e": 1866, "s": 1837, "text": "You can see the result here:" }, { "code": null, "e": 1890, "s": 1866, "text": "THIS IS JUST AWESOME :)" }, { "code": null, "e": 2023, "s": 1890, "text": "Right now there’s no much documentation about the software but the code is open source so you can go to the repo and see everything." }, { "code": null, "e": 2044, "s": 2023, "text": "The basic command is" }, { "code": null, "e": 2095, "s": 2044, "text": "python jumpcutter.py --input_file path/to/file.mp4" }, { "code": null, "e": 2127, "s": 2095, "text": "You can play with this options:" }, { "code": null, "e": 3585, "s": 2127, "text": "optional arguments: -h, --help show this help message and exit --input_file INPUT_FILE the video file you want modified --url URL A youtube url to download and process --output_file OUTPUT_FILE the output file. (optional. if not included, it'll just modify the input file name) --silent_threshold SILENT_THRESHOLD the volume amount that frames' audio needs to surpass to be consider \"sounded\". It ranges from 0 (silence) to 1 (max volume) --sounded_speed SOUNDED_SPEED the speed that sounded (spoken) frames should be played at. Typically 1. --silent_speed SILENT_SPEED the speed that silent frames should be played at. 999999 for jumpcutting. --frame_margin FRAME_MARGIN some silent frames adjacent to sounded frames are included to provide context. How many frames on either the side of speech should be included? That's this variable. --sample_rate SAMPLE_RATE sample rate of the input and output videos --frame_rate FRAME_RATE frame rate of the input and output videos. optional... I try to find it out myself, but it doesn't always work. --frame_quality FRAME_QUALITY quality of frames to be extracted from input video. 1 is highest, 31 is lowest, 3 is the default." }, { "code": null, "e": 3751, "s": 3585, "text": "Yes! You can even pass a YouTube video link and it will download the original and also change the video creating a new one. For that the command will look like this:" }, { "code": null, "e": 3880, "s": 3751, "text": "python3 jumpcutter.py --url https://youtu.be/2MjlMpEzDA8 --sounded_speed 1 --silent_speed 999999 --frame_margin 2 --frame_rate 3" }, { "code": null, "e": 3895, "s": 3880, "text": "And that’s it." }, { "code": null, "e": 3992, "s": 3895, "text": "Lovely work. Btw, the code are just 203 lines of code! The power of Python these days amazes me." }, { "code": null, "e": 4065, "s": 3992, "text": "Thanks for reading this. If you have any questions please write me here:" }, { "code": null, "e": 4082, "s": 4065, "text": "www.linkedin.com" } ]
C++ Program to Display Armstrong Number Between Two Intervals
An Armstrong Number is a number where the sum of the digits raised to the power of total number of digits is equal to the number. Some examples of Armstrong numbers are as follows − 3 = 3^1 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 407 = 4^3 + 0^3 + 7^3 = 64 +0 + 343 = 407 1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634 A program that displays the Armstrong numbers between two intervals is as follows. Live Demo #include <iostream> #include <cmath> using namespace std; int main() { int lowerbound, upperbound, digitSum, temp, remainderNum, digitNum ; lowerbound = 100; upperbound = 500; cout<<"Armstrong Numbers between "<<lowerbound<<" and "<<upperbound<<" are: "; for(int num = lowerbound; num <= upperbound; num++) { temp = num; digitNum = 0; while (temp != 0) { digitNum++; temp = temp/10; } temp = num; digitSum = 0; while (temp != 0) { remainderNum = temp%10; digitSum = digitSum + pow(remainderNum, digitNum); temp = temp/10; } if (num == digitSum) cout<<num<<" "; } return 0; } Armstrong Numbers between 100 and 500 are: 153 370 371 407 In the above program, Armstrong numbers between the given intervals are found. This is done using multiple steps. The lowerbound and upperbound of the interval are given. Using these, a for loop is started from lowerbound to upperbound and each number is evaluated to see if it is an Armstrong number or not. This can be seen in the following code snippet. lowerbound = 100; upperbound = 500; cout<<"Armstrong Numbers between "<<lowerbound<<" and "<<upperbound<<" are: "; for(int num = lowerbound; num <= upperbound; num++) In the for loop, first the number of digits in the number i.e in num are found. This is done by adding one to digitNum for each digit. This is demonstrated by the following code snippet. temp = num; digitNum = 0; while (temp != 0) { digitNum++; temp = temp/10; } After the number of digits are known, digitSum is calculated by adding each digit raised to the power of digitNum i.e. number of digits. This can be seen in the following code snippet. temp = num; digitSum = 0; while (temp != 0) { remainderNum = temp%10; digitSum = digitSum + pow(remainderNum, digitNum); temp = temp/10; } If the number is equal to the digitSum, then that number is an Armstrong number and it is printed. If not, then it is not an Armstrong number. This is seen in the below code snippet. if (num == digitSum) cout<<num<<" ";
[ { "code": null, "e": 1192, "s": 1062, "text": "An Armstrong Number is a number where the sum of the digits raised to the power of total number of digits is equal to the number." }, { "code": null, "e": 1244, "s": 1192, "text": "Some examples of Armstrong numbers are as follows −" }, { "code": null, "e": 1395, "s": 1244, "text": "3 = 3^1\n153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153\n407 = 4^3 + 0^3 + 7^3 = 64 +0 + 343 = 407\n1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634" }, { "code": null, "e": 1478, "s": 1395, "text": "A program that displays the Armstrong numbers between two intervals is as follows." }, { "code": null, "e": 1489, "s": 1478, "text": " Live Demo" }, { "code": null, "e": 2190, "s": 1489, "text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint main() {\n int lowerbound, upperbound, digitSum, temp, remainderNum, digitNum ;\n lowerbound = 100;\n upperbound = 500;\n cout<<\"Armstrong Numbers between \"<<lowerbound<<\" and \"<<upperbound<<\" are: \";\n for(int num = lowerbound; num <= upperbound; num++) {\n temp = num;\n digitNum = 0;\n while (temp != 0) {\n digitNum++;\n temp = temp/10;\n }\n temp = num;\n digitSum = 0;\n while (temp != 0) {\n remainderNum = temp%10;\n digitSum = digitSum + pow(remainderNum, digitNum);\n temp = temp/10;\n }\n if (num == digitSum)\n cout<<num<<\" \";\n }\n return 0;\n}" }, { "code": null, "e": 2249, "s": 2190, "text": "Armstrong Numbers between 100 and 500 are: 153 370 371 407" }, { "code": null, "e": 2558, "s": 2249, "text": "In the above program, Armstrong numbers between the given intervals are found. This is done using multiple steps. The lowerbound and upperbound of the interval are given. Using these, a for loop is started from lowerbound to upperbound and each number is evaluated to see if it is an Armstrong number or not." }, { "code": null, "e": 2606, "s": 2558, "text": "This can be seen in the following code snippet." }, { "code": null, "e": 2773, "s": 2606, "text": "lowerbound = 100;\nupperbound = 500;\ncout<<\"Armstrong Numbers between \"<<lowerbound<<\" and \"<<upperbound<<\" are: \";\nfor(int num = lowerbound; num <= upperbound; num++)" }, { "code": null, "e": 2908, "s": 2773, "text": "In the for loop, first the number of digits in the number i.e in num are found. This is done by adding one to digitNum for each digit." }, { "code": null, "e": 2960, "s": 2908, "text": "This is demonstrated by the following code snippet." }, { "code": null, "e": 3042, "s": 2960, "text": "temp = num;\ndigitNum = 0;\nwhile (temp != 0) {\n digitNum++;\n temp = temp/10;\n}" }, { "code": null, "e": 3179, "s": 3042, "text": "After the number of digits are known, digitSum is calculated by adding each digit raised to the power of digitNum i.e. number of digits." }, { "code": null, "e": 3227, "s": 3179, "text": "This can be seen in the following code snippet." }, { "code": null, "e": 3375, "s": 3227, "text": "temp = num;\ndigitSum = 0;\nwhile (temp != 0) {\n remainderNum = temp%10;\n digitSum = digitSum + pow(remainderNum, digitNum);\n temp = temp/10;\n}" }, { "code": null, "e": 3558, "s": 3375, "text": "If the number is equal to the digitSum, then that number is an Armstrong number and it is printed. If not, then it is not an Armstrong number. This is seen in the below code snippet." }, { "code": null, "e": 3595, "s": 3558, "text": "if (num == digitSum)\ncout<<num<<\" \";" } ]
iText - Rotating an Image
In this chapter, we will see how to insert an image in a PDF document and how to rotate that image, using the functions available in the iText library. You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor. To add image to the PDF, create an object of the image that is required to be added and add it using the add() method of the Document class. You can rotate an image using the setRotationAngle() method. Following are the steps to rotate an image in a PDF document. The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created. Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below. // Creating a PdfWriter String dest = "C:/itextExamples/rotatingImage.pdf"; PdfWriter writer = new PdfWriter(dest); When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified. The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor. Instantiate the PdfDocument class by passing the PdfWriter object to its constructor, as shown below. // Creating a PdfDocument PdfDocument pdfDoc = new PdfDocument(writer); Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class. The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument. Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below. // Creating a Document Document document = new Document(pdfDoc); To create an image object, first of all, create an ImageData object using the create()method of the ImageDataFactory class. As a parameter of this method, pass a string parameter representing the path of the image, as shown below. // Creating an ImageData object String imageFile = "C:/itextExamples/javafxLogo.jpg"; ImageData data = ImageDataFactory.create(imageFile); Now, instantiate the Image class of the com.itextpdf.layout.element package. While instantiating, pass the ImageData object, as a parameter to its constructor, as shown below. // Creating an Image object Image img = new Image(data); You can rotate an image using the setRotationAngle() method. To this method, you need to pass an integer representing the rotation angle by which you want to rotate the image. // Rotating the image image.setRotationAngle(45); Now, add the image object created in the previous step using the add() method of the Document class, as shown below. // Adding image to the document document.add(img); Close the document using the close() method of the Document class, as shown below. // Closing the document document.close(); The following Java program demonstrates how to rotate an image by a given angle on a PDF document using the iText library. It creates a PDF document with the name rotatingImage.pdf, adds an image to it, rotates it, and saves it in the path C:/itextExamples/. Save this code in a file with the name RotatingImage.java. import com.itextpdf.io.image.ImageData; import com.itextpdf.io.image.ImageDataFactory; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Image; public class RotatingImage { public static void main(String args[]) throws Exception { // Creating a PdfWriter String dest = "C:/itextExamples/rotatingImage.pdf"; PdfWriter writer = new PdfWriter(dest); // Creating a PdfDocument PdfDocument pdfDoc = new PdfDocument(writer); // Creating a Document Document document = new Document(pdfDoc); // Creating an ImageData object String imFile = "C:/itextExamples/logo.jpg"; ImageData data = ImageDataFactory.create(imFile); // Creating an Image object Image image = new Image(data); // Rotating the image image.setRotationAngle(45); // Adding image to the document document.add(image); // Closing the document document.close(); System.out.println("Image rotated"); } } Compile and execute the saved Java file from the Command prompt using the following commands − javac RotatingImage.java java RotatingImage Upon execution, the above program creates a PDF document displaying the following message. Image Rotated If you verify the specified path, you can find the created PDF document as shown below. Print Add Notes Bookmark this page
[ { "code": null, "e": 2520, "s": 2368, "text": "In this chapter, we will see how to insert an image in a PDF document and how to rotate that image, using the functions available in the iText library." }, { "code": null, "e": 2699, "s": 2520, "text": "You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor." }, { "code": null, "e": 2901, "s": 2699, "text": "To add image to the PDF, create an object of the image that is required to be added and add it using the add() method of the Document class. You can rotate an image using the setRotationAngle() method." }, { "code": null, "e": 2963, "s": 2901, "text": "Following are the steps to rotate an image in a PDF document." }, { "code": null, "e": 3192, "s": 2963, "text": "The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created." }, { "code": null, "e": 3341, "s": 3192, "text": "Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below." }, { "code": null, "e": 3461, "s": 3341, "text": "// Creating a PdfWriter \nString dest = \"C:/itextExamples/rotatingImage.pdf\"; \nPdfWriter writer = new PdfWriter(dest); \n" }, { "code": null, "e": 3601, "s": 3461, "text": "When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified." }, { "code": null, "e": 3853, "s": 3601, "text": "The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor." }, { "code": null, "e": 3955, "s": 3853, "text": "Instantiate the PdfDocument class by passing the PdfWriter object to its constructor, as shown below." }, { "code": null, "e": 4031, "s": 3955, "text": "// Creating a PdfDocument \nPdfDocument pdfDoc = new PdfDocument(writer); \n" }, { "code": null, "e": 4202, "s": 4031, "text": "Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class." }, { "code": null, "e": 4396, "s": 4202, "text": "The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument." }, { "code": null, "e": 4521, "s": 4396, "text": "Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below." }, { "code": null, "e": 4591, "s": 4521, "text": "// Creating a Document \nDocument document = new Document(pdfDoc); \n" }, { "code": null, "e": 4822, "s": 4591, "text": "To create an image object, first of all, create an ImageData object using the create()method of the ImageDataFactory class. As a parameter of this method, pass a string parameter representing the path of the image, as shown below." }, { "code": null, "e": 4965, "s": 4822, "text": "// Creating an ImageData object \nString imageFile = \"C:/itextExamples/javafxLogo.jpg\"; \nImageData data = ImageDataFactory.create(imageFile); \n" }, { "code": null, "e": 5141, "s": 4965, "text": "Now, instantiate the Image class of the com.itextpdf.layout.element package. While instantiating, pass the ImageData object, as a parameter to its constructor, as shown below." }, { "code": null, "e": 5200, "s": 5141, "text": "// Creating an Image object \nImage img = new Image(data);\n" }, { "code": null, "e": 5376, "s": 5200, "text": "You can rotate an image using the setRotationAngle() method. To this method, you need to pass an integer representing the rotation angle by which you want to rotate the image." }, { "code": null, "e": 5429, "s": 5376, "text": "// Rotating the image \nimage.setRotationAngle(45); \n" }, { "code": null, "e": 5546, "s": 5429, "text": "Now, add the image object created in the previous step using the add() method of the Document class, as shown below." }, { "code": null, "e": 5600, "s": 5546, "text": "// Adding image to the document \ndocument.add(img); \n" }, { "code": null, "e": 5683, "s": 5600, "text": "Close the document using the close() method of the Document class, as shown below." }, { "code": null, "e": 5728, "s": 5683, "text": "// Closing the document \ndocument.close(); \n" }, { "code": null, "e": 5851, "s": 5728, "text": "The following Java program demonstrates how to rotate an image by a given angle on a PDF document using the iText library." }, { "code": null, "e": 5987, "s": 5851, "text": "It creates a PDF document with the name rotatingImage.pdf, adds an image to it, rotates it, and saves it in the path C:/itextExamples/." }, { "code": null, "e": 6046, "s": 5987, "text": "Save this code in a file with the name RotatingImage.java." }, { "code": null, "e": 7405, "s": 6046, "text": "import com.itextpdf.io.image.ImageData; \nimport com.itextpdf.io.image.ImageDataFactory; \n\nimport com.itextpdf.kernel.pdf.PdfDocument; \nimport com.itextpdf.kernel.pdf.PdfWriter; \n\nimport com.itextpdf.layout.Document; \nimport com.itextpdf.layout.element.Image; \n\npublic class RotatingImage { \n public static void main(String args[]) throws Exception { \n // Creating a PdfWriter \n String dest = \"C:/itextExamples/rotatingImage.pdf\"; \n PdfWriter writer = new PdfWriter(dest); \n \n // Creating a PdfDocument \n PdfDocument pdfDoc = new PdfDocument(writer); \n \n // Creating a Document \n Document document = new Document(pdfDoc); \n \n // Creating an ImageData object \n String imFile = \"C:/itextExamples/logo.jpg\"; \n ImageData data = ImageDataFactory.create(imFile); \n \n // Creating an Image object \n Image image = new Image(data); \n \n // Rotating the image \n image.setRotationAngle(45); \n \n // Adding image to the document \n document.add(image); \n \n // Closing the document \n document.close(); \n \n System.out.println(\"Image rotated\"); \n } \n} " }, { "code": null, "e": 7500, "s": 7405, "text": "Compile and execute the saved Java file from the Command prompt using the following commands −" }, { "code": null, "e": 7547, "s": 7500, "text": "javac RotatingImage.java \njava RotatingImage \n" }, { "code": null, "e": 7638, "s": 7547, "text": "Upon execution, the above program creates a PDF document displaying the following message." }, { "code": null, "e": 7653, "s": 7638, "text": "Image Rotated\n" }, { "code": null, "e": 7741, "s": 7653, "text": "If you verify the specified path, you can find the created PDF document as shown below." }, { "code": null, "e": 7748, "s": 7741, "text": " Print" }, { "code": null, "e": 7759, "s": 7748, "text": " Add Notes" } ]
Find minimum element of ArrayList with Java Collections
In order to compute minimum element of ArrayList with Java Collections, we use the Collections.min() method. The java.util.Collections.min() returns the minimum element of the given collection. All elements must be mutually comparable and implement the comparable interface. They shouldn’t throw a ClassCastException. Declaration −The Collections.min() method is declared as follows − public static <T extends Object & Comparable> T min(Collection c) where c is the collection object whose minimum is to be found. Let us see a program to find the minimum element of ArrayList with Java collections − Live Demo import java.util.*; public class Example { public static void main (String[] args) { List<Integer> list = new ArrayList<Integer>(); try { list.add(14); list.add(2); list.add(73); System.out.println("Minimum element : " + Collections.min(list)); } catch (ClassCastException | NoSuchElementException e) { System.out.println("Exception caught : " + e); } } } Minimum element : 2
[ { "code": null, "e": 1380, "s": 1062, "text": "In order to compute minimum element of ArrayList with Java Collections, we use the Collections.min() method. The java.util.Collections.min() returns the minimum element of the given collection. All elements must be mutually comparable and implement the comparable interface. They shouldn’t throw a ClassCastException." }, { "code": null, "e": 1447, "s": 1380, "text": "Declaration −The Collections.min() method is declared as follows −" }, { "code": null, "e": 1513, "s": 1447, "text": "public static <T extends Object & Comparable> T min(Collection c)" }, { "code": null, "e": 1576, "s": 1513, "text": "where c is the collection object whose minimum is to be found." }, { "code": null, "e": 1662, "s": 1576, "text": "Let us see a program to find the minimum element of ArrayList with Java collections −" }, { "code": null, "e": 1673, "s": 1662, "text": " Live Demo" }, { "code": null, "e": 2110, "s": 1673, "text": "import java.util.*;\npublic class Example {\n public static void main (String[] args) {\n List<Integer> list = new ArrayList<Integer>();\n try {\n list.add(14);\n list.add(2);\n list.add(73);\n System.out.println(\"Minimum element : \" + Collections.min(list));\n }\n catch (ClassCastException | NoSuchElementException e) {\n System.out.println(\"Exception caught : \" + e);\n }\n }\n}" }, { "code": null, "e": 2130, "s": 2110, "text": "Minimum element : 2" } ]
Microprocessor - 8085 Instruction Sets
Let us take a look at the programming of 8085 Microprocessor. Instruction sets are instruction codes to perform some task. It is classified into five categories. Following is the table showing the list of Control instructions with their meanings. Following is the table showing the list of Logical instructions with their meanings. Following is the table showing the list of Branching instructions with their meanings. Following is the table showing the list of Arithmetic instructions with their meanings. Following is the table showing the list of Data-transfer instructions with their meanings. Now, let us take a look at some program demonstrations using the above instructions − Write a program to add data at 3005H & 3006H memory location and store the result at 3007H memory location. Problem demo − (3005H) = 14H (3006H) = 89H Result − 14H + 89H = 9DH The program code can be written like this − LXI H 3005H : "HL points 3005H" MOV A, M : "Getting first operand" INX H : "HL points 3006H" ADD M : "Add second operand" INX H : "HL points 3007H" MOV M, A : "Store result at 3007H" HLT : "Exit program" Write a program to exchange the data at 5000M& 6000M memory location. LDA 5000M : "Getting the contents at5000M location into accumulator" MOV B, A : "Save the contents into B register" LDA 6000M : "Getting the contents at 6000M location into accumulator" STA 5000M : "Store the contents of accumulator at address 5000M" MOV A, B : "Get the saved contents back into A register" STA 6000M : "Store the contents of accumulator at address 6000M" Write a program to arrange first 10 numbers from memory address 3000H in an ascending order. MVI B, 09 :"Initialize counter" START :"LXI H, 3000H: Initialize memory pointer" MVI C, 09H :"Initialize counter 2" BACK: MOV A, M :"Get the number" INX H :"Increment memory pointer" CMP M :"Compare number with next number" JC SKIP :"If less, don’t interchange" JZ SKIP :"If equal, don’t interchange" MOV D, M MOV M, A DCX H MOV M, D INX H :"Interchange two numbers" SKIP:DCR C :"Decrement counter 2" JNZ BACK :"If not zero, repeat" DCR B :"Decrement counter 1" JNZ START HLT :"Terminate program execution" 50 Lectures 6.5 hours Gowthami Swarna Print Add Notes Bookmark this page
[ { "code": null, "e": 2523, "s": 2461, "text": "Let us take a look at the programming of 8085 Microprocessor." }, { "code": null, "e": 2623, "s": 2523, "text": "Instruction sets are instruction codes to perform some task. It is classified into five categories." }, { "code": null, "e": 2708, "s": 2623, "text": "Following is the table showing the list of Control instructions with their meanings." }, { "code": null, "e": 2793, "s": 2708, "text": "Following is the table showing the list of Logical instructions with their meanings." }, { "code": null, "e": 2880, "s": 2793, "text": "Following is the table showing the list of Branching instructions with their meanings." }, { "code": null, "e": 2968, "s": 2880, "text": "Following is the table showing the list of Arithmetic instructions with their meanings." }, { "code": null, "e": 3059, "s": 2968, "text": "Following is the table showing the list of Data-transfer instructions with their meanings." }, { "code": null, "e": 3145, "s": 3059, "text": "Now, let us take a look at some program demonstrations using the above instructions −" }, { "code": null, "e": 3253, "s": 3145, "text": "Write a program to add data at 3005H & 3006H memory location and store the result at 3007H memory location." }, { "code": null, "e": 3268, "s": 3253, "text": "Problem demo −" }, { "code": null, "e": 3301, "s": 3268, "text": "(3005H) = 14H \n (3006H) = 89H\n" }, { "code": null, "e": 3310, "s": 3301, "text": "Result −" }, { "code": null, "e": 3326, "s": 3310, "text": "14H + 89H = 9DH" }, { "code": null, "e": 3370, "s": 3326, "text": "The program code can be written like this −" }, { "code": null, "e": 3627, "s": 3370, "text": "LXI H 3005H : \"HL points 3005H\" \nMOV A, M : \"Getting first operand\" \nINX H : \"HL points 3006H\" \nADD M : \"Add second operand\" \nINX H : \"HL points 3007H\" \nMOV M, A : \"Store result at 3007H\" \nHLT : \"Exit program\" " }, { "code": null, "e": 3697, "s": 3627, "text": "Write a program to exchange the data at 5000M& 6000M memory location." }, { "code": null, "e": 4090, "s": 3697, "text": "LDA 5000M : \"Getting the contents at5000M location into accumulator\" \nMOV B, A : \"Save the contents into B register\" \nLDA 6000M : \"Getting the contents at 6000M location into accumulator\" \nSTA 5000M : \"Store the contents of accumulator at address 5000M\" \nMOV A, B : \"Get the saved contents back into A register\" \nSTA 6000M : \"Store the contents of accumulator at address 6000M\" " }, { "code": null, "e": 4183, "s": 4090, "text": "Write a program to arrange first 10 numbers from memory address 3000H in an ascending order." }, { "code": null, "e": 4841, "s": 4183, "text": "MVI B, 09 :\"Initialize counter\" \nSTART :\"LXI H, 3000H: Initialize memory pointer\" \nMVI C, 09H :\"Initialize counter 2\" \nBACK: MOV A, M :\"Get the number\" \nINX H :\"Increment memory pointer\" \nCMP M :\"Compare number with next number\" \nJC SKIP :\"If less, don’t interchange\" \nJZ SKIP :\"If equal, don’t interchange\" \nMOV D, M \nMOV M, A \nDCX H \nMOV M, D \nINX H :\"Interchange two numbers\" \nSKIP:DCR C :\"Decrement counter 2\" \nJNZ BACK :\"If not zero, repeat\" \nDCR B :\"Decrement counter 1\" \nJNZ START \nHLT :\"Terminate program execution\" " }, { "code": null, "e": 4876, "s": 4841, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4893, "s": 4876, "text": " Gowthami Swarna" }, { "code": null, "e": 4900, "s": 4893, "text": " Print" }, { "code": null, "e": 4911, "s": 4900, "text": " Add Notes" } ]
C++ Program to Find the Edge Connectivity of a Graph
In this program we need to find the Edge Connectivity of a Graph. An Edge Connectivity of a Graph of a graph means it is a bridge, removing it graph will be disconnected. Number of connected components increases with the removing of bridge in a disconnected undirected graph. Begin Function connections() is a recursive function to find out the connections: A) Mark the current node un visited. B) Initialize time and low value C) Go through all vertices adjacent to this D) Check if the subtree rooted with x has a connection to one of the ancestors of w. If the lowest vertex reachable from subtree under x is below u in DFS tree, then w-x has a connection. E) Update low value of w for parent function calls. End Begin Function Con() that uses connections(): A) Mark all the vertices as unvisited. B) Initialize par and visited, and connections. C) Print the connections between the edges in the graph. End #include<iostream> #include <list> #define N -1 using namespace std; class G { //declaration of functions int n; list<int> *adj; void connections(int n, bool visited[], int disc[], int low[], int par[]); public: G(int n); //constructor void addEd(int w, int x); void Con(); }; G::G(int n) { this->n = n; adj = new list<int> [n]; } //add edges to the graph void G::addEd(int w, int x) { adj[x].push_back(w); //add u to v's list adj[w].push_back(x); //add v to u's list } void G::connections(int w, bool visited[], int dis[], int low[], int par[]) { static int t = 0; //mark current node as visited visited[w] = true; dis[w] = low[w] = ++t; //Go through all adjacent vertices list<int>::iterator i; for (i = adj[w].begin(); i != adj[w].end(); ++i) { int x = *i; //x is current adjacent if (!visited[x]) { par[x] = w; connections(x, visited, dis, low, par); low[w] = min(low[w], low[x]); // If the lowest vertex reachable from subtree under x is below w in DFS tree, then w-x is a connection if (low[x] > dis[w]) cout << w << " " << x << endl; } else if (x != par[w]) low[w] = min(low[w], dis[x]); } } void G::Con() { // Mark all the vertices as unvisited bool *visited = new bool[n]; int *dis = new int[n]; int *low = new int[n]; int *par = new int[n]; for (int i = 0; i < n; i++) { par[i] = N; visited[i] = false; } //call the function connections() to find edge connections for (int i = 0; i < n; i++) if (visited[i] == false) connections(i, visited, dis, low, par); } int main() { cout << "\nConnections in first graph \n"; G g1(5); g1.addEd(1, 2); g1.addEd(3, 2); g1.addEd(2, 1); g1.addEd(0, 1); g1.addEd(1, 4); g1.Con(); return 0; } Connections in first graph 2 3 1 2 1 4 0 1
[ { "code": null, "e": 1338, "s": 1062, "text": "In this program we need to find the Edge Connectivity of a Graph. An Edge Connectivity of a Graph of a graph means it is a bridge, removing it graph will be disconnected. Number of connected components increases with the removing of bridge in a disconnected undirected graph." }, { "code": null, "e": 2002, "s": 1338, "text": "Begin\n Function connections() is a recursive function to find out the connections:\n A) Mark the current node un visited.\n B) Initialize time and low value\n C) Go through all vertices adjacent to this\n D) Check if the subtree rooted with x has a connection to one of the ancestors of w. If the lowest vertex reachable from subtree under x is below u in DFS tree, then w-x has a connection.\n E) Update low value of w for parent function calls.\nEnd\nBegin\n Function Con() that uses connections():\n A) Mark all the vertices as unvisited.\n B) Initialize par and visited, and connections.\n C) Print the connections between the edges in the graph.\nEnd" }, { "code": null, "e": 3875, "s": 2002, "text": "#include<iostream>\n#include <list>\n#define N -1\nusing namespace std;\nclass G {\n //declaration of functions\n int n;\n list<int> *adj;\n void connections(int n, bool visited[], int disc[], int low[],\n int par[]);\n public:\n G(int n); //constructor\n void addEd(int w, int x);\n void Con();\n};\nG::G(int n) {\n this->n = n;\n adj = new list<int> [n];\n}\n//add edges to the graph\nvoid G::addEd(int w, int x) {\n adj[x].push_back(w); //add u to v's list\n adj[w].push_back(x); //add v to u's list\n}\nvoid G::connections(int w, bool visited[], int dis[], int low[], int par[]) {\n static int t = 0;\n //mark current node as visited\n visited[w] = true;\n dis[w] = low[w] = ++t;\n //Go through all adjacent vertices\n list<int>::iterator i;\n for (i = adj[w].begin(); i != adj[w].end(); ++i) {\n int x = *i; //x is current adjacent\n if (!visited[x]) {\n par[x] = w;\n connections(x, visited, dis, low, par);\n low[w] = min(low[w], low[x]);\n // If the lowest vertex reachable from subtree under x is below w in DFS tree, then w-x is a connection\n if (low[x] > dis[w])\n cout << w << \" \" << x << endl;\n } else if (x != par[w])\n low[w] = min(low[w], dis[x]);\n }\n}\nvoid G::Con() {\n // Mark all the vertices as unvisited\n bool *visited = new bool[n];\n int *dis = new int[n];\n int *low = new int[n];\n int *par = new int[n];\n for (int i = 0; i < n; i++) {\n par[i] = N;\n visited[i] = false;\n }\n //call the function connections() to find edge connections\n for (int i = 0; i < n; i++)\n if (visited[i] == false)\n connections(i, visited, dis, low, par);\n}\nint main() {\n cout << \"\\nConnections in first graph \\n\";\n G g1(5);\n g1.addEd(1, 2);\n g1.addEd(3, 2);\n g1.addEd(2, 1);\n g1.addEd(0, 1);\n g1.addEd(1, 4);\n g1.Con();\n return 0;\n}" }, { "code": null, "e": 3918, "s": 3875, "text": "Connections in first graph\n2 3\n1 2\n1 4\n0 1" } ]
Dataset Biases: Institutionalized Discrimination or Adequate Transparency? | by Mathieu Lemay | Towards Data Science
[...] Why would we need such a law? Prior to Congress’s enacting HMDA in 1975, the public raised considerable concerns about mortgages — or, more importantly, the lack thereof — in some urban, often minority, neighborhoods. Certain areas seemed to decline, in part because their residents were not able to obtain home mortgages. (ClevelandFed) This was one of the sad realities of certain American population centers in the 1970s. Access to capital remained difficult, and social mobility for at-risk neighborhoods was quasi-non-existent. This difficulty was accentuated by some believed to be institutionalized racism in the banking system. “Congress believed that some financial institutions had contributed to the decline of some geographic areas by their failure to provide adequate home financing to qualified applicants on reasonable terms and conditions.” (Wikipedia) Therefore, a motion was brought forward to Congress to support transparency across all lending practices. They passed the Home Mortgage Disclosure Act of 1975 for mandatory reporting of all loan applications, and then the Community Reinvestment Act of 1977 for encouraging financial institutions to help meet the credit needs of their local communities. There is a very clear mandate to the HMDA, as explained by Investopedia: In general the primary purposes of the Home Mortgage Disclosure Act and Regulation C are to monitor the geographic targets of mortgage lenders, provide an identification mechanism for any predatory lending practices and to provide reporting statistics on the mortgage market to the government. The HMDA helps to support the community investment initiatives sponsored by government programs, with HMDA contributing to the oversight of the initiatives through statistical reporting. HMDA also helps government officials to identify any predatory lending practices which may be affecting mortgage loan issuance. HMDA submissions also provide a means for analyzing government resource allocations and ensuring that resources are appropriately allocated to fund community initiatives. Therefore, financial institutions must report on their lending practices specifically by reporting not only all of the loans issued but also every loan application with the associated metadata of the applicant(s), such as race, gender, and neighborhood, as well as if the loan was approved or denied. From a regulatory perspective, there was now a lens through which violations to social equality can be tracked and penalties applied. This also means that there is an intentional bias in the data — that of institutionalized racism across the banking sector, and all of its manifestations. Let’s explore the Home Mortgage Disclosure Data Files (1981–2014) from the US Archives to get a sense of what has been reported, and why. (If you want to explore this dataset at home, you’ll also need a few more datasets, such as the relevant census data. Luckily, the superstar team of librarians at the US Archives packaged everything up for us in a single page. Thank your local librarian.) By exploring the data, we see that the 1981–1990 period was primarily focused on tracking veterans, many of them returning from Vietnam. A lot more of the questions and data pertains to VA applicants, and if they had requested financial support to apply for the loan. The encoded format is quite straightforward, just needs a bit of mapping: [{'NAME': 'respondentName', 'START': 0, 'STOP': 28, 'LENGTH': 28}, {'NAME': 'respondentID', 'START': 28, 'STOP': 36, 'LENGTH': 8}, {'NAME': 'reportMSA', 'START': 36, 'STOP': 40, 'LENGTH': 4}, {'NAME': 'censusTract', 'START': 40, 'STOP': 46, 'LENGTH': 6}, {'NAME': 'state', 'START': 46, 'STOP': 48, 'LENGTH': 2}, {'NAME': 'county', 'START': 48, 'STOP': 51, 'LENGTH': 3}, {'NAME': 'supervisoryAgencyCode', 'START': 51, 'STOP': 52, 'LENGTH': 1}, {'NAME': 'censusValidityFlag', 'START': 52, 'STOP': 54, 'LENGTH': 2}, {'NAME': 'VA_FHA', 'START': 54, 'STOP': 55, 'LENGTH': 1}, {'NAME': 'vaNumLoans', 'START': 55, 'STOP': 59, 'LENGTH': 4}, {'NAME': 'vaTotalLoans', 'START': 59, 'STOP': 68, 'LENGTH': 8}, {'NAME': 'convLoansFlag', 'START': 68, 'STOP': 69, 'LENGTH': 1}, {'NAME': 'convNumLoans', 'START': 69, 'STOP': 73, 'LENGTH': 4}, {'NAME': 'convTotalLoans', 'START': 73, 'STOP': 82, 'LENGTH': 9}, {'NAME': 'hiFlag', 'START': 82, 'STOP': 83, 'LENGTH': 1}, {'NAME': 'hiNumLoans', 'START': 83, 'STOP': 87, 'LENGTH': 4}, {'NAME': 'hiTotalLoans', 'START': 87, 'STOP': 96, 'LENGTH': 9}, {'NAME': 'multiFlag', 'START': 96, 'STOP': 97, 'LENGTH': 1}, {'NAME': 'multiNumLoans', 'START': 97, 'STOP': 101, 'LENGTH': 4}, {'NAME': 'multiTotalLoans', 'START': 101, 'STOP': 110, 'LENGTH': 9}, {'NAME': 'nonFlag', 'START': 110, 'STOP': 111, 'LENGTH': 1}, {'NAME': 'nonNumLoans', 'START': 111, 'STOP': 115, 'LENGTH': 4}, {'NAME': 'nonTotalLoans', 'START': 115, 'STOP': 124, 'LENGTH': 9}, {'NAME': 'recordQuality', 'START': 124, 'STOP': 125, 'LENGTH': 1}] Overall, lots of VA considerations. A big change was introduced in 1989 to the tracking priorities. From the FFIEC: “[...] In 1989, the Federal Reserve Board revised Regulation C, to incorporate amendments contained in the Financial Institutions Reform, Recovery and Enforcement Act (FIRREA). The FIRREA amendments accomplished the following: expanded the coverage of HMDA to include mortgage lenders not affiliated with depository institutions or holding companies; required reporting of data regarding the disposition of applications for mortgage and home improvement loans in addition to data regarding loan originations and purchases; and required most lenders to identify the race, sex, and income of loan applicants and borrowers.” As expected, the file mappings changes significantly, bt now follows a pattern usable until 2014: [{'NAME': 'ASOF_DATE', 'START': 0, 'STOP': 4, 'LENGTH': 4}, {'NAME': 'RESP_ID', 'START': 4, 'STOP': 14, 'LENGTH': 10}, {'NAME': 'AGENCY_CODE', 'START': 14, 'STOP': 15, 'LENGTH': 1}, {'NAME': 'LOAN_TYPE', 'START': 15, 'STOP': 16, 'LENGTH': 1}, {'NAME': 'LOAN_PURPOSE', 'START': 16, 'STOP': 17, 'LENGTH': 1}, {'NAME': 'OCCUPANCY', 'START': 17, 'STOP': 18, 'LENGTH': 1}, {'NAME': 'LOAN_AMOUNT', 'START': 18, 'STOP': 23, 'LENGTH': 5}, {'NAME': 'ACTION_TYPE', 'START': 23, 'STOP': 24, 'LENGTH': 1}, {'NAME': 'PROPERTY_MSA', 'START': 24, 'STOP': 28, 'LENGTH': 4}, {'NAME': 'STATE_CODE', 'START': 28, 'STOP': 30, 'LENGTH': 2}, {'NAME': 'COUNTY_CODE', 'START': 30, 'STOP': 33, 'LENGTH': 3}, {'NAME': 'CENSUS_TRACT_NUMBER', 'START': 33, 'STOP': 40, 'LENGTH': 7}, {'NAME': 'RACE_APPLICANT', 'START': 40, 'STOP': 41, 'LENGTH': 1}, {'NAME': 'RACE_COAPPLICANT', 'START': 41, 'STOP': 42, 'LENGTH': 1}, {'NAME': 'SEX_APPLICANT', 'START': 42, 'STOP': 43, 'LENGTH': 1}, {'NAME': 'SEX_COAPPLICANT', 'START': 43, 'STOP': 44, 'LENGTH': 1}, {'NAME': 'APPLICANT_INCOME', 'START': 44, 'STOP': 48, 'LENGTH': 4}, {'NAME': 'PURCHASER_TYPE', 'START': 48, 'STOP': 49, 'LENGTH': 1}, {'NAME': 'DENIAL_REASON_1', 'START': 49, 'STOP': 50, 'LENGTH': 1}, {'NAME': 'DENIAL_REASON_2', 'START': 50, 'STOP': 51, 'LENGTH': 1}, {'NAME': 'DENIAL_REASON_3', 'START': 51, 'STOP': 52, 'LENGTH': 1}, {'NAME': 'EDIT_STATUS', 'START': 52, 'STOP': 53, 'LENGTH': 1}, {'NAME': 'SEQUENCE_NUMBER', 'START': 53, 'STOP': 60, 'LENGTH': 7}] This means that we can now tell, for every application: The race and gender of the applicant; the race and gender of the co-applicant; the neighborhood that they were in; the purpose of the loan (house or repair); the list of reasons why a loan might’ve been denied; the total number of forms required to be submitted; and each and every one of the dates of the application process. Was a loan application intentionally slowplayed? Was a home repair denied that would’ve otherwise been approved? What about same-sex co-applicants? All visible. (Note: we haven’t made our processed data available yet, as we’re still processing and investigating it. There are many reporting errors, like state acronyms instead of state codes, erroneous census tracks, and many other issues that still require a tremendous amount of preprocessing of the data to make sense of decades-long shifts in social norms. It would be unwise to come to any conclusions with it at this time. ) Over the years, there’s more and more adherence to the program across most banks. The digitization wave that spread across the US can be verified year over year. There’s also a distinct shift downwards of less and less mortgage loan applications, stemming most likely from the subprime mortgage crisis: Great so far, isn’t it? Now, here’s the double-edged sword about this data: The same data that can be used to protect citizens against predatory bank practices can be used as a discriminatory weapon against them if data scientists do not understand the data they are using. How so? This dataset now has within it every bias, preferential treatment, and erroneously or maliciously declined loan application. Every possible discriminatory event is permanently recorded. There is no sanitizing possible of this data. The HMDA dataset is biased — absolutely. It’s up to the data scientists to understand what are the right questions to ask, and more importantly, what not to ask. By any measure, this data set can be considered invasive and discriminatory. Canada, usually considered a (slightly) more tolerant country, has a different approach to tracking race and racism. As explained in The Conversation: Canada’s anti-racism strategy, which draws on decades’ worth of research, states that race is a social construct. There is no basis for classifying people according to race, but racial bias and discrimination have very real effects. The question is: How do we get relevant data from the census and other surveys on the impact of systemic racism? Statistics Canada tries to gather this information without directly asking about race. Race-based data is needed, says Jean-Pierre Corbeil, a diversity specialist at Statistics Canada. But he wonders whether that actually requires referring to race on the census. Historically, the government has been reluctant to ask directly about race, which has led to a lack of disaggregated data. After the Second World War, the census used indirect methods of estimating the non-white, non-Indigenous population through racial proxies like language or ethnocultural origin. (Note: one of the major complaints against Canadian multiculturalism as a pillar of civil society is that it allows for people to classify others by ethnicity or nationality, under the veil of a self-assigned permission structure, but that’s a topic for later.) So, this means some countries refuse to track the race and gender of bank loan applicants, as measuring racism fundamentally amplifies its very divisive nature of bucketing people into categories. And so, looking back at the HMDA data, the question that can be asked is, “should this data even exist?” I believe the answer is a strong yes. The Act has yielded tremendous protection to the public, especially with a major investigation back in 2005. From the Buffalo News: New York Attorney General Eliot Spitzer has fired his latest salvo, launching a preliminary probe into mortgage lending practices at eight major banks in the state, including HSBC Bank USA. [...] Investigators are trying to determine how the banks price their loans, and if fees and interest rates are being applied fairly, or whether there’s racial discrimination. [...] Citigroup already agreed in 2002 to pay $215 million to settle allegations by the Federal Trade Commission that Associates First Capital Corp. — which Citi bought in 2000 — had engaged in predatory lending. Associates’ rival Household International — acquired by HSBC Holdings Plc in 2003 — paid $484 million in 2002 to settle similar charges by all 50 states in the largest consumer settlement ever. However, although this data has yielded success, it’s up to the data scientists to understand what are the right questions to ask, and more importantly what not to ask. For instance, trying to build a mortgage loan approval pipeline from this data is a horrendous and terrible idea — you now have a racist, homophobic bot. However, if you wish to investigate the very nature of institutionalized discrimination by investigating outliers, then you have a tremendous weapon at your disposal. How you wield that weapon is up to you. Additional Reading Revisiting the CRA: Perspectives on the Future of the Community Reinvestment Act, A Joint Publication of the Federal Reserve Banks of Boston and San Francisco, February 2009. Privacy Impact Assessment of the Home Mortgage Disclosure Act Data Repository System, Board of Governors of the US Federal Reserve, November 2020. I wrote the law Bloomberg blames for the financial crisis. He’s wrong., Robert Kuttner, op-ed in the Washington Post, February 15, 2020. History of the HMDA, Federal Financial Institutions Examination Council, January 2018. Happy Consulting! -Matt. If you have additional questions about this article or our AI consulting framework, feel free to reach out by LinkedIn or by email. How Does AI Create Value? Implementing a Corporate AI Strategy Outlier-Aware Clustering: Beyond K-Means Rorschach Tests for Deep Learning Image Classifiers
[ { "code": null, "e": 515, "s": 171, "text": "[...] Why would we need such a law? Prior to Congress’s enacting HMDA in 1975, the public raised considerable concerns about mortgages — or, more importantly, the lack thereof — in some urban, often minority, neighborhoods. Certain areas seemed to decline, in part because their residents were not able to obtain home mortgages. (ClevelandFed)" }, { "code": null, "e": 1046, "s": 515, "text": "This was one of the sad realities of certain American population centers in the 1970s. Access to capital remained difficult, and social mobility for at-risk neighborhoods was quasi-non-existent. This difficulty was accentuated by some believed to be institutionalized racism in the banking system. “Congress believed that some financial institutions had contributed to the decline of some geographic areas by their failure to provide adequate home financing to qualified applicants on reasonable terms and conditions.” (Wikipedia)" }, { "code": null, "e": 1400, "s": 1046, "text": "Therefore, a motion was brought forward to Congress to support transparency across all lending practices. They passed the Home Mortgage Disclosure Act of 1975 for mandatory reporting of all loan applications, and then the Community Reinvestment Act of 1977 for encouraging financial institutions to help meet the credit needs of their local communities." }, { "code": null, "e": 1473, "s": 1400, "text": "There is a very clear mandate to the HMDA, as explained by Investopedia:" }, { "code": null, "e": 1767, "s": 1473, "text": "In general the primary purposes of the Home Mortgage Disclosure Act and Regulation C are to monitor the geographic targets of mortgage lenders, provide an identification mechanism for any predatory lending practices and to provide reporting statistics on the mortgage market to the government." }, { "code": null, "e": 2082, "s": 1767, "text": "The HMDA helps to support the community investment initiatives sponsored by government programs, with HMDA contributing to the oversight of the initiatives through statistical reporting. HMDA also helps government officials to identify any predatory lending practices which may be affecting mortgage loan issuance." }, { "code": null, "e": 2253, "s": 2082, "text": "HMDA submissions also provide a means for analyzing government resource allocations and ensuring that resources are appropriately allocated to fund community initiatives." }, { "code": null, "e": 2554, "s": 2253, "text": "Therefore, financial institutions must report on their lending practices specifically by reporting not only all of the loans issued but also every loan application with the associated metadata of the applicant(s), such as race, gender, and neighborhood, as well as if the loan was approved or denied." }, { "code": null, "e": 2843, "s": 2554, "text": "From a regulatory perspective, there was now a lens through which violations to social equality can be tracked and penalties applied. This also means that there is an intentional bias in the data — that of institutionalized racism across the banking sector, and all of its manifestations." }, { "code": null, "e": 2981, "s": 2843, "text": "Let’s explore the Home Mortgage Disclosure Data Files (1981–2014) from the US Archives to get a sense of what has been reported, and why." }, { "code": null, "e": 3237, "s": 2981, "text": "(If you want to explore this dataset at home, you’ll also need a few more datasets, such as the relevant census data. Luckily, the superstar team of librarians at the US Archives packaged everything up for us in a single page. Thank your local librarian.)" }, { "code": null, "e": 3505, "s": 3237, "text": "By exploring the data, we see that the 1981–1990 period was primarily focused on tracking veterans, many of them returning from Vietnam. A lot more of the questions and data pertains to VA applicants, and if they had requested financial support to apply for the loan." }, { "code": null, "e": 3579, "s": 3505, "text": "The encoded format is quite straightforward, just needs a bit of mapping:" }, { "code": null, "e": 5111, "s": 3579, "text": "[{'NAME': 'respondentName', 'START': 0, 'STOP': 28, 'LENGTH': 28}, {'NAME': 'respondentID', 'START': 28, 'STOP': 36, 'LENGTH': 8}, {'NAME': 'reportMSA', 'START': 36, 'STOP': 40, 'LENGTH': 4}, {'NAME': 'censusTract', 'START': 40, 'STOP': 46, 'LENGTH': 6}, {'NAME': 'state', 'START': 46, 'STOP': 48, 'LENGTH': 2}, {'NAME': 'county', 'START': 48, 'STOP': 51, 'LENGTH': 3}, {'NAME': 'supervisoryAgencyCode', 'START': 51, 'STOP': 52, 'LENGTH': 1}, {'NAME': 'censusValidityFlag', 'START': 52, 'STOP': 54, 'LENGTH': 2}, {'NAME': 'VA_FHA', 'START': 54, 'STOP': 55, 'LENGTH': 1}, {'NAME': 'vaNumLoans', 'START': 55, 'STOP': 59, 'LENGTH': 4}, {'NAME': 'vaTotalLoans', 'START': 59, 'STOP': 68, 'LENGTH': 8}, {'NAME': 'convLoansFlag', 'START': 68, 'STOP': 69, 'LENGTH': 1}, {'NAME': 'convNumLoans', 'START': 69, 'STOP': 73, 'LENGTH': 4}, {'NAME': 'convTotalLoans', 'START': 73, 'STOP': 82, 'LENGTH': 9}, {'NAME': 'hiFlag', 'START': 82, 'STOP': 83, 'LENGTH': 1}, {'NAME': 'hiNumLoans', 'START': 83, 'STOP': 87, 'LENGTH': 4}, {'NAME': 'hiTotalLoans', 'START': 87, 'STOP': 96, 'LENGTH': 9}, {'NAME': 'multiFlag', 'START': 96, 'STOP': 97, 'LENGTH': 1}, {'NAME': 'multiNumLoans', 'START': 97, 'STOP': 101, 'LENGTH': 4}, {'NAME': 'multiTotalLoans', 'START': 101, 'STOP': 110, 'LENGTH': 9}, {'NAME': 'nonFlag', 'START': 110, 'STOP': 111, 'LENGTH': 1}, {'NAME': 'nonNumLoans', 'START': 111, 'STOP': 115, 'LENGTH': 4}, {'NAME': 'nonTotalLoans', 'START': 115, 'STOP': 124, 'LENGTH': 9}, {'NAME': 'recordQuality', 'START': 124, 'STOP': 125, 'LENGTH': 1}]" }, { "code": null, "e": 5147, "s": 5111, "text": "Overall, lots of VA considerations." }, { "code": null, "e": 5227, "s": 5147, "text": "A big change was introduced in 1989 to the tracking priorities. From the FFIEC:" }, { "code": null, "e": 5849, "s": 5227, "text": "“[...] In 1989, the Federal Reserve Board revised Regulation C, to incorporate amendments contained in the Financial Institutions Reform, Recovery and Enforcement Act (FIRREA). The FIRREA amendments accomplished the following: expanded the coverage of HMDA to include mortgage lenders not affiliated with depository institutions or holding companies; required reporting of data regarding the disposition of applications for mortgage and home improvement loans in addition to data regarding loan originations and purchases; and required most lenders to identify the race, sex, and income of loan applicants and borrowers.”" }, { "code": null, "e": 5947, "s": 5849, "text": "As expected, the file mappings changes significantly, bt now follows a pattern usable until 2014:" }, { "code": null, "e": 7432, "s": 5947, "text": "[{'NAME': 'ASOF_DATE', 'START': 0, 'STOP': 4, 'LENGTH': 4}, {'NAME': 'RESP_ID', 'START': 4, 'STOP': 14, 'LENGTH': 10}, {'NAME': 'AGENCY_CODE', 'START': 14, 'STOP': 15, 'LENGTH': 1}, {'NAME': 'LOAN_TYPE', 'START': 15, 'STOP': 16, 'LENGTH': 1}, {'NAME': 'LOAN_PURPOSE', 'START': 16, 'STOP': 17, 'LENGTH': 1}, {'NAME': 'OCCUPANCY', 'START': 17, 'STOP': 18, 'LENGTH': 1}, {'NAME': 'LOAN_AMOUNT', 'START': 18, 'STOP': 23, 'LENGTH': 5}, {'NAME': 'ACTION_TYPE', 'START': 23, 'STOP': 24, 'LENGTH': 1}, {'NAME': 'PROPERTY_MSA', 'START': 24, 'STOP': 28, 'LENGTH': 4}, {'NAME': 'STATE_CODE', 'START': 28, 'STOP': 30, 'LENGTH': 2}, {'NAME': 'COUNTY_CODE', 'START': 30, 'STOP': 33, 'LENGTH': 3}, {'NAME': 'CENSUS_TRACT_NUMBER', 'START': 33, 'STOP': 40, 'LENGTH': 7}, {'NAME': 'RACE_APPLICANT', 'START': 40, 'STOP': 41, 'LENGTH': 1}, {'NAME': 'RACE_COAPPLICANT', 'START': 41, 'STOP': 42, 'LENGTH': 1}, {'NAME': 'SEX_APPLICANT', 'START': 42, 'STOP': 43, 'LENGTH': 1}, {'NAME': 'SEX_COAPPLICANT', 'START': 43, 'STOP': 44, 'LENGTH': 1}, {'NAME': 'APPLICANT_INCOME', 'START': 44, 'STOP': 48, 'LENGTH': 4}, {'NAME': 'PURCHASER_TYPE', 'START': 48, 'STOP': 49, 'LENGTH': 1}, {'NAME': 'DENIAL_REASON_1', 'START': 49, 'STOP': 50, 'LENGTH': 1}, {'NAME': 'DENIAL_REASON_2', 'START': 50, 'STOP': 51, 'LENGTH': 1}, {'NAME': 'DENIAL_REASON_3', 'START': 51, 'STOP': 52, 'LENGTH': 1}, {'NAME': 'EDIT_STATUS', 'START': 52, 'STOP': 53, 'LENGTH': 1}, {'NAME': 'SEQUENCE_NUMBER', 'START': 53, 'STOP': 60, 'LENGTH': 7}]" }, { "code": null, "e": 7488, "s": 7432, "text": "This means that we can now tell, for every application:" }, { "code": null, "e": 7526, "s": 7488, "text": "The race and gender of the applicant;" }, { "code": null, "e": 7567, "s": 7526, "text": "the race and gender of the co-applicant;" }, { "code": null, "e": 7603, "s": 7567, "text": "the neighborhood that they were in;" }, { "code": null, "e": 7646, "s": 7603, "text": "the purpose of the loan (house or repair);" }, { "code": null, "e": 7699, "s": 7646, "text": "the list of reasons why a loan might’ve been denied;" }, { "code": null, "e": 7755, "s": 7699, "text": "the total number of forms required to be submitted; and" }, { "code": null, "e": 7815, "s": 7755, "text": "each and every one of the dates of the application process." }, { "code": null, "e": 7976, "s": 7815, "text": "Was a loan application intentionally slowplayed? Was a home repair denied that would’ve otherwise been approved? What about same-sex co-applicants? All visible." }, { "code": null, "e": 8397, "s": 7976, "text": "(Note: we haven’t made our processed data available yet, as we’re still processing and investigating it. There are many reporting errors, like state acronyms instead of state codes, erroneous census tracks, and many other issues that still require a tremendous amount of preprocessing of the data to make sense of decades-long shifts in social norms. It would be unwise to come to any conclusions with it at this time. )" }, { "code": null, "e": 8700, "s": 8397, "text": "Over the years, there’s more and more adherence to the program across most banks. The digitization wave that spread across the US can be verified year over year. There’s also a distinct shift downwards of less and less mortgage loan applications, stemming most likely from the subprime mortgage crisis:" }, { "code": null, "e": 8776, "s": 8700, "text": "Great so far, isn’t it? Now, here’s the double-edged sword about this data:" }, { "code": null, "e": 8974, "s": 8776, "text": "The same data that can be used to protect citizens against predatory bank practices can be used as a discriminatory weapon against them if data scientists do not understand the data they are using." }, { "code": null, "e": 9214, "s": 8974, "text": "How so? This dataset now has within it every bias, preferential treatment, and erroneously or maliciously declined loan application. Every possible discriminatory event is permanently recorded. There is no sanitizing possible of this data." }, { "code": null, "e": 9255, "s": 9214, "text": "The HMDA dataset is biased — absolutely." }, { "code": null, "e": 9376, "s": 9255, "text": "It’s up to the data scientists to understand what are the right questions to ask, and more importantly, what not to ask." }, { "code": null, "e": 9604, "s": 9376, "text": "By any measure, this data set can be considered invasive and discriminatory. Canada, usually considered a (slightly) more tolerant country, has a different approach to tracking race and racism. As explained in The Conversation:" }, { "code": null, "e": 9950, "s": 9604, "text": "Canada’s anti-racism strategy, which draws on decades’ worth of research, states that race is a social construct. There is no basis for classifying people according to race, but racial bias and discrimination have very real effects. The question is: How do we get relevant data from the census and other surveys on the impact of systemic racism?" }, { "code": null, "e": 10214, "s": 9950, "text": "Statistics Canada tries to gather this information without directly asking about race. Race-based data is needed, says Jean-Pierre Corbeil, a diversity specialist at Statistics Canada. But he wonders whether that actually requires referring to race on the census." }, { "code": null, "e": 10515, "s": 10214, "text": "Historically, the government has been reluctant to ask directly about race, which has led to a lack of disaggregated data. After the Second World War, the census used indirect methods of estimating the non-white, non-Indigenous population through racial proxies like language or ethnocultural origin." }, { "code": null, "e": 10777, "s": 10515, "text": "(Note: one of the major complaints against Canadian multiculturalism as a pillar of civil society is that it allows for people to classify others by ethnicity or nationality, under the veil of a self-assigned permission structure, but that’s a topic for later.)" }, { "code": null, "e": 11079, "s": 10777, "text": "So, this means some countries refuse to track the race and gender of bank loan applicants, as measuring racism fundamentally amplifies its very divisive nature of bucketing people into categories. And so, looking back at the HMDA data, the question that can be asked is, “should this data even exist?”" }, { "code": null, "e": 11249, "s": 11079, "text": "I believe the answer is a strong yes. The Act has yielded tremendous protection to the public, especially with a major investigation back in 2005. From the Buffalo News:" }, { "code": null, "e": 11445, "s": 11249, "text": "New York Attorney General Eliot Spitzer has fired his latest salvo, launching a preliminary probe into mortgage lending practices at eight major banks in the state, including HSBC Bank USA. [...]" }, { "code": null, "e": 11621, "s": 11445, "text": "Investigators are trying to determine how the banks price their loans, and if fees and interest rates are being applied fairly, or whether there’s racial discrimination. [...]" }, { "code": null, "e": 12022, "s": 11621, "text": "Citigroup already agreed in 2002 to pay $215 million to settle allegations by the Federal Trade Commission that Associates First Capital Corp. — which Citi bought in 2000 — had engaged in predatory lending. Associates’ rival Household International — acquired by HSBC Holdings Plc in 2003 — paid $484 million in 2002 to settle similar charges by all 50 states in the largest consumer settlement ever." }, { "code": null, "e": 12512, "s": 12022, "text": "However, although this data has yielded success, it’s up to the data scientists to understand what are the right questions to ask, and more importantly what not to ask. For instance, trying to build a mortgage loan approval pipeline from this data is a horrendous and terrible idea — you now have a racist, homophobic bot. However, if you wish to investigate the very nature of institutionalized discrimination by investigating outliers, then you have a tremendous weapon at your disposal." }, { "code": null, "e": 12552, "s": 12512, "text": "How you wield that weapon is up to you." }, { "code": null, "e": 12571, "s": 12552, "text": "Additional Reading" }, { "code": null, "e": 12746, "s": 12571, "text": "Revisiting the CRA: Perspectives on the Future of the Community Reinvestment Act, A Joint Publication of the Federal Reserve Banks of Boston and San Francisco, February 2009." }, { "code": null, "e": 12893, "s": 12746, "text": "Privacy Impact Assessment of the Home Mortgage Disclosure Act Data Repository System, Board of Governors of the US Federal Reserve, November 2020." }, { "code": null, "e": 13030, "s": 12893, "text": "I wrote the law Bloomberg blames for the financial crisis. He’s wrong., Robert Kuttner, op-ed in the Washington Post, February 15, 2020." }, { "code": null, "e": 13117, "s": 13030, "text": "History of the HMDA, Federal Financial Institutions Examination Council, January 2018." }, { "code": null, "e": 13135, "s": 13117, "text": "Happy Consulting!" }, { "code": null, "e": 13142, "s": 13135, "text": "-Matt." }, { "code": null, "e": 13274, "s": 13142, "text": "If you have additional questions about this article or our AI consulting framework, feel free to reach out by LinkedIn or by email." }, { "code": null, "e": 13300, "s": 13274, "text": "How Does AI Create Value?" }, { "code": null, "e": 13337, "s": 13300, "text": "Implementing a Corporate AI Strategy" }, { "code": null, "e": 13378, "s": 13337, "text": "Outlier-Aware Clustering: Beyond K-Means" } ]
GraphQL With Python Flask. GraphQL, Graphene, Flask, and Mysql | by Manish Jain | Towards Data Science
Before we get started, let’s talk about our objective first. We are trying to develop a starter-kit project that runs on Flask, that has the following functionalities: GraphQL support Database integration For this tutorial, we will need: - Python- Pip- Virtualenv- Docker Flask is a micro framework for Python based on Werkzeug, Jinja 2 and good intentions. — Flask Documentation Setting up a barebones Flask project is really simple. However, since there’s quite a bit of functionality that we want to be built in, the following steps will take slightly longer than usual. Start by creating a virtual environment. $ virtualenv venv$ source venv/bin/activate Next, we can install the required packages. As to not confuse everyone, I’ll include only the required packages for each step respectively. $ pip install flask flask_script$ mkdir -p app/__init__.py$ touch manage.py We will first have to install the required dependencies $ pip install flask-sqlalchemy pymysql We can now start to set up our Flask app to connect with our MySQL service. For that, we will have to add a config.py file and also update our app/__init__.py file. Using a config file, we are able to separate our environment variables, as well as store our constant variables as required. With this, when we run the docker-compose up, the application will start running and it will be connected with the MySQL service. GraphQL is a query language for APIs and runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need, and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools. $ pip install graphene Flask-GraphQL Let’s do a breakdown of the packages that we just installed. Flask-GraphQL is a wrapper layer that adds GraphQL support to the Flask application. We’ll have to add a /graphql route for the client to access the APIs. To do that, we can simply update our app/__init__.py file. In this case, we have imported GraphQLView from the Flask-GraphQL module and have used it to implement our /graphql route. Next, we will be using the Graphene-Python package. Graphene is an open-source library that allows developers to build simple yet extendable APIs with GraphQL in Python. If you have noticed from our latest app/__init__.py file, we are actually missing an app/schema.py file for our Flask application to work. A GraphQL schema is at the core of any GraphQL server implementation and describes the functionality available to the clients which connect to it. In this case, we shall create a simple schema so that our application will be able to run without any error. With this, try running your application. When you access http://localhost:5000/graphql, you should be able to see this page. If you are familiar with GraphQL, this page should be very familiar to you. It’s an interface that allows you to enter GraphQL queries. I hope this article will give you a better understanding and overview of how you can build your Python application with GraphQL. This can also be done with the Django framework. I have also added a Github repository for reference here. Here is another story for GraphQL Best Practices, you might be interested in.
[ { "code": null, "e": 233, "s": 172, "text": "Before we get started, let’s talk about our objective first." }, { "code": null, "e": 340, "s": 233, "text": "We are trying to develop a starter-kit project that runs on Flask, that has the following functionalities:" }, { "code": null, "e": 356, "s": 340, "text": "GraphQL support" }, { "code": null, "e": 377, "s": 356, "text": "Database integration" }, { "code": null, "e": 410, "s": 377, "text": "For this tutorial, we will need:" }, { "code": null, "e": 444, "s": 410, "text": "- Python- Pip- Virtualenv- Docker" }, { "code": null, "e": 552, "s": 444, "text": "Flask is a micro framework for Python based on Werkzeug, Jinja 2 and good intentions. — Flask Documentation" }, { "code": null, "e": 746, "s": 552, "text": "Setting up a barebones Flask project is really simple. However, since there’s quite a bit of functionality that we want to be built in, the following steps will take slightly longer than usual." }, { "code": null, "e": 787, "s": 746, "text": "Start by creating a virtual environment." }, { "code": null, "e": 831, "s": 787, "text": "$ virtualenv venv$ source venv/bin/activate" }, { "code": null, "e": 971, "s": 831, "text": "Next, we can install the required packages. As to not confuse everyone, I’ll include only the required packages for each step respectively." }, { "code": null, "e": 1047, "s": 971, "text": "$ pip install flask flask_script$ mkdir -p app/__init__.py$ touch manage.py" }, { "code": null, "e": 1103, "s": 1047, "text": "We will first have to install the required dependencies" }, { "code": null, "e": 1142, "s": 1103, "text": "$ pip install flask-sqlalchemy pymysql" }, { "code": null, "e": 1307, "s": 1142, "text": "We can now start to set up our Flask app to connect with our MySQL service. For that, we will have to add a config.py file and also update our app/__init__.py file." }, { "code": null, "e": 1432, "s": 1307, "text": "Using a config file, we are able to separate our environment variables, as well as store our constant variables as required." }, { "code": null, "e": 1562, "s": 1432, "text": "With this, when we run the docker-compose up, the application will start running and it will be connected with the MySQL service." }, { "code": null, "e": 1906, "s": 1562, "text": "GraphQL is a query language for APIs and runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need, and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools." }, { "code": null, "e": 1943, "s": 1906, "text": "$ pip install graphene Flask-GraphQL" }, { "code": null, "e": 2004, "s": 1943, "text": "Let’s do a breakdown of the packages that we just installed." }, { "code": null, "e": 2089, "s": 2004, "text": "Flask-GraphQL is a wrapper layer that adds GraphQL support to the Flask application." }, { "code": null, "e": 2218, "s": 2089, "text": "We’ll have to add a /graphql route for the client to access the APIs. To do that, we can simply update our app/__init__.py file." }, { "code": null, "e": 2341, "s": 2218, "text": "In this case, we have imported GraphQLView from the Flask-GraphQL module and have used it to implement our /graphql route." }, { "code": null, "e": 2511, "s": 2341, "text": "Next, we will be using the Graphene-Python package. Graphene is an open-source library that allows developers to build simple yet extendable APIs with GraphQL in Python." }, { "code": null, "e": 2797, "s": 2511, "text": "If you have noticed from our latest app/__init__.py file, we are actually missing an app/schema.py file for our Flask application to work. A GraphQL schema is at the core of any GraphQL server implementation and describes the functionality available to the clients which connect to it." }, { "code": null, "e": 2906, "s": 2797, "text": "In this case, we shall create a simple schema so that our application will be able to run without any error." }, { "code": null, "e": 3167, "s": 2906, "text": "With this, try running your application. When you access http://localhost:5000/graphql, you should be able to see this page. If you are familiar with GraphQL, this page should be very familiar to you. It’s an interface that allows you to enter GraphQL queries." }, { "code": null, "e": 3345, "s": 3167, "text": "I hope this article will give you a better understanding and overview of how you can build your Python application with GraphQL. This can also be done with the Django framework." } ]
Repeated Character | Practice | GeeksforGeeks
Given a string consisting of lowercase english alphabets. Find the repeated character present first in the string. Example 1: Input: S = "geeksforgeeks" Output: g Explanation: g, e, k and s are the repeating characters. Out of these, g occurs first. ​Example 2: Input: S = "abcde" Output: -1 Explanation: No repeating character present. Your Task: You don't need to read input or print anything. Your task is to complete the function firstRep() which takes the string S as input and returns the the first repeating character in the string. In case there's no repeating character present, return '#'. Expected Time Complexity: O(|S|). Expected Auxiliary Space: O(1). Constraints: 1<=|S|<=105 0 krdmicrosoft5 days ago JAVA SIMPLE SOLUTION char firstRep(String S) { // your code here for(int i = 0;i<S.length()-1;i++) { if(S.substring(i+1,S.length()).contains(""+S.charAt(i))) return S.charAt(i); } return '#'; } 0 yuvanvj0001 week ago JAVA StringBuffer solution in one loop: just remove the character at ‘0’ index in string Buffer ,before removing store the the char , after removing check for the same character available in stringbuffer using “contains” method in String, if it is true return the stored char else return ‘#’. StringBuffer sb = new StringBuffer(s); int n = sb.length();while(n > 0) { char store = sb.charAt(0); sb.deleteCharAt(0); if(sb.toString().contains(String.valueOf(store))){ return store; } n--; }return '#'; 0 kingkrishna43712 weeks ago #PYTHON CODE... for i in s: l=s.count(i) if(l>1): return ireturn '#' 0 mayank180919994 weeks ago char firstRep (string s) { //code here. unordered_map<char,int>m; for(int i=0;i<s.length();i++){ m[s[i]]++; } for(int i=0;i<s.length();i++){ if(m[s[i]]>1){ return s[i]; } } return '#'; } 0 pritamaber1 month ago No solution can beat this crisp solution logic - for each char from left hand side , check from right hand side weather the char exist on its right char firstRep (string s) { //code here. for(int i=0; i<s.size(); i++){ int n = s.size()-1; while(n > i){ if(s[n] == s[i]){ return s[i]; } n--; } } return '#'; } +1 pratoshbm1 month ago char firstRep(String S) { HashMap<Character, Integer> map = new LinkedHashMap<>(); for(Character c: S.toCharArray()) map.put(c, map.getOrDefault(c, 0)+1); for(Map.Entry<Character, Integer> e: map.entrySet()){ if((int)e.getValue()>1) return (char)e.getKey(); } return '#'; } 0 kumarsurajroy36551 month ago //User function Template for Javaclass Solution{ char firstRep(String S) { // your code here int arr[] = new int[26]; for(int i=0;i<S.length();i++){ arr[S.charAt(i)-'a']++; } for(int i=0;i<S.length();i++){ if(arr[S.charAt(i)-'a']>1){ return S.charAt(i); } } return '#'; }} 0 amanavengeraman2 months ago LinkedHashMap<Character, Integer> hm = new LinkedHashMap<>(S.length()); Boolean flag = false; for(int i=0; i<S.length(); i++){ char ch = S.charAt(i); if(hm.containsKey(ch)){ hm.put(ch, hm.get(ch)+1); flag = true; }else{ hm.put(ch, 1); } } if(!flag) return '#'; // for(int i=0; i<S.length(); i++){ // int val = hm.get(S.charAt(i)); // if(val > 1){ // return S.charAt(i); // } // } for(Map.Entry map:hm.entrySet()){ if((int)map.getValue() > 1){ return (char)map.getKey(); } } return '#'; 0 akkeshri140420012 months ago char firstRep (string s) { //code here. unordered_map<char,int>m; char ch; for(int i=0;i<s.length();i++){ m[s[i]]++; } for(int i=0;i<s.length();i++){ if(m[s[i]]>=2){ return s[i]; } } return '#'; } 0 ilihaspatel443 months ago // I think find fuction would be better char firstRep (string s) { for(int i=0;i<s.size();i++){ string temp=s; temp.erase(i,1); size_t found=temp.find(s[i]); if(found!=string::npos) return s[i]; } return '#' ; } 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": 341, "s": 226, "text": "Given a string consisting of lowercase english alphabets. Find the repeated character present first in the string." }, { "code": null, "e": 352, "s": 341, "text": "Example 1:" }, { "code": null, "e": 478, "s": 352, "text": "Input:\nS = \"geeksforgeeks\"\nOutput: g\nExplanation: g, e, k and s are the repeating\ncharacters. Out of these, g occurs first. \n" }, { "code": null, "e": 493, "s": 478, "text": "​Example 2:" }, { "code": null, "e": 570, "s": 493, "text": "Input: \nS = \"abcde\"\nOutput: -1\nExplanation: No repeating character present.\n" }, { "code": null, "e": 834, "s": 570, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function firstRep() which takes the string S as input and returns the the first repeating character in the string. In case there's no repeating character present, return '#'." }, { "code": null, "e": 901, "s": 834, "text": "\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 927, "s": 901, "text": "\nConstraints:\n1<=|S|<=105" }, { "code": null, "e": 931, "s": 929, "text": "0" }, { "code": null, "e": 954, "s": 931, "text": "krdmicrosoft5 days ago" }, { "code": null, "e": 975, "s": 954, "text": "JAVA SIMPLE SOLUTION" }, { "code": null, "e": 1212, "s": 975, "text": " char firstRep(String S)\n {\n // your code here\n for(int i = 0;i<S.length()-1;i++)\n {\n if(S.substring(i+1,S.length()).contains(\"\"+S.charAt(i))) return S.charAt(i);\n }\n return '#';\n }" }, { "code": null, "e": 1214, "s": 1212, "text": "0" }, { "code": null, "e": 1235, "s": 1214, "text": "yuvanvj0001 week ago" }, { "code": null, "e": 1275, "s": 1235, "text": "JAVA StringBuffer solution in one loop:" }, { "code": null, "e": 1528, "s": 1275, "text": "just remove the character at ‘0’ index in string Buffer ,before removing store the the char , after removing check for the same character available in stringbuffer using “contains” method in String, if it is true return the stored char else return ‘#’." }, { "code": null, "e": 1743, "s": 1532, "text": "StringBuffer sb = new StringBuffer(s); int n = sb.length();while(n > 0) { char store = sb.charAt(0); sb.deleteCharAt(0); if(sb.toString().contains(String.valueOf(store))){ return store; } n--; }return '#';" }, { "code": null, "e": 1745, "s": 1743, "text": "0" }, { "code": null, "e": 1772, "s": 1745, "text": "kingkrishna43712 weeks ago" }, { "code": null, "e": 1788, "s": 1772, "text": "#PYTHON CODE..." }, { "code": null, "e": 1875, "s": 1788, "text": "for i in s: l=s.count(i) if(l>1): return ireturn '#'" }, { "code": null, "e": 1877, "s": 1875, "text": "0" }, { "code": null, "e": 1903, "s": 1877, "text": "mayank180919994 weeks ago" }, { "code": null, "e": 2205, "s": 1903, "text": " char firstRep (string s)\n {\n //code here.\n unordered_map<char,int>m;\n for(int i=0;i<s.length();i++){\n m[s[i]]++;\n }\n for(int i=0;i<s.length();i++){\n if(m[s[i]]>1){\n return s[i];\n }\n }\n return '#'; \n }" }, { "code": null, "e": 2207, "s": 2205, "text": "0" }, { "code": null, "e": 2229, "s": 2207, "text": "pritamaber1 month ago" }, { "code": null, "e": 2270, "s": 2229, "text": "No solution can beat this crisp solution" }, { "code": null, "e": 2379, "s": 2272, "text": "logic - for each char from left hand side , check from right hand side weather the char exist on its right" }, { "code": null, "e": 2690, "s": 2381, "text": " char firstRep (string s)\n {\n //code here.\n for(int i=0; i<s.size(); i++){\n int n = s.size()-1;\n while(n > i){\n if(s[n] == s[i]){\n return s[i];\n }\n n--;\n }\n }\n return '#';\n }" }, { "code": null, "e": 2693, "s": 2690, "text": "+1" }, { "code": null, "e": 2714, "s": 2693, "text": "pratoshbm1 month ago" }, { "code": null, "e": 2738, "s": 2714, "text": "char firstRep(String S)" }, { "code": null, "e": 2744, "s": 2738, "text": " {" }, { "code": null, "e": 2809, "s": 2744, "text": " HashMap<Character, Integer> map = new LinkedHashMap<>();" }, { "code": null, "e": 2851, "s": 2809, "text": " for(Character c: S.toCharArray())" }, { "code": null, "e": 2901, "s": 2851, "text": " map.put(c, map.getOrDefault(c, 0)+1);" }, { "code": null, "e": 2972, "s": 2910, "text": " for(Map.Entry<Character, Integer> e: map.entrySet()){" }, { "code": null, "e": 3008, "s": 2972, "text": " if((int)e.getValue()>1)" }, { "code": null, "e": 3049, "s": 3008, "text": " return (char)e.getKey();" }, { "code": null, "e": 3059, "s": 3049, "text": " }" }, { "code": null, "e": 3079, "s": 3059, "text": " return '#';" }, { "code": null, "e": 3085, "s": 3079, "text": " }" }, { "code": null, "e": 3087, "s": 3085, "text": "0" }, { "code": null, "e": 3116, "s": 3087, "text": "kumarsurajroy36551 month ago" }, { "code": null, "e": 3539, "s": 3116, "text": "//User function Template for Javaclass Solution{ char firstRep(String S) { // your code here int arr[] = new int[26]; for(int i=0;i<S.length();i++){ arr[S.charAt(i)-'a']++; } for(int i=0;i<S.length();i++){ if(arr[S.charAt(i)-'a']>1){ return S.charAt(i); } } return '#'; }}" }, { "code": null, "e": 3541, "s": 3539, "text": "0" }, { "code": null, "e": 3569, "s": 3541, "text": "amanavengeraman2 months ago" }, { "code": null, "e": 4330, "s": 3569, "text": " LinkedHashMap<Character, Integer> hm = new LinkedHashMap<>(S.length()); Boolean flag = false; for(int i=0; i<S.length(); i++){ char ch = S.charAt(i); if(hm.containsKey(ch)){ hm.put(ch, hm.get(ch)+1); flag = true; }else{ hm.put(ch, 1); } } if(!flag) return '#'; // for(int i=0; i<S.length(); i++){ // int val = hm.get(S.charAt(i)); // if(val > 1){ // return S.charAt(i); // } // } for(Map.Entry map:hm.entrySet()){ if((int)map.getValue() > 1){ return (char)map.getKey(); } } return '#';" }, { "code": null, "e": 4332, "s": 4330, "text": "0" }, { "code": null, "e": 4361, "s": 4332, "text": "akkeshri140420012 months ago" }, { "code": null, "e": 4671, "s": 4361, "text": "char firstRep (string s) { //code here. unordered_map<char,int>m; char ch; for(int i=0;i<s.length();i++){ m[s[i]]++; } for(int i=0;i<s.length();i++){ if(m[s[i]]>=2){ return s[i]; } } return '#'; }" }, { "code": null, "e": 4673, "s": 4671, "text": "0" }, { "code": null, "e": 4699, "s": 4673, "text": "ilihaspatel443 months ago" }, { "code": null, "e": 4739, "s": 4699, "text": "// I think find fuction would be better" }, { "code": null, "e": 5021, "s": 4743, "text": "char firstRep (string s) { for(int i=0;i<s.size();i++){ string temp=s; temp.erase(i,1); size_t found=temp.find(s[i]); if(found!=string::npos) return s[i]; } return '#' ; }" }, { "code": null, "e": 5167, "s": 5021, "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": 5203, "s": 5167, "text": " Login to access your submissions. " }, { "code": null, "e": 5213, "s": 5203, "text": "\nProblem\n" }, { "code": null, "e": 5223, "s": 5213, "text": "\nContest\n" }, { "code": null, "e": 5286, "s": 5223, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5434, "s": 5286, "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": 5642, "s": 5434, "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": 5748, "s": 5642, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Python | Pandas DatetimeIndex.floor() - GeeksforGeeks
29 Dec, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DatetimeIndex.floor() function floor the data to the specified frequency. The function takes the target frequency as input. It returns a new DatetimeIndex object. Syntax: DatetimeIndex.floor(freq) Parameters :freq : The frequency level to floor the index to. Must be a fixed frequency like ‘S’ (second) not ‘ME’ (month end). Return : Index of the same type for a DatetimeIndex or TimedeltaIndex, or a Series with the same index for a Series. Example #1: Use DatetimeIndex.floor() function to floor the data of the DatetimeIndex object to the specified frequency. # importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'S' represents secondly frequency didx = pd.DatetimeIndex(start ='2000-01-15 08:00', freq ='S', periods = 4) # Print the DatetimeIndexprint(didx) Output : Now we want to floor the second based frequency of the DatetimeIndex object to minute based frequency # convert to the passed frequency# 'T' represents minute based frequencydidx.floor('T') Output : As we can see in the output, the function has floored the values of the DatetimeIndex object to the desired frequency. Example #2: Use DatetimeIndex.floor() function to floor the data of the DatetimeIndex object to the specified frequency. # importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'T' represents minutely frequency didx = pd.DatetimeIndex(start ='2000-01-15 08:00', freq ='T', periods = 4) # Print the DatetimeIndexprint(didx) Output : Now we want to floor the minute based frequency of the DatetimeIndex object to hour based frequency # floor minute based frequency to hour based frequencydidx.floor('H') Output :As we can see in the output, the function has floored the values of the DatetimeIndex object to the desired frequency. Python pandas-datetimeIndex 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? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n29 Dec, 2018" }, { "code": null, "e": 25861, "s": 25647, "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": 26031, "s": 25861, "text": "Pandas DatetimeIndex.floor() function floor the data to the specified frequency. The function takes the target frequency as input. It returns a new DatetimeIndex object." }, { "code": null, "e": 26065, "s": 26031, "text": "Syntax: DatetimeIndex.floor(freq)" }, { "code": null, "e": 26193, "s": 26065, "text": "Parameters :freq : The frequency level to floor the index to. Must be a fixed frequency like ‘S’ (second) not ‘ME’ (month end)." }, { "code": null, "e": 26310, "s": 26193, "text": "Return : Index of the same type for a DatetimeIndex or TimedeltaIndex, or a Series with the same index for a Series." }, { "code": null, "e": 26431, "s": 26310, "text": "Example #1: Use DatetimeIndex.floor() function to floor the data of the DatetimeIndex object to the specified frequency." }, { "code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'S' represents secondly frequency didx = pd.DatetimeIndex(start ='2000-01-15 08:00', freq ='S', periods = 4) # Print the DatetimeIndexprint(didx)", "e": 26656, "s": 26431, "text": null }, { "code": null, "e": 26665, "s": 26656, "text": "Output :" }, { "code": null, "e": 26767, "s": 26665, "text": "Now we want to floor the second based frequency of the DatetimeIndex object to minute based frequency" }, { "code": "# convert to the passed frequency# 'T' represents minute based frequencydidx.floor('T')", "e": 26855, "s": 26767, "text": null }, { "code": null, "e": 26864, "s": 26855, "text": "Output :" }, { "code": null, "e": 27104, "s": 26864, "text": "As we can see in the output, the function has floored the values of the DatetimeIndex object to the desired frequency. Example #2: Use DatetimeIndex.floor() function to floor the data of the DatetimeIndex object to the specified frequency." }, { "code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'T' represents minutely frequency didx = pd.DatetimeIndex(start ='2000-01-15 08:00', freq ='T', periods = 4) # Print the DatetimeIndexprint(didx)", "e": 27329, "s": 27104, "text": null }, { "code": null, "e": 27338, "s": 27329, "text": "Output :" }, { "code": null, "e": 27438, "s": 27338, "text": "Now we want to floor the minute based frequency of the DatetimeIndex object to hour based frequency" }, { "code": "# floor minute based frequency to hour based frequencydidx.floor('H')", "e": 27508, "s": 27438, "text": null }, { "code": null, "e": 27635, "s": 27508, "text": "Output :As we can see in the output, the function has floored the values of the DatetimeIndex object to the desired frequency." }, { "code": null, "e": 27663, "s": 27635, "text": "Python pandas-datetimeIndex" }, { "code": null, "e": 27677, "s": 27663, "text": "Python-pandas" }, { "code": null, "e": 27684, "s": 27677, "text": "Python" }, { "code": null, "e": 27782, "s": 27684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27814, "s": 27782, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27856, "s": 27814, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27898, "s": 27856, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27954, "s": 27898, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27981, "s": 27954, "text": "Python Classes and Objects" }, { "code": null, "e": 28012, "s": 27981, "text": "Python | os.path.join() method" }, { "code": null, "e": 28041, "s": 28012, "text": "Create a directory in Python" }, { "code": null, "e": 28063, "s": 28041, "text": "Defaultdict in Python" }, { "code": null, "e": 28099, "s": 28063, "text": "Python | Pandas dataframe.groupby()" } ]
Time Series Forecasting in R. Exponential Smoothing, TBATS, ARIMA... | by François St-Amant | Towards Data Science
Python is great, but when it comes to forecasting, I personally think R still has the upper hand. The Forecast package is the most complete forecasting package available on R or Python, and it’s worth knowing about it. Here is what we will see in this article: Naive methodsExponential Smoothing (State-space models and DSHW)BATS and TBATSARIMA/SARIMA modelsHow to set up a one-step-ahead forecast Naive methods Exponential Smoothing (State-space models and DSHW) BATS and TBATS ARIMA/SARIMA models How to set up a one-step-ahead forecast For every method, we will build a model on a validation set, forecast with it for the duration of the validation set and compare the forecast with the real observations to obtain a Mean Absolute Percentage Error (MAPE). The data used will be coming from the Air Passengers Dataset, available on R. library(forecast)library(MLmetrics)data=AirPassengers#Create samplestraining=window(data, start = c(1949,1), end = c(1955,12))validation=window(data, start = c(1956,1)) Any forecasting method should be evaluated by being compared to a naive method. This helps ensure that the efforts put in having a more complex model are worth it in terms of performance. The simplest of all methods is called simple naive. Extremely simple: the forecast for tomorrow is what we are observing today. Another approach, seasonal naive, is a little more “complex”: the forecast for tomorrow is what we observed the week/month/year (depending what horizon we are working with) before. Here is how to do a seasonal naive forecast: naive = snaive(training, h=length(validation))MAPE(naive$mean, validation) * 100 That gives us an MAPE of 27.04%. That’s the score to beat. By the way, remove the s from “snaive” and you have the code for simple naive. Here is how to plot the forecast: plot(data, col="blue", xlab="Year", ylab="Passengers", main="Seasonal Naive Forecast", type='l')lines(naive$mean, col="red", lwd=2) We see that what happened in the last year of data is repeated as a forecast for the entire validation set. There are many ways to do exponential smoothing. The idea is always to have a declining weight given to observations. The more recent an observation, the more importance it will have in our forecast. Parameters can also be added. You can for instance add a trend paramenter (Holt method) or add a seasonality (Holt-Winters). With the Forecast Package, smoothing methods can be placed within the structure of state space models. By using this structure, we can find the optimal exponential smoothing model, using the ets function. ets_model = ets(training, allow.multiplicative.trend = TRUE)summary(ets_model) We see ETS (M, Md, M). This means we have an ets model with multiplicative errors, a multiplicative trend and a multiplicative seasonality. Basically, multiplicative means that the parameter is “amplified” over time. For instance the trend is getting bigger and bigger as time goes by (our case here). Here is how to forecast using the estimated optimal smoothing model: ets_forecast = forecast(ets_model, h=length(validation))MAPE(ets_forecast$mean, validation) *100 We see that the upward trend in demand is being capture a little bit (far from perfect, better than naive). It gives an MAPE of 12.6%. The ets function is good, but it only allows for one seasonality. Sometimes, the data we have can be composed of multiple seasonalities (monthly and yearly for instance). Double Seasonal Holt-Winters (DSHW) allows for two seasonalities: a smaller one repeated often and a bigger one repeated less often. For the method to work however, the seasonalities need to be nested, meaning one must be an integer multiple of the other (2 and 4, 24 and 168, etc.). The code here is a bit different since we need to specify the lenghts of our two seasonalities (which is not always something we know) and the forecast is computed directly when creating the model with the dshw function. dshw_model = dshw(training, period1=4, period2 = 12, h=length(validation))MAPE(dshw_model$mean, validation)*100 We get a MAPE of 3.7% with this method! DSHW is good, but some processes have more complex seasonalities, which our previous functions cannot handle. Indeed, you could have both a weekly and yearly seasonality. You could even have more than 2! BATS and TBATS allow for multiple seasonalities. TBATS is a modification (an improvement really) of BATS that allows for multiple non-integer seasonality cycles. Here is how to build a TBATS model and forecast with it: tbats_model = tbats(training)tbats_forecast = forecast(tbats_model, h=length(validation))MAPE(tbats_forecast$mean, validation) * 100 We get a MAPE of 12.9% for this method. ARIMA models contain three things: AR(p): autoregressive part of the model. Means that we use p past observations from the timeseries as predictors. Differencing (d): Used to transform the timeseries into a stationary one by taking the differences between successive observations at appropriate lags d. MA(q): uses q past forecast errors as predictors. That’s it for ARIMA but if you know the data you have is seasonal, then you need more. That’s where SARIMA comes into play. SARIMA adds a seasonal part to the model. P represents the seasonal AR order, D the seasonal differencing order, Q the seasonal MA order and m the number of observations per year. The auto.arima function can be used to return the best estimated model. Here is the code: arima_optimal = auto.arima(training) The function returned the following model: ARIMA(0,1,1)(1,1,0)[12]. To forecast a SARIMA model (which is what we have here since we have a seasonal part), we can use the sarima.for function from the astsa package. library(astsa)sarima_forecast = sarima.for(training, n.ahead=length(validation), p=0,d=1,q=1,P=1,D=1,Q=0,S=12)MAPE(sarima_forecast$pred, validation) * 100 We get a MAPE of 6.5% with this SARIMA model. Just so you know, we could in theory complexify things even more by adding exogenous variables (explanatory variables) to an ARIMA/SARIMA model, which would make it SARIMAX. For this data, DSHW gave the best results. Keep in mind however that no model does best all the time. In all the previous examples, I forecasted 5 years into the future. However, if you want to forecast on a daily basis, why would you use a forecasted value from 5 years ago when you could use the real observations to predict tomorrow? The idea of setting up a one-step-ahead forecast is to evaluate how well a model would have done if you were forecasting for one day ahead, during 5 years, using latest observations to make your forecast. Simply put: instead of forecasting once for the 60 months ahead, we forecast 60 times for the upcoming month, using latest observations. Coding this is quite simple. All we need is to iteratively add the latest observation to the training dataset, forecast from there and repeat. Here is the code to do it using the SARIMA model we found earlier. one_step_ahead_sarima = matrix(ncol = 2, nrow = 60)for (i in 1:60){ training_observed = window(data, start = c(1949,1), end = c(1955,(12+i)), frequency = 12) forecasted.sarima = sarima.for(training_observed,n.ahead=1,p=0,d=1,q=1,P=1,D=1,Q=0,S=12) demandforecast = forecasted.sarima$pred observed = validation[[i]] one_step_ahead_sarima[i,1]= observed one_step_ahead_sarima[i,2]= demandforecast}MAPE(one_step_ahead_sarima[,1], one_step_ahead_sarima[,2]) * 100 As you see, for every iteration, the training set grows by one observation, a new forecast for n.ahead=1 is computed and results are stored in the one_step_ahead_sarima matrix. Here is how to get the plot: plot(data, col="blue", xlab="Year", ylab="Passengers", main="SARIMA Forecast", type='l')lines(ts(one_step_ahead_sarima[,2], start = c(1956,1), frequency = 12), col="red", lwd=3) We get a MAPE of 4.1%, which is an improvement of more than 2% on what we had when using the same SARIMA model to forecast 5 years ahead. That’s not surprising considering that the shorter the forecasting horizon, the better the forecast should be. That is why you should always set up a one-step-ahead forecast if it is possible! I hope this helped. Thanks a lot for reading! To become a member: https://francoisstamant.medium.com/membership
[ { "code": null, "e": 391, "s": 172, "text": "Python is great, but when it comes to forecasting, I personally think R still has the upper hand. The Forecast package is the most complete forecasting package available on R or Python, and it’s worth knowing about it." }, { "code": null, "e": 433, "s": 391, "text": "Here is what we will see in this article:" }, { "code": null, "e": 570, "s": 433, "text": "Naive methodsExponential Smoothing (State-space models and DSHW)BATS and TBATSARIMA/SARIMA modelsHow to set up a one-step-ahead forecast" }, { "code": null, "e": 584, "s": 570, "text": "Naive methods" }, { "code": null, "e": 636, "s": 584, "text": "Exponential Smoothing (State-space models and DSHW)" }, { "code": null, "e": 651, "s": 636, "text": "BATS and TBATS" }, { "code": null, "e": 671, "s": 651, "text": "ARIMA/SARIMA models" }, { "code": null, "e": 711, "s": 671, "text": "How to set up a one-step-ahead forecast" }, { "code": null, "e": 931, "s": 711, "text": "For every method, we will build a model on a validation set, forecast with it for the duration of the validation set and compare the forecast with the real observations to obtain a Mean Absolute Percentage Error (MAPE)." }, { "code": null, "e": 1009, "s": 931, "text": "The data used will be coming from the Air Passengers Dataset, available on R." }, { "code": null, "e": 1178, "s": 1009, "text": "library(forecast)library(MLmetrics)data=AirPassengers#Create samplestraining=window(data, start = c(1949,1), end = c(1955,12))validation=window(data, start = c(1956,1))" }, { "code": null, "e": 1366, "s": 1178, "text": "Any forecasting method should be evaluated by being compared to a naive method. This helps ensure that the efforts put in having a more complex model are worth it in terms of performance." }, { "code": null, "e": 1494, "s": 1366, "text": "The simplest of all methods is called simple naive. Extremely simple: the forecast for tomorrow is what we are observing today." }, { "code": null, "e": 1675, "s": 1494, "text": "Another approach, seasonal naive, is a little more “complex”: the forecast for tomorrow is what we observed the week/month/year (depending what horizon we are working with) before." }, { "code": null, "e": 1720, "s": 1675, "text": "Here is how to do a seasonal naive forecast:" }, { "code": null, "e": 1801, "s": 1720, "text": "naive = snaive(training, h=length(validation))MAPE(naive$mean, validation) * 100" }, { "code": null, "e": 1973, "s": 1801, "text": "That gives us an MAPE of 27.04%. That’s the score to beat. By the way, remove the s from “snaive” and you have the code for simple naive. Here is how to plot the forecast:" }, { "code": null, "e": 2105, "s": 1973, "text": "plot(data, col=\"blue\", xlab=\"Year\", ylab=\"Passengers\", main=\"Seasonal Naive Forecast\", type='l')lines(naive$mean, col=\"red\", lwd=2)" }, { "code": null, "e": 2213, "s": 2105, "text": "We see that what happened in the last year of data is repeated as a forecast for the entire validation set." }, { "code": null, "e": 2413, "s": 2213, "text": "There are many ways to do exponential smoothing. The idea is always to have a declining weight given to observations. The more recent an observation, the more importance it will have in our forecast." }, { "code": null, "e": 2538, "s": 2413, "text": "Parameters can also be added. You can for instance add a trend paramenter (Holt method) or add a seasonality (Holt-Winters)." }, { "code": null, "e": 2743, "s": 2538, "text": "With the Forecast Package, smoothing methods can be placed within the structure of state space models. By using this structure, we can find the optimal exponential smoothing model, using the ets function." }, { "code": null, "e": 2822, "s": 2743, "text": "ets_model = ets(training, allow.multiplicative.trend = TRUE)summary(ets_model)" }, { "code": null, "e": 3124, "s": 2822, "text": "We see ETS (M, Md, M). This means we have an ets model with multiplicative errors, a multiplicative trend and a multiplicative seasonality. Basically, multiplicative means that the parameter is “amplified” over time. For instance the trend is getting bigger and bigger as time goes by (our case here)." }, { "code": null, "e": 3193, "s": 3124, "text": "Here is how to forecast using the estimated optimal smoothing model:" }, { "code": null, "e": 3290, "s": 3193, "text": "ets_forecast = forecast(ets_model, h=length(validation))MAPE(ets_forecast$mean, validation) *100" }, { "code": null, "e": 3425, "s": 3290, "text": "We see that the upward trend in demand is being capture a little bit (far from perfect, better than naive). It gives an MAPE of 12.6%." }, { "code": null, "e": 3596, "s": 3425, "text": "The ets function is good, but it only allows for one seasonality. Sometimes, the data we have can be composed of multiple seasonalities (monthly and yearly for instance)." }, { "code": null, "e": 3880, "s": 3596, "text": "Double Seasonal Holt-Winters (DSHW) allows for two seasonalities: a smaller one repeated often and a bigger one repeated less often. For the method to work however, the seasonalities need to be nested, meaning one must be an integer multiple of the other (2 and 4, 24 and 168, etc.)." }, { "code": null, "e": 4101, "s": 3880, "text": "The code here is a bit different since we need to specify the lenghts of our two seasonalities (which is not always something we know) and the forecast is computed directly when creating the model with the dshw function." }, { "code": null, "e": 4213, "s": 4101, "text": "dshw_model = dshw(training, period1=4, period2 = 12, h=length(validation))MAPE(dshw_model$mean, validation)*100" }, { "code": null, "e": 4253, "s": 4213, "text": "We get a MAPE of 3.7% with this method!" }, { "code": null, "e": 4457, "s": 4253, "text": "DSHW is good, but some processes have more complex seasonalities, which our previous functions cannot handle. Indeed, you could have both a weekly and yearly seasonality. You could even have more than 2!" }, { "code": null, "e": 4619, "s": 4457, "text": "BATS and TBATS allow for multiple seasonalities. TBATS is a modification (an improvement really) of BATS that allows for multiple non-integer seasonality cycles." }, { "code": null, "e": 4676, "s": 4619, "text": "Here is how to build a TBATS model and forecast with it:" }, { "code": null, "e": 4809, "s": 4676, "text": "tbats_model = tbats(training)tbats_forecast = forecast(tbats_model, h=length(validation))MAPE(tbats_forecast$mean, validation) * 100" }, { "code": null, "e": 4849, "s": 4809, "text": "We get a MAPE of 12.9% for this method." }, { "code": null, "e": 4884, "s": 4849, "text": "ARIMA models contain three things:" }, { "code": null, "e": 4998, "s": 4884, "text": "AR(p): autoregressive part of the model. Means that we use p past observations from the timeseries as predictors." }, { "code": null, "e": 5152, "s": 4998, "text": "Differencing (d): Used to transform the timeseries into a stationary one by taking the differences between successive observations at appropriate lags d." }, { "code": null, "e": 5202, "s": 5152, "text": "MA(q): uses q past forecast errors as predictors." }, { "code": null, "e": 5326, "s": 5202, "text": "That’s it for ARIMA but if you know the data you have is seasonal, then you need more. That’s where SARIMA comes into play." }, { "code": null, "e": 5368, "s": 5326, "text": "SARIMA adds a seasonal part to the model." }, { "code": null, "e": 5506, "s": 5368, "text": "P represents the seasonal AR order, D the seasonal differencing order, Q the seasonal MA order and m the number of observations per year." }, { "code": null, "e": 5596, "s": 5506, "text": "The auto.arima function can be used to return the best estimated model. Here is the code:" }, { "code": null, "e": 5633, "s": 5596, "text": "arima_optimal = auto.arima(training)" }, { "code": null, "e": 5701, "s": 5633, "text": "The function returned the following model: ARIMA(0,1,1)(1,1,0)[12]." }, { "code": null, "e": 5847, "s": 5701, "text": "To forecast a SARIMA model (which is what we have here since we have a seasonal part), we can use the sarima.for function from the astsa package." }, { "code": null, "e": 6031, "s": 5847, "text": "library(astsa)sarima_forecast = sarima.for(training, n.ahead=length(validation), p=0,d=1,q=1,P=1,D=1,Q=0,S=12)MAPE(sarima_forecast$pred, validation) * 100" }, { "code": null, "e": 6077, "s": 6031, "text": "We get a MAPE of 6.5% with this SARIMA model." }, { "code": null, "e": 6251, "s": 6077, "text": "Just so you know, we could in theory complexify things even more by adding exogenous variables (explanatory variables) to an ARIMA/SARIMA model, which would make it SARIMAX." }, { "code": null, "e": 6353, "s": 6251, "text": "For this data, DSHW gave the best results. Keep in mind however that no model does best all the time." }, { "code": null, "e": 6588, "s": 6353, "text": "In all the previous examples, I forecasted 5 years into the future. However, if you want to forecast on a daily basis, why would you use a forecasted value from 5 years ago when you could use the real observations to predict tomorrow?" }, { "code": null, "e": 6793, "s": 6588, "text": "The idea of setting up a one-step-ahead forecast is to evaluate how well a model would have done if you were forecasting for one day ahead, during 5 years, using latest observations to make your forecast." }, { "code": null, "e": 6930, "s": 6793, "text": "Simply put: instead of forecasting once for the 60 months ahead, we forecast 60 times for the upcoming month, using latest observations." }, { "code": null, "e": 7140, "s": 6930, "text": "Coding this is quite simple. All we need is to iteratively add the latest observation to the training dataset, forecast from there and repeat. Here is the code to do it using the SARIMA model we found earlier." }, { "code": null, "e": 7613, "s": 7140, "text": "one_step_ahead_sarima = matrix(ncol = 2, nrow = 60)for (i in 1:60){ training_observed = window(data, start = c(1949,1), end = c(1955,(12+i)), frequency = 12) forecasted.sarima = sarima.for(training_observed,n.ahead=1,p=0,d=1,q=1,P=1,D=1,Q=0,S=12) demandforecast = forecasted.sarima$pred observed = validation[[i]] one_step_ahead_sarima[i,1]= observed one_step_ahead_sarima[i,2]= demandforecast}MAPE(one_step_ahead_sarima[,1], one_step_ahead_sarima[,2]) * 100" }, { "code": null, "e": 7790, "s": 7613, "text": "As you see, for every iteration, the training set grows by one observation, a new forecast for n.ahead=1 is computed and results are stored in the one_step_ahead_sarima matrix." }, { "code": null, "e": 7819, "s": 7790, "text": "Here is how to get the plot:" }, { "code": null, "e": 7997, "s": 7819, "text": "plot(data, col=\"blue\", xlab=\"Year\", ylab=\"Passengers\", main=\"SARIMA Forecast\", type='l')lines(ts(one_step_ahead_sarima[,2], start = c(1956,1), frequency = 12), col=\"red\", lwd=3)" }, { "code": null, "e": 8135, "s": 7997, "text": "We get a MAPE of 4.1%, which is an improvement of more than 2% on what we had when using the same SARIMA model to forecast 5 years ahead." }, { "code": null, "e": 8328, "s": 8135, "text": "That’s not surprising considering that the shorter the forecasting horizon, the better the forecast should be. That is why you should always set up a one-step-ahead forecast if it is possible!" }, { "code": null, "e": 8374, "s": 8328, "text": "I hope this helped. Thanks a lot for reading!" } ]
Java - Inner classes
In this chapter, we will discuss inner classes of Java. In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class. Syntax Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class and the class Inner_Demo is the nested class. class Outer_Demo { class Inner_Demo { } } Nested classes are divided into two types − Non-static nested classes − These are the non-static members of a class. Non-static nested classes − These are the non-static members of a class. Static nested classes − These are the static members of a class. Static nested classes − These are the static members of a class. Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class. Inner classes are of three types depending on how and where you define them. They are − Inner Class Method-local Inner Class Anonymous Inner Class Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class. Following is the program to create an inner class and access it. In the given example, we make the inner class private and access the class through a method. Example class Outer_Demo { int num; // inner class private class Inner_Demo { public void print() { System.out.println("This is an inner class"); } } // Accessing he inner class from the method within void display_Inner() { Inner_Demo inner = new Inner_Demo(); inner.print(); } } public class My_class { public static void main(String args[]) { // Instantiating the outer class Outer_Demo outer = new Outer_Demo(); // Accessing the display_Inner() method. outer.display_Inner(); } } Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner class, display_Inner() is the method inside which we are instantiating the inner class, and this method is invoked from the main method. If you compile and execute the above program, you will get the following result − Output This is an inner class. As mentioned earlier, inner classes are also used to access the private members of a class. Suppose, a class is having private members to access them. Write an inner class in it, return the private members from a method within the inner class, say, getValue(), and finally from another class (from which you want to access the private members) call the getValue() method of the inner class. To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using the object of the outer class, following is the way in which you can instantiate the inner class. Outer_Demo outer = new Outer_Demo(); Outer_Demo.Inner_Demo inner = outer.new Inner_Demo(); The following program shows how to access the private members of a class using inner class. Example class Outer_Demo { // private variable of the outer class private int num = 175; // inner class public class Inner_Demo { public int getNum() { System.out.println("This is the getnum method of the inner class"); return num; } } } public class My_class2 { public static void main(String args[]) { // Instantiating the outer class Outer_Demo outer = new Outer_Demo(); // Instantiating the inner class Outer_Demo.Inner_Demo inner = outer.new Inner_Demo(); System.out.println(inner.getNum()); } } If you compile and execute the above program, you will get the following result − Output This is the getnum method of the inner class: 175 In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method. A method-local inner class can be instantiated only within the method where the inner class is defined. The following program shows how to use a method-local inner class. Example public class Outerclass { // instance method of the outer class void my_Method() { int num = 23; // method-local inner class class MethodInner_Demo { public void print() { System.out.println("This is method inner class "+num); } } // end of inner class // Accessing the inner class MethodInner_Demo inner = new MethodInner_Demo(); inner.print(); } public static void main(String args[]) { Outerclass outer = new Outerclass(); outer.my_Method(); } } If you compile and execute the above program, you will get the following result − Output This is method inner class 23 An inner class declared without a class name is known as an anonymous inner class. In case of anonymous inner classes, we declare and instantiate them at the same time. Generally, they are used whenever you need to override the method of a class or an interface. The syntax of an anonymous inner class is as follows − Syntax AnonymousInner an_inner = new AnonymousInner() { public void my_method() { ........ ........ } }; The following program shows how to override the method of a class using anonymous inner class. Example abstract class AnonymousInner { public abstract void mymethod(); } public class Outer_class { public static void main(String args[]) { AnonymousInner inner = new AnonymousInner() { public void mymethod() { System.out.println("This is an example of anonymous inner class"); } }; inner.mymethod(); } } If you compile and execute the above program, you will get the following result − Output This is an example of anonymous inner class In the same way, you can override the methods of the concrete class as well as the interface using an anonymous inner class. Generally, if a method accepts an object of an interface, an abstract class, or a concrete class, then we can implement the interface, extend the abstract class, and pass the object to the method. If it is a class, then we can directly pass it to the method. But in all the three cases, you can pass an anonymous inner class to the method. Here is the syntax of passing an anonymous inner class as a method argument − obj.my_Method(new My_Class() { public void Do() { ..... ..... } }); The following program shows how to pass an anonymous inner class as a method argument. Example // interface interface Message { String greet(); } public class My_class { // method which accepts the object of interface Message public void displayMessage(Message m) { System.out.println(m.greet() + ", This is an example of anonymous inner class as an argument"); } public static void main(String args[]) { // Instantiating the class My_class obj = new My_class(); // Passing an anonymous inner class as an argument obj.displayMessage(new Message() { public String greet() { return "Hello"; } }); } } If you compile and execute the above program, it gives you the following result − Output Hello, This is an example of anonymous inner class as an argument A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class. The syntax of static nested class is as follows − Syntax class MyOuter { static class Nested_Demo { } } Instantiating a static nested class is a bit different from instantiating an inner class. The following program shows how to use a static nested class. Example public class Outer { static class Nested_Demo { public void my_method() { System.out.println("This is my nested class"); } } public static void main(String args[]) { Outer.Nested_Demo nested = new Outer.Nested_Demo(); nested.my_method(); } } If you compile and execute the above program, you will get the following result − Output This is my nested class 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": 2433, "s": 2377, "text": "In this chapter, we will discuss inner classes of Java." }, { "code": null, "e": 2696, "s": 2433, "text": "In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class." }, { "code": null, "e": 2703, "s": 2696, "text": "Syntax" }, { "code": null, "e": 2844, "s": 2703, "text": "Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class and the class Inner_Demo is the nested class." }, { "code": null, "e": 2893, "s": 2844, "text": "class Outer_Demo {\n class Inner_Demo {\n }\n}\n" }, { "code": null, "e": 2937, "s": 2893, "text": "Nested classes are divided into two types −" }, { "code": null, "e": 3010, "s": 2937, "text": "Non-static nested classes − These are the non-static members of a class." }, { "code": null, "e": 3083, "s": 3010, "text": "Non-static nested classes − These are the non-static members of a class." }, { "code": null, "e": 3148, "s": 3083, "text": "Static nested classes − These are the static members of a class." }, { "code": null, "e": 3213, "s": 3148, "text": "Static nested classes − These are the static members of a class." }, { "code": null, "e": 3491, "s": 3213, "text": "Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class." }, { "code": null, "e": 3579, "s": 3491, "text": "Inner classes are of three types depending on how and where you define them. They are −" }, { "code": null, "e": 3591, "s": 3579, "text": "Inner Class" }, { "code": null, "e": 3616, "s": 3591, "text": "Method-local Inner Class" }, { "code": null, "e": 3638, "s": 3616, "text": "Anonymous Inner Class" }, { "code": null, "e": 3873, "s": 3638, "text": "Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class." }, { "code": null, "e": 4031, "s": 3873, "text": "Following is the program to create an inner class and access it. In the given example, we make the inner class private and access the class through a method." }, { "code": null, "e": 4039, "s": 4031, "text": "Example" }, { "code": null, "e": 4619, "s": 4039, "text": "class Outer_Demo {\n int num;\n \n // inner class\n private class Inner_Demo {\n public void print() {\n System.out.println(\"This is an inner class\");\n }\n }\n \n // Accessing he inner class from the method within\n void display_Inner() {\n Inner_Demo inner = new Inner_Demo();\n inner.print();\n }\n}\n \npublic class My_class {\n\n public static void main(String args[]) {\n // Instantiating the outer class \n Outer_Demo outer = new Outer_Demo();\n \n // Accessing the display_Inner() method.\n outer.display_Inner();\n }\n}" }, { "code": null, "e": 4837, "s": 4619, "text": "Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner class, display_Inner() is the method inside which we are instantiating the inner class, and this method is invoked from the main method." }, { "code": null, "e": 4919, "s": 4837, "text": "If you compile and execute the above program, you will get the following result −" }, { "code": null, "e": 4926, "s": 4919, "text": "Output" }, { "code": null, "e": 4951, "s": 4926, "text": "This is an inner class.\n" }, { "code": null, "e": 5342, "s": 4951, "text": "As mentioned earlier, inner classes are also used to access the private members of a class. Suppose, a class is having private members to access them. Write an inner class in it, return the private members from a method within the inner class, say, getValue(), and finally from another class (from which you want to access the private members) call the getValue() method of the inner class." }, { "code": null, "e": 5541, "s": 5342, "text": "To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using the object of the outer class, following is the way in which you can instantiate the inner class." }, { "code": null, "e": 5633, "s": 5541, "text": "Outer_Demo outer = new Outer_Demo();\nOuter_Demo.Inner_Demo inner = outer.new Inner_Demo();\n" }, { "code": null, "e": 5725, "s": 5633, "text": "The following program shows how to access the private members of a class using inner class." }, { "code": null, "e": 5733, "s": 5725, "text": "Example" }, { "code": null, "e": 6322, "s": 5733, "text": "class Outer_Demo {\n // private variable of the outer class\n private int num = 175; \n \n // inner class\n public class Inner_Demo {\n public int getNum() {\n System.out.println(\"This is the getnum method of the inner class\");\n return num;\n }\n }\n}\n\npublic class My_class2 {\n\n public static void main(String args[]) {\n // Instantiating the outer class\n Outer_Demo outer = new Outer_Demo();\n \n // Instantiating the inner class\n Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();\n System.out.println(inner.getNum());\n }\n}" }, { "code": null, "e": 6404, "s": 6322, "text": "If you compile and execute the above program, you will get the following result −" }, { "code": null, "e": 6411, "s": 6404, "text": "Output" }, { "code": null, "e": 6462, "s": 6411, "text": "This is the getnum method of the inner class: 175\n" }, { "code": null, "e": 6623, "s": 6462, "text": "In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method." }, { "code": null, "e": 6794, "s": 6623, "text": "A method-local inner class can be instantiated only within the method where the inner class is defined. The following program shows how to use a method-local inner class." }, { "code": null, "e": 6802, "s": 6794, "text": "Example" }, { "code": null, "e": 7376, "s": 6802, "text": "public class Outerclass {\n // instance method of the outer class \n void my_Method() {\n int num = 23;\n\n // method-local inner class\n class MethodInner_Demo {\n public void print() {\n System.out.println(\"This is method inner class \"+num);\t \n } \n } // end of inner class\n\t \n // Accessing the inner class\n MethodInner_Demo inner = new MethodInner_Demo();\n inner.print();\n }\n \n public static void main(String args[]) {\n Outerclass outer = new Outerclass();\n outer.my_Method();\t \t \n }\n}" }, { "code": null, "e": 7458, "s": 7376, "text": "If you compile and execute the above program, you will get the following result −" }, { "code": null, "e": 7465, "s": 7458, "text": "Output" }, { "code": null, "e": 7496, "s": 7465, "text": "This is method inner class 23\n" }, { "code": null, "e": 7814, "s": 7496, "text": "An inner class declared without a class name is known as an anonymous inner class. In case of anonymous inner classes, we declare and instantiate them at the same time. Generally, they are used whenever you need to override the method of a class or an interface. The syntax of an anonymous inner class is as follows −" }, { "code": null, "e": 7821, "s": 7814, "text": "Syntax" }, { "code": null, "e": 7941, "s": 7821, "text": "AnonymousInner an_inner = new AnonymousInner() {\n public void my_method() {\n ........\n ........\n } \n};\n" }, { "code": null, "e": 8036, "s": 7941, "text": "The following program shows how to override the method of a class using anonymous inner class." }, { "code": null, "e": 8044, "s": 8036, "text": "Example" }, { "code": null, "e": 8404, "s": 8044, "text": "abstract class AnonymousInner {\n public abstract void mymethod();\n}\n\npublic class Outer_class {\n\n public static void main(String args[]) {\n AnonymousInner inner = new AnonymousInner() {\n public void mymethod() {\n System.out.println(\"This is an example of anonymous inner class\");\n }\n };\n inner.mymethod();\t\n }\n}" }, { "code": null, "e": 8486, "s": 8404, "text": "If you compile and execute the above program, you will get the following result −" }, { "code": null, "e": 8493, "s": 8486, "text": "Output" }, { "code": null, "e": 8538, "s": 8493, "text": "This is an example of anonymous inner class\n" }, { "code": null, "e": 8663, "s": 8538, "text": "In the same way, you can override the methods of the concrete class as well as the interface using an anonymous inner class." }, { "code": null, "e": 8922, "s": 8663, "text": "Generally, if a method accepts an object of an interface, an abstract class, or a concrete class, then we can implement the interface, extend the abstract class, and pass the object to the method. If it is a class, then we can directly pass it to the method." }, { "code": null, "e": 9081, "s": 8922, "text": "But in all the three cases, you can pass an anonymous inner class to the method. Here is the syntax of passing an anonymous inner class as a method argument −" }, { "code": null, "e": 9168, "s": 9081, "text": "obj.my_Method(new My_Class() {\n public void Do() {\n .....\n .....\n }\n});\n" }, { "code": null, "e": 9255, "s": 9168, "text": "The following program shows how to pass an anonymous inner class as a method argument." }, { "code": null, "e": 9263, "s": 9255, "text": "Example" }, { "code": null, "e": 9865, "s": 9263, "text": "// interface\ninterface Message {\n String greet();\n}\n\npublic class My_class {\n // method which accepts the object of interface Message\n public void displayMessage(Message m) {\n System.out.println(m.greet() +\n \", This is an example of anonymous inner class as an argument\"); \n }\n\n public static void main(String args[]) {\n // Instantiating the class\n My_class obj = new My_class();\n\n // Passing an anonymous inner class as an argument\n obj.displayMessage(new Message() {\n public String greet() {\n return \"Hello\";\n }\n });\n }\n}" }, { "code": null, "e": 9947, "s": 9865, "text": "If you compile and execute the above program, it gives you the following result −" }, { "code": null, "e": 9954, "s": 9947, "text": "Output" }, { "code": null, "e": 10021, "s": 9954, "text": "Hello, This is an example of anonymous inner class as an argument\n" }, { "code": null, "e": 10368, "s": 10021, "text": "A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class. The syntax of static nested class is as follows −" }, { "code": null, "e": 10375, "s": 10368, "text": "Syntax" }, { "code": null, "e": 10429, "s": 10375, "text": "class MyOuter {\n static class Nested_Demo {\n }\n}\n" }, { "code": null, "e": 10581, "s": 10429, "text": "Instantiating a static nested class is a bit different from instantiating an inner class. The following program shows how to use a static nested class." }, { "code": null, "e": 10589, "s": 10581, "text": "Example" }, { "code": null, "e": 10882, "s": 10589, "text": "public class Outer {\n static class Nested_Demo {\n public void my_method() {\n System.out.println(\"This is my nested class\");\n }\n }\n \n public static void main(String args[]) {\n Outer.Nested_Demo nested = new Outer.Nested_Demo();\t \n nested.my_method();\n }\n}" }, { "code": null, "e": 10964, "s": 10882, "text": "If you compile and execute the above program, you will get the following result −" }, { "code": null, "e": 10971, "s": 10964, "text": "Output" }, { "code": null, "e": 10996, "s": 10971, "text": "This is my nested class\n" }, { "code": null, "e": 11029, "s": 10996, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 11045, "s": 11029, "text": " Malhar Lathkar" }, { "code": null, "e": 11078, "s": 11045, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 11094, "s": 11078, "text": " Malhar Lathkar" }, { "code": null, "e": 11129, "s": 11094, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11143, "s": 11129, "text": " Anadi Sharma" }, { "code": null, "e": 11177, "s": 11143, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 11191, "s": 11177, "text": " Tushar Kale" }, { "code": null, "e": 11228, "s": 11191, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 11243, "s": 11228, "text": " Monica Mittal" }, { "code": null, "e": 11276, "s": 11243, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 11295, "s": 11276, "text": " Arnab Chakraborty" }, { "code": null, "e": 11302, "s": 11295, "text": " Print" }, { "code": null, "e": 11313, "s": 11302, "text": " Add Notes" } ]
Non-Restoring Division For Unsigned Integer - GeeksforGeeks
04 Oct, 2018 In earlier post Restoring Division learned about restoring division. Now, here perform Non-Restoring division, it is less complex than the restoring one because simpler operation are involved i.e. addition and subtraction, also now restoring step is performed. In the method, rely on the sign bit of the register which initially contain zero named as A. Here is the flow chart given below. Let’s pick the step involved: Step-1: First the registers are initialized with corresponding values (Q = Dividend, M = Divisor, A = 0, n = number of bits in dividend) Step-2: Check the sign bit of register A Step-3: If it is 1 shift left content of AQ and perform A = A+M, otherwise shift left AQ and perform A = A-M (means add 2’s complement of M to A and store it to A) Step-4: Again the sign bit of register A Step-5: If sign bit is 1 Q[0] become 0 otherwise Q[0] become 1 (Q[0] means least significant bit of register Q) Step-6: Decrements value of N by 1 Step-7: If N is not equal to zero go to Step 2 otherwise go to next step Step-8: If sign bit of A is 1 then perform A = A+M Step-9: Register Q contain quotient and A contain remainderExamples: Perform Non_Restoring Division for Unsigned IntegerDividend =11 Divisor =3 -M =11101 NMAQAction400011000001011Start00001011_Left shift AQ11110011_A=A-M3111100110Q[0]=011100110_Left shift AQ11111110_A=A+M2111111100Q[0]=011111100_Left Shift AQ00010100_A=A+M1000101001Q[0]=100101001_Left Shift AQ00010001_A=A-M0000100011Q[0]=1Quotient = 3 (Q) Remainder = 2 (A) My Personal Notes arrow_drop_upSave Examples: Perform Non_Restoring Division for Unsigned Integer Dividend =11 Divisor =3 -M =11101 Quotient = 3 (Q) Remainder = 2 (A) SubhajitNandi utkarshkalia Computer Organization & Architecture Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Cache Memory in Computer Organization Addressing Modes Logical and Physical Address in Operating System Computer Organization | RISC and CISC Random Access Memory (RAM) and Read Only Memory (ROM) IEEE Standard 754 Floating Point Numbers 4-bit binary Adder-Subtractor Difference between Unipolar, Polar and Bipolar Line Coding Schemes Introduction to memory and memory units Difference between RAM and ROM
[ { "code": null, "e": 28189, "s": 28161, "text": "\n04 Oct, 2018" }, { "code": null, "e": 28543, "s": 28189, "text": "In earlier post Restoring Division learned about restoring division. Now, here perform Non-Restoring division, it is less complex than the restoring one because simpler operation are involved i.e. addition and subtraction, also now restoring step is performed. In the method, rely on the sign bit of the register which initially contain zero named as A." }, { "code": null, "e": 28579, "s": 28543, "text": "Here is the flow chart given below." }, { "code": null, "e": 28609, "s": 28579, "text": "Let’s pick the step involved:" }, { "code": null, "e": 28746, "s": 28609, "text": "Step-1: First the registers are initialized with corresponding values (Q = Dividend, M = Divisor, A = 0, n = number of bits in dividend)" }, { "code": null, "e": 28787, "s": 28746, "text": "Step-2: Check the sign bit of register A" }, { "code": null, "e": 28951, "s": 28787, "text": "Step-3: If it is 1 shift left content of AQ and perform A = A+M, otherwise shift left AQ and perform A = A-M (means add 2’s complement of M to A and store it to A)" }, { "code": null, "e": 28992, "s": 28951, "text": "Step-4: Again the sign bit of register A" }, { "code": null, "e": 29104, "s": 28992, "text": "Step-5: If sign bit is 1 Q[0] become 0 otherwise Q[0] become 1 (Q[0] means least significant bit of register Q)" }, { "code": null, "e": 29139, "s": 29104, "text": "Step-6: Decrements value of N by 1" }, { "code": null, "e": 29212, "s": 29139, "text": "Step-7: If N is not equal to zero go to Step 2 otherwise go to next step" }, { "code": null, "e": 29263, "s": 29212, "text": "Step-8: If sign bit of A is 1 then perform A = A+M" }, { "code": null, "e": 29730, "s": 29263, "text": "Step-9: Register Q contain quotient and A contain remainderExamples: Perform Non_Restoring Division for Unsigned IntegerDividend =11\nDivisor =3 \n-M =11101\nNMAQAction400011000001011Start00001011_Left shift AQ11110011_A=A-M3111100110Q[0]=011100110_Left shift AQ11111110_A=A+M2111111100Q[0]=011111100_Left Shift AQ00010100_A=A+M1000101001Q[0]=100101001_Left Shift AQ00010001_A=A-M0000100011Q[0]=1Quotient = 3 (Q)\nRemainder = 2 (A)\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29792, "s": 29730, "text": "Examples: Perform Non_Restoring Division for Unsigned Integer" }, { "code": null, "e": 29830, "s": 29792, "text": "Dividend =11\nDivisor =3 \n-M =11101\n" }, { "code": null, "e": 29867, "s": 29830, "text": "Quotient = 3 (Q)\nRemainder = 2 (A)\n" }, { "code": null, "e": 29881, "s": 29867, "text": "SubhajitNandi" }, { "code": null, "e": 29894, "s": 29881, "text": "utkarshkalia" }, { "code": null, "e": 29931, "s": 29894, "text": "Computer Organization & Architecture" }, { "code": null, "e": 29966, "s": 29931, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 29974, "s": 29966, "text": "GATE CS" }, { "code": null, "e": 30072, "s": 29974, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30110, "s": 30072, "text": "Cache Memory in Computer Organization" }, { "code": null, "e": 30127, "s": 30110, "text": "Addressing Modes" }, { "code": null, "e": 30176, "s": 30127, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 30214, "s": 30176, "text": "Computer Organization | RISC and CISC" }, { "code": null, "e": 30268, "s": 30214, "text": "Random Access Memory (RAM) and Read Only Memory (ROM)" }, { "code": null, "e": 30309, "s": 30268, "text": "IEEE Standard 754 Floating Point Numbers" }, { "code": null, "e": 30339, "s": 30309, "text": "4-bit binary Adder-Subtractor" }, { "code": null, "e": 30406, "s": 30339, "text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes" }, { "code": null, "e": 30446, "s": 30406, "text": "Introduction to memory and memory units" } ]
Cycles of length n in an undirected and connected graph - GeeksforGeeks
02 Jul, 2021 Given an undirected and connected graph and a number n, count total number of cycles of length n in the graph. A cycle of length n simply means that the cycle contains n vertices and n edges. And we have to count all such cycles that exist. Example : Input : n = 4 Output : Total cycles = 3 Explanation : Following 3 unique cycles 0 -> 1 -> 2 -> 3 -> 0 0 -> 1 -> 4 -> 3 -> 0 1 -> 2 -> 3 -> 4 -> 1 Note* : There are more cycles but these 3 are unique as 0 -> 3 -> 2 -> 1 -> 0 and 0 -> 1 -> 2 -> 3 -> 0 are same cycles and hence will be counted as 1. To solve this Problem, DFS(Depth First Search) can be effectively used. Using DFS we find every possible path of length (n-1) for a particular source (or starting point). Then we check if this path ends with the vertex it started with, if yes then we count this as the cycle of length n. Notice that we looked for path of length (n-1) because the nth edge will be the closing edge of cycle.Every possible path of length (n-1) can be searched using only V – (n – 1) vertices (where V is the total number of vertices). For above example, all the cycles of length 4 can be searched using only 5-(4-1) = 2 vertices. The reason behind this is quite simple, because we search for all possible path of length (n-1) = 3 using these 2 vertices which include the remaining 3 vertices. So, these 2 vertices cover the cycles of remaining 3 vertices as well, and using only 3 vertices we can’t form a cycle of length 4 anyways. One more thing to notice is that, every vertex finds 2 duplicate cycles for every cycle that it forms. For above example 0th vertex finds two duplicate cycle namely 0 -> 3 -> 2 -> 1 -> 0 and 0 -> 1 -> 2 -> 3 -> 0. Hence the total count must be divided by 2 because every cycle is counted twice. C++ Java Python3 C# Javascript // CPP Program to count cycles of length n// in a given graph.#include <bits/stdc++.h>using namespace std; // Number of verticesconst int V = 5; void DFS(bool graph[][V], bool marked[], int n, int vert, int start, int &count){ // mark the vertex vert as visited marked[vert] = true; // if the path of length (n-1) is found if (n == 0) { // mark vert as un-visited to make // it usable again. marked[vert] = false; // Check if vertex vert can end with // vertex start if (graph[vert][start]) { count++; return; } else return; } // For searching every possible path of // length (n-1) for (int i = 0; i < V; i++) if (!marked[i] && graph[vert][i]) // DFS for searching path by decreasing // length by 1 DFS(graph, marked, n-1, i, start, count); // marking vert as unvisited to make it // usable again. marked[vert] = false;} // Counts cycles of length N in an undirected// and connected graph.int countCycles(bool graph[][V], int n){ // all vertex are marked un-visited initially. bool marked[V]; memset(marked, 0, sizeof(marked)); // Searching for cycle by using v-n+1 vertices int count = 0; for (int i = 0; i < V - (n - 1); i++) { DFS(graph, marked, n-1, i, i, count); // ith vertex is marked as visited and // will not be visited again. marked[i] = true; } return count/2;} int main(){ bool graph[][V] = {{0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}}; int n = 4; cout << "Total cycles of length " << n << " are " << countCycles(graph, n); return 0;} // Java program to calculate cycles of// length n in a given graphpublic class Main { // Number of vertices public static final int V = 5; static int count = 0; static void DFS(int graph[][], boolean marked[], int n, int vert, int start) { // mark the vertex vert as visited marked[vert] = true; // if the path of length (n-1) is found if (n == 0) { // mark vert as un-visited to // make it usable again marked[vert] = false; // Check if vertex vert end // with vertex start if (graph[vert][start] == 1) { count++; return; } else return; } // For searching every possible // path of length (n-1) for (int i = 0; i < V; i++) if (!marked[i] && graph[vert][i] == 1) // DFS for searching path by // decreasing length by 1 DFS(graph, marked, n-1, i, start); // marking vert as unvisited to make it // usable again marked[vert] = false; } // Count cycles of length N in an // undirected and connected graph. static int countCycles(int graph[][], int n) { // all vertex are marked un-visited // initially. boolean marked[] = new boolean[V]; // Searching for cycle by using // v-n+1 vertices for (int i = 0; i < V - (n - 1); i++) { DFS(graph, marked, n-1, i, i); // ith vertex is marked as visited // and will not be visited again marked[i] = true; } return count / 2; } // driver code public static void main(String[] args) { int graph[][] = {{0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}}; int n = 4; System.out.println("Total cycles of length "+ n + " are "+ countCycles(graph, n)); }} // This code is contributed by nuclode # Python Program to count# cycles of length n# in a given graph. # Number of verticesV = 5 def DFS(graph, marked, n, vert, start, count): # mark the vertex vert as visited marked[vert] = True # if the path of length (n-1) is found if n == 0: # mark vert as un-visited to make # it usable again. marked[vert] = False # Check if vertex vert can end with # vertex start if graph[vert][start] == 1: count = count + 1 return count else: return count # For searching every possible path of # length (n-1) for i in range(V): if marked[i] == False and graph[vert][i] == 1: # DFS for searching path by decreasing # length by 1 count = DFS(graph, marked, n-1, i, start, count) # marking vert as unvisited to make it # usable again. marked[vert] = False return count # Counts cycles of length# N in an undirected# and connected graph.def countCycles( graph, n): # all vertex are marked un-visited initially. marked = [False] * V # Searching for cycle by using v-n+1 vertices count = 0 for i in range(V-(n-1)): count = DFS(graph, marked, n-1, i, i, count) # ith vertex is marked as visited and # will not be visited again. marked[i] = True return int(count/2) # main :graph = [[0, 1, 0, 1, 0], [1 ,0 ,1 ,0, 1], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]] n = 4print("Total cycles of length ",n," are ",countCycles(graph, n)) # this code is contributed by Shivani Ghughtyal // C# program to calculate cycles of// length n in a given graphusing System; class GFG{ // Number of vertices public static int V = 5; static int count = 0; static void DFS(int [,]graph, bool []marked, int n, int vert, int start) { // mark the vertex vert as visited marked[vert] = true; // if the path of length (n-1) is found if (n == 0) { // mark vert as un-visited to // make it usable again marked[vert] = false; // Check if vertex vert end // with vertex start if (graph[vert, start] == 1) { count++; return; } else return; } // For searching every possible // path of length (n-1) for (int i = 0; i < V; i++) if (!marked[i] && graph[vert, i] == 1) // DFS for searching path by // decreasing length by 1 DFS(graph, marked, n - 1, i, start); // marking vert as unvisited to make it // usable again marked[vert] = false; } // Count cycles of length N in an // undirected and connected graph. static int countCycles(int [,]graph, int n) { // all vertex are marked un-visited // initially. bool []marked = new bool[V]; // Searching for cycle by using // v-n+1 vertices for (int i = 0; i < V - (n - 1); i++) { DFS(graph, marked, n - 1, i, i); // ith vertex is marked as visited // and will not be visited again marked[i] = true; } return count / 2; } // Driver code public static void Main() { int [,]graph = {{0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}}; int n = 4; Console.WriteLine("Total cycles of length "+ n + " are "+ countCycles(graph, n)); }} /* This code contributed by PrinciRaj1992 */ <script> // JavaScript program to calculate cycles of// length n in a given graph // Number of verticesvar V = 5;var count = 0; function DFS(graph, marked, n, vert, start){ // mark the vertex vert as visited marked[vert] = true; // if the path of length (n-1) is found if (n == 0) { // mark vert as un-visited to // make it usable again marked[vert] = false; // Check if vertex vert end // with vertex start if (graph[vert][start] == 1) { count++; return; } else return; } // For searching every possible // path of length (n-1) for (var i = 0; i < V; i++) if (!marked[i] && graph[vert][i] == 1) // DFS for searching path by // decreasing length by 1 DFS(graph, marked, n - 1, i, start); // marking vert as unvisited to make it // usable again marked[vert] = false;} // Count cycles of length N in an// undirected and connected graph.function countCycles(graph, n){ // all vertex are marked un-visited // initially. var marked = Array(V).fill(false); // Searching for cycle by using // v-n+1 vertices for (var i = 0; i < V - (n - 1); i++) { DFS(graph, marked, n - 1, i, i); // ith vertex is marked as visited // and will not be visited again marked[i] = true; } return parseInt(count / 2);} // Driver codevar graph = [[0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]]; var n = 4; document.write("Total cycles of length "+ n + " are "+ countCycles(graph, n)); </script> Output: Total cycles of length 4 are 3 This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. princiraj1992 Akanksha_Rai itsok graph-connectivity graph-cycle Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Detect Cycle in a Directed Graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Ford-Fulkerson Algorithm for Maximum Flow Problem Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Traveling Salesman Problem (TSP) Implementation Detect cycle in an undirected graph Hamiltonian Cycle | Backtracking-6 m Coloring Problem | Backtracking-5 Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 26533, "s": 26505, "text": "\n02 Jul, 2021" }, { "code": null, "e": 26786, "s": 26533, "text": "Given an undirected and connected graph and a number n, count total number of cycles of length n in the graph. A cycle of length n simply means that the cycle contains n vertices and n edges. And we have to count all such cycles that exist. Example : " }, { "code": null, "e": 26801, "s": 26786, "text": "Input : n = 4" }, { "code": null, "e": 27096, "s": 26801, "text": "Output : Total cycles = 3\nExplanation : Following 3 unique cycles \n 0 -> 1 -> 2 -> 3 -> 0\n 0 -> 1 -> 4 -> 3 -> 0\n 1 -> 2 -> 3 -> 4 -> 1\nNote* : There are more cycles but\nthese 3 are unique as 0 -> 3 -> 2 -> 1\n-> 0 and 0 -> 1 -> 2 -> 3 -> 0 are \nsame cycles and hence will be counted as 1." }, { "code": null, "e": 28307, "s": 27096, "text": "To solve this Problem, DFS(Depth First Search) can be effectively used. Using DFS we find every possible path of length (n-1) for a particular source (or starting point). Then we check if this path ends with the vertex it started with, if yes then we count this as the cycle of length n. Notice that we looked for path of length (n-1) because the nth edge will be the closing edge of cycle.Every possible path of length (n-1) can be searched using only V – (n – 1) vertices (where V is the total number of vertices). For above example, all the cycles of length 4 can be searched using only 5-(4-1) = 2 vertices. The reason behind this is quite simple, because we search for all possible path of length (n-1) = 3 using these 2 vertices which include the remaining 3 vertices. So, these 2 vertices cover the cycles of remaining 3 vertices as well, and using only 3 vertices we can’t form a cycle of length 4 anyways. One more thing to notice is that, every vertex finds 2 duplicate cycles for every cycle that it forms. For above example 0th vertex finds two duplicate cycle namely 0 -> 3 -> 2 -> 1 -> 0 and 0 -> 1 -> 2 -> 3 -> 0. Hence the total count must be divided by 2 because every cycle is counted twice. " }, { "code": null, "e": 28311, "s": 28307, "text": "C++" }, { "code": null, "e": 28316, "s": 28311, "text": "Java" }, { "code": null, "e": 28324, "s": 28316, "text": "Python3" }, { "code": null, "e": 28327, "s": 28324, "text": "C#" }, { "code": null, "e": 28338, "s": 28327, "text": "Javascript" }, { "code": "// CPP Program to count cycles of length n// in a given graph.#include <bits/stdc++.h>using namespace std; // Number of verticesconst int V = 5; void DFS(bool graph[][V], bool marked[], int n, int vert, int start, int &count){ // mark the vertex vert as visited marked[vert] = true; // if the path of length (n-1) is found if (n == 0) { // mark vert as un-visited to make // it usable again. marked[vert] = false; // Check if vertex vert can end with // vertex start if (graph[vert][start]) { count++; return; } else return; } // For searching every possible path of // length (n-1) for (int i = 0; i < V; i++) if (!marked[i] && graph[vert][i]) // DFS for searching path by decreasing // length by 1 DFS(graph, marked, n-1, i, start, count); // marking vert as unvisited to make it // usable again. marked[vert] = false;} // Counts cycles of length N in an undirected// and connected graph.int countCycles(bool graph[][V], int n){ // all vertex are marked un-visited initially. bool marked[V]; memset(marked, 0, sizeof(marked)); // Searching for cycle by using v-n+1 vertices int count = 0; for (int i = 0; i < V - (n - 1); i++) { DFS(graph, marked, n-1, i, i, count); // ith vertex is marked as visited and // will not be visited again. marked[i] = true; } return count/2;} int main(){ bool graph[][V] = {{0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}}; int n = 4; cout << \"Total cycles of length \" << n << \" are \" << countCycles(graph, n); return 0;}", "e": 30169, "s": 28338, "text": null }, { "code": "// Java program to calculate cycles of// length n in a given graphpublic class Main { // Number of vertices public static final int V = 5; static int count = 0; static void DFS(int graph[][], boolean marked[], int n, int vert, int start) { // mark the vertex vert as visited marked[vert] = true; // if the path of length (n-1) is found if (n == 0) { // mark vert as un-visited to // make it usable again marked[vert] = false; // Check if vertex vert end // with vertex start if (graph[vert][start] == 1) { count++; return; } else return; } // For searching every possible // path of length (n-1) for (int i = 0; i < V; i++) if (!marked[i] && graph[vert][i] == 1) // DFS for searching path by // decreasing length by 1 DFS(graph, marked, n-1, i, start); // marking vert as unvisited to make it // usable again marked[vert] = false; } // Count cycles of length N in an // undirected and connected graph. static int countCycles(int graph[][], int n) { // all vertex are marked un-visited // initially. boolean marked[] = new boolean[V]; // Searching for cycle by using // v-n+1 vertices for (int i = 0; i < V - (n - 1); i++) { DFS(graph, marked, n-1, i, i); // ith vertex is marked as visited // and will not be visited again marked[i] = true; } return count / 2; } // driver code public static void main(String[] args) { int graph[][] = {{0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}}; int n = 4; System.out.println(\"Total cycles of length \"+ n + \" are \"+ countCycles(graph, n)); }} // This code is contributed by nuclode", "e": 32453, "s": 30169, "text": null }, { "code": "# Python Program to count# cycles of length n# in a given graph. # Number of verticesV = 5 def DFS(graph, marked, n, vert, start, count): # mark the vertex vert as visited marked[vert] = True # if the path of length (n-1) is found if n == 0: # mark vert as un-visited to make # it usable again. marked[vert] = False # Check if vertex vert can end with # vertex start if graph[vert][start] == 1: count = count + 1 return count else: return count # For searching every possible path of # length (n-1) for i in range(V): if marked[i] == False and graph[vert][i] == 1: # DFS for searching path by decreasing # length by 1 count = DFS(graph, marked, n-1, i, start, count) # marking vert as unvisited to make it # usable again. marked[vert] = False return count # Counts cycles of length# N in an undirected# and connected graph.def countCycles( graph, n): # all vertex are marked un-visited initially. marked = [False] * V # Searching for cycle by using v-n+1 vertices count = 0 for i in range(V-(n-1)): count = DFS(graph, marked, n-1, i, i, count) # ith vertex is marked as visited and # will not be visited again. marked[i] = True return int(count/2) # main :graph = [[0, 1, 0, 1, 0], [1 ,0 ,1 ,0, 1], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]] n = 4print(\"Total cycles of length \",n,\" are \",countCycles(graph, n)) # this code is contributed by Shivani Ghughtyal", "e": 34088, "s": 32453, "text": null }, { "code": "// C# program to calculate cycles of// length n in a given graphusing System; class GFG{ // Number of vertices public static int V = 5; static int count = 0; static void DFS(int [,]graph, bool []marked, int n, int vert, int start) { // mark the vertex vert as visited marked[vert] = true; // if the path of length (n-1) is found if (n == 0) { // mark vert as un-visited to // make it usable again marked[vert] = false; // Check if vertex vert end // with vertex start if (graph[vert, start] == 1) { count++; return; } else return; } // For searching every possible // path of length (n-1) for (int i = 0; i < V; i++) if (!marked[i] && graph[vert, i] == 1) // DFS for searching path by // decreasing length by 1 DFS(graph, marked, n - 1, i, start); // marking vert as unvisited to make it // usable again marked[vert] = false; } // Count cycles of length N in an // undirected and connected graph. static int countCycles(int [,]graph, int n) { // all vertex are marked un-visited // initially. bool []marked = new bool[V]; // Searching for cycle by using // v-n+1 vertices for (int i = 0; i < V - (n - 1); i++) { DFS(graph, marked, n - 1, i, i); // ith vertex is marked as visited // and will not be visited again marked[i] = true; } return count / 2; } // Driver code public static void Main() { int [,]graph = {{0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}}; int n = 4; Console.WriteLine(\"Total cycles of length \"+ n + \" are \"+ countCycles(graph, n)); }} /* This code contributed by PrinciRaj1992 */", "e": 36394, "s": 34088, "text": null }, { "code": "<script> // JavaScript program to calculate cycles of// length n in a given graph // Number of verticesvar V = 5;var count = 0; function DFS(graph, marked, n, vert, start){ // mark the vertex vert as visited marked[vert] = true; // if the path of length (n-1) is found if (n == 0) { // mark vert as un-visited to // make it usable again marked[vert] = false; // Check if vertex vert end // with vertex start if (graph[vert][start] == 1) { count++; return; } else return; } // For searching every possible // path of length (n-1) for (var i = 0; i < V; i++) if (!marked[i] && graph[vert][i] == 1) // DFS for searching path by // decreasing length by 1 DFS(graph, marked, n - 1, i, start); // marking vert as unvisited to make it // usable again marked[vert] = false;} // Count cycles of length N in an// undirected and connected graph.function countCycles(graph, n){ // all vertex are marked un-visited // initially. var marked = Array(V).fill(false); // Searching for cycle by using // v-n+1 vertices for (var i = 0; i < V - (n - 1); i++) { DFS(graph, marked, n - 1, i, i); // ith vertex is marked as visited // and will not be visited again marked[i] = true; } return parseInt(count / 2);} // Driver codevar graph = [[0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]]; var n = 4; document.write(\"Total cycles of length \"+ n + \" are \"+ countCycles(graph, n)); </script>", "e": 38186, "s": 36394, "text": null }, { "code": null, "e": 38196, "s": 38186, "text": "Output: " }, { "code": null, "e": 38227, "s": 38196, "text": "Total cycles of length 4 are 3" }, { "code": null, "e": 38648, "s": 38227, "text": "This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 38662, "s": 38648, "text": "princiraj1992" }, { "code": null, "e": 38675, "s": 38662, "text": "Akanksha_Rai" }, { "code": null, "e": 38681, "s": 38675, "text": "itsok" }, { "code": null, "e": 38700, "s": 38681, "text": "graph-connectivity" }, { "code": null, "e": 38712, "s": 38700, "text": "graph-cycle" }, { "code": null, "e": 38718, "s": 38712, "text": "Graph" }, { "code": null, "e": 38724, "s": 38718, "text": "Graph" }, { "code": null, "e": 38822, "s": 38724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38842, "s": 38822, "text": "Topological Sorting" }, { "code": null, "e": 38875, "s": 38842, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 38943, "s": 38875, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 38993, "s": 38943, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 39068, "s": 38993, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 39116, "s": 39068, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 39152, "s": 39116, "text": "Detect cycle in an undirected graph" }, { "code": null, "e": 39187, "s": 39152, "text": "Hamiltonian Cycle | Backtracking-6" }, { "code": null, "e": 39223, "s": 39187, "text": "m Coloring Problem | Backtracking-5" } ]
Weekend Hack: Building an Image Recognition bot for Telegram using Python | by Alain Perkaz | Towards Data Science
The goal of this post is to build a Telegram bot with Python that performs image recognition using neural networks. The post is divided into three main sections: introduction, technology choices, and step-by-step setup. This post is the fourth instance of the Weekend Hack series, a series of short development stories about the exploration of new concepts. Focused on learning by doing, step-by-step instructions are provided. Automated image recognition (ex. object recognition and image classification) can provide immense value for businesses. If you run a forum, dating app, or any platform where users upload content, automating the recognition of images can be critical. The benefits are twofold: On the one hand, it provides value to the end-users, allowing them to perform searches over the images by classified topic while avoiding the tedious task of manual classification. A practical example of this is the Unsplash search functionality, which searches high-quality images by topic. On the other hand, automated image recognition also provides value to the system owners, as it allows to filter out images that contain nudity, for example. In short, it allows improving the quality of the provided services in an automated manner. Good right? As we see, applications are endless, and benefits clear. The main question remains, which solution to choose for this task? Plenty of third party solutions exists, along with the possibility of building your own image recognition pipeline from open-source or proprietary software. On the next section, we will explore the different alternatives. As hinted above, there is a myriad of providers that provide image and video recognition using APIs: Google Vision, Amazon Rekognition, Clarify... One of the main questions is, will my data be secure? As Google says in its Data Usage FAQs: When you send an image to Cloud Vision API, we must store that image for a short period of time in order to perform the analysis and return the results to you. The stored image is typically deleted in a few hours. Google also temporarily logs some metadata about your Vision API requests (such as the time the request was received and the size of the request) to improve our service and combat abuse. “tipically deleted”... what does tipically means? If data ownership and privacy are concerns for you, there is also the option to build your own image recognition pipeline leveraging existing technologies. There are also a bunch of alternatives in open-source: TensorFlow, Darknet, MLpack, Keras... Which allow you to better control where the image data ownership lays. In this tutorial, we will focus on building our own image classifier and object recognition bot, using Darnet. We will set up a Telegram bot written in Python hosted in Glitch to interface with the image classifier. The user flow will be the following: select a picture and send it to our Telegram bot. It will classify and perform object recognition over it, and send us the results. Easy right? Alright, let's get into it! In order to not repeat myself, I will recommend you to follow the step-by-step instructions given in the post below. Follow the first two steps, and modify the app name to your liking. Don't focus too much on the bot handles, as we will add a specific handle, later on, to act on received pictures. medium.com In order to analyze the images send to the bot, first we need to install and build Darknet. All the installation commands are available on the install.sh file in the Glitch project. To input the commands, in our Glitch project select Tools > Full Page Console. To install Darknet, navigate to .data directory within your Glitch app. This is crucial, as this directory will be persisted when your Glitch app goes to sleep! cd .datagit clone https://github.com/pjreddie/darknet.gitcd darknetmake It is important to mention that while you can train your own models (and should, depending on the use case), it is usually a quite computationally expensive operation. Considering that we will be running our bot from a Glitch instance with very limited power and space (1 CPU, 512 RAM, 200 MB storage), training the models is quite unfeasible. For our case, using pre-trained model weights is the best solution. We will use existing weights generated from previous trainings, allowing us to quickly get up to speed. We will download two weights files, darknet19.weights for the image classification, and yolov3-tiny.weights for the object recognition. # execute in the ./darkent directorywget https://pjreddie.com/media/files/darknet19.weightswget https://pjreddie.com/media/files/yolov3-tiny.weights Note that we have selected rather small weight files, due to the limitations of space and CPU power available in Glitch at the moment. Feel free to try out other weights (image classification, object detection) if you are running this in another more powerful environment. You will also get better results! Perfect, now that we have our bot skeleton ready, and Darknet installed, we can wire it up. I will not explain each line of code, for the full commented code you can head to the Glitch project. Below there is the code extract of the main handler (note that it uses helper functions). It is triggered every time a new picture is sent to the bot. @bot.message_handler(content_types=['photo'])def handle(message): # extract the image name for further operations image_name = save_image_from_message(message) # execute object recognition object_recognition_image(image_name) # send object recognition results bot.send_photo(message.chat.id, open('.data/darknet/predictions.jpg','rb'), 'Identified objects') # execute image classification classification_list_result = classify_image(image_name) # send classification results output = 'The image classifies as:\n' for result in classification_list_result: output += result output += '\n🚀 Gimme more pics! 🚀' bot.reply_to(message, output) # remove picture from server cleanup_remove_image(image_name); The full source code is available in: glitch.com Perfect, now that we are ready, let's do some testing! Our bot’s Telegram ID is: @wh_image_classificator_bot, feel free to test it out. The classification and recognition capabilities are limited by the technical restrictions in place, but the results are encouraging. On-demand image recognition APIs provide unparallel capabilities, but when privacy or offline processing is critical, custom image recognition pipelines are a great alternative. Note that our example only scratched the surface, and more accurate image recognition can be achieved with other training sets and approaches. Glitch project → https://glitch.com/~telegram-image-classfication-bot Darknet docs → https://pjreddie.com/darknet/ Other Weekend Hack posts:
[ { "code": null, "e": 267, "s": 47, "text": "The goal of this post is to build a Telegram bot with Python that performs image recognition using neural networks. The post is divided into three main sections: introduction, technology choices, and step-by-step setup." }, { "code": null, "e": 475, "s": 267, "text": "This post is the fourth instance of the Weekend Hack series, a series of short development stories about the exploration of new concepts. Focused on learning by doing, step-by-step instructions are provided." }, { "code": null, "e": 751, "s": 475, "text": "Automated image recognition (ex. object recognition and image classification) can provide immense value for businesses. If you run a forum, dating app, or any platform where users upload content, automating the recognition of images can be critical. The benefits are twofold:" }, { "code": null, "e": 1043, "s": 751, "text": "On the one hand, it provides value to the end-users, allowing them to perform searches over the images by classified topic while avoiding the tedious task of manual classification. A practical example of this is the Unsplash search functionality, which searches high-quality images by topic." }, { "code": null, "e": 1303, "s": 1043, "text": "On the other hand, automated image recognition also provides value to the system owners, as it allows to filter out images that contain nudity, for example. In short, it allows improving the quality of the provided services in an automated manner. Good right?" }, { "code": null, "e": 1649, "s": 1303, "text": "As we see, applications are endless, and benefits clear. The main question remains, which solution to choose for this task? Plenty of third party solutions exists, along with the possibility of building your own image recognition pipeline from open-source or proprietary software. On the next section, we will explore the different alternatives." }, { "code": null, "e": 1889, "s": 1649, "text": "As hinted above, there is a myriad of providers that provide image and video recognition using APIs: Google Vision, Amazon Rekognition, Clarify... One of the main questions is, will my data be secure? As Google says in its Data Usage FAQs:" }, { "code": null, "e": 2290, "s": 1889, "text": "When you send an image to Cloud Vision API, we must store that image for a short period of time in order to perform the analysis and return the results to you. The stored image is typically deleted in a few hours. Google also temporarily logs some metadata about your Vision API requests (such as the time the request was received and the size of the request) to improve our service and combat abuse." }, { "code": null, "e": 2340, "s": 2290, "text": "“tipically deleted”... what does tipically means?" }, { "code": null, "e": 2660, "s": 2340, "text": "If data ownership and privacy are concerns for you, there is also the option to build your own image recognition pipeline leveraging existing technologies. There are also a bunch of alternatives in open-source: TensorFlow, Darknet, MLpack, Keras... Which allow you to better control where the image data ownership lays." }, { "code": null, "e": 2876, "s": 2660, "text": "In this tutorial, we will focus on building our own image classifier and object recognition bot, using Darnet. We will set up a Telegram bot written in Python hosted in Glitch to interface with the image classifier." }, { "code": null, "e": 3057, "s": 2876, "text": "The user flow will be the following: select a picture and send it to our Telegram bot. It will classify and perform object recognition over it, and send us the results. Easy right?" }, { "code": null, "e": 3085, "s": 3057, "text": "Alright, let's get into it!" }, { "code": null, "e": 3384, "s": 3085, "text": "In order to not repeat myself, I will recommend you to follow the step-by-step instructions given in the post below. Follow the first two steps, and modify the app name to your liking. Don't focus too much on the bot handles, as we will add a specific handle, later on, to act on received pictures." }, { "code": null, "e": 3395, "s": 3384, "text": "medium.com" }, { "code": null, "e": 3577, "s": 3395, "text": "In order to analyze the images send to the bot, first we need to install and build Darknet. All the installation commands are available on the install.sh file in the Glitch project." }, { "code": null, "e": 3656, "s": 3577, "text": "To input the commands, in our Glitch project select Tools > Full Page Console." }, { "code": null, "e": 3817, "s": 3656, "text": "To install Darknet, navigate to .data directory within your Glitch app. This is crucial, as this directory will be persisted when your Glitch app goes to sleep!" }, { "code": null, "e": 3889, "s": 3817, "text": "cd .datagit clone https://github.com/pjreddie/darknet.gitcd darknetmake" }, { "code": null, "e": 4233, "s": 3889, "text": "It is important to mention that while you can train your own models (and should, depending on the use case), it is usually a quite computationally expensive operation. Considering that we will be running our bot from a Glitch instance with very limited power and space (1 CPU, 512 RAM, 200 MB storage), training the models is quite unfeasible." }, { "code": null, "e": 4541, "s": 4233, "text": "For our case, using pre-trained model weights is the best solution. We will use existing weights generated from previous trainings, allowing us to quickly get up to speed. We will download two weights files, darknet19.weights for the image classification, and yolov3-tiny.weights for the object recognition." }, { "code": null, "e": 4690, "s": 4541, "text": "# execute in the ./darkent directorywget https://pjreddie.com/media/files/darknet19.weightswget https://pjreddie.com/media/files/yolov3-tiny.weights" }, { "code": null, "e": 4997, "s": 4690, "text": "Note that we have selected rather small weight files, due to the limitations of space and CPU power available in Glitch at the moment. Feel free to try out other weights (image classification, object detection) if you are running this in another more powerful environment. You will also get better results!" }, { "code": null, "e": 5191, "s": 4997, "text": "Perfect, now that we have our bot skeleton ready, and Darknet installed, we can wire it up. I will not explain each line of code, for the full commented code you can head to the Glitch project." }, { "code": null, "e": 5342, "s": 5191, "text": "Below there is the code extract of the main handler (note that it uses helper functions). It is triggered every time a new picture is sent to the bot." }, { "code": null, "e": 6072, "s": 5342, "text": "@bot.message_handler(content_types=['photo'])def handle(message): # extract the image name for further operations image_name = save_image_from_message(message) # execute object recognition object_recognition_image(image_name) # send object recognition results bot.send_photo(message.chat.id, open('.data/darknet/predictions.jpg','rb'), 'Identified objects') # execute image classification classification_list_result = classify_image(image_name) # send classification results output = 'The image classifies as:\\n' for result in classification_list_result: output += result output += '\\n🚀 Gimme more pics! 🚀' bot.reply_to(message, output) # remove picture from server cleanup_remove_image(image_name);" }, { "code": null, "e": 6110, "s": 6072, "text": "The full source code is available in:" }, { "code": null, "e": 6121, "s": 6110, "text": "glitch.com" }, { "code": null, "e": 6176, "s": 6121, "text": "Perfect, now that we are ready, let's do some testing!" }, { "code": null, "e": 6390, "s": 6176, "text": "Our bot’s Telegram ID is: @wh_image_classificator_bot, feel free to test it out. The classification and recognition capabilities are limited by the technical restrictions in place, but the results are encouraging." }, { "code": null, "e": 6568, "s": 6390, "text": "On-demand image recognition APIs provide unparallel capabilities, but when privacy or offline processing is critical, custom image recognition pipelines are a great alternative." }, { "code": null, "e": 6711, "s": 6568, "text": "Note that our example only scratched the surface, and more accurate image recognition can be achieved with other training sets and approaches." }, { "code": null, "e": 6781, "s": 6711, "text": "Glitch project → https://glitch.com/~telegram-image-classfication-bot" }, { "code": null, "e": 6826, "s": 6781, "text": "Darknet docs → https://pjreddie.com/darknet/" } ]
E -Library Management System - GeeksforGeeks
15 Mar, 2021 In this article, we will discuss the approach to create an E-Library Management System where the user has the following options: Add book information. Display book information. To list all books of a given author. To list the count of books in the library. Functionalities Required: If the user tries to add a book then the user must have to provide the below specific Information about the book as:Enter Book Name:Enter Author Name:Enter Pages:Enter Price: Enter Book Name: Enter Author Name: Enter Pages: Enter Price: When the user tries to display all books of a particular author then the user must have to enter the name of the author:Enter the author name: Enter the author name: The E-Library management System must be also capable of counting all the books available in the library. Below is the program to implement the E-Library Management System: C // C program for the E-library// Management System#include <stdio.h>#include <stdlib.h>#include <string.h> // Create Structure of Librarystruct library { char book_name[20]; char author[20]; int pages; float price;}; // Driver Codeint main(){ // Create a instance struct library lib[100]; char ar_nm[30], bk_nm[30]; // Keep the track of the number of // of books available in the library int i, input, count; i = input = count = 0; // Iterate the loop while (input != 5) { printf("\n\n********######" "WELCOME TO E-LIBRARY " "#####********\n"); printf("\n\n1. Add book infor" "mation\n2. Display " "book information\n"); printf("3. List all books of " "given author\n"); printf( "4. List the count of book" "s in the library\n"); printf("5. Exit"); // Enter the book details printf("\n\nEnter one of " "the above: "); scanf("%d", &input); // Process the input switch (input) { // Add book case 1: printf("Enter book name = "); scanf("%s", lib[i].book_name); printf("Enter author name = "); scanf("%s", lib[i].author); printf("Enter pages = "); scanf("%d", &lib[i].pages); printf("Enter price = "); scanf("%f", &lib[i].price); count++; break; // Print book information case 2: printf("you have entered" " the following " "information\n"); for (i = 0; i < count; i++) { printf("book name = %s", lib[i].book_name); printf("\t author name = %s", lib[i].author); printf("\t pages = %d", lib[i].pages); printf("\t price = %f", lib[i].price); } break; // Take the author name as input case 3: printf("Enter author name : "); scanf("%s", ar_nm); for (i = 0; i < count; i++) { if (strcmp(ar_nm, lib[i].author) == 0) printf("%s %s %d %f", lib[i].book_name, lib[i].author, lib[i].pages, lib[i].price); } break; // Print total count case 4: printf("\n No of books in " "brary : %d", count); break; case 5: exit(0); } } return 0;} Output: Displaying the functoionalities and input for option 1: For Choice 2 and 3: For choice 4 and 5: Binary Tree Technical Scripter 2020 C Programs Project Recursion Technical Scripter Tree Recursion Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Header files in C/C++ and its uses C Program to read contents of Whole File Program to print ASCII Value of a character How to Append a Character to a String in C C program to sort an array in ascending order SDE SHEET - A Complete Guide for SDE Preparation Working with zip files in Python XML parsing in Python Python | Simple GUI calculator using Tkinter Implementing Web Scraping in Python with BeautifulSoup
[ { "code": null, "e": 26097, "s": 26069, "text": "\n15 Mar, 2021" }, { "code": null, "e": 26226, "s": 26097, "text": "In this article, we will discuss the approach to create an E-Library Management System where the user has the following options:" }, { "code": null, "e": 26248, "s": 26226, "text": "Add book information." }, { "code": null, "e": 26274, "s": 26248, "text": "Display book information." }, { "code": null, "e": 26311, "s": 26274, "text": "To list all books of a given author." }, { "code": null, "e": 26354, "s": 26311, "text": "To list the count of books in the library." }, { "code": null, "e": 26380, "s": 26354, "text": "Functionalities Required:" }, { "code": null, "e": 26555, "s": 26380, "text": "If the user tries to add a book then the user must have to provide the below specific Information about the book as:Enter Book Name:Enter Author Name:Enter Pages:Enter Price:" }, { "code": null, "e": 26572, "s": 26555, "text": "Enter Book Name:" }, { "code": null, "e": 26591, "s": 26572, "text": "Enter Author Name:" }, { "code": null, "e": 26604, "s": 26591, "text": "Enter Pages:" }, { "code": null, "e": 26617, "s": 26604, "text": "Enter Price:" }, { "code": null, "e": 26760, "s": 26617, "text": "When the user tries to display all books of a particular author then the user must have to enter the name of the author:Enter the author name:" }, { "code": null, "e": 26783, "s": 26760, "text": "Enter the author name:" }, { "code": null, "e": 26888, "s": 26783, "text": "The E-Library management System must be also capable of counting all the books available in the library." }, { "code": null, "e": 26955, "s": 26888, "text": "Below is the program to implement the E-Library Management System:" }, { "code": null, "e": 26957, "s": 26955, "text": "C" }, { "code": "// C program for the E-library// Management System#include <stdio.h>#include <stdlib.h>#include <string.h> // Create Structure of Librarystruct library { char book_name[20]; char author[20]; int pages; float price;}; // Driver Codeint main(){ // Create a instance struct library lib[100]; char ar_nm[30], bk_nm[30]; // Keep the track of the number of // of books available in the library int i, input, count; i = input = count = 0; // Iterate the loop while (input != 5) { printf(\"\\n\\n********######\" \"WELCOME TO E-LIBRARY \" \"#####********\\n\"); printf(\"\\n\\n1. Add book infor\" \"mation\\n2. Display \" \"book information\\n\"); printf(\"3. List all books of \" \"given author\\n\"); printf( \"4. List the count of book\" \"s in the library\\n\"); printf(\"5. Exit\"); // Enter the book details printf(\"\\n\\nEnter one of \" \"the above: \"); scanf(\"%d\", &input); // Process the input switch (input) { // Add book case 1: printf(\"Enter book name = \"); scanf(\"%s\", lib[i].book_name); printf(\"Enter author name = \"); scanf(\"%s\", lib[i].author); printf(\"Enter pages = \"); scanf(\"%d\", &lib[i].pages); printf(\"Enter price = \"); scanf(\"%f\", &lib[i].price); count++; break; // Print book information case 2: printf(\"you have entered\" \" the following \" \"information\\n\"); for (i = 0; i < count; i++) { printf(\"book name = %s\", lib[i].book_name); printf(\"\\t author name = %s\", lib[i].author); printf(\"\\t pages = %d\", lib[i].pages); printf(\"\\t price = %f\", lib[i].price); } break; // Take the author name as input case 3: printf(\"Enter author name : \"); scanf(\"%s\", ar_nm); for (i = 0; i < count; i++) { if (strcmp(ar_nm, lib[i].author) == 0) printf(\"%s %s %d %f\", lib[i].book_name, lib[i].author, lib[i].pages, lib[i].price); } break; // Print total count case 4: printf(\"\\n No of books in \" \"brary : %d\", count); break; case 5: exit(0); } } return 0;}", "e": 29757, "s": 26957, "text": null }, { "code": null, "e": 29765, "s": 29757, "text": "Output:" }, { "code": null, "e": 29821, "s": 29765, "text": "Displaying the functoionalities and input for option 1:" }, { "code": null, "e": 29841, "s": 29821, "text": "For Choice 2 and 3:" }, { "code": null, "e": 29861, "s": 29841, "text": "For choice 4 and 5:" }, { "code": null, "e": 29873, "s": 29861, "text": "Binary Tree" }, { "code": null, "e": 29897, "s": 29873, "text": "Technical Scripter 2020" }, { "code": null, "e": 29908, "s": 29897, "text": "C Programs" }, { "code": null, "e": 29916, "s": 29908, "text": "Project" }, { "code": null, "e": 29926, "s": 29916, "text": "Recursion" }, { "code": null, "e": 29945, "s": 29926, "text": "Technical Scripter" }, { "code": null, "e": 29950, "s": 29945, "text": "Tree" }, { "code": null, "e": 29960, "s": 29950, "text": "Recursion" }, { "code": null, "e": 29965, "s": 29960, "text": "Tree" }, { "code": null, "e": 30063, "s": 29965, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30098, "s": 30063, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 30139, "s": 30098, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 30183, "s": 30139, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 30226, "s": 30183, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 30272, "s": 30226, "text": "C program to sort an array in ascending order" }, { "code": null, "e": 30321, "s": 30272, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 30354, "s": 30321, "text": "Working with zip files in Python" }, { "code": null, "e": 30376, "s": 30354, "text": "XML parsing in Python" }, { "code": null, "e": 30421, "s": 30376, "text": "Python | Simple GUI calculator using Tkinter" } ]
Calculate the length of an associative array using JavaScript - GeeksforGeeks
12 Dec, 2021 Associative Array: In JavaScript, we have normal arrays in which an element is present at a particular index. Whereas Associative arrays are basically Objects in JavaScript where the index is replaced with user-defined keys. Basically, we can say that it stores Key-Value pairs. Syntax: let arr = { key1: 'value'1, key2: 'value2', key3: 'value3'} Here, arr is the associative array, and key1, key2, and key3 are its indexes, and value1, value2, and value3 are its elements. Example: let arr = {"apple": 10, "grapes": 20}; Javascript <script> let arr = { "apple": 10, "grapes": 20 }; arr["guava"] = 30; arr["banana"] = 40; document.writeln("Apple = " + arr.apple) document.write("Banana = " + arr.banana)</script> Output: Apple = 10 Banana = 40 Length of an associative array: Like in a normal array, an associative array does not have a length property. So we will see other ways to calculate the length of associative arrays. To calculate the length of an associative array, we will traverse the array element and count all the keys present in the array. Javascript <script> // Function to calculate the // length of an array sizeOfArray = function (array) { // A variable to store // the size of arrays let size = 0; // Traversing the array for (let key in array) { // Checking if key is present // in arrays or not if (array.hasOwnProperty(key)) { size++; } } // Return the size return size; } // Driver code let arr = { "apple": 10, "grapes": 20 }; arr["guava"] = 30; arr["banana"] = 40; // Printing the array console.log(arr); // Printing the size console.log("size = " + sizeOfArray(arr)); // Adding another element to array arr["fruits"] = 100; // Printing the array and size again console.log(arr); console.log("Size = " + sizeOfArray(arr));</script> Output: {apple: 10, grapes: 20, guava: 30, banana: 40} size = 4 {apple: 10, grapes: 20, guava: 30, banana: 40, fruits: 100} Size = 5 Using the keys method: The keys() method returns an array containing all the keys present in the associative array. So, we can use the length property on this array to get the length of associative array. Javascript <script> let arr = { "apple": 10, "grapes": 20 }; arr["guava"] = 30; arr["banana"] = 40; // Printing the array // returned by keys() method console.log(Object.keys(arr)) // printing the size console.log("Size = " + Object.keys(arr).length)</script> Output: ['apple', 'grapes', 'guava', 'banana'] Size = 4 simranarora5sos javascript-array JavaScript-Questions Picked 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": 26655, "s": 26627, "text": "\n12 Dec, 2021" }, { "code": null, "e": 26934, "s": 26655, "text": "Associative Array: In JavaScript, we have normal arrays in which an element is present at a particular index. Whereas Associative arrays are basically Objects in JavaScript where the index is replaced with user-defined keys. Basically, we can say that it stores Key-Value pairs." }, { "code": null, "e": 26942, "s": 26934, "text": "Syntax:" }, { "code": null, "e": 27002, "s": 26942, "text": "let arr = { key1: 'value'1, key2: 'value2', key3: 'value3'}" }, { "code": null, "e": 27129, "s": 27002, "text": "Here, arr is the associative array, and key1, key2, and key3 are its indexes, and value1, value2, and value3 are its elements." }, { "code": null, "e": 27138, "s": 27129, "text": "Example:" }, { "code": null, "e": 27177, "s": 27138, "text": "let arr = {\"apple\": 10, \"grapes\": 20};" }, { "code": null, "e": 27188, "s": 27177, "text": "Javascript" }, { "code": "<script> let arr = { \"apple\": 10, \"grapes\": 20 }; arr[\"guava\"] = 30; arr[\"banana\"] = 40; document.writeln(\"Apple = \" + arr.apple) document.write(\"Banana = \" + arr.banana)</script>", "e": 27400, "s": 27188, "text": null }, { "code": null, "e": 27410, "s": 27400, "text": " Output:" }, { "code": null, "e": 27433, "s": 27410, "text": "Apple = 10 Banana = 40" }, { "code": null, "e": 27616, "s": 27433, "text": "Length of an associative array: Like in a normal array, an associative array does not have a length property. So we will see other ways to calculate the length of associative arrays." }, { "code": null, "e": 27745, "s": 27616, "text": "To calculate the length of an associative array, we will traverse the array element and count all the keys present in the array." }, { "code": null, "e": 27756, "s": 27745, "text": "Javascript" }, { "code": "<script> // Function to calculate the // length of an array sizeOfArray = function (array) { // A variable to store // the size of arrays let size = 0; // Traversing the array for (let key in array) { // Checking if key is present // in arrays or not if (array.hasOwnProperty(key)) { size++; } } // Return the size return size; } // Driver code let arr = { \"apple\": 10, \"grapes\": 20 }; arr[\"guava\"] = 30; arr[\"banana\"] = 40; // Printing the array console.log(arr); // Printing the size console.log(\"size = \" + sizeOfArray(arr)); // Adding another element to array arr[\"fruits\"] = 100; // Printing the array and size again console.log(arr); console.log(\"Size = \" + sizeOfArray(arr));</script>", "e": 28624, "s": 27756, "text": null }, { "code": null, "e": 28632, "s": 28624, "text": "Output:" }, { "code": null, "e": 28757, "s": 28632, "text": "{apple: 10, grapes: 20, guava: 30, banana: 40}\nsize = 4\n{apple: 10, grapes: 20, guava: 30, banana: 40, fruits: 100}\nSize = 5" }, { "code": null, "e": 28963, "s": 28757, "text": "Using the keys method: The keys() method returns an array containing all the keys present in the associative array. So, we can use the length property on this array to get the length of associative array." }, { "code": null, "e": 28974, "s": 28963, "text": "Javascript" }, { "code": "<script> let arr = { \"apple\": 10, \"grapes\": 20 }; arr[\"guava\"] = 30; arr[\"banana\"] = 40; // Printing the array // returned by keys() method console.log(Object.keys(arr)) // printing the size console.log(\"Size = \" + Object.keys(arr).length)</script>", "e": 29249, "s": 28974, "text": null }, { "code": null, "e": 29257, "s": 29249, "text": "Output:" }, { "code": null, "e": 29305, "s": 29257, "text": "['apple', 'grapes', 'guava', 'banana']\nSize = 4" }, { "code": null, "e": 29321, "s": 29305, "text": "simranarora5sos" }, { "code": null, "e": 29338, "s": 29321, "text": "javascript-array" }, { "code": null, "e": 29359, "s": 29338, "text": "JavaScript-Questions" }, { "code": null, "e": 29366, "s": 29359, "text": "Picked" }, { "code": null, "e": 29377, "s": 29366, "text": "JavaScript" }, { "code": null, "e": 29394, "s": 29377, "text": "Web Technologies" }, { "code": null, "e": 29492, "s": 29394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29532, "s": 29492, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29593, "s": 29532, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29634, "s": 29593, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29656, "s": 29634, "text": "JavaScript | Promises" }, { "code": null, "e": 29710, "s": 29656, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29750, "s": 29710, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29783, "s": 29750, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29826, "s": 29783, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29876, "s": 29826, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Introduction to Vectors in R. Learn how to analyze your gambling... | by Linda Ngo | Towards Data Science
Let’s take a trip to a Statisticians Paradise, otherwise known as Vegas! Thanks to R and your new data analytical skills, you will learn how to uplift your performance at the tables and make some profits. After this tutorial, you will be able to easily track your betting progress and analyze your past action. Vectors are one-dimensional arrays that can store numeric data, character data, or logical data. They are a simple tool to store data. For example, you can store your daily gains and losses in the casinos. In R, you create a vector with the combine function c() . You place the vector elements separated by a comma between the parentheses. For example: numeric_vector <- c(1, 2, 3)character_vector <- c("a", "b", "c") Once you have created these vectors in R, you can use them to do calculations. Create a vector that contains the three elements: TRUE , FALSE , and TRUE (in that order) boolean_vector <- c(TRUE, FALSE, TRUE) After a week in Vegas, you still aren’t rolling in dough. So, you decide to start using your new data analysis skills. Before doing an analysis first, you decide to collect the outcomes for the last week: For Poker: On Monday you won $140. Tuesday you lost $50. Wednesday you won $20. Thursday you lost $120. Friday you won $240. For Roulette: On Monday you lost $24. Tuesday you lost $50. Wednesday you won $100. Thursday you lost $350. Friday you won $10. You only played poker and roulette. Assign the winnings/losses to variables. # Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)# Roulette winnings from Monday to Fridayroulette_vector <- c(-24, -50, 100, -350, 10) As a data analyst, it is important to have a clear view on the data being used. Thus, understanding what each element refers to is essential. In the previous exercise, we created a vector with your winnings over the week. Each vector element refers to a day of the week, but it is hard to tell which element belongs to which day. To show that in the vector itself by giving a name to the elements of a vector with the names() function. Here’s an example: some_vector <- c("John Doe", "poker player" This code first creates a vector some_vector and then gives the two elements a name. The first element is assigned the name Name , while the second element is labeled Profession . Printing the contents to the console yields the following output: Name the elements of your poker and roulette vector from the previous exercise with the days of the week. # Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)# Roulette winnings from Monday to Fridayroulette_vector <- c(-24, -50, 100, -350, 10)# Assign days as names of poker_vectornames(poker_vector) <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")# Assign days as names of roulette_vectornames(roulette_vector) <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") In the previous exercise, it may have been boring and frustrating to type and retype information such as the days of the week. There is a more efficient way to do this, namely, to assign the days of the week vector to a variable. Just like you did with the poker and roulette returns, you can also create a variable that contains the days of the week. This way, you can use and re-use it. Create a vector that contains the days of the week. Use this vector to set the names of your poker and roulette vectors. You will get the same output as you did from the previous exercise. # Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)# Roulette winnings from Monday to Fridayroulette_vector <- c(-24, -50, 100, -350, 10)# The variable days_vectordays_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")# Assign the names of the day to roulette_vector and poker_vectornames(poker_vector) <- days_vectornames(roulette_vector) <- days_vector Now that you have the poker and roulette returns names, you can starting some data analysis. You want to find out the following type of information: How much has been your overall profit or loss per day of the week? Have you lost money over the week in total? Are you winning/losing money on poker or on roulette? To get the answers, you have to do arithmetic calculations on vectors. If you sum two vectors in R, it takes the element-wise sum. For example, the following three statements are completely equivalent: c(1, 2, 3) + c(4, 5, 6)c(1 + 4, 2 + 5, 3 + 6)c(5, 7, 9) You can also do the calculations with variables that represent vectors: a <- c(1, 2, 3) b <- c(4, 5, 6)c <- a + b The overall daily profit is the sum of the profit/loss realized on poker per day, and the profit/loss realized on roulette per day. Assign to a variable how much you won/lost on each day in total (poker and roulette combined). # Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Assign to total_daily how much you won/lost on each daytotal_daily <- poker_vector + roulette_vector# Print the total won/lost per daytotal_daily Based on the previous analysis, it looks like you had a mix of good and bad days. Is there a change you may have lost money over the week in total? To answer this question, use the function sum() . It calculates the sum of all elements of a vector. For example, to calculate the total amount of money you have lost/won with poker: total_poker <- sum(poker_vector) Calculate the total amount of money you have won/lost with roulette. After you have the totals for roulette and poker, calculate the sum of all gains/losses of the week. # Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Total winnings with pokertotal_poker <- sum(poker_vector)# Total winnings with roulettetotal_roulette <- sum(roulette_vector)# Total winnings overalltotal_week <- total_poker + total_roulette# Print out total_weektotal_week It looks like you are losing money. You’ll need some deeper analysis to adapt your strategy. Is it possible that you are better in one game than the other? Maybe your total gains in poker are higher (or > ) than in roulette. Calculate the total gains in poker and roulette as in the previous exercise. Check if your total gains in poker are higher than for roulette by using a comparison. Print out the result of this comparison. # Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Calculate total gains for poker and roulettetotal_poker <- sum(poker_vector)# Check if you realized higher total gains in poker than in roulettetotal_poker > total_roulette It appears that you are better at poker than roulette. Let’s investigate your performance at the beginning of the working week compared to the end of it. You did have a couple of “vacation” drinks at the end of the week... To investigate this, you will only focus on a selection of the total_vector . In other words, our goal is to select specific elements of the vector. To select elements of the vector, you can use square brackets (the same is true for matrices, data frames, ...). Between the square brackets, indicate what element to select. For example, to select the first element of the vector, you use poker_vector[1] . To select the second element, use poker_vector[2] , and so on for the remaining elements. Notice that the first element has index 1, not 0 (as in many other programming languages). Let’s analyze your midweek results. To select multiple elements from a vector, indicate which elements should be selected using a vector within the square brackets. For example, to select the first and fifth day of the week, use the vector c(1,5) between the square brackets. poker_vector[c(1,5)] will give the first and fifth element of poker_vector . Another way to do this is the define the selection vector as a range. That is, c(2,3,4) can be abbreviated to 2:4 . We can then use poker_vector[2:4] to find the mid-week results. You can also select elements using the names of the vector elements (e.g. Monday, Tuesday,...) instead of their numeric positions. For example, poker_vector["Monday"] will select the element with the name "Monday" . This is the first element of poker_vector since "Monday" is the name of the first element. Assign the poker results of Wednesday to a variable. # Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Defined a new variable based on a selectionpoker_wednesday <- poker_vector[3] Assign the poker results of Tuesday, Wednesday, and Thursday to a variable. # Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Define a new variable based on a selection (Method 1)poker_midweek <- poker_vector[c(2,3,4)]# Method 2 - abbreviating the vector rangepoker_midweek <- poker_vector[2:4]# Method 3 - using the names of the elementspoker_midweek <- poker_vector[c("Tuesday", "Wednesday", "Thursday")] The (logical) comparison operators known to R are: < for less than > for greater than <= for less than or equal to >= for greater than or equal to == for equal to each other != for not equal to each other We can use these comparison operators on vectors. For example, > c(4, 5, 6) > 5[1] FALSE FALSE TRUE This command tests for every element of the vector if the condition stated by the comparison operators is TRUE or FALSE . In the example, this checks if each element of the vector is greater than 5. Check which elements in the poker vector are positive (i.e. >0) . # Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Which days did you make money on poker?selection_vector <- poker_vector > 0# Print out selection_vectorselection_vector Working with comparisons will make your data analysis easier. Instead of selecting a subset of days to investigate yourself (like before, where you selected between Tuesday, Wednesday, and Thursday), you can simply ask R to return only those days where you realized a positive return for poker. Using selection_vector <- poker_vector > 0 , you can find the days on which you had a positive poker return. Suppose you would like to know not only the days on which you won, but also how much you won on those days. You can select the desired elements, by putting selection_vector between the square brackets that follow poker_vector : poker_vector[selection_vector] R knows what to do when you pass a logical vector in square brackets: it will only select the elements that correspond to TRUE in selection_vector . Assign the amounts that you won on the profitable poker days to a variable. # Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Which days did you make money on poker?selection_vector <- poker_vector > 0# Select from poker_vector these dayspoker_winning_days <- poker_vector[selection_vector] Just like you did for poker, determine which days you realized a positive return for roulette. Create a variable that contains the positive winnings from roulette. # Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Which days did you make money on roulette?selection_vector <- roulette_vector > 0# Select from poker_vector these daysroulette_winning_days <- roulette_vector[selection_vector] All images, unless specified, are owned by the author. The banner image was created using Canva.
[ { "code": null, "e": 245, "s": 172, "text": "Let’s take a trip to a Statisticians Paradise, otherwise known as Vegas!" }, { "code": null, "e": 483, "s": 245, "text": "Thanks to R and your new data analytical skills, you will learn how to uplift your performance at the tables and make some profits. After this tutorial, you will be able to easily track your betting progress and analyze your past action." }, { "code": null, "e": 689, "s": 483, "text": "Vectors are one-dimensional arrays that can store numeric data, character data, or logical data. They are a simple tool to store data. For example, you can store your daily gains and losses in the casinos." }, { "code": null, "e": 836, "s": 689, "text": "In R, you create a vector with the combine function c() . You place the vector elements separated by a comma between the parentheses. For example:" }, { "code": null, "e": 901, "s": 836, "text": "numeric_vector <- c(1, 2, 3)character_vector <- c(\"a\", \"b\", \"c\")" }, { "code": null, "e": 980, "s": 901, "text": "Once you have created these vectors in R, you can use them to do calculations." }, { "code": null, "e": 1070, "s": 980, "text": "Create a vector that contains the three elements: TRUE , FALSE , and TRUE (in that order)" }, { "code": null, "e": 1109, "s": 1070, "text": "boolean_vector <- c(TRUE, FALSE, TRUE)" }, { "code": null, "e": 1228, "s": 1109, "text": "After a week in Vegas, you still aren’t rolling in dough. So, you decide to start using your new data analysis skills." }, { "code": null, "e": 1314, "s": 1228, "text": "Before doing an analysis first, you decide to collect the outcomes for the last week:" }, { "code": null, "e": 1325, "s": 1314, "text": "For Poker:" }, { "code": null, "e": 1349, "s": 1325, "text": "On Monday you won $140." }, { "code": null, "e": 1371, "s": 1349, "text": "Tuesday you lost $50." }, { "code": null, "e": 1394, "s": 1371, "text": "Wednesday you won $20." }, { "code": null, "e": 1418, "s": 1394, "text": "Thursday you lost $120." }, { "code": null, "e": 1439, "s": 1418, "text": "Friday you won $240." }, { "code": null, "e": 1453, "s": 1439, "text": "For Roulette:" }, { "code": null, "e": 1477, "s": 1453, "text": "On Monday you lost $24." }, { "code": null, "e": 1499, "s": 1477, "text": "Tuesday you lost $50." }, { "code": null, "e": 1523, "s": 1499, "text": "Wednesday you won $100." }, { "code": null, "e": 1547, "s": 1523, "text": "Thursday you lost $350." }, { "code": null, "e": 1567, "s": 1547, "text": "Friday you won $10." }, { "code": null, "e": 1644, "s": 1567, "text": "You only played poker and roulette. Assign the winnings/losses to variables." }, { "code": null, "e": 1811, "s": 1644, "text": "# Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)# Roulette winnings from Monday to Fridayroulette_vector <- c(-24, -50, 100, -350, 10)" }, { "code": null, "e": 1953, "s": 1811, "text": "As a data analyst, it is important to have a clear view on the data being used. Thus, understanding what each element refers to is essential." }, { "code": null, "e": 2141, "s": 1953, "text": "In the previous exercise, we created a vector with your winnings over the week. Each vector element refers to a day of the week, but it is hard to tell which element belongs to which day." }, { "code": null, "e": 2266, "s": 2141, "text": "To show that in the vector itself by giving a name to the elements of a vector with the names() function. Here’s an example:" }, { "code": null, "e": 2310, "s": 2266, "text": "some_vector <- c(\"John Doe\", \"poker player\"" }, { "code": null, "e": 2556, "s": 2310, "text": "This code first creates a vector some_vector and then gives the two elements a name. The first element is assigned the name Name , while the second element is labeled Profession . Printing the contents to the console yields the following output:" }, { "code": null, "e": 2662, "s": 2556, "text": "Name the elements of your poker and roulette vector from the previous exercise with the days of the week." }, { "code": null, "e": 3071, "s": 2662, "text": "# Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)# Roulette winnings from Monday to Fridayroulette_vector <- c(-24, -50, 100, -350, 10)# Assign days as names of poker_vectornames(poker_vector) <- c(\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\")# Assign days as names of roulette_vectornames(roulette_vector) <- c(\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\")" }, { "code": null, "e": 3301, "s": 3071, "text": "In the previous exercise, it may have been boring and frustrating to type and retype information such as the days of the week. There is a more efficient way to do this, namely, to assign the days of the week vector to a variable." }, { "code": null, "e": 3460, "s": 3301, "text": "Just like you did with the poker and roulette returns, you can also create a variable that contains the days of the week. This way, you can use and re-use it." }, { "code": null, "e": 3649, "s": 3460, "text": "Create a vector that contains the days of the week. Use this vector to set the names of your poker and roulette vectors. You will get the same output as you did from the previous exercise." }, { "code": null, "e": 4050, "s": 3649, "text": "# Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)# Roulette winnings from Monday to Fridayroulette_vector <- c(-24, -50, 100, -350, 10)# The variable days_vectordays_vector <- c(\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\")# Assign the names of the day to roulette_vector and poker_vectornames(poker_vector) <- days_vectornames(roulette_vector) <- days_vector" }, { "code": null, "e": 4143, "s": 4050, "text": "Now that you have the poker and roulette returns names, you can starting some data analysis." }, { "code": null, "e": 4199, "s": 4143, "text": "You want to find out the following type of information:" }, { "code": null, "e": 4266, "s": 4199, "text": "How much has been your overall profit or loss per day of the week?" }, { "code": null, "e": 4310, "s": 4266, "text": "Have you lost money over the week in total?" }, { "code": null, "e": 4364, "s": 4310, "text": "Are you winning/losing money on poker or on roulette?" }, { "code": null, "e": 4435, "s": 4364, "text": "To get the answers, you have to do arithmetic calculations on vectors." }, { "code": null, "e": 4566, "s": 4435, "text": "If you sum two vectors in R, it takes the element-wise sum. For example, the following three statements are completely equivalent:" }, { "code": null, "e": 4622, "s": 4566, "text": "c(1, 2, 3) + c(4, 5, 6)c(1 + 4, 2 + 5, 3 + 6)c(5, 7, 9)" }, { "code": null, "e": 4694, "s": 4622, "text": "You can also do the calculations with variables that represent vectors:" }, { "code": null, "e": 4736, "s": 4694, "text": "a <- c(1, 2, 3) b <- c(4, 5, 6)c <- a + b" }, { "code": null, "e": 4868, "s": 4736, "text": "The overall daily profit is the sum of the profit/loss realized on poker per day, and the profit/loss realized on roulette per day." }, { "code": null, "e": 4963, "s": 4868, "text": "Assign to a variable how much you won/lost on each day in total (poker and roulette combined)." }, { "code": null, "e": 5379, "s": 4963, "text": "# Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c(\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Assign to total_daily how much you won/lost on each daytotal_daily <- poker_vector + roulette_vector# Print the total won/lost per daytotal_daily" }, { "code": null, "e": 5527, "s": 5379, "text": "Based on the previous analysis, it looks like you had a mix of good and bad days. Is there a change you may have lost money over the week in total?" }, { "code": null, "e": 5710, "s": 5527, "text": "To answer this question, use the function sum() . It calculates the sum of all elements of a vector. For example, to calculate the total amount of money you have lost/won with poker:" }, { "code": null, "e": 5743, "s": 5710, "text": "total_poker <- sum(poker_vector)" }, { "code": null, "e": 5812, "s": 5743, "text": "Calculate the total amount of money you have won/lost with roulette." }, { "code": null, "e": 5913, "s": 5812, "text": "After you have the totals for roulette and poker, calculate the sum of all gains/losses of the week." }, { "code": null, "e": 6407, "s": 5913, "text": "# Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c(\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Total winnings with pokertotal_poker <- sum(poker_vector)# Total winnings with roulettetotal_roulette <- sum(roulette_vector)# Total winnings overalltotal_week <- total_poker + total_roulette# Print out total_weektotal_week" }, { "code": null, "e": 6500, "s": 6407, "text": "It looks like you are losing money. You’ll need some deeper analysis to adapt your strategy." }, { "code": null, "e": 6632, "s": 6500, "text": "Is it possible that you are better in one game than the other? Maybe your total gains in poker are higher (or > ) than in roulette." }, { "code": null, "e": 6837, "s": 6632, "text": "Calculate the total gains in poker and roulette as in the previous exercise. Check if your total gains in poker are higher than for roulette by using a comparison. Print out the result of this comparison." }, { "code": null, "e": 7280, "s": 6837, "text": "# Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c(\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Calculate total gains for poker and roulettetotal_poker <- sum(poker_vector)# Check if you realized higher total gains in poker than in roulettetotal_poker > total_roulette" }, { "code": null, "e": 7335, "s": 7280, "text": "It appears that you are better at poker than roulette." }, { "code": null, "e": 7503, "s": 7335, "text": "Let’s investigate your performance at the beginning of the working week compared to the end of it. You did have a couple of “vacation” drinks at the end of the week..." }, { "code": null, "e": 8090, "s": 7503, "text": "To investigate this, you will only focus on a selection of the total_vector . In other words, our goal is to select specific elements of the vector. To select elements of the vector, you can use square brackets (the same is true for matrices, data frames, ...). Between the square brackets, indicate what element to select. For example, to select the first element of the vector, you use poker_vector[1] . To select the second element, use poker_vector[2] , and so on for the remaining elements. Notice that the first element has index 1, not 0 (as in many other programming languages)." }, { "code": null, "e": 8126, "s": 8090, "text": "Let’s analyze your midweek results." }, { "code": null, "e": 8443, "s": 8126, "text": "To select multiple elements from a vector, indicate which elements should be selected using a vector within the square brackets. For example, to select the first and fifth day of the week, use the vector c(1,5) between the square brackets. poker_vector[c(1,5)] will give the first and fifth element of poker_vector ." }, { "code": null, "e": 8623, "s": 8443, "text": "Another way to do this is the define the selection vector as a range. That is, c(2,3,4) can be abbreviated to 2:4 . We can then use poker_vector[2:4] to find the mid-week results." }, { "code": null, "e": 8930, "s": 8623, "text": "You can also select elements using the names of the vector elements (e.g. Monday, Tuesday,...) instead of their numeric positions. For example, poker_vector[\"Monday\"] will select the element with the name \"Monday\" . This is the first element of poker_vector since \"Monday\" is the name of the first element." }, { "code": null, "e": 8983, "s": 8930, "text": "Assign the poker results of Wednesday to a variable." }, { "code": null, "e": 9331, "s": 8983, "text": "# Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c(\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Defined a new variable based on a selectionpoker_wednesday <- poker_vector[3]" }, { "code": null, "e": 9407, "s": 9331, "text": "Assign the poker results of Tuesday, Wednesday, and Thursday to a variable." }, { "code": null, "e": 9958, "s": 9407, "text": "# Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c(\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Define a new variable based on a selection (Method 1)poker_midweek <- poker_vector[c(2,3,4)]# Method 2 - abbreviating the vector rangepoker_midweek <- poker_vector[2:4]# Method 3 - using the names of the elementspoker_midweek <- poker_vector[c(\"Tuesday\", \"Wednesday\", \"Thursday\")]" }, { "code": null, "e": 10009, "s": 9958, "text": "The (logical) comparison operators known to R are:" }, { "code": null, "e": 10025, "s": 10009, "text": "< for less than" }, { "code": null, "e": 10044, "s": 10025, "text": "> for greater than" }, { "code": null, "e": 10073, "s": 10044, "text": "<= for less than or equal to" }, { "code": null, "e": 10105, "s": 10073, "text": ">= for greater than or equal to" }, { "code": null, "e": 10132, "s": 10105, "text": "== for equal to each other" }, { "code": null, "e": 10163, "s": 10132, "text": "!= for not equal to each other" }, { "code": null, "e": 10226, "s": 10163, "text": "We can use these comparison operators on vectors. For example," }, { "code": null, "e": 10263, "s": 10226, "text": "> c(4, 5, 6) > 5[1] FALSE FALSE TRUE" }, { "code": null, "e": 10462, "s": 10263, "text": "This command tests for every element of the vector if the condition stated by the comparison operators is TRUE or FALSE . In the example, this checks if each element of the vector is greater than 5." }, { "code": null, "e": 10528, "s": 10462, "text": "Check which elements in the poker vector are positive (i.e. >0) ." }, { "code": null, "e": 10918, "s": 10528, "text": "# Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c(\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Which days did you make money on poker?selection_vector <- poker_vector > 0# Print out selection_vectorselection_vector" }, { "code": null, "e": 11213, "s": 10918, "text": "Working with comparisons will make your data analysis easier. Instead of selecting a subset of days to investigate yourself (like before, where you selected between Tuesday, Wednesday, and Thursday), you can simply ask R to return only those days where you realized a positive return for poker." }, { "code": null, "e": 11430, "s": 11213, "text": "Using selection_vector <- poker_vector > 0 , you can find the days on which you had a positive poker return. Suppose you would like to know not only the days on which you won, but also how much you won on those days." }, { "code": null, "e": 11550, "s": 11430, "text": "You can select the desired elements, by putting selection_vector between the square brackets that follow poker_vector :" }, { "code": null, "e": 11581, "s": 11550, "text": "poker_vector[selection_vector]" }, { "code": null, "e": 11730, "s": 11581, "text": "R knows what to do when you pass a logical vector in square brackets: it will only select the elements that correspond to TRUE in selection_vector ." }, { "code": null, "e": 11806, "s": 11730, "text": "Assign the amounts that you won on the profitable poker days to a variable." }, { "code": null, "e": 12241, "s": 11806, "text": "# Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c(\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Which days did you make money on poker?selection_vector <- poker_vector > 0# Select from poker_vector these dayspoker_winning_days <- poker_vector[selection_vector]" }, { "code": null, "e": 12405, "s": 12241, "text": "Just like you did for poker, determine which days you realized a positive return for roulette. Create a variable that contains the positive winnings from roulette." }, { "code": null, "e": 12852, "s": 12405, "text": "# Poker winnings from Monday to Fridaypoker_vector <- c(140, -50, 20, -120, 240)roulette_vector <- c(-24, -50, 100, -350, 10)days_vector <- c(\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\")names(poker_vector) <- days_vectornames(roulette_vector) <- days_vector# Which days did you make money on roulette?selection_vector <- roulette_vector > 0# Select from poker_vector these daysroulette_winning_days <- roulette_vector[selection_vector]" } ]
Find maximum difference between nearest left and right smaller elements in Python
Suppose we have an array of integers; we have to find the maximum absolute difference between the nearest left and the right smaller element of each of the elements in the array. If there is no smaller element on the right-hand side or left-hand side of any element then we will put zero as the smaller element. So, if the input is like A = [3, 5, 9, 8, 8, 10, 4], then the output will be 4 as left elements L = [0, 3, 5, 5, 5, 8, 3], right elements R = [0, 4, 8, 4, 4, 4, 0], maximum absolute difference L[i] - R[i] = 8 - 4 = 4. To solve this, we will follow these steps − Define a function left_small_element() . This will take A, temp Define a function left_small_element() . This will take A, temp n := size of A n := size of A stack := a new list stack := a new list for i in range 0 to n, dowhile stack is not empty and top element of stack >= A[i], dodelete last element from stackif stack is not empty, thentemp[i]:= top element of stackotherwise,temp[i]:= 0insert A[i] at the end of stack for i in range 0 to n, do while stack is not empty and top element of stack >= A[i], dodelete last element from stack while stack is not empty and top element of stack >= A[i], do delete last element from stack delete last element from stack if stack is not empty, thentemp[i]:= top element of stack if stack is not empty, then temp[i]:= top element of stack temp[i]:= top element of stack otherwise,temp[i]:= 0 otherwise, temp[i]:= 0 temp[i]:= 0 insert A[i] at the end of stack insert A[i] at the end of stack From the main method, do the following − From the main method, do the following − n := size of A n := size of A left:= a list of size n and fill with 0 left:= a list of size n and fill with 0 right:= a list of size n and fill with 0 right:= a list of size n and fill with 0 left_small_element(A, left) left_small_element(A, left) left_small_element(reversed A, right) left_small_element(reversed A, right) res := -1 res := -1 for i in range 0 to n, dores := maximum of res, |left[i] - right[n-1-i]| for i in range 0 to n, do res := maximum of res, |left[i] - right[n-1-i]| res := maximum of res, |left[i] - right[n-1-i]| Let us see the following implementation to get better understanding − Live Demo def left_small_element(A, temp): n = len(A) stack = [] for i in range(n): while(stack != [] and stack[len(stack)-1] >= A[i]): stack.pop() if(stack != []): temp[i]=stack[len(stack)-1] else: temp[i]=0 stack.append(A[i]) def find_maximum_difference(A): n = len(A) left=[0]*n right=[0]*n left_small_element(A, left) left_small_element(A[::-1], right) res = -1 for i in range(n): res = max(res, abs(left[i] - right[n-1-i])) return res A = [3, 5, 9, 8, 8, 10, 4] print(find_maximum_difference(A)) [3, 5, 9, 8, 8, 10, 4] 4
[ { "code": null, "e": 1374, "s": 1062, "text": "Suppose we have an array of integers; we have to find the maximum absolute difference between the nearest left and the right smaller element of each of the elements in the array. If there is no smaller element on the right-hand side or left-hand side of any element then we will put zero as the smaller element." }, { "code": null, "e": 1592, "s": 1374, "text": "So, if the input is like A = [3, 5, 9, 8, 8, 10, 4], then the output will be 4 as left elements L = [0, 3, 5, 5, 5, 8, 3], right elements R = [0, 4, 8, 4, 4, 4, 0], maximum absolute difference L[i] - R[i] = 8 - 4 = 4." }, { "code": null, "e": 1636, "s": 1592, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1700, "s": 1636, "text": "Define a function left_small_element() . This will take A, temp" }, { "code": null, "e": 1764, "s": 1700, "text": "Define a function left_small_element() . This will take A, temp" }, { "code": null, "e": 1779, "s": 1764, "text": "n := size of A" }, { "code": null, "e": 1794, "s": 1779, "text": "n := size of A" }, { "code": null, "e": 1814, "s": 1794, "text": "stack := a new list" }, { "code": null, "e": 1834, "s": 1814, "text": "stack := a new list" }, { "code": null, "e": 2060, "s": 1834, "text": "for i in range 0 to n, dowhile stack is not empty and top element of stack >= A[i], dodelete last element from stackif stack is not empty, thentemp[i]:= top element of stackotherwise,temp[i]:= 0insert A[i] at the end of stack" }, { "code": null, "e": 2086, "s": 2060, "text": "for i in range 0 to n, do" }, { "code": null, "e": 2178, "s": 2086, "text": "while stack is not empty and top element of stack >= A[i], dodelete last element from stack" }, { "code": null, "e": 2240, "s": 2178, "text": "while stack is not empty and top element of stack >= A[i], do" }, { "code": null, "e": 2271, "s": 2240, "text": "delete last element from stack" }, { "code": null, "e": 2302, "s": 2271, "text": "delete last element from stack" }, { "code": null, "e": 2360, "s": 2302, "text": "if stack is not empty, thentemp[i]:= top element of stack" }, { "code": null, "e": 2388, "s": 2360, "text": "if stack is not empty, then" }, { "code": null, "e": 2419, "s": 2388, "text": "temp[i]:= top element of stack" }, { "code": null, "e": 2450, "s": 2419, "text": "temp[i]:= top element of stack" }, { "code": null, "e": 2472, "s": 2450, "text": "otherwise,temp[i]:= 0" }, { "code": null, "e": 2483, "s": 2472, "text": "otherwise," }, { "code": null, "e": 2495, "s": 2483, "text": "temp[i]:= 0" }, { "code": null, "e": 2507, "s": 2495, "text": "temp[i]:= 0" }, { "code": null, "e": 2539, "s": 2507, "text": "insert A[i] at the end of stack" }, { "code": null, "e": 2571, "s": 2539, "text": "insert A[i] at the end of stack" }, { "code": null, "e": 2612, "s": 2571, "text": "From the main method, do the following −" }, { "code": null, "e": 2653, "s": 2612, "text": "From the main method, do the following −" }, { "code": null, "e": 2668, "s": 2653, "text": "n := size of A" }, { "code": null, "e": 2683, "s": 2668, "text": "n := size of A" }, { "code": null, "e": 2723, "s": 2683, "text": "left:= a list of size n and fill with 0" }, { "code": null, "e": 2763, "s": 2723, "text": "left:= a list of size n and fill with 0" }, { "code": null, "e": 2804, "s": 2763, "text": "right:= a list of size n and fill with 0" }, { "code": null, "e": 2845, "s": 2804, "text": "right:= a list of size n and fill with 0" }, { "code": null, "e": 2873, "s": 2845, "text": "left_small_element(A, left)" }, { "code": null, "e": 2901, "s": 2873, "text": "left_small_element(A, left)" }, { "code": null, "e": 2939, "s": 2901, "text": "left_small_element(reversed A, right)" }, { "code": null, "e": 2977, "s": 2939, "text": "left_small_element(reversed A, right)" }, { "code": null, "e": 2987, "s": 2977, "text": "res := -1" }, { "code": null, "e": 2997, "s": 2987, "text": "res := -1" }, { "code": null, "e": 3070, "s": 2997, "text": "for i in range 0 to n, dores := maximum of res, |left[i] - right[n-1-i]|" }, { "code": null, "e": 3096, "s": 3070, "text": "for i in range 0 to n, do" }, { "code": null, "e": 3144, "s": 3096, "text": "res := maximum of res, |left[i] - right[n-1-i]|" }, { "code": null, "e": 3192, "s": 3144, "text": "res := maximum of res, |left[i] - right[n-1-i]|" }, { "code": null, "e": 3262, "s": 3192, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3273, "s": 3262, "text": " Live Demo" }, { "code": null, "e": 3854, "s": 3273, "text": "def left_small_element(A, temp):\n n = len(A)\n stack = []\n for i in range(n):\n while(stack != [] and stack[len(stack)-1] >= A[i]):\n stack.pop()\n if(stack != []):\n temp[i]=stack[len(stack)-1]\n else:\n temp[i]=0\n stack.append(A[i])\ndef find_maximum_difference(A):\n n = len(A)\n left=[0]*n\n right=[0]*n\n left_small_element(A, left)\n left_small_element(A[::-1], right)\n res = -1\n for i in range(n):\n res = max(res, abs(left[i] - right[n-1-i]))\n return res\nA = [3, 5, 9, 8, 8, 10, 4]\nprint(find_maximum_difference(A))" }, { "code": null, "e": 3877, "s": 3854, "text": "[3, 5, 9, 8, 8, 10, 4]" }, { "code": null, "e": 3879, "s": 3877, "text": "4" } ]
JSTL - Core <c:param> Tag
The <c:param> tag allows proper URL request parameter to be specified with URL and also does the necessary URL encoding required. Within a <c:param> tag, the name attribute indicates the parameter name, and the value attribute indicates the parameter value − The <c:param> tag has the following attributes − If you need to pass parameters to a <c:import> tag, use the <c:url> tag to create the URL first as shown below − <c:url value = "/index.jsp" var = "myURL"> <c:param name = "trackingId" value = "1234"/> <c:param name = "reportType" value = "summary"/> </c:url> <c:import url = "${myURL}"/> The above request will pass the URL as below - Try it yourself. "/index.jsp?trackingId=1234;reportType=summary" 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2369, "s": 2239, "text": "The <c:param> tag allows proper URL request parameter to be specified with URL and also does the necessary URL encoding required." }, { "code": null, "e": 2498, "s": 2369, "text": "Within a <c:param> tag, the name attribute indicates the parameter name, and the value attribute indicates the parameter value −" }, { "code": null, "e": 2547, "s": 2498, "text": "The <c:param> tag has the following attributes −" }, { "code": null, "e": 2660, "s": 2547, "text": "If you need to pass parameters to a <c:import> tag, use the <c:url> tag to create the URL first as shown below −" }, { "code": null, "e": 2842, "s": 2660, "text": "<c:url value = \"/index.jsp\" var = \"myURL\">\n <c:param name = \"trackingId\" value = \"1234\"/>\n <c:param name = \"reportType\" value = \"summary\"/>\n</c:url>\n<c:import url = \"${myURL}\"/>" }, { "code": null, "e": 2906, "s": 2842, "text": "The above request will pass the URL as below - Try it yourself." }, { "code": null, "e": 2955, "s": 2906, "text": "\"/index.jsp?trackingId=1234;reportType=summary\"\n" }, { "code": null, "e": 2990, "s": 2955, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 3005, "s": 2990, "text": " Chaand Sheikh" }, { "code": null, "e": 3040, "s": 3005, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 3055, "s": 3040, "text": " Chaand Sheikh" }, { "code": null, "e": 3090, "s": 3055, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3104, "s": 3090, "text": " Karthikeya T" }, { "code": null, "e": 3139, "s": 3104, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3155, "s": 3139, "text": " TELCOMA Global" }, { "code": null, "e": 3188, "s": 3155, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 3204, "s": 3188, "text": " TELCOMA Global" }, { "code": null, "e": 3238, "s": 3204, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 3246, "s": 3238, "text": " Uplatz" }, { "code": null, "e": 3253, "s": 3246, "text": " Print" }, { "code": null, "e": 3264, "s": 3253, "text": " Add Notes" } ]
Difference between process.cwd() and __dirname in Node.js - GeeksforGeeks
23 Feb, 2021 NodeJS is a JavaScript runtime that was built on top of Chrome’s V8 Engine. The traditional JavaScript is executed in browsers but with Node.js we can execute JavaScript on servers, hardware devices, etc. process.cwd(): Similar to window objects on browsers, Node.js has got a global object called global, and the process object lies inside the global object. This process object provides information about, and control over, the current Node.js process. It gives the current working directory of the Node.js process. __dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file. Difference between process.cwd() vs __dirname in Node.js is as follows: Example 1: index.js // Logging process.cwd() outputconsole.log("process.cwd(): ", process.cwd()); // Logging __dirname outputconsole.log("__dirname: ", __dirname); Run the index.js file using the following command: node index.js Output: process.cwd(): C:\src __dirname: C:\src In this case node process is running in the current directory Example 2: Create the following 2 files with the following folder structure: src/ ___ index.js ___ src2/ ___index2.js FilePath: src/index.js index.js // Read and execute the index2.js file require('./sub1/index2.js') FilePath: src/src2/index2.js index2.js // Logging process.cwd() outputconsole.log("process.cwd(): ", process.cwd()); // Logging __dirname outputconsole.log("__dirname: ", __dirname); Run the index.js file using the following command: node index2.js Output: process cwd: C:\src __dirname: C:\src\src2 This shows that the current node process was running in src/ folder i.e node index.js and the directory of the file index2.js was at src/src2. Node.js-process-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Express.js express.Router() Function JWT Authentication with Node.js Express.js req.params Property Mongoose Populate() Method How to build a basic CRUD app with Node.js and ReactJS ? Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Convert a string to an integer in JavaScript
[ { "code": null, "e": 25002, "s": 24974, "text": "\n23 Feb, 2021" }, { "code": null, "e": 25207, "s": 25002, "text": "NodeJS is a JavaScript runtime that was built on top of Chrome’s V8 Engine. The traditional JavaScript is executed in browsers but with Node.js we can execute JavaScript on servers, hardware devices, etc." }, { "code": null, "e": 25520, "s": 25207, "text": "process.cwd(): Similar to window objects on browsers, Node.js has got a global object called global, and the process object lies inside the global object. This process object provides information about, and control over, the current Node.js process. It gives the current working directory of the Node.js process." }, { "code": null, "e": 25668, "s": 25520, "text": "__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file." }, { "code": null, "e": 25740, "s": 25668, "text": "Difference between process.cwd() vs __dirname in Node.js is as follows:" }, { "code": null, "e": 25751, "s": 25740, "text": "Example 1:" }, { "code": null, "e": 25760, "s": 25751, "text": "index.js" }, { "code": "// Logging process.cwd() outputconsole.log(\"process.cwd(): \", process.cwd()); // Logging __dirname outputconsole.log(\"__dirname: \", __dirname);", "e": 25905, "s": 25760, "text": null }, { "code": null, "e": 25956, "s": 25905, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 25970, "s": 25956, "text": "node index.js" }, { "code": null, "e": 25978, "s": 25970, "text": "Output:" }, { "code": null, "e": 26018, "s": 25978, "text": "process.cwd(): C:\\src\n__dirname: C:\\src" }, { "code": null, "e": 26080, "s": 26018, "text": "In this case node process is running in the current directory" }, { "code": null, "e": 26157, "s": 26080, "text": "Example 2: Create the following 2 files with the following folder structure:" }, { "code": null, "e": 26202, "s": 26157, "text": "src/\n___ index.js\n___ src2/\n ___index2.js" }, { "code": null, "e": 26225, "s": 26202, "text": "FilePath: src/index.js" }, { "code": null, "e": 26234, "s": 26225, "text": "index.js" }, { "code": "// Read and execute the index2.js file require('./sub1/index2.js')", "e": 26301, "s": 26234, "text": null }, { "code": null, "e": 26330, "s": 26301, "text": "FilePath: src/src2/index2.js" }, { "code": null, "e": 26340, "s": 26330, "text": "index2.js" }, { "code": "// Logging process.cwd() outputconsole.log(\"process.cwd(): \", process.cwd()); // Logging __dirname outputconsole.log(\"__dirname: \", __dirname);", "e": 26485, "s": 26340, "text": null }, { "code": null, "e": 26536, "s": 26485, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 26551, "s": 26536, "text": "node index2.js" }, { "code": null, "e": 26559, "s": 26551, "text": "Output:" }, { "code": null, "e": 26604, "s": 26559, "text": "process cwd: C:\\src\n__dirname: C:\\src\\src2" }, { "code": null, "e": 26747, "s": 26604, "text": "This shows that the current node process was running in src/ folder i.e node index.js and the directory of the file index2.js was at src/src2." }, { "code": null, "e": 26770, "s": 26747, "text": "Node.js-process-module" }, { "code": null, "e": 26777, "s": 26770, "text": "Picked" }, { "code": null, "e": 26785, "s": 26777, "text": "Node.js" }, { "code": null, "e": 26802, "s": 26785, "text": "Web Technologies" }, { "code": null, "e": 26900, "s": 26802, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26937, "s": 26900, "text": "Express.js express.Router() Function" }, { "code": null, "e": 26969, "s": 26937, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 27000, "s": 26969, "text": "Express.js req.params Property" }, { "code": null, "e": 27027, "s": 27000, "text": "Mongoose Populate() Method" }, { "code": null, "e": 27084, "s": 27027, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 27126, "s": 27084, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27169, "s": 27126, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27231, "s": 27169, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27281, "s": 27231, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Dockerize Your Dash App. Get Dash Ready for Simple, Modern... | by Edward Krueger | Towards Data Science
By Edward Krueger and Erin Oefelein This article will look at how to Dockerize a Dash app that we have already built. It's important to understand the app's structure, so please look at the repository here. If you'd like some more details and explanation, have a look at our article detailing the structure here: towardsdatascience.com Now that you've structured your Dash app according to our first article, you are all set up to Dockerize your app. Docker is a platform that provides containers. Like a virtual machine (VM), a Docker container is a packaged computing environment that combines various software components in isolation from the rest of a system. The main difference between the two pertains to scale and portability. Containers are more lightweight than VMs, and container images are measured in megabytes rather than in gigabytes. Docker containers solve a pain point seen with software for decades. Managing software across different platforms is time-consuming because each requires application dependencies, interpreters, binaries, etc. Docker provides consistency across platforms, simplifying software maintenance and deployment. It's no wonder platforms like Google, Azure, AWS, and others use Docker to simplify app deployment for all users and all their different operating systems. Here, you'll learn how to take advantage of a technology that has revolutionized deployment! To Dockerize your app, you'll first need to have Docker installed. Install Docker is simple for Mac users but a little more complex for Windows users. Windows machines cannot run Docker without installing Windows System for Linux (WSL2) and running Docker from within this service. We've linked a guide for those wishing to use this option here. Once installed, you'll need to initialize Docker on your machine. Docker commands will not work unless the service is running in the background. A Dockerfile is a set of commands that tells Docker how to build your container. It includes information about what base image your Docker container should extend, any additional installation or configuration steps needed, and instructions on running your application. We've provided our Dockerfile below so you can easily create your Dockerfile with the correct specifications: FROM python:3.9-slimCOPY requirements.txt ./requirements.txtRUN pip install -r requirements.txtCOPY . ./CMD gunicorn -b 0.0.0.0:80 app.app:server One thing that may seem confusing about this Dockerfile is that it copies files in two stages. We do this because Docker builds containers in layers where, roughly speaking, each line corresponds to a layer. The first time the build runs, it caches every layer. If a layer doesn't need to be changed, we can use Docker's cached layers to make builds faster. Let's have a closer look at the behavior. In the first COPY command, we copy only the requirements.txt file into the container. Now for theRUN line. In a build, if requirements.txthas not been changed, then the next layer, the installation, can be skipped. If it is cached, Docker will not rerun this layer, so the Python dependencies will not need to be reinstalled. In the second COPY line, we then copy the rest of the application's file into the container. Some of the application code will likely have changed since the last build, which means that cache for later layers is out of data. Still, since the earlier layers have already been built or retrieved from that cache, this line doesn't trigger the other dependencies to reinstall. If we copied all of our code and dependencies at one, then changing the code would invalidate the cache, and the dependencies would be reinstalled even if the requirements didn't change. For a deep dive into optimizing containers, check out this article by Sciforce. medium.com To initiate your Docker container build, run: docker build -t tiny_home . The -t flag "tags" our image and allows us to name the container. Tags are helpful because it allows us to refer to our container with a more human-readable name rather than machine speak. Here, we've named our container tiny_home. This command uses our Dockerfile to build a new container image. As Docker processes our Dockerfile, it starts with the base Python container containing the Docker Python image. There are many types of Docker base images. We are using the slim version of the Python image, which is optimal when you wish to install the minimal packages necessary to run Python. The -slim suffix denotes that the container should only contain the essentials. For many base images, there are both a slim and a full version. Less included with slim than with the full version, so the image is smaller and is ideal when dealing with space constraints. For most languages, there is also a maintained full version of the image. A full image is usually the best choice if you're unsure of which type to use with your application. Should you wish to read more on the topic, have a look at this article by Julie Perilla Garcia! medium.com Images usually include many layers. Layers may include system libraries, tools, dependencies and other files. In our case, the Python slim image starts by accessing the existing Python slim container from DockerHub. After the image has been downloaded locally, the most current stable release of the Debian/Linux OS distribution and Python are installed. Finally, Docker compies all application files and install the application requirements. In our setup, we generate requirements.txt and requirements-dev.txt from our Pipfile by running pipenv-to-requirements in a pre-commit hook. Since we only reference requirements.txtDocker never sees the development. Using only the dependencies necessary to run the app in our container speeds up the build process, decreases the container's size, and potentially improves security. If you haven't done so, please refer to our first article and run these hooks. It will make this process so much easier! Once you build your Docker container, you can view it by running: docker image ls And then you'll see the tiny_home image populate here: As we've successfully built our docker container, the app will run through gunicorn on port 80. To visit the address at which our app is running, we'll need to map the port from where it's running on Docker's host at port 80 to a port on our localhost. Here, we will map our app to port 8080. To do a port mapping and run our app simultaneously, run: docker run -p 8080:80 tiny_home When you visit http://localhost:8080/ (or 0.0.0.0:8080 depending on your operating system), you should see your app running within your Docker container! For those unaware, localhost is an alias for 127.0.0.1, while 0.0.0.0 references all local IP addresses. If you get an error indicating that "Bind for 0.0.0.0:8080 failed: port is already allocated", you can follow this stack overflow conversation and the provided solution to kill whatever process is using port 8080. Your app is now Dockerized! Stay tuned for our next article on deploying your app to GCP's Cloud Run service! We hope you've enjoyed this article! For more content on data science, machine learning, and development, check out Edward's YouTube Channel and subscribe to my mailing list below to be the first to hear about new articles!
[ { "code": null, "e": 208, "s": 172, "text": "By Edward Krueger and Erin Oefelein" }, { "code": null, "e": 485, "s": 208, "text": "This article will look at how to Dockerize a Dash app that we have already built. It's important to understand the app's structure, so please look at the repository here. If you'd like some more details and explanation, have a look at our article detailing the structure here:" }, { "code": null, "e": 508, "s": 485, "text": "towardsdatascience.com" }, { "code": null, "e": 623, "s": 508, "text": "Now that you've structured your Dash app according to our first article, you are all set up to Dockerize your app." }, { "code": null, "e": 1022, "s": 623, "text": "Docker is a platform that provides containers. Like a virtual machine (VM), a Docker container is a packaged computing environment that combines various software components in isolation from the rest of a system. The main difference between the two pertains to scale and portability. Containers are more lightweight than VMs, and container images are measured in megabytes rather than in gigabytes." }, { "code": null, "e": 1326, "s": 1022, "text": "Docker containers solve a pain point seen with software for decades. Managing software across different platforms is time-consuming because each requires application dependencies, interpreters, binaries, etc. Docker provides consistency across platforms, simplifying software maintenance and deployment." }, { "code": null, "e": 1575, "s": 1326, "text": "It's no wonder platforms like Google, Azure, AWS, and others use Docker to simplify app deployment for all users and all their different operating systems. Here, you'll learn how to take advantage of a technology that has revolutionized deployment!" }, { "code": null, "e": 1921, "s": 1575, "text": "To Dockerize your app, you'll first need to have Docker installed. Install Docker is simple for Mac users but a little more complex for Windows users. Windows machines cannot run Docker without installing Windows System for Linux (WSL2) and running Docker from within this service. We've linked a guide for those wishing to use this option here." }, { "code": null, "e": 2066, "s": 1921, "text": "Once installed, you'll need to initialize Docker on your machine. Docker commands will not work unless the service is running in the background." }, { "code": null, "e": 2335, "s": 2066, "text": "A Dockerfile is a set of commands that tells Docker how to build your container. It includes information about what base image your Docker container should extend, any additional installation or configuration steps needed, and instructions on running your application." }, { "code": null, "e": 2445, "s": 2335, "text": "We've provided our Dockerfile below so you can easily create your Dockerfile with the correct specifications:" }, { "code": null, "e": 2591, "s": 2445, "text": "FROM python:3.9-slimCOPY requirements.txt ./requirements.txtRUN pip install -r requirements.txtCOPY . ./CMD gunicorn -b 0.0.0.0:80 app.app:server" }, { "code": null, "e": 2949, "s": 2591, "text": "One thing that may seem confusing about this Dockerfile is that it copies files in two stages. We do this because Docker builds containers in layers where, roughly speaking, each line corresponds to a layer. The first time the build runs, it caches every layer. If a layer doesn't need to be changed, we can use Docker's cached layers to make builds faster." }, { "code": null, "e": 3077, "s": 2949, "text": "Let's have a closer look at the behavior. In the first COPY command, we copy only the requirements.txt file into the container." }, { "code": null, "e": 3317, "s": 3077, "text": "Now for theRUN line. In a build, if requirements.txthas not been changed, then the next layer, the installation, can be skipped. If it is cached, Docker will not rerun this layer, so the Python dependencies will not need to be reinstalled." }, { "code": null, "e": 3691, "s": 3317, "text": "In the second COPY line, we then copy the rest of the application's file into the container. Some of the application code will likely have changed since the last build, which means that cache for later layers is out of data. Still, since the earlier layers have already been built or retrieved from that cache, this line doesn't trigger the other dependencies to reinstall." }, { "code": null, "e": 3878, "s": 3691, "text": "If we copied all of our code and dependencies at one, then changing the code would invalidate the cache, and the dependencies would be reinstalled even if the requirements didn't change." }, { "code": null, "e": 3958, "s": 3878, "text": "For a deep dive into optimizing containers, check out this article by Sciforce." }, { "code": null, "e": 3969, "s": 3958, "text": "medium.com" }, { "code": null, "e": 4015, "s": 3969, "text": "To initiate your Docker container build, run:" }, { "code": null, "e": 4043, "s": 4015, "text": "docker build -t tiny_home ." }, { "code": null, "e": 4275, "s": 4043, "text": "The -t flag \"tags\" our image and allows us to name the container. Tags are helpful because it allows us to refer to our container with a more human-readable name rather than machine speak. Here, we've named our container tiny_home." }, { "code": null, "e": 4453, "s": 4275, "text": "This command uses our Dockerfile to build a new container image. As Docker processes our Dockerfile, it starts with the base Python container containing the Docker Python image." }, { "code": null, "e": 5177, "s": 4453, "text": "There are many types of Docker base images. We are using the slim version of the Python image, which is optimal when you wish to install the minimal packages necessary to run Python. The -slim suffix denotes that the container should only contain the essentials. For many base images, there are both a slim and a full version. Less included with slim than with the full version, so the image is smaller and is ideal when dealing with space constraints. For most languages, there is also a maintained full version of the image. A full image is usually the best choice if you're unsure of which type to use with your application. Should you wish to read more on the topic, have a look at this article by Julie Perilla Garcia!" }, { "code": null, "e": 5188, "s": 5177, "text": "medium.com" }, { "code": null, "e": 5631, "s": 5188, "text": "Images usually include many layers. Layers may include system libraries, tools, dependencies and other files. In our case, the Python slim image starts by accessing the existing Python slim container from DockerHub. After the image has been downloaded locally, the most current stable release of the Debian/Linux OS distribution and Python are installed. Finally, Docker compies all application files and install the application requirements." }, { "code": null, "e": 6134, "s": 5631, "text": "In our setup, we generate requirements.txt and requirements-dev.txt from our Pipfile by running pipenv-to-requirements in a pre-commit hook. Since we only reference requirements.txtDocker never sees the development. Using only the dependencies necessary to run the app in our container speeds up the build process, decreases the container's size, and potentially improves security. If you haven't done so, please refer to our first article and run these hooks. It will make this process so much easier!" }, { "code": null, "e": 6200, "s": 6134, "text": "Once you build your Docker container, you can view it by running:" }, { "code": null, "e": 6216, "s": 6200, "text": "docker image ls" }, { "code": null, "e": 6271, "s": 6216, "text": "And then you'll see the tiny_home image populate here:" }, { "code": null, "e": 6622, "s": 6271, "text": "As we've successfully built our docker container, the app will run through gunicorn on port 80. To visit the address at which our app is running, we'll need to map the port from where it's running on Docker's host at port 80 to a port on our localhost. Here, we will map our app to port 8080. To do a port mapping and run our app simultaneously, run:" }, { "code": null, "e": 6654, "s": 6622, "text": "docker run -p 8080:80 tiny_home" }, { "code": null, "e": 6913, "s": 6654, "text": "When you visit http://localhost:8080/ (or 0.0.0.0:8080 depending on your operating system), you should see your app running within your Docker container! For those unaware, localhost is an alias for 127.0.0.1, while 0.0.0.0 references all local IP addresses." }, { "code": null, "e": 7127, "s": 6913, "text": "If you get an error indicating that \"Bind for 0.0.0.0:8080 failed: port is already allocated\", you can follow this stack overflow conversation and the provided solution to kill whatever process is using port 8080." }, { "code": null, "e": 7155, "s": 7127, "text": "Your app is now Dockerized!" }, { "code": null, "e": 7237, "s": 7155, "text": "Stay tuned for our next article on deploying your app to GCP's Cloud Run service!" } ]
Hibernate - SortedSet Mappings
A SortedSet is a java collection that does not contain any duplicate element and elements are ordered using their natural ordering or by a comparator provided. A SortedSet is mapped with a <set> element in the mapping table and initialized with java.util.TreeSet. The sort attribute can be set to either a comparator or natural ordering. If we use natural ordering, then its iterator will traverse the set in ascending element order. Consider a situation where we need to store our employee records in the EMPLOYEE table, which will have the following structure − create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) ); Further, assume each employee can have one or more certificate associated with him/her. So, we will store certificate related information in a separate table having the following structure − create table CERTIFICATE ( id INT NOT NULL auto_increment, certificate_name VARCHAR(30) default NULL, employee_id INT default NULL, PRIMARY KEY (id) ); There will be one-to-many relationship between EMPLOYEE and CERTIFICATE objects − Let us implement our POJO class Employee, which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in SortedSet variable. import java.util.*; public class Employee { private int id; private String firstName; private String lastName; private int salary; private SortedSet certificates; public Employee() {} public Employee(String fname, String lname, int salary) { this.firstName = fname; this.lastName = lname; this.salary = salary; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String first_name ) { this.firstName = first_name; } public String getLastName() { return lastName; } public void setLastName( String last_name ) { this.lastName = last_name; } public int getSalary() { return salary; } public void setSalary( int salary ) { this.salary = salary; } public SortedSet getCertificates() { return certificates; } public void setCertificates( SortedSet certificates ) { this.certificates = certificates; } } Now let us define another POJO class corresponding to CERTIFICATE table so that certificate objects can be stored and retrieved into the CERTIFICATE table. This class should also implement Comparable interface and compareTo method, which will be used to sort the elements in case you set sort="natural" in your mapping file (see below mapping file) − public class Certificate implements Comparable <Certificate>{ private int id; private String name; public Certificate() {} public Certificate(String name) { this.name = name; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public int compareTo(Certificate that){ final int BEFORE = -1; final int AFTER = 1; if (that == null) { return BEFORE; } Comparable thisCertificate = this.getName(); Comparable thatCertificate = that.getName(); if(thisCertificate == null) { return AFTER; } else if(thatCertificate == null) { return BEFORE; } else { return thisCertificate.compareTo(thatCertificate); } } } Let us develop our mapping file, which instructs Hibernate how to map the defined classes to the database tables. The <set> element will be used to define the rule for SortedSet collection used. <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name = "Employee" table = "EMPLOYEE"> <meta attribute = "class-description"> This class contains the employee detail. </meta> <id name = "id" type = "int" column = "id"> <generator class="native"/> </id> <set name = "certificates" cascade="all" sort="MyClass"> <key column = "employee_id"/> <one-to-many class="Certificate"/> </set> <property name = "firstName" column = "first_name" type = "string"/> <property name = "lastName" column = "last_name" type = "string"/> <property name = "salary" column = "salary" type = "int"/> </class> <class name = "Certificate" table = "CERTIFICATE"> <meta attribute = "class-description"> This class contains the certificate records. </meta> <id name = "id" type = "int" column = "id"> <generator class="native"/> </id> <property name = "name" column = "certificate_name" type = "string"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. You are already familiar with most of the mapping detail, but let us see all the elements of mapping file once again − The mapping document is an XML document having <hibernate-mapping> as the root element, which contains two <class> elements corresponding to each class. The mapping document is an XML document having <hibernate-mapping> as the root element, which contains two <class> elements corresponding to each class. The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. The <meta> element is optional element and can be used to create the class description. The <meta> element is optional element and can be used to create the class description. The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database. The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database. The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <set> element is used to set the relationship between Certificate and Employee classes. We used the cascade attribute in the <set> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects. The name attribute is set to the defined SortedSet variable in the parent class, in our case it is certificates. The sort attribute can be set to natural to have natural sorting or it can be set to a custom class implementing java.util.Comparator. We have used a class MyClass which implements java.util.Comparator to reverse the sorting order implemented in Certificate class. The <set> element is used to set the relationship between Certificate and Employee classes. We used the cascade attribute in the <set> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects. The name attribute is set to the defined SortedSet variable in the parent class, in our case it is certificates. The sort attribute can be set to natural to have natural sorting or it can be set to a custom class implementing java.util.Comparator. We have used a class MyClass which implements java.util.Comparator to reverse the sorting order implemented in Certificate class. The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object i.e. table EMPLOYEE. The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object i.e. table EMPLOYEE. The <one-to-many> element indicates that one Employee object relates to many Certificate objects and, as such, the Certificate object must have an Employee parent associated with it. You can use either <one-to-one>, <many-to-one> or <many-to-many> elements based on your requirement. The <one-to-many> element indicates that one Employee object relates to many Certificate objects and, as such, the Certificate object must have an Employee parent associated with it. You can use either <one-to-one>, <many-to-one> or <many-to-many> elements based on your requirement. If we use sort="natural" setting, then we do not need to create a separate class because Certificate class already has implemented Comparable interface and hibernate will use compareTo() method defined in Certificate class to compare certificate names. But we are using a custom comparator class MyClass in our mapping file so we would have to create this class based on our sorting algorithm. Let us do descending sorting in this class using this class. import java.util.Comparator; public class MyClass implements Comparator<Certificate>{ public int compare(Certificate o1, Certificate o2) { final int BEFORE = -1; final int AFTER = 1; /* To reverse the sorting order, multiple by -1 */ if (o2 == null) { return BEFORE * -1; } Comparable thisCertificate = o1.getName(); Comparable thatCertificate = o2.getName(); if(thisCertificate == null) { return AFTER * 1; } else if(thatCertificate == null) { return BEFORE * -1; } else { return thisCertificate.compareTo(thatCertificate) * -1; } } } Finally, we will create our application class with the main() method to run the application. We will use this application to save few Employees’ records along with their certificates and then we will apply CRUD operations on those records. import java.util.*; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class ManageEmployee { private static SessionFactory factory; public static void main(String[] args) { try{ factory = new Configuration().configure().buildSessionFactory(); }catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); } ManageEmployee ME = new ManageEmployee(); /* Let us have a set of certificates for the first employee */ TreeSet set1 = new TreeSet(); set1.add(new Certificate("MCA")); set1.add(new Certificate("MBA")); set1.add(new Certificate("PMP")); /* Add employee records in the database */ Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1); /* Another set of certificates for the second employee */ TreeSet set2 = new TreeSet(); set2.add(new Certificate("BCA")); set2.add(new Certificate("BA")); /* Add another employee record in the database */ Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, set2); /* List down all the employees */ ME.listEmployees(); /* Update employee's salary records */ ME.updateEmployee(empID1, 5000); /* Delete an employee from the database */ ME.deleteEmployee(empID2); /* List down all the employees */ ME.listEmployees(); } /* Method to add an employee record in the database */ public Integer addEmployee(String fname, String lname, int salary, SortedSet cert){ Session session = factory.openSession(); Transaction tx = null; Integer employeeID = null; try{ tx = session.beginTransaction(); Employee employee = new Employee(fname, lname, salary); employee.setCertificates(cert); employeeID = (Integer) session.save(employee); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } return employeeID; } /* Method to list all the employees detail */ public void listEmployees( ){ Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); List employees = session.createQuery("FROM Employee").list(); for (Iterator iterator1 = employees.iterator(); iterator1.hasNext();){ Employee employee = (Employee) iterator1.next(); System.out.print("First Name: " + employee.getFirstName()); System.out.print(" Last Name: " + employee.getLastName()); System.out.println(" Salary: " + employee.getSalary()); SortedSet certificates = employee.getCertificates(); for (Iterator iterator2 = certificates.iterator(); iterator2.hasNext();){ Certificate certName = (Certificate) iterator2.next(); System.out.println("Certificate: " + certName.getName()); } } tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } } /* Method to update salary for an employee */ public void updateEmployee(Integer EmployeeID, int salary ){ Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, EmployeeID); employee.setSalary( salary ); session.update(employee); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } } /* Method to delete an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, EmployeeID); session.delete(employee); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } } } Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution. Create hibernate.cfg.xml configuration file as explained in configuration chapter. Create hibernate.cfg.xml configuration file as explained in configuration chapter. Create Employee.hbm.xml mapping file as shown above. Create Employee.hbm.xml mapping file as shown above. Create Employee.java source file as shown above and compile it. Create Employee.java source file as shown above and compile it. Create Certificate.java source file as shown above and compile it. Create Certificate.java source file as shown above and compile it. Create MyClass.java source file as shown above and compile it. Create MyClass.java source file as shown above and compile it. Create ManageEmployee.java source file as shown above and compile it. Create ManageEmployee.java source file as shown above and compile it. Execute ManageEmployee binary to run the program. Execute ManageEmployee binary to run the program. You would get the following result on the screen, and same time records would be created in EMPLOYEE and CERTIFICATE tables. You can see certificates have been sorted in reverse order. You can try by changing your mapping file, simply set sort="natural" and execute your program and compare the results. $java ManageEmployee .......VARIOUS LOG MESSAGES WILL DISPLAY HERE........ First Name: Manoj Last Name: Kumar Salary: 4000 Certificate: PMP Certificate: MCA Certificate: MBA First Name: Dilip Last Name: Kumar Salary: 3000 Certificate: BCA Certificate: BA First Name: Manoj Last Name: Kumar Salary: 5000 Certificate: PMP Certificate: MCA Certificate: MBA If you check your EMPLOYEE and CERTIFICATE tables, they should have the following records − mysql> select * from employee; +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0.00 sec) mysql> select * from certificate; +----+------------------+-------------+ | id | certificate_name | employee_id | +----+------------------+-------------+ | 1 | MBA | 1 | | 2 | PMP | 1 | | 3 | MCA | 1 | +----+------------------+-------------+ 3 rows in set (0.00 sec) mysql> 108 Lectures 11 hours Chaand Sheikh 65 Lectures 5 hours Karthikeya T 39 Lectures 4.5 hours TELCOMA Global Print Add Notes Bookmark this page
[ { "code": null, "e": 2223, "s": 2063, "text": "A SortedSet is a java collection that does not contain any duplicate element and elements are ordered using their natural ordering or by a comparator provided." }, { "code": null, "e": 2497, "s": 2223, "text": "A SortedSet is mapped with a <set> element in the mapping table and initialized with java.util.TreeSet. The sort attribute can be set to either a comparator or natural ordering. If we use natural ordering, then its iterator will traverse the set in ascending element order." }, { "code": null, "e": 2627, "s": 2497, "text": "Consider a situation where we need to store our employee records in the EMPLOYEE table, which will have the following structure −" }, { "code": null, "e": 2822, "s": 2627, "text": "create table EMPLOYEE (\n id INT NOT NULL auto_increment,\n first_name VARCHAR(20) default NULL,\n last_name VARCHAR(20) default NULL,\n salary INT default NULL,\n PRIMARY KEY (id)\n);" }, { "code": null, "e": 3013, "s": 2822, "text": "Further, assume each employee can have one or more certificate associated with him/her. So, we will store certificate related information in a separate table having the following structure −" }, { "code": null, "e": 3177, "s": 3013, "text": "create table CERTIFICATE (\n id INT NOT NULL auto_increment,\n certificate_name VARCHAR(30) default NULL,\n employee_id INT default NULL,\n PRIMARY KEY (id)\n);" }, { "code": null, "e": 3259, "s": 3177, "text": "There will be one-to-many relationship between EMPLOYEE and CERTIFICATE objects −" }, { "code": null, "e": 3432, "s": 3259, "text": "Let us implement our POJO class Employee, which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in SortedSet variable." }, { "code": null, "e": 4546, "s": 3432, "text": "import java.util.*;\n\npublic class Employee {\n private int id;\n private String firstName; \n private String lastName; \n private int salary;\n private SortedSet certificates;\n\n public Employee() {}\n \n public Employee(String fname, String lname, int salary) {\n this.firstName = fname;\n this.lastName = lname;\n this.salary = salary;\n }\n \n public int getId() {\n return id;\n }\n \n public void setId( int id ) {\n this.id = id;\n }\n \n public String getFirstName() {\n return firstName;\n }\n \n public void setFirstName( String first_name ) {\n this.firstName = first_name;\n }\n \n public String getLastName() {\n return lastName;\n }\n \n public void setLastName( String last_name ) {\n this.lastName = last_name;\n }\n \n public int getSalary() {\n return salary;\n }\n \n public void setSalary( int salary ) {\n this.salary = salary;\n }\n\n public SortedSet getCertificates() {\n return certificates;\n }\n \n public void setCertificates( SortedSet certificates ) {\n this.certificates = certificates;\n }\n}" }, { "code": null, "e": 4897, "s": 4546, "text": "Now let us define another POJO class corresponding to CERTIFICATE table so that certificate objects can be stored and retrieved into the CERTIFICATE table. This class should also implement Comparable interface and compareTo method, which will be used to sort the elements in case you set sort=\"natural\" in your mapping file (see below mapping file) −" }, { "code": null, "e": 5825, "s": 4897, "text": "public class Certificate implements Comparable <Certificate>{\n private int id;\n private String name; \n\n public Certificate() {}\n \n public Certificate(String name) {\n this.name = name;\n }\n \n public int getId() {\n return id;\n }\n \n public void setId( int id ) {\n this.id = id;\n }\n \n public String getName() {\n return name;\n }\n \n public void setName( String name ) {\n this.name = name;\n }\n \n public int compareTo(Certificate that){\n final int BEFORE = -1;\n final int AFTER = 1;\n\n if (that == null) {\n return BEFORE;\n }\n\n Comparable thisCertificate = this.getName();\n Comparable thatCertificate = that.getName();\n\n if(thisCertificate == null) {\n return AFTER;\n } else if(thatCertificate == null) {\n return BEFORE;\n } else {\n return thisCertificate.compareTo(thatCertificate);\n }\n }\n}" }, { "code": null, "e": 6020, "s": 5825, "text": "Let us develop our mapping file, which instructs Hibernate how to map the defined classes to the database tables. The <set> element will be used to define the rule for SortedSet collection used." }, { "code": null, "e": 7239, "s": 6020, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<!DOCTYPE hibernate-mapping PUBLIC \n\"-//Hibernate/Hibernate Mapping DTD//EN\"\n\"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\"> \n\n<hibernate-mapping>\n <class name = \"Employee\" table = \"EMPLOYEE\">\n <meta attribute = \"class-description\">\n This class contains the employee detail. \n </meta>\n <id name = \"id\" type = \"int\" column = \"id\">\n <generator class=\"native\"/>\n </id>\n <set name = \"certificates\" cascade=\"all\" sort=\"MyClass\">\n <key column = \"employee_id\"/>\n <one-to-many class=\"Certificate\"/>\n </set>\n <property name = \"firstName\" column = \"first_name\" type = \"string\"/>\n <property name = \"lastName\" column = \"last_name\" type = \"string\"/>\n <property name = \"salary\" column = \"salary\" type = \"int\"/>\n </class>\n\n <class name = \"Certificate\" table = \"CERTIFICATE\">\n <meta attribute = \"class-description\">\n This class contains the certificate records. \n </meta>\n <id name = \"id\" type = \"int\" column = \"id\">\n <generator class=\"native\"/>\n </id>\n <property name = \"name\" column = \"certificate_name\" type = \"string\"/>\n </class>\n\n</hibernate-mapping>" }, { "code": null, "e": 7502, "s": 7239, "text": "You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. You are already familiar with most of the mapping detail, but let us see all the elements of mapping file once again −" }, { "code": null, "e": 7655, "s": 7502, "text": "The mapping document is an XML document having <hibernate-mapping> as the root element, which contains two <class> elements corresponding to each class." }, { "code": null, "e": 7808, "s": 7655, "text": "The mapping document is an XML document having <hibernate-mapping> as the root element, which contains two <class> elements corresponding to each class." }, { "code": null, "e": 8057, "s": 7808, "text": "The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute." }, { "code": null, "e": 8306, "s": 8057, "text": "The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute." }, { "code": null, "e": 8394, "s": 8306, "text": "The <meta> element is optional element and can be used to create the class description." }, { "code": null, "e": 8482, "s": 8394, "text": "The <meta> element is optional element and can be used to create the class description." }, { "code": null, "e": 8834, "s": 8482, "text": "The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type." }, { "code": null, "e": 9186, "s": 8834, "text": "The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type." }, { "code": null, "e": 9503, "s": 9186, "text": "The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database." }, { "code": null, "e": 9820, "s": 9503, "text": "The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database." }, { "code": null, "e": 10167, "s": 9820, "text": "The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type." }, { "code": null, "e": 10514, "s": 10167, "text": "The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type." }, { "code": null, "e": 11130, "s": 10514, "text": "The <set> element is used to set the relationship between Certificate and Employee classes. We used the cascade attribute in the <set> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects. The name attribute is set to the defined SortedSet variable in the parent class, in our case it is certificates. The sort attribute can be set to natural to have natural sorting or it can be set to a custom class implementing java.util.Comparator. We have used a class MyClass which implements java.util.Comparator to reverse the sorting order implemented in Certificate class." }, { "code": null, "e": 11746, "s": 11130, "text": "The <set> element is used to set the relationship between Certificate and Employee classes. We used the cascade attribute in the <set> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects. The name attribute is set to the defined SortedSet variable in the parent class, in our case it is certificates. The sort attribute can be set to natural to have natural sorting or it can be set to a custom class implementing java.util.Comparator. We have used a class MyClass which implements java.util.Comparator to reverse the sorting order implemented in Certificate class." }, { "code": null, "e": 11872, "s": 11746, "text": "The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object i.e. table EMPLOYEE." }, { "code": null, "e": 11998, "s": 11872, "text": "The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object i.e. table EMPLOYEE." }, { "code": null, "e": 12282, "s": 11998, "text": "The <one-to-many> element indicates that one Employee object relates to many Certificate objects and, as such, the Certificate object must have an Employee parent associated with it. You can use either <one-to-one>, <many-to-one> or <many-to-many> elements based on your requirement." }, { "code": null, "e": 12566, "s": 12282, "text": "The <one-to-many> element indicates that one Employee object relates to many Certificate objects and, as such, the Certificate object must have an Employee parent associated with it. You can use either <one-to-one>, <many-to-one> or <many-to-many> elements based on your requirement." }, { "code": null, "e": 13021, "s": 12566, "text": "If we use sort=\"natural\" setting, then we do not need to create a separate class because Certificate class already has implemented Comparable interface and hibernate will use compareTo() method defined in Certificate class to compare certificate names. But we are using a custom comparator class MyClass in our mapping file so we would have to create this class based on our sorting algorithm. Let us do descending sorting in this class using this class." }, { "code": null, "e": 13669, "s": 13021, "text": "import java.util.Comparator;\n\npublic class MyClass implements Comparator<Certificate>{\n public int compare(Certificate o1, Certificate o2) {\n final int BEFORE = -1;\n final int AFTER = 1;\n\n /* To reverse the sorting order, multiple by -1 */\n if (o2 == null) {\n return BEFORE * -1;\n }\n\n Comparable thisCertificate = o1.getName();\n Comparable thatCertificate = o2.getName();\n\n if(thisCertificate == null) {\n return AFTER * 1;\n } else if(thatCertificate == null) {\n return BEFORE * -1;\n } else {\n return thisCertificate.compareTo(thatCertificate) * -1;\n }\n }\n}" }, { "code": null, "e": 13909, "s": 13669, "text": "Finally, we will create our application class with the main() method to run the application. We will use this application to save few Employees’ records along with their certificates and then we will apply CRUD operations on those records." }, { "code": null, "e": 18456, "s": 13909, "text": "import java.util.*;\n \nimport org.hibernate.HibernateException; \nimport org.hibernate.Session; \nimport org.hibernate.Transaction;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\n\npublic class ManageEmployee {\n private static SessionFactory factory; \n public static void main(String[] args) {\n try{\n factory = new Configuration().configure().buildSessionFactory();\n }catch (Throwable ex) { \n System.err.println(\"Failed to create sessionFactory object.\" + ex);\n throw new ExceptionInInitializerError(ex); \n }\n\t\t\n ManageEmployee ME = new ManageEmployee();\n /* Let us have a set of certificates for the first employee */\n TreeSet set1 = new TreeSet();\n set1.add(new Certificate(\"MCA\"));\n set1.add(new Certificate(\"MBA\"));\n set1.add(new Certificate(\"PMP\"));\n \n /* Add employee records in the database */\n Integer empID1 = ME.addEmployee(\"Manoj\", \"Kumar\", 4000, set1);\n\n /* Another set of certificates for the second employee */\n TreeSet set2 = new TreeSet();\n set2.add(new Certificate(\"BCA\"));\n set2.add(new Certificate(\"BA\"));\n\n /* Add another employee record in the database */\n Integer empID2 = ME.addEmployee(\"Dilip\", \"Kumar\", 3000, set2);\n\n /* List down all the employees */\n ME.listEmployees();\n\n /* Update employee's salary records */\n ME.updateEmployee(empID1, 5000);\n\n /* Delete an employee from the database */\n ME.deleteEmployee(empID2);\n\n /* List down all the employees */\n ME.listEmployees();\n\n }\n\n /* Method to add an employee record in the database */\n public Integer addEmployee(String fname, String lname, int salary, SortedSet cert){\n Session session = factory.openSession();\n Transaction tx = null;\n Integer employeeID = null;\n try{\n tx = session.beginTransaction();\n Employee employee = new Employee(fname, lname, salary);\n employee.setCertificates(cert);\n employeeID = (Integer) session.save(employee); \n tx.commit();\n }catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n }finally {\n session.close(); \n }\n return employeeID;\n }\n\n /* Method to list all the employees detail */\n public void listEmployees( ){\n Session session = factory.openSession();\n Transaction tx = null;\n try{\n tx = session.beginTransaction();\n List employees = session.createQuery(\"FROM Employee\").list(); \n for (Iterator iterator1 = employees.iterator(); iterator1.hasNext();){\n Employee employee = (Employee) iterator1.next(); \n System.out.print(\"First Name: \" + employee.getFirstName()); \n System.out.print(\" Last Name: \" + employee.getLastName()); \n System.out.println(\" Salary: \" + employee.getSalary());\n SortedSet certificates = employee.getCertificates();\n for (Iterator iterator2 = certificates.iterator(); iterator2.hasNext();){\n Certificate certName = (Certificate) iterator2.next(); \n System.out.println(\"Certificate: \" + certName.getName()); \n }\n }\n tx.commit();\n }catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n }finally {\n session.close(); \n }\n }\n /* Method to update salary for an employee */\n public void updateEmployee(Integer EmployeeID, int salary ){\n Session session = factory.openSession();\n Transaction tx = null;\n try{\n tx = session.beginTransaction();\n Employee employee = (Employee)session.get(Employee.class, EmployeeID); \n employee.setSalary( salary );\n session.update(employee);\n tx.commit();\n }catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n }finally {\n session.close(); \n }\n }\n /* Method to delete an employee from the records */\n public void deleteEmployee(Integer EmployeeID){\n Session session = factory.openSession();\n Transaction tx = null;\n try{\n tx = session.beginTransaction();\n Employee employee = (Employee)session.get(Employee.class, EmployeeID); \n session.delete(employee); \n tx.commit();\n }catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n }finally {\n session.close(); \n }\n }\n}" }, { "code": null, "e": 18636, "s": 18456, "text": "Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution." }, { "code": null, "e": 18719, "s": 18636, "text": "Create hibernate.cfg.xml configuration file as explained in configuration chapter." }, { "code": null, "e": 18802, "s": 18719, "text": "Create hibernate.cfg.xml configuration file as explained in configuration chapter." }, { "code": null, "e": 18855, "s": 18802, "text": "Create Employee.hbm.xml mapping file as shown above." }, { "code": null, "e": 18908, "s": 18855, "text": "Create Employee.hbm.xml mapping file as shown above." }, { "code": null, "e": 18972, "s": 18908, "text": "Create Employee.java source file as shown above and compile it." }, { "code": null, "e": 19036, "s": 18972, "text": "Create Employee.java source file as shown above and compile it." }, { "code": null, "e": 19103, "s": 19036, "text": "Create Certificate.java source file as shown above and compile it." }, { "code": null, "e": 19170, "s": 19103, "text": "Create Certificate.java source file as shown above and compile it." }, { "code": null, "e": 19233, "s": 19170, "text": "Create MyClass.java source file as shown above and compile it." }, { "code": null, "e": 19296, "s": 19233, "text": "Create MyClass.java source file as shown above and compile it." }, { "code": null, "e": 19366, "s": 19296, "text": "Create ManageEmployee.java source file as shown above and compile it." }, { "code": null, "e": 19436, "s": 19366, "text": "Create ManageEmployee.java source file as shown above and compile it." }, { "code": null, "e": 19486, "s": 19436, "text": "Execute ManageEmployee binary to run the program." }, { "code": null, "e": 19536, "s": 19486, "text": "Execute ManageEmployee binary to run the program." }, { "code": null, "e": 19840, "s": 19536, "text": "You would get the following result on the screen, and same time records would be created in EMPLOYEE and CERTIFICATE tables. You can see certificates have been sorted in reverse order. You can try by changing your mapping file, simply set sort=\"natural\" and execute your program and compare the results." }, { "code": null, "e": 20201, "s": 19840, "text": "$java ManageEmployee\n.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........\n\nFirst Name: Manoj Last Name: Kumar Salary: 4000\nCertificate: PMP\nCertificate: MCA\nCertificate: MBA\nFirst Name: Dilip Last Name: Kumar Salary: 3000\nCertificate: BCA\nCertificate: BA\nFirst Name: Manoj Last Name: Kumar Salary: 5000\nCertificate: PMP\nCertificate: MCA\nCertificate: MBA" }, { "code": null, "e": 20293, "s": 20201, "text": "If you check your EMPLOYEE and CERTIFICATE tables, they should have the following records −" }, { "code": null, "e": 20901, "s": 20293, "text": "mysql> select * from employee;\n+----+------------+-----------+--------+\n| id | first_name | last_name | salary |\n+----+------------+-----------+--------+\n| 1 | Manoj | Kumar | 5000 |\n+----+------------+-----------+--------+\n1 row in set (0.00 sec)\n\nmysql> select * from certificate;\n+----+------------------+-------------+\n| id | certificate_name | employee_id |\n+----+------------------+-------------+\n| 1 | MBA | 1 |\n| 2 | PMP | 1 |\n| 3 | MCA | 1 |\n+----+------------------+-------------+\n3 rows in set (0.00 sec)\n\nmysql>" }, { "code": null, "e": 20936, "s": 20901, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 20951, "s": 20936, "text": " Chaand Sheikh" }, { "code": null, "e": 20984, "s": 20951, "text": "\n 65 Lectures \n 5 hours \n" }, { "code": null, "e": 20998, "s": 20984, "text": " Karthikeya T" }, { "code": null, "e": 21033, "s": 20998, "text": "\n 39 Lectures \n 4.5 hours \n" }, { "code": null, "e": 21049, "s": 21033, "text": " TELCOMA Global" }, { "code": null, "e": 21056, "s": 21049, "text": " Print" }, { "code": null, "e": 21067, "s": 21056, "text": " Add Notes" } ]
C# | Creating a synchronized (thread-safe) wrapper for the Hashtable - GeeksforGeeks
09 Aug, 2021 Hashtable.Synchronized(Hashtable) Method is used to return a synchronized (thread-safe) wrapper for the Hashtable.Syntax: public static System.Collections.Hashtable Synchronized (System.Collections.Hashtable table); Here table is the Hashtable which is to be synchronized.Return Value: This method returns a synchronized (thread-safe) wrapper for the Hashtable.Exception: This method will throw the ArgumentNullException if the table is null. Below programs illustrate the use of above-discussed method:Example 1: CSharp // C# code to get a synchronized (thread-// safe) wrapper for the Hashtableusing System;using System.Collections; class GFG { // Main method static void Main(string[] args) { // create and initialize Hash table // using Add() method Hashtable has1 = new Hashtable(); has1.Add("1", "Welcome"); has1.Add("2", "to"); has1.Add("3", "geeks"); has1.Add("4", "for"); has1.Add("5", "geeks"); // Creating a synchronized packing // around the Hashtable Hashtable has2 = Hashtable.Synchronized(has1); // --------- Using IsSynchronized Property // print the status of both Hashtables Console.WriteLine("has1 Hashtable is {0}.", has1.IsSynchronized ? "synchronized" : "not synchronized"); Console.WriteLine("has2 Hashtable is {0}.", has2.IsSynchronized ? "synchronized" : "not synchronized"); }} Output: has1 Hashtable is not synchronized. has2 Hashtable is synchronized. Example 2: CSharp // C# code to get a synchronized (thread-// safe) wrapper for the Hashtableusing System;using System.Collections; class GFG { // Main method static void Main(string[] args) { // create and initialize Hash table // there will be no elements Hashtable has1 = new Hashtable(); // it will give runtime error as // table parameter can't be null Hashtable has2 = Hashtable.Synchronized(null); }} Runtime Error: Unhandled Exception: System.ArgumentNullException: Value cannot be null. Parameter name: table Note: This method is a thread-safe for multiple readers and writers. Furthermore, the synchronized wrapper ensures that there is only one writer writing at a time. Enumerating through a collection is intrinsically not a thread-safe process. Other threads can still modify the collection, which causes the enumerator to throw an exception even when a collection is synchronized. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads. This method is an O(1) operation. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.synchronized?view=netframework-4.7.2 anikaseth98 CSharp-Collections-Hashtable CSharp-Collections-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 C# Interview Questions & Answers Extension Method in C# HashSet in C# with Examples Partial Classes in C# C# | Inheritance Convert String to Character Array in C# Linked List Implementation in C# C# | How to insert an element in an Array? C# | List Class Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 23911, "s": 23883, "text": "\n09 Aug, 2021" }, { "code": null, "e": 24033, "s": 23911, "text": "Hashtable.Synchronized(Hashtable) Method is used to return a synchronized (thread-safe) wrapper for the Hashtable.Syntax:" }, { "code": null, "e": 24127, "s": 24033, "text": "public static System.Collections.Hashtable Synchronized (System.Collections.Hashtable table);" }, { "code": null, "e": 24425, "s": 24127, "text": "Here table is the Hashtable which is to be synchronized.Return Value: This method returns a synchronized (thread-safe) wrapper for the Hashtable.Exception: This method will throw the ArgumentNullException if the table is null. Below programs illustrate the use of above-discussed method:Example 1:" }, { "code": null, "e": 24432, "s": 24425, "text": "CSharp" }, { "code": "// C# code to get a synchronized (thread-// safe) wrapper for the Hashtableusing System;using System.Collections; class GFG { // Main method static void Main(string[] args) { // create and initialize Hash table // using Add() method Hashtable has1 = new Hashtable(); has1.Add(\"1\", \"Welcome\"); has1.Add(\"2\", \"to\"); has1.Add(\"3\", \"geeks\"); has1.Add(\"4\", \"for\"); has1.Add(\"5\", \"geeks\"); // Creating a synchronized packing // around the Hashtable Hashtable has2 = Hashtable.Synchronized(has1); // --------- Using IsSynchronized Property // print the status of both Hashtables Console.WriteLine(\"has1 Hashtable is {0}.\", has1.IsSynchronized ? \"synchronized\" : \"not synchronized\"); Console.WriteLine(\"has2 Hashtable is {0}.\", has2.IsSynchronized ? \"synchronized\" : \"not synchronized\"); }}", "e": 25420, "s": 24432, "text": null }, { "code": null, "e": 25430, "s": 25420, "text": "Output: " }, { "code": null, "e": 25498, "s": 25430, "text": "has1 Hashtable is not synchronized.\nhas2 Hashtable is synchronized." }, { "code": null, "e": 25509, "s": 25498, "text": "Example 2:" }, { "code": null, "e": 25516, "s": 25509, "text": "CSharp" }, { "code": "// C# code to get a synchronized (thread-// safe) wrapper for the Hashtableusing System;using System.Collections; class GFG { // Main method static void Main(string[] args) { // create and initialize Hash table // there will be no elements Hashtable has1 = new Hashtable(); // it will give runtime error as // table parameter can't be null Hashtable has2 = Hashtable.Synchronized(null); }}", "e": 25963, "s": 25516, "text": null }, { "code": null, "e": 25979, "s": 25963, "text": "Runtime Error: " }, { "code": null, "e": 26076, "s": 25979, "text": "Unhandled Exception: System.ArgumentNullException: Value cannot be null. Parameter name: table " }, { "code": null, "e": 26082, "s": 26076, "text": "Note:" }, { "code": null, "e": 26240, "s": 26082, "text": "This method is a thread-safe for multiple readers and writers. Furthermore, the synchronized wrapper ensures that there is only one writer writing at a time." }, { "code": null, "e": 26454, "s": 26240, "text": "Enumerating through a collection is intrinsically not a thread-safe process. Other threads can still modify the collection, which causes the enumerator to throw an exception even when a collection is synchronized." }, { "code": null, "e": 26636, "s": 26454, "text": "To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads." }, { "code": null, "e": 26670, "s": 26636, "text": "This method is an O(1) operation." }, { "code": null, "e": 26682, "s": 26670, "text": "Reference: " }, { "code": null, "e": 26792, "s": 26682, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.synchronized?view=netframework-4.7.2" }, { "code": null, "e": 26806, "s": 26794, "text": "anikaseth98" }, { "code": null, "e": 26835, "s": 26806, "text": "CSharp-Collections-Hashtable" }, { "code": null, "e": 26864, "s": 26835, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 26878, "s": 26864, "text": "CSharp-method" }, { "code": null, "e": 26881, "s": 26878, "text": "C#" }, { "code": null, "e": 26979, "s": 26881, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26988, "s": 26979, "text": "Comments" }, { "code": null, "e": 27001, "s": 26988, "text": "Old Comments" }, { "code": null, "e": 27041, "s": 27001, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27064, "s": 27041, "text": "Extension Method in C#" }, { "code": null, "e": 27092, "s": 27064, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27114, "s": 27092, "text": "Partial Classes in C#" }, { "code": null, "e": 27131, "s": 27114, "text": "C# | Inheritance" }, { "code": null, "e": 27171, "s": 27131, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27204, "s": 27171, "text": "Linked List Implementation in C#" }, { "code": null, "e": 27247, "s": 27204, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27263, "s": 27247, "text": "C# | List Class" } ]
What is the syntax for passing Scanner object as a parameter in a method using java?
Until Java 1.5 to read data from the user programmers used to depend on the character stream classes and byte stream classes. From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. By default, whitespace is considered as the delimiter (to break the data into tokens). To read various datatypes from the source using the nextXXX() methods provided by this class namely, nextInt(), nextShort(), nextFloat(), nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(), nextFloat(), next(). You can pass Scanner object to a method as a parameter. The following Java program demonstrates how to pass a Scanner object to a method. This object reads the contents of a file. import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; public class ScannerExample { public String sampleMethod(Scanner sc){ StringBuffer sb = new StringBuffer(); while(sc.hasNext()) { sb.append(sc.nextLine()); } return sb.toString(); } public static void main(String args[]) throws IOException { //Instantiating the inputStream class InputStream stream = new FileInputStream("D:\\sample.txt"); //Instantiating the Scanner class Scanner sc = new Scanner(stream); ScannerExample obj = new ScannerExample(); //Calling the method String result = obj.sampleMethod(sc); System.out.println("Contents of the file:"); System.out.println(result); } } Contents of the file: Tutorials Point originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. In the following example, we creating a Scanner object which has Standard input (System.in) as source and passing it as a parameter to a method. import java.io.IOException; import java.util.Scanner; public class ScannerExample { public void sampleMethod(Scanner sc){ StringBuffer sb = new StringBuffer(); System.out.println("Enter your name: "); String name = sc.next(); System.out.println("Enter your age: "); String age = sc.next(); System.out.println("Hello "+name+" You are "+age+" years old"); } public static void main(String args[]) throws IOException { //Instantiating the Scanner class Scanner sc = new Scanner(System.in); ScannerExample obj = new ScannerExample(); //Calling the method obj.sampleMethod(sc); } } Enter your name: Krishna Enter your age: 25 Hello Krishna You are 25 years old
[ { "code": null, "e": 1188, "s": 1062, "text": "Until Java 1.5 to read data from the user programmers used to depend on the character stream classes and byte stream classes." }, { "code": null, "e": 1411, "s": 1188, "text": "From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions." }, { "code": null, "e": 1498, "s": 1411, "text": "By default, whitespace is considered as the delimiter (to break the data into tokens)." }, { "code": null, "e": 1756, "s": 1498, "text": "To read various datatypes from the source using the nextXXX() methods provided by this class namely, nextInt(), nextShort(), nextFloat(), nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(), nextFloat(), next()." }, { "code": null, "e": 1812, "s": 1756, "text": "You can pass Scanner object to a method as a parameter." }, { "code": null, "e": 1936, "s": 1812, "text": "The following Java program demonstrates how to pass a Scanner object to a method. This object reads the contents of a file." }, { "code": null, "e": 2736, "s": 1936, "text": "import java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Scanner;\npublic class ScannerExample {\n public String sampleMethod(Scanner sc){\n StringBuffer sb = new StringBuffer();\n while(sc.hasNext()) {\n sb.append(sc.nextLine());\n }\n return sb.toString();\n }\n public static void main(String args[]) throws IOException {\n //Instantiating the inputStream class\n InputStream stream = new FileInputStream(\"D:\\\\sample.txt\");\n //Instantiating the Scanner class\n Scanner sc = new Scanner(stream);\n ScannerExample obj = new ScannerExample();\n //Calling the method\n String result = obj.sampleMethod(sc);\n System.out.println(\"Contents of the file:\");\n System.out.println(result);\n }\n}" }, { "code": null, "e": 2965, "s": 2736, "text": "Contents of the file:\nTutorials Point originated from the idea that there exists a class of readers who respond better to on-line\ncontent and prefer to learn new skills at their own pace from the comforts of their drawing rooms." }, { "code": null, "e": 3110, "s": 2965, "text": "In the following example, we creating a Scanner object which has Standard input (System.in) as source and passing it as a parameter to a method." }, { "code": null, "e": 3765, "s": 3110, "text": "import java.io.IOException;\nimport java.util.Scanner;\npublic class ScannerExample {\n public void sampleMethod(Scanner sc){\n StringBuffer sb = new StringBuffer();\n System.out.println(\"Enter your name: \");\n String name = sc.next();\n System.out.println(\"Enter your age: \");\n String age = sc.next();\n System.out.println(\"Hello \"+name+\" You are \"+age+\" years old\");\n }\n public static void main(String args[]) throws IOException {\n //Instantiating the Scanner class\n Scanner sc = new Scanner(System.in);\n ScannerExample obj = new ScannerExample();\n //Calling the method\n obj.sampleMethod(sc);\n }\n}" }, { "code": null, "e": 3844, "s": 3765, "text": "Enter your name:\nKrishna\nEnter your age:\n25\nHello Krishna You are 25 years old" } ]
Ways to sum to N using array elements with repetition allowed in C++
In this problem, we are given an array of integers and a number N. Our task is to count the total number of ways N can be generated by adding elements of the array. All combinations and repetitions are allowed. Let’s take an example to understand the problem, arr = {1, 3, 5} N = 6 8 The ways are − 5+1, 1+5, 3+3, 3+1+1+1, 1+3+1+1, 1+1+3+1, 1+1+1+3, 1+1+1+1+1+1 To solve this problem, we need to use a different approach as all types of combinations will be treated differently so, if the number is a sum of 4 elements of array 4 different ways are considered(as shown in example). For solve such a problem, we need to use dynamic programming approach and the below program will show the implementation. Live Demo #include <iostream> #include <cstring> using namespace std; int arraySumWays(int array[], int size, int N){ int count[N + 1]; memset(count, 0, sizeof(count)); count[0] = 1; for (int i = 1; i <= N; i++) for (int j = 0; j < size; j++) if (i >= array[j]) count[i] += count[i - array[j]]; return count[N]; } int main() { int array[] = {1, 5, 6}; int size = sizeof(array) / sizeof(array[0]); int N = 7; cout<<"Total number of ways inwhich "<<N<<" can be generated using sum of elements of array is " <<arraySumWays(array, size, N); return 0; } Total number of ways inwhich 7 can be generated using sum of elements of array is 6
[ { "code": null, "e": 1273, "s": 1062, "text": "In this problem, we are given an array of integers and a number N. Our task is to count the total number of ways N can be generated by adding elements of the array. All combinations and repetitions are allowed." }, { "code": null, "e": 1322, "s": 1273, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1344, "s": 1322, "text": "arr = {1, 3, 5} N = 6" }, { "code": null, "e": 1346, "s": 1344, "text": "8" }, { "code": null, "e": 1361, "s": 1346, "text": "The ways are −" }, { "code": null, "e": 1424, "s": 1361, "text": "5+1, 1+5, 3+3, 3+1+1+1, 1+3+1+1, 1+1+3+1, 1+1+1+3, 1+1+1+1+1+1" }, { "code": null, "e": 1766, "s": 1424, "text": "To solve this problem, we need to use a different approach as all types of combinations will be treated differently so, if the number is a sum of 4 elements of array 4 different ways are considered(as shown in example). For solve such a problem, we need to use dynamic programming approach and the below program will show the implementation." }, { "code": null, "e": 1777, "s": 1766, "text": " Live Demo" }, { "code": null, "e": 2378, "s": 1777, "text": "#include <iostream>\n#include <cstring>\nusing namespace std;\nint arraySumWays(int array[], int size, int N){\n int count[N + 1];\n memset(count, 0, sizeof(count));\n count[0] = 1;\n for (int i = 1; i <= N; i++)\n for (int j = 0; j < size; j++)\n if (i >= array[j])\n count[i] += count[i - array[j]];\n return count[N];\n}\nint main() {\n int array[] = {1, 5, 6};\n int size = sizeof(array) / sizeof(array[0]);\n int N = 7;\n cout<<\"Total number of ways inwhich \"<<N<<\" can be generated using sum of elements of array is \" <<arraySumWays(array, size, N);\n return 0;\n}" }, { "code": null, "e": 2462, "s": 2378, "text": "Total number of ways inwhich 7 can be generated using sum of elements of array is 6" } ]
Kotlin Exception Handling | try, catch, throw and finally
28 Mar, 2022 An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. Exception handling is a technique, using which we can handle errors and prevent run time crashes that can stop our program. There are two types of Exceptions – Checked Exception – Exceptions that are typically set on methods and checked at the compile time, for example IOException, FileNotFoundException etcUnChecked Exception – Exceptions that are generally due to logical errors and checked at the run time, for example NullPointerException, ArrayIndexOutOfBoundException etc Checked Exception – Exceptions that are typically set on methods and checked at the compile time, for example IOException, FileNotFoundException etc UnChecked Exception – Exceptions that are generally due to logical errors and checked at the run time, for example NullPointerException, ArrayIndexOutOfBoundException etc In Kotlin, we have only unchecked exceptions and can be caught only at run time. All the exception classes are descendants of Throwable class. We generally use the throw-expression, to throw an exception object – throw Exception("Throw me") Some of the common exceptions are: NullPointerException: It is thrown when we try to invoke a property or method on null object. Arithmetic Exception: It is thrown when invalid arithmetic operations are performed on numbers. eg – divide by zero. SecurityException: It is thrown to indicate security violation. ArrayIndexOutOfBoundException: It is thrown when we try to access invalid index value of an array. Kotlin program of throwing arithmetic exception – Kotlin fun main(args : Array<String>){ var num = 10 / 0 // throws exception println(num)} Output: Exception in thread "main" java.lang.ArithmeticException: / by zero In the above program, we initialize the num variable with value 10/0, but we know in arithmetic divide by zero is not allowed. While we are trying to run the program it throws an exception. To solve this problem, we have to use try-catch block. In Kotlin, we use try-catch block for exception handling in the program. The try block encloses the code which is responsible for throwing an exception and the catch block is used for handling the exception. This block must be written within the main or other methods. Try block should be followed by either catch block or finally block or both. Syntax for try-catch block – try { // code that can throw exception } catch(e: ExceptionName) { // catch the exception and handle it } Kotlin program of arithmetic exception handling using try-catch block – Kotlin import kotlin.ArithmeticException fun main(args : Array<String>){ try{ var num = 10 / 0 } catch(e: ArithmeticException){ // caught and handles it println("Divide by zero not allowed") }} Output: Divide by zero not allowed Explanation:In the above program, we have used try-catch block. The num variable which can throw exception is enclosed within the braces of try block because divide by zero not defined in arithmetic. The exception caught by the catch block and execute the println() statement. As we already know, expression always returns a value. We can use kotlin try-catch block as an expression in our program. The value returned by the expression will be either last expression of try block or last expression of catch block. If an exception occurs in the code, then catch block returns the value. Kotlin program of using try-catch as an expression – Kotlin fun test(a: Int, b: Int) : Any { return try { a/b //println("The Result is: "+ a / b) } catch(e:Exception){ println(e) "Divide by zero not allowed" }}// main functionfun main(args: Array<String>) { // invoke test function var result1 = test(10,2 ) //execute try block println(result1) var result = test(10,0 ) // execute catch block println(result)} Output: 5 java.lang.ArithmeticException: / by zero Divide by zero not allowed In the above code, we have used try-catch as an expression. Declare a function test on the top of program and it return a value using try-catch block. We have invoked the test function from main method and passed the parameter values (10,2) The test function evaluate the arguments and return try value (10/2 = 5). But in next call, we passed (b=0) and this time exception is caught and returns expression of catch block. In Kotlin, finally block is always executes irrespective of whether an exception is handled or not by the catch block. So it is used to execute important code statement.We can also use finally block with try block and skip the catch block from there. Syntax of finally block with try block – try { // code that can throw exception } finally { // finally block code } Kotlin program of using finally block with try block block – Kotlin fun main(args : Array<String>){ try{ var ar = arrayOf(1,2,3,4,5) var int = ar[6] println(int) } finally { println("This block always executes") }} Output: This block always executesException in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 5 In the above program, we have used try with finally block and skipped the catch block. Here, exception is not handled by catch block but executes the finally block. Syntax of finally block with try-catch block – try { // code that can throw exception } catch(e: ExceptionName) { // catch the exception and handle it. } finally { // finally block code } We can also use try, catch and finally blocks all together.Kotlin program of using finally block with try-catch block- Kotlin fun main (args: Array<String>){ try { var int = 10 / 0 println(int) } catch (e: ArithmeticException) { println(e) } finally { println("This block always executes") } } Output: java.lang.ArithmeticException: / by zero This block always executes In Kotlin, we use throw keyword to throw an explicit exception. It can also be used to throw a custom exception. Kotlin program of using throw keyword – Kotlin fun main(args: Array<String>) { test("abcd") println("executes after the validation")}fun test(password: String) { // calculate length of the entered password and compare if (password.length < 6) throw ArithmeticException("Password is too short") else println("Strong password")} Output: Exception in thread "main" java.lang.ArithmeticException: Password is too short ayushpandey3july Kotlin Exception-Handling Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Mar, 2022" }, { "code": null, "e": 326, "s": 28, "text": "An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. Exception handling is a technique, using which we can handle errors and prevent run time crashes that can stop our program." }, { "code": null, "e": 362, "s": 326, "text": "There are two types of Exceptions –" }, { "code": null, "e": 681, "s": 362, "text": "Checked Exception – Exceptions that are typically set on methods and checked at the compile time, for example IOException, FileNotFoundException etcUnChecked Exception – Exceptions that are generally due to logical errors and checked at the run time, for example NullPointerException, ArrayIndexOutOfBoundException etc" }, { "code": null, "e": 830, "s": 681, "text": "Checked Exception – Exceptions that are typically set on methods and checked at the compile time, for example IOException, FileNotFoundException etc" }, { "code": null, "e": 1001, "s": 830, "text": "UnChecked Exception – Exceptions that are generally due to logical errors and checked at the run time, for example NullPointerException, ArrayIndexOutOfBoundException etc" }, { "code": null, "e": 1144, "s": 1001, "text": "In Kotlin, we have only unchecked exceptions and can be caught only at run time. All the exception classes are descendants of Throwable class." }, { "code": null, "e": 1214, "s": 1144, "text": "We generally use the throw-expression, to throw an exception object –" }, { "code": null, "e": 1242, "s": 1214, "text": "throw Exception(\"Throw me\")" }, { "code": null, "e": 1277, "s": 1242, "text": "Some of the common exceptions are:" }, { "code": null, "e": 1371, "s": 1277, "text": "NullPointerException: It is thrown when we try to invoke a property or method on null object." }, { "code": null, "e": 1488, "s": 1371, "text": "Arithmetic Exception: It is thrown when invalid arithmetic operations are performed on numbers. eg – divide by zero." }, { "code": null, "e": 1552, "s": 1488, "text": "SecurityException: It is thrown to indicate security violation." }, { "code": null, "e": 1651, "s": 1552, "text": "ArrayIndexOutOfBoundException: It is thrown when we try to access invalid index value of an array." }, { "code": null, "e": 1701, "s": 1651, "text": "Kotlin program of throwing arithmetic exception –" }, { "code": null, "e": 1708, "s": 1701, "text": "Kotlin" }, { "code": "fun main(args : Array<String>){ var num = 10 / 0 // throws exception println(num)}", "e": 1802, "s": 1708, "text": null }, { "code": null, "e": 1810, "s": 1802, "text": "Output:" }, { "code": null, "e": 1878, "s": 1810, "text": "Exception in thread \"main\" java.lang.ArithmeticException: / by zero" }, { "code": null, "e": 2068, "s": 1878, "text": "In the above program, we initialize the num variable with value 10/0, but we know in arithmetic divide by zero is not allowed. While we are trying to run the program it throws an exception." }, { "code": null, "e": 2123, "s": 2068, "text": "To solve this problem, we have to use try-catch block." }, { "code": null, "e": 2469, "s": 2123, "text": "In Kotlin, we use try-catch block for exception handling in the program. The try block encloses the code which is responsible for throwing an exception and the catch block is used for handling the exception. This block must be written within the main or other methods. Try block should be followed by either catch block or finally block or both." }, { "code": null, "e": 2498, "s": 2469, "text": "Syntax for try-catch block –" }, { "code": null, "e": 2611, "s": 2498, "text": "try {\n // code that can throw exception\n} catch(e: ExceptionName) {\n // catch the exception and handle it\n}\n" }, { "code": null, "e": 2683, "s": 2611, "text": "Kotlin program of arithmetic exception handling using try-catch block –" }, { "code": null, "e": 2690, "s": 2683, "text": "Kotlin" }, { "code": "import kotlin.ArithmeticException fun main(args : Array<String>){ try{ var num = 10 / 0 } catch(e: ArithmeticException){ // caught and handles it println(\"Divide by zero not allowed\") }}", "e": 2911, "s": 2690, "text": null }, { "code": null, "e": 2919, "s": 2911, "text": "Output:" }, { "code": null, "e": 2946, "s": 2919, "text": "Divide by zero not allowed" }, { "code": null, "e": 3223, "s": 2946, "text": "Explanation:In the above program, we have used try-catch block. The num variable which can throw exception is enclosed within the braces of try block because divide by zero not defined in arithmetic. The exception caught by the catch block and execute the println() statement." }, { "code": null, "e": 3533, "s": 3223, "text": "As we already know, expression always returns a value. We can use kotlin try-catch block as an expression in our program. The value returned by the expression will be either last expression of try block or last expression of catch block. If an exception occurs in the code, then catch block returns the value." }, { "code": null, "e": 3586, "s": 3533, "text": "Kotlin program of using try-catch as an expression –" }, { "code": null, "e": 3593, "s": 3586, "text": "Kotlin" }, { "code": "fun test(a: Int, b: Int) : Any { return try { a/b //println(\"The Result is: \"+ a / b) } catch(e:Exception){ println(e) \"Divide by zero not allowed\" }}// main functionfun main(args: Array<String>) { // invoke test function var result1 = test(10,2 ) //execute try block println(result1) var result = test(10,0 ) // execute catch block println(result)}", "e": 4001, "s": 3593, "text": null }, { "code": null, "e": 4009, "s": 4001, "text": "Output:" }, { "code": null, "e": 4080, "s": 4009, "text": "5\njava.lang.ArithmeticException: / by zero\nDivide by zero not allowed\n" }, { "code": null, "e": 4502, "s": 4080, "text": "In the above code, we have used try-catch as an expression. Declare a function test on the top of program and it return a value using try-catch block. We have invoked the test function from main method and passed the parameter values (10,2) The test function evaluate the arguments and return try value (10/2 = 5). But in next call, we passed (b=0) and this time exception is caught and returns expression of catch block." }, { "code": null, "e": 4753, "s": 4502, "text": "In Kotlin, finally block is always executes irrespective of whether an exception is handled or not by the catch block. So it is used to execute important code statement.We can also use finally block with try block and skip the catch block from there." }, { "code": null, "e": 4794, "s": 4753, "text": "Syntax of finally block with try block –" }, { "code": null, "e": 4876, "s": 4794, "text": "try {\n // code that can throw exception\n} finally {\n // finally block code\n}\n" }, { "code": null, "e": 4937, "s": 4876, "text": "Kotlin program of using finally block with try block block –" }, { "code": null, "e": 4944, "s": 4937, "text": "Kotlin" }, { "code": "fun main(args : Array<String>){ try{ var ar = arrayOf(1,2,3,4,5) var int = ar[6] println(int) } finally { println(\"This block always executes\") }}", "e": 5129, "s": 4944, "text": null }, { "code": null, "e": 5137, "s": 5129, "text": "Output:" }, { "code": null, "e": 5267, "s": 5137, "text": "This block always executesException in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 5" }, { "code": null, "e": 5432, "s": 5267, "text": "In the above program, we have used try with finally block and skipped the catch block. Here, exception is not handled by catch block but executes the finally block." }, { "code": null, "e": 5479, "s": 5432, "text": "Syntax of finally block with try-catch block –" }, { "code": null, "e": 5629, "s": 5479, "text": "try {\n // code that can throw exception\n} catch(e: ExceptionName) {\n // catch the exception and handle it.\n} finally {\n // finally block code\n}\n" }, { "code": null, "e": 5748, "s": 5629, "text": "We can also use try, catch and finally blocks all together.Kotlin program of using finally block with try-catch block-" }, { "code": null, "e": 5755, "s": 5748, "text": "Kotlin" }, { "code": "fun main (args: Array<String>){ try { var int = 10 / 0 println(int) } catch (e: ArithmeticException) { println(e) } finally { println(\"This block always executes\") } } ", "e": 5982, "s": 5755, "text": null }, { "code": null, "e": 5990, "s": 5982, "text": "Output:" }, { "code": null, "e": 6059, "s": 5990, "text": "java.lang.ArithmeticException: / by zero\nThis block always executes\n" }, { "code": null, "e": 6172, "s": 6059, "text": "In Kotlin, we use throw keyword to throw an explicit exception. It can also be used to throw a custom exception." }, { "code": null, "e": 6212, "s": 6172, "text": "Kotlin program of using throw keyword –" }, { "code": null, "e": 6219, "s": 6212, "text": "Kotlin" }, { "code": "fun main(args: Array<String>) { test(\"abcd\") println(\"executes after the validation\")}fun test(password: String) { // calculate length of the entered password and compare if (password.length < 6) throw ArithmeticException(\"Password is too short\") else println(\"Strong password\")}", "e": 6528, "s": 6219, "text": null }, { "code": null, "e": 6536, "s": 6528, "text": "Output:" }, { "code": null, "e": 6616, "s": 6536, "text": "Exception in thread \"main\" java.lang.ArithmeticException: Password is too short" }, { "code": null, "e": 6633, "s": 6616, "text": "ayushpandey3july" }, { "code": null, "e": 6659, "s": 6633, "text": "Kotlin Exception-Handling" }, { "code": null, "e": 6666, "s": 6659, "text": "Kotlin" } ]
Allocating kernel memory (buddy system and slab system)
15 Jul, 2021 Prerequisite – Buddy System Two strategies for managing free memory that is assigned to kernel processes: Buddy allocation system is an algorithm in which a larger memory block is divided into small parts to satisfy the request. This algorithm is used to give best fit. The two smaller parts of block are of equal size and called as buddies. In the same manner one of the two buddies will further divide into smaller parts until the request is fulfilled. Benefit of this technique is that the two buddies can combine to form the block of larger size according to the memory request. Example – If the request of 25Kb is made then block of size 32Kb is allocated. Four Types of Buddy System – Binary buddy systemFibonacci buddy systemWeighted buddy systemTertiary buddy system Binary buddy system Fibonacci buddy system Weighted buddy system Tertiary buddy system Why buddy system? If the partition size and process size are different then poor match occurs and may use space inefficiently. It is easy to implement and efficient then dynamic allocation. Binary buddy system – The buddy system maintains a list of the free blocks of each size (called a free list), so that it is easy to find a block of the desired size, if one is available. If no block of the requested size is available, Allocate searches for the first non-empty list for blocks of atleast the size requested. In either case, a block is removed from the free list. Example – Assume the size of memory segment is initially 256kb and the kernel requests 25kb of memory. The segment is initially divided into two buddies. Let we call A1 and A2 each 128kb in size. One of these buddies is further divided into two 64kb buddies let say B1 and B2. But the next highest power of 25kb is 32kb so, either B1 or B2 is further divided into two 32kb buddies(C1 and C2) and finally one of these buddies is used to satisfy the 25kb request. A split block can only be merged with its unique buddy block, which then reforms the larger block they were split from. Fibonacci buddy system – This is the system in which blocks are divided into sizes which are Fibonacci numbers. It satisfies the following relation: Zi = Z(i-1)+Z(i-2) 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 144, 233, 377, 610. The address calculation for the binary and weighted buddy systems is straight forward, but the original procedure for the Fibonacci buddy system was either limited to a small, fixed number of block sizes or a time consuming computation. Advantages – In comparison to other simpler techniques such as dynamic allocation, the buddy memory system has little external fragmentation. The buddy memory allocation system is implemented with the use of a binary tree to represent used or unused split memory blocks. The buddy system is very fast to allocate or deallocate memory. In buddy systems, the cost to allocate and free a block of memory is low compared to that of best-fit or first-fit algorithms. Other advantage is coalescing. Address calculation is easy. What is coalescing? It is defined as how quickly adjacent buddies can be combined to form larger segments this is known as coalescing. For example, when the kernel releases the C1 unit it was allocated, the system can coalesce C1 and C2 into a 64kb segment. This segment B1 can in turn be coalesced with its buddy B2 to form a 128kb segment. Ultimately we can end up with the original 256kb segment. Drawback – The main drawback in buddy system is internal fragmentation as larger block of memory is acquired then required. For example if a 36 kb request is made then it can only be satisfied by 64 kb segment and remaining memory is wasted. A second strategy for allocating kernel memory is known as slab allocation. It eliminates fragmentation caused by allocations and deallocations. This method is used to retain allocated memory that contains a data object of a certain type for reuse upon subsequent allocations of objects of the same type. In slab allocation memory chunks suitable to fit data objects of certain type or size are preallocated. Cache does not free the space immediately after use although it keeps track of data which are required frequently so that whenever request is made the data will reach very fast. Two terms required are: Slab – A slab is made up of one or more physically contiguous pages. The slab is the actual container of data associated with objects of the specific kind of the containing cache. Cache – Cache represents a small amount of very fast memory. A cache consists of one or more slabs. There is a single cache for each unique kernel data structure. Example – A separate cache for a data structure representing processes descriptors Separate cache for file objects Separate cache for semaphores etc. Each cache is populated with objects that are instantiations of the kernel data structure the cache represents. For example the cache representing semaphores stores instances of semaphore objects, the cache representing process descriptors stores instances of process descriptor objects. Implementation – The slab allocation algorithm uses caches to store kernel objects. When a cache is created a number of objects which are initially marked as free are allocated to the cache. The number of objects in the cache depends on size of the associated slab. Example – A 12 kb slab (made up of three contiguous 4 kb pages) could store six 2 kb objects. Initially all objects in the cache are marked as free. When a new object for a kernel data structure is needed, the allocator can assign any free object from the cache to satisfy the request. The object assigned from the cache is marked as used. In linux, a slab may in one of three possible states: Full – All objects in the slab are marked as usedEmpty – All objects in the slab are marked as freePartial – The slab consists of both Full – All objects in the slab are marked as used Empty – All objects in the slab are marked as free Partial – The slab consists of both The slab allocator first attempts to satisfy the request with a free object in a partial slab. If none exists, a free object is assigned from an empty slab. If no empty slabs are available, a new slab is allocated from contiguous physical pages and assigned to a cache. Benefits of slab allocator – No memory is wasted due to fragmentation because each unique kernel data structure has an associated cache. Memory request can be satisfied quickly. The slab allocating scheme is particularly effective for managing when objects are frequently allocated or deallocated. The act of allocating and releasing memory can be a time consuming process. However, objects are created in advance and thus can be quickly allocated from the cache. When the kernel has finished with an object and releases it, it is marked as free and return to its cache, thus making it immediately available for subsequent request from the kernel. gabaa406 ruhelaa48 GATE CS Operating Systems Technical Scripter Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Three address code in Compiler Difference between Clustered and Non-clustered index Introduction of Process Synchronization Differences between IPv4 and IPv6 Phases of a Compiler Banker's Algorithm in Operating System Disk Scheduling Algorithms Introduction of Deadlock in Operating System File Allocation Methods Paging in Operating System
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jul, 2021" }, { "code": null, "e": 83, "s": 54, "text": "Prerequisite – Buddy System " }, { "code": null, "e": 161, "s": 83, "text": "Two strategies for managing free memory that is assigned to kernel processes:" }, { "code": null, "e": 639, "s": 161, "text": "Buddy allocation system is an algorithm in which a larger memory block is divided into small parts to satisfy the request. This algorithm is used to give best fit. The two smaller parts of block are of equal size and called as buddies. In the same manner one of the two buddies will further divide into smaller parts until the request is fulfilled. Benefit of this technique is that the two buddies can combine to form the block of larger size according to the memory request. " }, { "code": null, "e": 719, "s": 639, "text": "Example – If the request of 25Kb is made then block of size 32Kb is allocated. " }, { "code": null, "e": 749, "s": 719, "text": "Four Types of Buddy System – " }, { "code": null, "e": 833, "s": 749, "text": "Binary buddy systemFibonacci buddy systemWeighted buddy systemTertiary buddy system" }, { "code": null, "e": 853, "s": 833, "text": "Binary buddy system" }, { "code": null, "e": 876, "s": 853, "text": "Fibonacci buddy system" }, { "code": null, "e": 898, "s": 876, "text": "Weighted buddy system" }, { "code": null, "e": 920, "s": 898, "text": "Tertiary buddy system" }, { "code": null, "e": 1111, "s": 920, "text": "Why buddy system? If the partition size and process size are different then poor match occurs and may use space inefficiently. It is easy to implement and efficient then dynamic allocation. " }, { "code": null, "e": 1491, "s": 1111, "text": "Binary buddy system – The buddy system maintains a list of the free blocks of each size (called a free list), so that it is easy to find a block of the desired size, if one is available. If no block of the requested size is available, Allocate searches for the first non-empty list for blocks of atleast the size requested. In either case, a block is removed from the free list. " }, { "code": null, "e": 2074, "s": 1491, "text": "Example – Assume the size of memory segment is initially 256kb and the kernel requests 25kb of memory. The segment is initially divided into two buddies. Let we call A1 and A2 each 128kb in size. One of these buddies is further divided into two 64kb buddies let say B1 and B2. But the next highest power of 25kb is 32kb so, either B1 or B2 is further divided into two 32kb buddies(C1 and C2) and finally one of these buddies is used to satisfy the 25kb request. A split block can only be merged with its unique buddy block, which then reforms the larger block they were split from. " }, { "code": null, "e": 2224, "s": 2074, "text": "Fibonacci buddy system – This is the system in which blocks are divided into sizes which are Fibonacci numbers. It satisfies the following relation: " }, { "code": null, "e": 2245, "s": 2224, "text": " Zi = Z(i-1)+Z(i-2)" }, { "code": null, "e": 2540, "s": 2245, "text": "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 144, 233, 377, 610. The address calculation for the binary and weighted buddy systems is straight forward, but the original procedure for the Fibonacci buddy system was either limited to a small, fixed number of block sizes or a time consuming computation. " }, { "code": null, "e": 2554, "s": 2540, "text": "Advantages – " }, { "code": null, "e": 2683, "s": 2554, "text": "In comparison to other simpler techniques such as dynamic allocation, the buddy memory system has little external fragmentation." }, { "code": null, "e": 2812, "s": 2683, "text": "The buddy memory allocation system is implemented with the use of a binary tree to represent used or unused split memory blocks." }, { "code": null, "e": 2876, "s": 2812, "text": "The buddy system is very fast to allocate or deallocate memory." }, { "code": null, "e": 3003, "s": 2876, "text": "In buddy systems, the cost to allocate and free a block of memory is low compared to that of best-fit or first-fit algorithms." }, { "code": null, "e": 3034, "s": 3003, "text": "Other advantage is coalescing." }, { "code": null, "e": 3063, "s": 3034, "text": "Address calculation is easy." }, { "code": null, "e": 3464, "s": 3063, "text": "What is coalescing? It is defined as how quickly adjacent buddies can be combined to form larger segments this is known as coalescing. For example, when the kernel releases the C1 unit it was allocated, the system can coalesce C1 and C2 into a 64kb segment. This segment B1 can in turn be coalesced with its buddy B2 to form a 128kb segment. Ultimately we can end up with the original 256kb segment. " }, { "code": null, "e": 3707, "s": 3464, "text": "Drawback – The main drawback in buddy system is internal fragmentation as larger block of memory is acquired then required. For example if a 36 kb request is made then it can only be satisfied by 64 kb segment and remaining memory is wasted. " }, { "code": null, "e": 4320, "s": 3707, "text": "A second strategy for allocating kernel memory is known as slab allocation. It eliminates fragmentation caused by allocations and deallocations. This method is used to retain allocated memory that contains a data object of a certain type for reuse upon subsequent allocations of objects of the same type. In slab allocation memory chunks suitable to fit data objects of certain type or size are preallocated. Cache does not free the space immediately after use although it keeps track of data which are required frequently so that whenever request is made the data will reach very fast. Two terms required are: " }, { "code": null, "e": 4500, "s": 4320, "text": "Slab – A slab is made up of one or more physically contiguous pages. The slab is the actual container of data associated with objects of the specific kind of the containing cache." }, { "code": null, "e": 4663, "s": 4500, "text": "Cache – Cache represents a small amount of very fast memory. A cache consists of one or more slabs. There is a single cache for each unique kernel data structure." }, { "code": null, "e": 4675, "s": 4663, "text": "Example – " }, { "code": null, "e": 4748, "s": 4675, "text": "A separate cache for a data structure representing processes descriptors" }, { "code": null, "e": 4780, "s": 4748, "text": "Separate cache for file objects" }, { "code": null, "e": 4815, "s": 4780, "text": "Separate cache for semaphores etc." }, { "code": null, "e": 5104, "s": 4815, "text": "Each cache is populated with objects that are instantiations of the kernel data structure the cache represents. For example the cache representing semaphores stores instances of semaphore objects, the cache representing process descriptors stores instances of process descriptor objects. " }, { "code": null, "e": 5711, "s": 5104, "text": "Implementation – The slab allocation algorithm uses caches to store kernel objects. When a cache is created a number of objects which are initially marked as free are allocated to the cache. The number of objects in the cache depends on size of the associated slab. Example – A 12 kb slab (made up of three contiguous 4 kb pages) could store six 2 kb objects. Initially all objects in the cache are marked as free. When a new object for a kernel data structure is needed, the allocator can assign any free object from the cache to satisfy the request. The object assigned from the cache is marked as used. " }, { "code": null, "e": 5767, "s": 5711, "text": "In linux, a slab may in one of three possible states: " }, { "code": null, "e": 5902, "s": 5767, "text": "Full – All objects in the slab are marked as usedEmpty – All objects in the slab are marked as freePartial – The slab consists of both" }, { "code": null, "e": 5952, "s": 5902, "text": "Full – All objects in the slab are marked as used" }, { "code": null, "e": 6003, "s": 5952, "text": "Empty – All objects in the slab are marked as free" }, { "code": null, "e": 6039, "s": 6003, "text": "Partial – The slab consists of both" }, { "code": null, "e": 6310, "s": 6039, "text": "The slab allocator first attempts to satisfy the request with a free object in a partial slab. If none exists, a free object is assigned from an empty slab. If no empty slabs are available, a new slab is allocated from contiguous physical pages and assigned to a cache. " }, { "code": null, "e": 6340, "s": 6310, "text": "Benefits of slab allocator – " }, { "code": null, "e": 6448, "s": 6340, "text": "No memory is wasted due to fragmentation because each unique kernel data structure has an associated cache." }, { "code": null, "e": 6489, "s": 6448, "text": "Memory request can be satisfied quickly." }, { "code": null, "e": 6959, "s": 6489, "text": "The slab allocating scheme is particularly effective for managing when objects are frequently allocated or deallocated. The act of allocating and releasing memory can be a time consuming process. However, objects are created in advance and thus can be quickly allocated from the cache. When the kernel has finished with an object and releases it, it is marked as free and return to its cache, thus making it immediately available for subsequent request from the kernel." }, { "code": null, "e": 6968, "s": 6959, "text": "gabaa406" }, { "code": null, "e": 6978, "s": 6968, "text": "ruhelaa48" }, { "code": null, "e": 6986, "s": 6978, "text": "GATE CS" }, { "code": null, "e": 7004, "s": 6986, "text": "Operating Systems" }, { "code": null, "e": 7023, "s": 7004, "text": "Technical Scripter" }, { "code": null, "e": 7041, "s": 7023, "text": "Operating Systems" }, { "code": null, "e": 7139, "s": 7041, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7170, "s": 7139, "text": "Three address code in Compiler" }, { "code": null, "e": 7223, "s": 7170, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 7263, "s": 7223, "text": "Introduction of Process Synchronization" }, { "code": null, "e": 7297, "s": 7263, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 7318, "s": 7297, "text": "Phases of a Compiler" }, { "code": null, "e": 7357, "s": 7318, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 7384, "s": 7357, "text": "Disk Scheduling Algorithms" }, { "code": null, "e": 7429, "s": 7384, "text": "Introduction of Deadlock in Operating System" }, { "code": null, "e": 7453, "s": 7429, "text": "File Allocation Methods" } ]
Patience Sorting
19 Jul, 2021 Patience sorting is a sorting algorithm based on card game Patience. In this sorting algorithm the rules of patience game is used to sort an list of elements based on their values.Rules of Patience Game: Cards with lower value can be placed over the card. If there is no possible position for a card, then a new pile can be created. Goal is to form as much as few piles possible. Below is the visualization of the game as follows: As in the above visualization, It’s clear that cards are only placed when the value of them is less than the highest card of the pile. Otherwise, If there is no such pile then create a new one.Patience Sorting: There are generally two steps in the patience sorting that is creation of the piles and merging the piles. Below is the illustration of the steps: Initialize a 2D array to store the piles. Traverse the given array and perform the following operations: Iterate over all the piles and check the top of the stack of each pile is less than the current element or not. IF found to be true, then push the current element to the top of the stack.Otherwise, create a new pile with the current element as the top of that stack. Iterate over all the piles and check the top of the stack of each pile is less than the current element or not. IF found to be true, then push the current element to the top of the stack.Otherwise, create a new pile with the current element as the top of that stack. Iterate over all the piles and check the top of the stack of each pile is less than the current element or not. IF found to be true, then push the current element to the top of the stack. Otherwise, create a new pile with the current element as the top of that stack. Merge the Piles:The idea is to perform a k-way merge of the p piles, each of which is internally sorted. Iterate over all the piles while count of elements in the pile is greater than or equal to 0 and find the minimum element from the top of each stack and push it into the sorted array. Below is the visualization of the sorting steps: Below is the implementation of the above approach: C++ Javascript // C++ program of the above approach #include <bits/stdc++.h>using namespace std; // Function to merge piles in a sorted ordervector<int> merge_piles(vector<vector<int> >& v){ // Store minimum element from // the top of stack vector<int> ans; // In every iteration find the smallest element // of top of pile and remove it from the piles // and store into the final array while (1) { // Stores the smallest element // of the top of the piles int minu = INT_MAX; // Stores index of the smallest element // of the top of the piles int index = -1; // Calculate the smallest element // of the top of the every stack for (int i = 0; i < v.size(); i++) { // If minu is greater than // the top of the current stack if (minu > v[i][v[i].size() - 1]) { // Update minu minu = v[i][v[i].size() - 1]; // Update index index = i; } } // Insert the smallest element // of the top of the stack ans.push_back(minu); // Remove the top element from // the current pile v[index].pop_back(); // If current pile is empty if (v[index].empty()) { // Remove current pile // from all piles v.erase(v.begin() + index); } // If all the piles are empty if (v.size() == 0) break; } return ans;} // Function to sort the given array// using the patience sortingvector<int> patienceSorting(vector<int> arr){ // Store all the created piles vector<vector<int> > piles; // Traverse the array for (int i = 0; i < arr.size(); i++) { // If no piles are created if (piles.empty()) { // Initialize a new pile vector<int> temp; // Insert current element // into the pile temp.push_back(arr[i]); // Insert current pile into // all the piles piles.push_back(temp); } else { // Check if top element of each pile // is less than or equal to // current element or not int flag = 1; // Traverse all the piles for (int j = 0; j < piles.size(); j++) { // Check if the element to be // inserted is less than // current pile's top if (arr[i] < piles[j][piles[j].size() - 1]) { piles[j].push_back(arr[i]); // Update flag flag = 0; break; } } // If flag is true if (flag) { // Create a new pile vector<int> temp; // Insert current element // into temp temp.push_back(arr[i]); // Insert current pile // into all the piles piles.push_back(temp); } } } // Store the sorted sequence // of the given array vector<int> ans; // Sort the given array ans = merge_piles(piles); // Traverse the array, ans[] for (int i = 0; i < ans.size(); i++) cout << ans[i] << " "; return ans;} // Driver Codeint main(){ vector<int> arr = { 6, 12, 2, 8, 3, 7 }; // Function Call patienceSorting(arr);} <script>// Javascript program of the above approach // Function to merge piles in a sorted orderfunction merge_piles(v) { // Store minimum element from // the top of stack let ans = []; // In every iteration find the smallest element // of top of pile and remove it from the piles // and store into the final array while (1) { // Stores the smallest element // of the top of the piles let minu = Number.MAX_SAFE_INTEGER; // Stores index of the smallest element // of the top of the piles let index = -1; // Calculate the smallest element // of the top of the every stack for (let i = 0; i < v.length; i++) { // If minu is greater than // the top of the current stack if (minu > v[i][v[i].length - 1]) { // Update minu minu = v[i][v[i].length - 1]; // Update index index = i; } } // Insert the smallest element // of the top of the stack ans.push(minu); // Remove the top element from // the current pile v[index].pop(); // If current pile is empty if (v[index].length == 0) { // Remove current pile // from all piles v.splice(index, 1); } // If all the piles are empty if (v.length == 0) break; } return ans;} // Function to sort the given array// using the patience sortingfunction patienceSorting(arr) { // Store all the created piles let piles = []; // Traverse the array for (let i = 0; i < arr.length; i++) { // If no piles are created if (piles.length == 0) { // Initialize a new pile let temp = []; // Insert current element // into the pile temp.push(arr[i]); // Insert current pile into // all the piles piles.push(temp); } else { // Check if top element of each pile // is less than or equal to // current element or not let flag = 1; // Traverse all the piles for (let j = 0; j < piles.length; j++) { // Check if the element to be // inserted is less than // current pile's top if (arr[i] < piles[j][piles[j].length - 1]) { piles[j].push(arr[i]); // Update flag flag = 0; break; } } // If flag is true if (flag) { // Create a new pile let temp = []; // Insert current element // into temp temp.push(arr[i]); // Insert current pile // into all the piles piles.push(temp); } } } // Store the sorted sequence // of the given array let ans = []; // Sort the given array ans = merge_piles(piles); // Traverse the array, ans[] for (let i = 0; i < ans.length; i++) document.write(ans[i] + " "); return ans;} // Driver Code let arr = [6, 12, 2, 8, 3, 7]; // Function CallpatienceSorting(arr); // This code is contributed by _saurabh_jaiswal.</script> 2 3 6 7 8 12 Time Complexity: O(N2) Auxiliary Space: O(N) Note: The above approach can be optimized by merging of piles using priority_queue. Time Complexity: O(N * log(N)) Auxiliary Space: O(N) </br>function playGif(){ </br> var gif = document.getElementById(‘gif’); </br> if (gif.src == “https://media.geeksforgeeks.org/wp-content/uploads/20200501171647/Patience.gif”){ </br> gif.src = “https://media.geeksforgeeks.org/wp-content/uploads/20200501175532/base2.jpg”; </br> }else{ </br> gif.src = “https://media.geeksforgeeks.org/wp-content/uploads/20200501171647/Patience.gif”; </br> } </br>} </br>function playSortingGif(){ </br> var gif1 = document.getElementById(‘sorting’); </br> var gif2 = document.getElementById(‘sorting_gif1’); </br> gif1.style.display = “none”; </br> gif2.style.display = “block”; </br>}</br>function pauseSortingGif(){ </br> var gif1 = document.getElementById(‘sorting’); </br> var gif2 = document.getElementById(‘sorting_gif1’); </br> gif1.style.display = “block”; </br> gif2.style.display = “none”; </br>} </br> _saurabh_jaiswal Algorithms Greedy Sorting Greedy Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Jul, 2021" }, { "code": null, "e": 258, "s": 52, "text": "Patience sorting is a sorting algorithm based on card game Patience. In this sorting algorithm the rules of patience game is used to sort an list of elements based on their values.Rules of Patience Game: " }, { "code": null, "e": 310, "s": 258, "text": "Cards with lower value can be placed over the card." }, { "code": null, "e": 387, "s": 310, "text": "If there is no possible position for a card, then a new pile can be created." }, { "code": null, "e": 434, "s": 387, "text": "Goal is to form as much as few piles possible." }, { "code": null, "e": 487, "s": 434, "text": "Below is the visualization of the game as follows: " }, { "code": null, "e": 847, "s": 487, "text": "As in the above visualization, It’s clear that cards are only placed when the value of them is less than the highest card of the pile. Otherwise, If there is no such pile then create a new one.Patience Sorting: There are generally two steps in the patience sorting that is creation of the piles and merging the piles. Below is the illustration of the steps: " }, { "code": null, "e": 889, "s": 847, "text": "Initialize a 2D array to store the piles." }, { "code": null, "e": 1219, "s": 889, "text": "Traverse the given array and perform the following operations: Iterate over all the piles and check the top of the stack of each pile is less than the current element or not. IF found to be true, then push the current element to the top of the stack.Otherwise, create a new pile with the current element as the top of that stack." }, { "code": null, "e": 1486, "s": 1219, "text": "Iterate over all the piles and check the top of the stack of each pile is less than the current element or not. IF found to be true, then push the current element to the top of the stack.Otherwise, create a new pile with the current element as the top of that stack." }, { "code": null, "e": 1674, "s": 1486, "text": "Iterate over all the piles and check the top of the stack of each pile is less than the current element or not. IF found to be true, then push the current element to the top of the stack." }, { "code": null, "e": 1754, "s": 1674, "text": "Otherwise, create a new pile with the current element as the top of that stack." }, { "code": null, "e": 2043, "s": 1754, "text": "Merge the Piles:The idea is to perform a k-way merge of the p piles, each of which is internally sorted. Iterate over all the piles while count of elements in the pile is greater than or equal to 0 and find the minimum element from the top of each stack and push it into the sorted array." }, { "code": null, "e": 2094, "s": 2043, "text": "Below is the visualization of the sorting steps: " }, { "code": null, "e": 2146, "s": 2094, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2150, "s": 2146, "text": "C++" }, { "code": null, "e": 2161, "s": 2150, "text": "Javascript" }, { "code": "// C++ program of the above approach #include <bits/stdc++.h>using namespace std; // Function to merge piles in a sorted ordervector<int> merge_piles(vector<vector<int> >& v){ // Store minimum element from // the top of stack vector<int> ans; // In every iteration find the smallest element // of top of pile and remove it from the piles // and store into the final array while (1) { // Stores the smallest element // of the top of the piles int minu = INT_MAX; // Stores index of the smallest element // of the top of the piles int index = -1; // Calculate the smallest element // of the top of the every stack for (int i = 0; i < v.size(); i++) { // If minu is greater than // the top of the current stack if (minu > v[i][v[i].size() - 1]) { // Update minu minu = v[i][v[i].size() - 1]; // Update index index = i; } } // Insert the smallest element // of the top of the stack ans.push_back(minu); // Remove the top element from // the current pile v[index].pop_back(); // If current pile is empty if (v[index].empty()) { // Remove current pile // from all piles v.erase(v.begin() + index); } // If all the piles are empty if (v.size() == 0) break; } return ans;} // Function to sort the given array// using the patience sortingvector<int> patienceSorting(vector<int> arr){ // Store all the created piles vector<vector<int> > piles; // Traverse the array for (int i = 0; i < arr.size(); i++) { // If no piles are created if (piles.empty()) { // Initialize a new pile vector<int> temp; // Insert current element // into the pile temp.push_back(arr[i]); // Insert current pile into // all the piles piles.push_back(temp); } else { // Check if top element of each pile // is less than or equal to // current element or not int flag = 1; // Traverse all the piles for (int j = 0; j < piles.size(); j++) { // Check if the element to be // inserted is less than // current pile's top if (arr[i] < piles[j][piles[j].size() - 1]) { piles[j].push_back(arr[i]); // Update flag flag = 0; break; } } // If flag is true if (flag) { // Create a new pile vector<int> temp; // Insert current element // into temp temp.push_back(arr[i]); // Insert current pile // into all the piles piles.push_back(temp); } } } // Store the sorted sequence // of the given array vector<int> ans; // Sort the given array ans = merge_piles(piles); // Traverse the array, ans[] for (int i = 0; i < ans.size(); i++) cout << ans[i] << \" \"; return ans;} // Driver Codeint main(){ vector<int> arr = { 6, 12, 2, 8, 3, 7 }; // Function Call patienceSorting(arr);}", "e": 5597, "s": 2161, "text": null }, { "code": "<script>// Javascript program of the above approach // Function to merge piles in a sorted orderfunction merge_piles(v) { // Store minimum element from // the top of stack let ans = []; // In every iteration find the smallest element // of top of pile and remove it from the piles // and store into the final array while (1) { // Stores the smallest element // of the top of the piles let minu = Number.MAX_SAFE_INTEGER; // Stores index of the smallest element // of the top of the piles let index = -1; // Calculate the smallest element // of the top of the every stack for (let i = 0; i < v.length; i++) { // If minu is greater than // the top of the current stack if (minu > v[i][v[i].length - 1]) { // Update minu minu = v[i][v[i].length - 1]; // Update index index = i; } } // Insert the smallest element // of the top of the stack ans.push(minu); // Remove the top element from // the current pile v[index].pop(); // If current pile is empty if (v[index].length == 0) { // Remove current pile // from all piles v.splice(index, 1); } // If all the piles are empty if (v.length == 0) break; } return ans;} // Function to sort the given array// using the patience sortingfunction patienceSorting(arr) { // Store all the created piles let piles = []; // Traverse the array for (let i = 0; i < arr.length; i++) { // If no piles are created if (piles.length == 0) { // Initialize a new pile let temp = []; // Insert current element // into the pile temp.push(arr[i]); // Insert current pile into // all the piles piles.push(temp); } else { // Check if top element of each pile // is less than or equal to // current element or not let flag = 1; // Traverse all the piles for (let j = 0; j < piles.length; j++) { // Check if the element to be // inserted is less than // current pile's top if (arr[i] < piles[j][piles[j].length - 1]) { piles[j].push(arr[i]); // Update flag flag = 0; break; } } // If flag is true if (flag) { // Create a new pile let temp = []; // Insert current element // into temp temp.push(arr[i]); // Insert current pile // into all the piles piles.push(temp); } } } // Store the sorted sequence // of the given array let ans = []; // Sort the given array ans = merge_piles(piles); // Traverse the array, ans[] for (let i = 0; i < ans.length; i++) document.write(ans[i] + \" \"); return ans;} // Driver Code let arr = [6, 12, 2, 8, 3, 7]; // Function CallpatienceSorting(arr); // This code is contributed by _saurabh_jaiswal.</script>", "e": 8954, "s": 5597, "text": null }, { "code": null, "e": 8967, "s": 8954, "text": "2 3 6 7 8 12" }, { "code": null, "e": 9014, "s": 8969, "text": "Time Complexity: O(N2) Auxiliary Space: O(N)" }, { "code": null, "e": 9151, "s": 9014, "text": "Note: The above approach can be optimized by merging of piles using priority_queue. Time Complexity: O(N * log(N)) Auxiliary Space: O(N)" }, { "code": null, "e": 9998, "s": 9151, "text": "</br>function playGif(){ </br> var gif = document.getElementById(‘gif’); </br> if (gif.src == “https://media.geeksforgeeks.org/wp-content/uploads/20200501171647/Patience.gif”){ </br> gif.src = “https://media.geeksforgeeks.org/wp-content/uploads/20200501175532/base2.jpg”; </br> }else{ </br> gif.src = “https://media.geeksforgeeks.org/wp-content/uploads/20200501171647/Patience.gif”; </br> } </br>} </br>function playSortingGif(){ </br> var gif1 = document.getElementById(‘sorting’); </br> var gif2 = document.getElementById(‘sorting_gif1’); </br> gif1.style.display = “none”; </br> gif2.style.display = “block”; </br>}</br>function pauseSortingGif(){ </br> var gif1 = document.getElementById(‘sorting’); </br> var gif2 = document.getElementById(‘sorting_gif1’); </br> gif1.style.display = “block”; </br> gif2.style.display = “none”; </br>} </br> " }, { "code": null, "e": 10015, "s": 9998, "text": "_saurabh_jaiswal" }, { "code": null, "e": 10026, "s": 10015, "text": "Algorithms" }, { "code": null, "e": 10033, "s": 10026, "text": "Greedy" }, { "code": null, "e": 10041, "s": 10033, "text": "Sorting" }, { "code": null, "e": 10048, "s": 10041, "text": "Greedy" }, { "code": null, "e": 10056, "s": 10048, "text": "Sorting" }, { "code": null, "e": 10067, "s": 10056, "text": "Algorithms" } ]
Python | Split on last occurrence of delimiter
25 Jun, 2022 The splitting of strings has always been discussed in various applications and use cases. One of the interesting variations of list splitting can be splitting the list on delimiter but this time only on the last occurrence of it. Let’s discuss certain ways in which this can be done. Method #1: Using rsplit(str, 1) The normal string split can perform the split from the front, but Python also offers another method that can perform this very task from the rear end, hence increasing the versatility of applications. Python3 # Python3 code to demonstrate# Split on last occurrence of delimiter# using rsplit() # initializing stringtest_string = "gfg, is, good, better, and best" # printing original stringprint("The original string : " + str(test_string)) # using rsplit()# Split on last occurrence of delimiterres = test_string.rsplit(', ', 1) # print resultprint("The splitted list at the last comma : " + str(res)) The original string : gfg, is, good, better, and best The splitted list at the last comma : ['gfg, is, good, better', 'and best'] Method #2: Using rpartition() This function can also perform the desired reverse partition, but the drawbacks to using this is the construction of additional delimiter value and also the speed is slower than the above method and hence not recommended. Python3 # Python3 code to demonstrate# Split on last occurrence of delimiter# using rpartition() # initializing stringtest_string = "gfg, is, good, better, and best" # printing original stringprint("The original string : " + str(test_string)) # using rpartition()# Split on last occurrence of delimiterres = test_string.rpartition(', ') # print resultprint("The splitted list at the last comma : " + str(res)) The original string : gfg, is, good, better, and best The splitted list at the last comma : ('gfg, is, good, better', ', ', 'and best') Method #3 : Using split() and replace() methods. Python3 # Python3 code to demonstrate# Split on last occurrence of delimiter # initializing stringtest_string = "gfg, is, good, better, and best" # printing original stringprint("The original string : " + str(test_string)) # Split on last occurrence of delimiterp=test_string.count(",")c=0new=""for i in test_string: if(i=="," and c<p-1): new+="*" c+=1 else: new+=ix=new.split(",") x[0]=x[0].replace("*",",") # print resultprint("The splitted list at the last comma : " + str(x)) The original string : gfg, is, good, better, and best The splitted list at the last comma : ['gfg, is, good, better', ' and best'] kogantibhavya Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2022" }, { "code": null, "e": 312, "s": 28, "text": "The splitting of strings has always been discussed in various applications and use cases. One of the interesting variations of list splitting can be splitting the list on delimiter but this time only on the last occurrence of it. Let’s discuss certain ways in which this can be done." }, { "code": null, "e": 546, "s": 312, "text": "Method #1: Using rsplit(str, 1) The normal string split can perform the split from the front, but Python also offers another method that can perform this very task from the rear end, hence increasing the versatility of applications. " }, { "code": null, "e": 554, "s": 546, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Split on last occurrence of delimiter# using rsplit() # initializing stringtest_string = \"gfg, is, good, better, and best\" # printing original stringprint(\"The original string : \" + str(test_string)) # using rsplit()# Split on last occurrence of delimiterres = test_string.rsplit(', ', 1) # print resultprint(\"The splitted list at the last comma : \" + str(res))", "e": 947, "s": 554, "text": null }, { "code": null, "e": 1077, "s": 947, "text": "The original string : gfg, is, good, better, and best\nThe splitted list at the last comma : ['gfg, is, good, better', 'and best']" }, { "code": null, "e": 1332, "s": 1077, "text": " Method #2: Using rpartition() This function can also perform the desired reverse partition, but the drawbacks to using this is the construction of additional delimiter value and also the speed is slower than the above method and hence not recommended. " }, { "code": null, "e": 1340, "s": 1332, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Split on last occurrence of delimiter# using rpartition() # initializing stringtest_string = \"gfg, is, good, better, and best\" # printing original stringprint(\"The original string : \" + str(test_string)) # using rpartition()# Split on last occurrence of delimiterres = test_string.rpartition(', ') # print resultprint(\"The splitted list at the last comma : \" + str(res))", "e": 1742, "s": 1340, "text": null }, { "code": null, "e": 1878, "s": 1742, "text": "The original string : gfg, is, good, better, and best\nThe splitted list at the last comma : ('gfg, is, good, better', ', ', 'and best')" }, { "code": null, "e": 1927, "s": 1878, "text": "Method #3 : Using split() and replace() methods." }, { "code": null, "e": 1935, "s": 1927, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Split on last occurrence of delimiter # initializing stringtest_string = \"gfg, is, good, better, and best\" # printing original stringprint(\"The original string : \" + str(test_string)) # Split on last occurrence of delimiterp=test_string.count(\",\")c=0new=\"\"for i in test_string: if(i==\",\" and c<p-1): new+=\"*\" c+=1 else: new+=ix=new.split(\",\") x[0]=x[0].replace(\"*\",\",\") # print resultprint(\"The splitted list at the last comma : \" + str(x))", "e": 2437, "s": 1935, "text": null }, { "code": null, "e": 2568, "s": 2437, "text": "The original string : gfg, is, good, better, and best\nThe splitted list at the last comma : ['gfg, is, good, better', ' and best']" }, { "code": null, "e": 2582, "s": 2568, "text": "kogantibhavya" }, { "code": null, "e": 2605, "s": 2582, "text": "Python string-programs" }, { "code": null, "e": 2612, "s": 2605, "text": "Python" }, { "code": null, "e": 2628, "s": 2612, "text": "Python Programs" } ]
Serialize and Deserialize array of string
15 Jul, 2017 We have given an array of string and we have to serialize the array of string and deserialize the serialized string.Examples: Input : "geeks", "are", "awesome" Output : Serialized String : 5~geeks3~are7~awesome Deserialized String : geeks are awesome Input : "hello", "guys", "whats", "up!!!" Output : Serialized String : 5~hello4~guys5~whats5~up!!! Deserialized String : hello guys whats up!!! Serialization : Scan each element in a string, calculate its length and append it with a string and a element separator or deliminator (that deliminator should not be present in the string). We append the length of the string so that we know the length of each element. Deserialized Function : Find the position of the deliminator, then from the position + 1 to length of word we store it in an array as a single element. // CPP program to serialize and// deserialize the array of string #include<iostream> using namespace std; // Function to serialized the array of stringstring serialize(string str[], int ln){ string temp = ""; for (int i=0; i<ln; i++) { int ln = str[i].length(); temp.push_back('0' + ln); temp = temp + "~" + str[i]; } return temp;} // Function to deserialize the stringvoid deserialized(string str, string deserialize[], int ln){ int len, pos=0; string temp = ""; int i = 0; while(pos>-1) { pos = str.find("~", pos+1); if(pos>0) { len = str[pos-1] - 48; temp.append(str, pos+1, len); deserialize[i++] = temp; temp = ""; } }} // Driver functionint main(){ string str[] = {"geeks", "are", "awesome"}; int ln = sizeof(str)/sizeof(str[0]); string serializedstr = serialize(str, ln); cout << "Serialized String : " << serializedstr <<endl; string deserialize[ln]; deserialized(serializedstr,deserialize,ln); cout << "Deserialized String : "; for(int i=0; i<ln; i++) cout << deserialize[i] << " "; return 0;} Output: Serialized String : 5~geeks3~are7~awesome Deserialized String : geeks are awesome References :1. https://stackoverflow.com/questions/13271503/converting-array-string-to-string-and-back-in-java2. https://www.careercup.com/question?id=5684077627703296 This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Search, insert and delete in an unsorted array Window Sliding Technique Chocolate Distribution Problem Move all negative numbers to beginning and positive to end with constant extra space Find duplicates in O(n) time and O(1) extra space | Set 1 Next Greater Element Longest Consecutive Subsequence Count pairs with given sum What is Data Structure: Types, Classifications and Applications
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jul, 2017" }, { "code": null, "e": 178, "s": 52, "text": "We have given an array of string and we have to serialize the array of string and deserialize the serialized string.Examples:" }, { "code": null, "e": 469, "s": 178, "text": "Input : \"geeks\", \"are\", \"awesome\"\nOutput : Serialized String : 5~geeks3~are7~awesome\n Deserialized String : geeks are awesome\n\nInput : \"hello\", \"guys\", \"whats\", \"up!!!\"\nOutput : Serialized String : 5~hello4~guys5~whats5~up!!!\n Deserialized String : hello guys whats up!!!\n" }, { "code": null, "e": 739, "s": 469, "text": "Serialization : Scan each element in a string, calculate its length and append it with a string and a element separator or deliminator (that deliminator should not be present in the string). We append the length of the string so that we know the length of each element." }, { "code": null, "e": 891, "s": 739, "text": "Deserialized Function : Find the position of the deliminator, then from the position + 1 to length of word we store it in an array as a single element." }, { "code": "// CPP program to serialize and// deserialize the array of string #include<iostream> using namespace std; // Function to serialized the array of stringstring serialize(string str[], int ln){ string temp = \"\"; for (int i=0; i<ln; i++) { int ln = str[i].length(); temp.push_back('0' + ln); temp = temp + \"~\" + str[i]; } return temp;} // Function to deserialize the stringvoid deserialized(string str, string deserialize[], int ln){ int len, pos=0; string temp = \"\"; int i = 0; while(pos>-1) { pos = str.find(\"~\", pos+1); if(pos>0) { len = str[pos-1] - 48; temp.append(str, pos+1, len); deserialize[i++] = temp; temp = \"\"; } }} // Driver functionint main(){ string str[] = {\"geeks\", \"are\", \"awesome\"}; int ln = sizeof(str)/sizeof(str[0]); string serializedstr = serialize(str, ln); cout << \"Serialized String : \" << serializedstr <<endl; string deserialize[ln]; deserialized(serializedstr,deserialize,ln); cout << \"Deserialized String : \"; for(int i=0; i<ln; i++) cout << deserialize[i] << \" \"; return 0;}", "e": 2069, "s": 891, "text": null }, { "code": null, "e": 2077, "s": 2069, "text": "Output:" }, { "code": null, "e": 2160, "s": 2077, "text": "Serialized String : 5~geeks3~are7~awesome\nDeserialized String : geeks are awesome\n" }, { "code": null, "e": 2328, "s": 2160, "text": "References :1. https://stackoverflow.com/questions/13271503/converting-array-string-to-string-and-back-in-java2. https://www.careercup.com/question?id=5684077627703296" }, { "code": null, "e": 2628, "s": 2328, "text": "This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2753, "s": 2628, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2760, "s": 2753, "text": "Arrays" }, { "code": null, "e": 2767, "s": 2760, "text": "Arrays" }, { "code": null, "e": 2865, "s": 2767, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2897, "s": 2865, "text": "Introduction to Data Structures" }, { "code": null, "e": 2944, "s": 2897, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 2969, "s": 2944, "text": "Window Sliding Technique" }, { "code": null, "e": 3000, "s": 2969, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 3085, "s": 3000, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 3143, "s": 3085, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 3164, "s": 3143, "text": "Next Greater Element" }, { "code": null, "e": 3196, "s": 3164, "text": "Longest Consecutive Subsequence" }, { "code": null, "e": 3223, "s": 3196, "text": "Count pairs with given sum" } ]
Tree Sort
23 Jun, 2022 Tree sort is a sorting algorithm that is based on Binary Search Tree data structure. It first creates a binary search tree from the elements of the input list or array and then performs an in-order traversal on the created binary search tree to get the elements in sorted order. Step 1: Take the elements input in an array. Step 2: Create a Binary search tree by inserting data items from the array into the binary search tree. Step 3: Perform in-order traversal on the tree to get the elements in sorted order. Its most common use is to edit the elements online: after each installation, a set of objects seen so far is available in a structured program. If you use a splay tree as a binary search tree, the resulting algorithm (called splaysort) has an additional property that it is an adaptive sort, which means its working time is faster than O (n log n) for virtual inputs. Below is the implementation for the above approach: C++ Java Python3 C# Javascript // C++ program to implement Tree Sort#include<bits/stdc++.h> using namespace std; struct Node{ int key; struct Node *left, *right;}; // A utility function to create a new BST Nodestruct Node *newNode(int item){ struct Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} // Stores inorder traversal of the BST// in arr[]void storeSorted(Node *root, int arr[], int &i){ if (root != NULL) { storeSorted(root->left, arr, i); arr[i++] = root->key; storeSorted(root->right, arr, i); }} /* A utility function to insert a new Node with given key in BST */Node* insert(Node* node, int key){ /* If the tree is empty, return a new Node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) Node pointer */ return node;} // This function sorts arr[0..n-1] using Tree Sortvoid treeSort(int arr[], int n){ struct Node *root = NULL; // Construct the BST root = insert(root, arr[0]); for (int i=1; i<n; i++) root = insert(root, arr[i]); // Store inorder traversal of the BST // in arr[] int i = 0; storeSorted(root, arr, i);} // Driver Program to test above functionsint main(){ //create input array int arr[] = {5, 4, 7, 2, 11}; int n = sizeof(arr)/sizeof(arr[0]); treeSort(arr, n); for (int i=0; i<n; i++) cout << arr[i] << " "; return 0;} // Java program to// implement Tree Sortclass GFG{ // Class containing left and // right child of current // node and key value class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; } } // Root of BST Node root; // Constructor GFG() { root = null; } // This method mainly // calls insertRec() void insert(int key) { root = insertRec(root, key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root, int key) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise, recur down the tree */ if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); /* return the root */ return root; } // A function to do // inorder traversal of BST void inorderRec(Node root) { if (root != null) { inorderRec(root.left); System.out.print(root.key + " "); inorderRec(root.right); } } void treeins(int arr[]) { for(int i = 0; i < arr.length; i++) { insert(arr[i]); } } // Driver Code public static void main(String[] args) { GFG tree = new GFG(); int arr[] = {5, 4, 7, 2, 11}; tree.treeins(arr); tree.inorderRec(tree.root); }} // This code is contributed// by Vibin M # Python3 program to# implement Tree Sort # Class containing left and# right child of current# node and key valueclass Node: def __init__(self,item = 0): self.key = item self.left,self.right = None,None # Root of BSTroot = Node() root = None # This method mainly# calls insertRec()def insert(key): global root root = insertRec(root, key) # A recursive function to# insert a new key in BSTdef insertRec(root, key): # If the tree is empty, # return a new node if (root == None): root = Node(key) return root # Otherwise, recur # down the tree if (key < root.key): root.left = insertRec(root.left, key) elif (key > root.key): root.right = insertRec(root.right, key) # return the root return root # A function to do# inorder traversal of BSTdef inorderRec(root): if (root != None): inorderRec(root.left) print(root.key ,end = " ") inorderRec(root.right) def treeins(arr): for i in range(len(arr)): insert(arr[i]) # Driver Codearr = [5, 4, 7, 2, 11]treeins(arr)inorderRec(root) # This code is contributed by shinjanpatra // C# program to// implement Tree Sortusing System;public class GFG{ // Class containing left and // right child of current // node and key value public class Node { public int key; public Node left, right; public Node(int item) { key = item; left = right = null; } } // Root of BST Node root; // Constructor GFG() { root = null; } // This method mainly // calls insertRec() void insert(int key) { root = insertRec(root, key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root, int key) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise, recur down the tree */ if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); /* return the root */ return root; } // A function to do // inorder traversal of BST void inorderRec(Node root) { if (root != null) { inorderRec(root.left); Console.Write(root.key + " "); inorderRec(root.right); } } void treeins(int []arr) { for(int i = 0; i < arr.Length; i++) { insert(arr[i]); } } // Driver Code public static void Main(String[] args) { GFG tree = new GFG(); int []arr = {5, 4, 7, 2, 11}; tree.treeins(arr); tree.inorderRec(tree.root); }} // This code is contributed by Rajput-Ji <script> // Javascript program to// implement Tree Sort // Class containing left and// right child of current// node and key valueclass Node { constructor(item) { this.key = item; this.left = this.right = null; }} // Root of BSTlet root = new Node(); root = null; // This method mainly// calls insertRec()function insert(key) { root = insertRec(root, key);} /* A recursive function toinsert a new key in BST */function insertRec(root, key) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise, recur down the tree */ if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); /* return the root */ return root;} // A function to do// inorder traversal of BSTfunction inorderRec(root) { if (root != null) { inorderRec(root.left); document.write(root.key + " "); inorderRec(root.right); }}function treeins(arr) { for (let i = 0; i < arr.length; i++) { insert(arr[i]); } } // Driver Code let arr = [5, 4, 7, 2, 11];treeins(arr);inorderRec(root); // This code is contributed// by Saurabh Jaiswal </script> 2 4 5 7 11 Average Case Time Complexity: O(n log n) Adding one item to a Binary Search tree on average takes O(log n) time. Therefore, adding n items will take O(n log n) time Worst Case Time Complexity: O(n2). The worst case time complexity of Tree Sort can be improved by using a self-balancing binary search tree like Red Black Tree, AVL Tree. Using self-balancing binary tree Tree Sort will take O(n log n) time to sort the array in worst case. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Auxiliary Space: O(n) https://www.youtube.com/watch?v=n2MLjGeK7qA References: https://en.wikipedia.org/wiki/Tree_sort This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vibi vsushko jerryraj06 Rajput-Ji gabaa406 kashishkumar2 _saurabh_jaiswal shinjanpatra Self-Balancing-BST Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. std::sort() in C++ STL Time Complexities of all Sorting Algorithms Count Inversions in an array | Set 1 (Using Merge Sort) Merge two sorted arrays Radix Sort Chocolate Distribution Problem Sort an array of 0s, 1s and 2s | Dutch National Flag problem Longest Consecutive Subsequence k largest(or smallest) elements in an array Find a triplet that sum to a given value
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 332, "s": 52, "text": "Tree sort is a sorting algorithm that is based on Binary Search Tree data structure. It first creates a binary search tree from the elements of the input list or array and then performs an in-order traversal on the created binary search tree to get the elements in sorted order. " }, { "code": null, "e": 377, "s": 332, "text": "Step 1: Take the elements input in an array." }, { "code": null, "e": 481, "s": 377, "text": "Step 2: Create a Binary search tree by inserting data items from the array into the binary search tree." }, { "code": null, "e": 565, "s": 481, "text": "Step 3: Perform in-order traversal on the tree to get the elements in sorted order." }, { "code": null, "e": 709, "s": 565, "text": "Its most common use is to edit the elements online: after each installation, a set of objects seen so far is available in a structured program." }, { "code": null, "e": 933, "s": 709, "text": "If you use a splay tree as a binary search tree, the resulting algorithm (called splaysort) has an additional property that it is an adaptive sort, which means its working time is faster than O (n log n) for virtual inputs." }, { "code": null, "e": 985, "s": 933, "text": "Below is the implementation for the above approach:" }, { "code": null, "e": 989, "s": 985, "text": "C++" }, { "code": null, "e": 994, "s": 989, "text": "Java" }, { "code": null, "e": 1002, "s": 994, "text": "Python3" }, { "code": null, "e": 1005, "s": 1002, "text": "C#" }, { "code": null, "e": 1016, "s": 1005, "text": "Javascript" }, { "code": "// C++ program to implement Tree Sort#include<bits/stdc++.h> using namespace std; struct Node{ int key; struct Node *left, *right;}; // A utility function to create a new BST Nodestruct Node *newNode(int item){ struct Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} // Stores inorder traversal of the BST// in arr[]void storeSorted(Node *root, int arr[], int &i){ if (root != NULL) { storeSorted(root->left, arr, i); arr[i++] = root->key; storeSorted(root->right, arr, i); }} /* A utility function to insert a new Node with given key in BST */Node* insert(Node* node, int key){ /* If the tree is empty, return a new Node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) Node pointer */ return node;} // This function sorts arr[0..n-1] using Tree Sortvoid treeSort(int arr[], int n){ struct Node *root = NULL; // Construct the BST root = insert(root, arr[0]); for (int i=1; i<n; i++) root = insert(root, arr[i]); // Store inorder traversal of the BST // in arr[] int i = 0; storeSorted(root, arr, i);} // Driver Program to test above functionsint main(){ //create input array int arr[] = {5, 4, 7, 2, 11}; int n = sizeof(arr)/sizeof(arr[0]); treeSort(arr, n); for (int i=0; i<n; i++) cout << arr[i] << \" \"; return 0;}", "e": 2606, "s": 1016, "text": null }, { "code": "// Java program to// implement Tree Sortclass GFG{ // Class containing left and // right child of current // node and key value class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; } } // Root of BST Node root; // Constructor GFG() { root = null; } // This method mainly // calls insertRec() void insert(int key) { root = insertRec(root, key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root, int key) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise, recur down the tree */ if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); /* return the root */ return root; } // A function to do // inorder traversal of BST void inorderRec(Node root) { if (root != null) { inorderRec(root.left); System.out.print(root.key + \" \"); inorderRec(root.right); } } void treeins(int arr[]) { for(int i = 0; i < arr.length; i++) { insert(arr[i]); } } // Driver Code public static void main(String[] args) { GFG tree = new GFG(); int arr[] = {5, 4, 7, 2, 11}; tree.treeins(arr); tree.inorderRec(tree.root); }} // This code is contributed// by Vibin M", "e": 4290, "s": 2606, "text": null }, { "code": "# Python3 program to# implement Tree Sort # Class containing left and# right child of current# node and key valueclass Node: def __init__(self,item = 0): self.key = item self.left,self.right = None,None # Root of BSTroot = Node() root = None # This method mainly# calls insertRec()def insert(key): global root root = insertRec(root, key) # A recursive function to# insert a new key in BSTdef insertRec(root, key): # If the tree is empty, # return a new node if (root == None): root = Node(key) return root # Otherwise, recur # down the tree if (key < root.key): root.left = insertRec(root.left, key) elif (key > root.key): root.right = insertRec(root.right, key) # return the root return root # A function to do# inorder traversal of BSTdef inorderRec(root): if (root != None): inorderRec(root.left) print(root.key ,end = \" \") inorderRec(root.right) def treeins(arr): for i in range(len(arr)): insert(arr[i]) # Driver Codearr = [5, 4, 7, 2, 11]treeins(arr)inorderRec(root) # This code is contributed by shinjanpatra", "e": 5358, "s": 4290, "text": null }, { "code": "// C# program to// implement Tree Sortusing System;public class GFG{ // Class containing left and // right child of current // node and key value public class Node { public int key; public Node left, right; public Node(int item) { key = item; left = right = null; } } // Root of BST Node root; // Constructor GFG() { root = null; } // This method mainly // calls insertRec() void insert(int key) { root = insertRec(root, key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root, int key) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise, recur down the tree */ if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); /* return the root */ return root; } // A function to do // inorder traversal of BST void inorderRec(Node root) { if (root != null) { inorderRec(root.left); Console.Write(root.key + \" \"); inorderRec(root.right); } } void treeins(int []arr) { for(int i = 0; i < arr.Length; i++) { insert(arr[i]); } } // Driver Code public static void Main(String[] args) { GFG tree = new GFG(); int []arr = {5, 4, 7, 2, 11}; tree.treeins(arr); tree.inorderRec(tree.root); }} // This code is contributed by Rajput-Ji", "e": 6832, "s": 5358, "text": null }, { "code": "<script> // Javascript program to// implement Tree Sort // Class containing left and// right child of current// node and key valueclass Node { constructor(item) { this.key = item; this.left = this.right = null; }} // Root of BSTlet root = new Node(); root = null; // This method mainly// calls insertRec()function insert(key) { root = insertRec(root, key);} /* A recursive function toinsert a new key in BST */function insertRec(root, key) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise, recur down the tree */ if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); /* return the root */ return root;} // A function to do// inorder traversal of BSTfunction inorderRec(root) { if (root != null) { inorderRec(root.left); document.write(root.key + \" \"); inorderRec(root.right); }}function treeins(arr) { for (let i = 0; i < arr.length; i++) { insert(arr[i]); } } // Driver Code let arr = [5, 4, 7, 2, 11];treeins(arr);inorderRec(root); // This code is contributed// by Saurabh Jaiswal </script>", "e": 8019, "s": 6832, "text": null }, { "code": null, "e": 8031, "s": 8019, "text": "2 4 5 7 11 " }, { "code": null, "e": 8196, "s": 8031, "text": "Average Case Time Complexity: O(n log n) Adding one item to a Binary Search tree on average takes O(log n) time. Therefore, adding n items will take O(n log n) time" }, { "code": null, "e": 8470, "s": 8196, "text": "Worst Case Time Complexity: O(n2). The worst case time complexity of Tree Sort can be improved by using a self-balancing binary search tree like Red Black Tree, AVL Tree. Using self-balancing binary tree Tree Sort will take O(n log n) time to sort the array in worst case. " }, { "code": null, "e": 8479, "s": 8470, "text": "Chapters" }, { "code": null, "e": 8506, "s": 8479, "text": "descriptions off, selected" }, { "code": null, "e": 8556, "s": 8506, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 8579, "s": 8556, "text": "captions off, selected" }, { "code": null, "e": 8587, "s": 8579, "text": "English" }, { "code": null, "e": 8611, "s": 8587, "text": "This is a modal window." }, { "code": null, "e": 8680, "s": 8611, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 8702, "s": 8680, "text": "End of dialog window." }, { "code": null, "e": 8725, "s": 8702, "text": "Auxiliary Space: O(n) " }, { "code": null, "e": 8769, "s": 8725, "text": "https://www.youtube.com/watch?v=n2MLjGeK7qA" }, { "code": null, "e": 8823, "s": 8771, "text": "References: https://en.wikipedia.org/wiki/Tree_sort" }, { "code": null, "e": 9245, "s": 8823, "text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9250, "s": 9245, "text": "vibi" }, { "code": null, "e": 9258, "s": 9250, "text": "vsushko" }, { "code": null, "e": 9269, "s": 9258, "text": "jerryraj06" }, { "code": null, "e": 9279, "s": 9269, "text": "Rajput-Ji" }, { "code": null, "e": 9288, "s": 9279, "text": "gabaa406" }, { "code": null, "e": 9302, "s": 9288, "text": "kashishkumar2" }, { "code": null, "e": 9319, "s": 9302, "text": "_saurabh_jaiswal" }, { "code": null, "e": 9332, "s": 9319, "text": "shinjanpatra" }, { "code": null, "e": 9351, "s": 9332, "text": "Self-Balancing-BST" }, { "code": null, "e": 9359, "s": 9351, "text": "Sorting" }, { "code": null, "e": 9367, "s": 9359, "text": "Sorting" }, { "code": null, "e": 9465, "s": 9367, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9488, "s": 9465, "text": "std::sort() in C++ STL" }, { "code": null, "e": 9532, "s": 9488, "text": "Time Complexities of all Sorting Algorithms" }, { "code": null, "e": 9588, "s": 9532, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 9612, "s": 9588, "text": "Merge two sorted arrays" }, { "code": null, "e": 9623, "s": 9612, "text": "Radix Sort" }, { "code": null, "e": 9654, "s": 9623, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 9715, "s": 9654, "text": "Sort an array of 0s, 1s and 2s | Dutch National Flag problem" }, { "code": null, "e": 9747, "s": 9715, "text": "Longest Consecutive Subsequence" }, { "code": null, "e": 9791, "s": 9747, "text": "k largest(or smallest) elements in an array" } ]
Python – Group Similar items to Dictionary Values List
29 Apr, 2022 Given a list of elements, perform grouping of similar elements, as different key-value list in dictionary. Input : test_list = [4, 6, 6, 4, 2, 2, 4, 8, 5, 8] Output : {4: [4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]} Explanation : Similar items grouped together on occurrences. Input : test_list = [7, 7, 7, 7] Output : {7 : [7, 7, 7, 7]} Explanation : Similar items grouped together on occurrences. Method #1 : Using defaultdict() + loop This is one of the ways in which this task can be performed. In this, we construct a defaultdict() with default list and keep appending similar values into similar list. Python3 # Python3 code to demonstrate working of# Group Similar items to Dictionary Values List# Using defaultdict + loopfrom collections import defaultdict # initializing listtest_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] # printing original listprint("The original list : " + str(test_list)) # using defaultdict for default listres = defaultdict(list)for ele in test_list: # appending Similar values res[ele].append(ele) # printing resultprint("Similar grouped dictionary : " + str(dict(res))) The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] Similar grouped dictionary : {4: [4, 4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]} Method #2 : Using dictionary comprehension + Counter() This is yet another way in which this task can be performed. In this, we extract frequency using Counter() and then repeat occurrences using multiplication. Python3 # Python3 code to demonstrate working of# Group Similar items to Dictionary Values List# Using dictionary comprehension + Counter()from collections import Counter # initializing listtest_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] # printing original listprint("The original list : " + str(test_list)) # using * operator to perform multiplicationres = {key : [key] * val for key, val in Counter(test_list).items()} # printing resultprint("Similar grouped dictionary : " + str(res)) The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] Similar grouped dictionary : {4: [4, 4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]} ajmalhussain410 Python dictionary-programs Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Apr, 2022" }, { "code": null, "e": 135, "s": 28, "text": "Given a list of elements, perform grouping of similar elements, as different key-value list in dictionary." }, { "code": null, "e": 434, "s": 135, "text": "Input : test_list = [4, 6, 6, 4, 2, 2, 4, 8, 5, 8] Output : {4: [4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]} Explanation : Similar items grouped together on occurrences. Input : test_list = [7, 7, 7, 7] Output : {7 : [7, 7, 7, 7]} Explanation : Similar items grouped together on occurrences." }, { "code": null, "e": 473, "s": 434, "text": "Method #1 : Using defaultdict() + loop" }, { "code": null, "e": 643, "s": 473, "text": "This is one of the ways in which this task can be performed. In this, we construct a defaultdict() with default list and keep appending similar values into similar list." }, { "code": null, "e": 651, "s": 643, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Group Similar items to Dictionary Values List# Using defaultdict + loopfrom collections import defaultdict # initializing listtest_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] # printing original listprint(\"The original list : \" + str(test_list)) # using defaultdict for default listres = defaultdict(list)for ele in test_list: # appending Similar values res[ele].append(ele) # printing resultprint(\"Similar grouped dictionary : \" + str(dict(res)))", "e": 1149, "s": 651, "text": null }, { "code": null, "e": 1291, "s": 1149, "text": "The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]\nSimilar grouped dictionary : {4: [4, 4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]}" }, { "code": null, "e": 1346, "s": 1291, "text": "Method #2 : Using dictionary comprehension + Counter()" }, { "code": null, "e": 1503, "s": 1346, "text": "This is yet another way in which this task can be performed. In this, we extract frequency using Counter() and then repeat occurrences using multiplication." }, { "code": null, "e": 1511, "s": 1503, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Group Similar items to Dictionary Values List# Using dictionary comprehension + Counter()from collections import Counter # initializing listtest_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] # printing original listprint(\"The original list : \" + str(test_list)) # using * operator to perform multiplicationres = {key : [key] * val for key, val in Counter(test_list).items()} # printing resultprint(\"Similar grouped dictionary : \" + str(res))", "e": 1990, "s": 1511, "text": null }, { "code": null, "e": 2132, "s": 1990, "text": "The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]\nSimilar grouped dictionary : {4: [4, 4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]}" }, { "code": null, "e": 2148, "s": 2132, "text": "ajmalhussain410" }, { "code": null, "e": 2175, "s": 2148, "text": "Python dictionary-programs" }, { "code": null, "e": 2196, "s": 2175, "text": "Python list-programs" }, { "code": null, "e": 2203, "s": 2196, "text": "Python" }, { "code": null, "e": 2219, "s": 2203, "text": "Python Programs" }, { "code": null, "e": 2317, "s": 2219, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2335, "s": 2317, "text": "Python Dictionary" }, { "code": null, "e": 2377, "s": 2335, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2399, "s": 2377, "text": "Enumerate() in Python" }, { "code": null, "e": 2434, "s": 2399, "text": "Read a file line by line in Python" }, { "code": null, "e": 2466, "s": 2434, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2509, "s": 2466, "text": "Python program to convert a list to string" }, { "code": null, "e": 2531, "s": 2509, "text": "Defaultdict in Python" }, { "code": null, "e": 2570, "s": 2531, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2608, "s": 2570, "text": "Python | Convert a list to dictionary" } ]
Find the maximum distance covered using n bikes
16 Aug, 2021 There are n bikes and each can cover 100 km when fully fueled. What is the maximum amount of distance you can go using n bikes? You may assume that all bikes are similar and a bike takes 1 litre to cover 1 km.You have n bikes and using one bike you can only cover 100 km. so if n bikes start from same point and run simultaneously you can go only 100 km. Let’s think bit differently, trick is when you want to cover maximum distance, you should always try to waste minimum fuel. Minimum wastage of fuel means to run minimum number of bikes. Instead of parallel running of n bikes, you can think of serially running them. That means if you transfer some amount of fuel from last bike to another bikes and throw the last bike i.e., don’t run the last bike after certain point. But the question is, after what distance the fuel transfer has to be done so that the maximum distance is covered and fuel tank of remaining bikes do not overflow. Let us take following base cases and then generalize the solution. Base Case 1: There is one bike: This is simple, we can cover 100 kms only. Base Case 2: There are two bikes: What is the maximum distance we can cover when there are 2 bikes? To maximize the distance, we must drop second bike at some point and transfer its fuel to first bike. Let we do the transfer after x kms. Total distance covered = Distance covered by 100 ltr in first bike + Distance covered by fuel transferred from first bike. Remaining fuel in second bike is 100 – x. If we transfer this much fuel to first bike, then the total distance would become 100 + 100 – x which is 200 – x. So our task is to maximize 200-x. The constraint is, 100 – x must be less than or equal to the space created in first bike after x kms, i.e., 100 – x <= x. The value of 200-x becomes maximum when x is minimum. The minimum possible value of x is 50. So we are able to travel 150 kms. Base Case 3: There are three bikes : Let the first transfer is done after x kms. After x distance all bikes contain 100-x amount of fuel. If we take 100-x amount of fuel from 3rd bike and distribute it among 1st and 2nd bike so that fuel tanks of 1st and 2nd bikes get full. So 100-x <= 2*x; or, x=33.333 so we should transfer the remaining fuel of third bike and distribute that amount of fuel among 1st and 2nd bike after exactly 33.33 km. Let us generalize it. If we take a closer look at above cases, we can observe that if there are n bikes, then the first transfer is done (or a bike is dropped) after 100/n kms. To generalize it more, when we have x litre remaining fuel in every bike and n remaining bikes, we drop a bike after x/n kms. Following is the implementation of a general function. C++ Java Python3 C# PHP Javascript #include <stdio.h> // Returns maximum distance that can be traveled by n bikes and given fuel// in every bikedouble maxDistance(int n, int fuel){ // dist_covered is the result of this function double dist_covered = 0; while (n > 0) { // after ever fuel/n km we are discarding one bike and filling // all the other bikes with fuel/n liters of fuel i.e. to their // maximum limit (100 litre) dist_covered += (double)fuel / n; n -= 1; // reduce number of bikes } return dist_covered;} // Driver program to test above functionint main(){ int n = 3; // number of bikes int fuel = 100; printf("Maximum distance possible with %d bikes is %f", n, maxDistance(n, fuel)); return 0;} // Java program to find the maximum// distance covered using n bikesimport java.io.*; class GFG{ // Function that returns maximum distance that can be traveled by n bikes // and given fuel in every bike static double maxDistance(int n, int fuel) { // dist_covered is the result of this function double dist_covered = 0; while (n > 0) { // after ever fuel/n km we are discarding one bike and filling // all the other bikes with fuel/n liters of fuel i.e. to their // maximum limit (100 litre) dist_covered += (double)fuel / n; n -= 1; // reduce number of bikes } return dist_covered; } // driver program public static void main (String[] args) { int n = 3; // number of bikes int fuel = 100; System.out.println("Maximum distance possible with " + n + " bikes is " + maxDistance(n, fuel)); }} // Contributed by Pramod Kumar # Python 3 program to find the maximum# distance covered using n bikes # Returns maximum distance that can be# traveled by n bikes and given fuel# in every bikedef maxDistance(n, fuel): # dist_covered is the result # of this function dist_covered = 0 while (n > 0): # after ever fuel/n km we are # discarding one bike and filling # all the other bikes with fuel/n # liters of fuel i.e. to their # maximum limit (100 litre) dist_covered = dist_covered + (fuel / n) # reduce number of bikes n = n - 1 return dist_covered # Driver Codeif __name__ =='__main__': n = 3 # number of bikes fuel = 100 print("Maximum distance possible with", n, "bikes is", maxDistance(n, fuel)) # This code is contributed by# Surendra_Gangwar // C# program to find the maximum// distance covered using n bikesusing System; class GFG { // Function that returns maximum distance // that can be travelled by n bikes // and given fuel in every bike static double maxDistance(int n, int fuel) { // dist_covered is the result of this function double dist_covered = 0; while (n > 0) { // after ever fuel/n km we are discarding // one bike and filling all the other bikes // with fuel/n liters of fuel i.e. to their // maximum limit (100 litre) dist_covered += (double)fuel / n; n -= 1; // reduce number of bikes } return dist_covered; } // driver program public static void Main() { // number of bikes int n = 3; int fuel = 100; Console.WriteLine("Maximum distance possible with " + n + " bikes is " + maxDistance(n, fuel)); }} // This code is contributed by Sam007 <?php// Returns maximum distance that can// be traveled by n bikes and given// fuel in every bike function maxDistance($n, $fuel){ // dist_covered is the result // of this function $dist_covered = 0; while ($n > 0) { // after ever fuel/n km we are // discarding one bike and filling // all the other bikes with fuel/n // liters of fuel i.e. to their // maximum limit (100 litre) $dist_covered += (double)$fuel / $n; // reduce number of bikes $n -= 1; } return $dist_covered;} // Driver Code // number of bikes$n = 3;$fuel = 100;echo "Maximum distance possible with ", $n, " bikes is ", maxDistance($n, $fuel); // This code is contributed by ajit?> <script> // Javascript program to find the maximum// distance covered using n bikes // Function that returns maximum distance// that can be travelled by n bikes// and given fuel in every bikefunction maxDistance(n, fuel){ // dist_covered is the result of this function let dist_covered = 0; while (n > 0) { // After ever fuel/n km we are discarding // one bike and filling all the other bikes // with fuel/n liters of fuel i.e. to their // maximum limit (100 litre) dist_covered += fuel / n; // Reduce number of bikes n -= 1; } return dist_covered.toFixed(6);} // Driver code // Number of bikeslet n = 3;let fuel = 100; document.write("Maximum distance possible with " + n + " bikes is " + maxDistance(n, fuel)); // This code is contributed by divyesh072019 </script> Output : Maximum distance possible with 3 bikes is 183.333333 Time Complexity: O(N)Auxiliary Space: O(1) This article is contributed by Shamik Mitra. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t SURENDRA_GANGWAR divyesh072019 pankajsharmagfg Algorithms Mathematical Mathematical Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Aug, 2021" }, { "code": null, "e": 995, "s": 54, "text": "There are n bikes and each can cover 100 km when fully fueled. What is the maximum amount of distance you can go using n bikes? You may assume that all bikes are similar and a bike takes 1 litre to cover 1 km.You have n bikes and using one bike you can only cover 100 km. so if n bikes start from same point and run simultaneously you can go only 100 km. Let’s think bit differently, trick is when you want to cover maximum distance, you should always try to waste minimum fuel. Minimum wastage of fuel means to run minimum number of bikes. Instead of parallel running of n bikes, you can think of serially running them. That means if you transfer some amount of fuel from last bike to another bikes and throw the last bike i.e., don’t run the last bike after certain point. But the question is, after what distance the fuel transfer has to be done so that the maximum distance is covered and fuel tank of remaining bikes do not overflow. " }, { "code": null, "e": 1064, "s": 995, "text": "Let us take following base cases and then generalize the solution. " }, { "code": null, "e": 1139, "s": 1064, "text": "Base Case 1: There is one bike: This is simple, we can cover 100 kms only." }, { "code": null, "e": 1377, "s": 1139, "text": "Base Case 2: There are two bikes: What is the maximum distance we can cover when there are 2 bikes? To maximize the distance, we must drop second bike at some point and transfer its fuel to first bike. Let we do the transfer after x kms." }, { "code": null, "e": 1554, "s": 1377, "text": "Total distance covered = Distance covered by 100 ltr in first bike + \n Distance covered by fuel transferred from \n first bike. " }, { "code": null, "e": 1995, "s": 1554, "text": "Remaining fuel in second bike is 100 – x. If we transfer this much fuel to first bike, then the total distance would become 100 + 100 – x which is 200 – x. So our task is to maximize 200-x. The constraint is, 100 – x must be less than or equal to the space created in first bike after x kms, i.e., 100 – x <= x. The value of 200-x becomes maximum when x is minimum. The minimum possible value of x is 50. So we are able to travel 150 kms. " }, { "code": null, "e": 2437, "s": 1995, "text": "Base Case 3: There are three bikes : Let the first transfer is done after x kms. After x distance all bikes contain 100-x amount of fuel. If we take 100-x amount of fuel from 3rd bike and distribute it among 1st and 2nd bike so that fuel tanks of 1st and 2nd bikes get full. So 100-x <= 2*x; or, x=33.333 so we should transfer the remaining fuel of third bike and distribute that amount of fuel among 1st and 2nd bike after exactly 33.33 km." }, { "code": null, "e": 2740, "s": 2437, "text": "Let us generalize it. If we take a closer look at above cases, we can observe that if there are n bikes, then the first transfer is done (or a bike is dropped) after 100/n kms. To generalize it more, when we have x litre remaining fuel in every bike and n remaining bikes, we drop a bike after x/n kms." }, { "code": null, "e": 2796, "s": 2740, "text": "Following is the implementation of a general function. " }, { "code": null, "e": 2800, "s": 2796, "text": "C++" }, { "code": null, "e": 2805, "s": 2800, "text": "Java" }, { "code": null, "e": 2813, "s": 2805, "text": "Python3" }, { "code": null, "e": 2816, "s": 2813, "text": "C#" }, { "code": null, "e": 2820, "s": 2816, "text": "PHP" }, { "code": null, "e": 2831, "s": 2820, "text": "Javascript" }, { "code": "#include <stdio.h> // Returns maximum distance that can be traveled by n bikes and given fuel// in every bikedouble maxDistance(int n, int fuel){ // dist_covered is the result of this function double dist_covered = 0; while (n > 0) { // after ever fuel/n km we are discarding one bike and filling // all the other bikes with fuel/n liters of fuel i.e. to their // maximum limit (100 litre) dist_covered += (double)fuel / n; n -= 1; // reduce number of bikes } return dist_covered;} // Driver program to test above functionint main(){ int n = 3; // number of bikes int fuel = 100; printf(\"Maximum distance possible with %d bikes is %f\", n, maxDistance(n, fuel)); return 0;}", "e": 3583, "s": 2831, "text": null }, { "code": "// Java program to find the maximum// distance covered using n bikesimport java.io.*; class GFG{ // Function that returns maximum distance that can be traveled by n bikes // and given fuel in every bike static double maxDistance(int n, int fuel) { // dist_covered is the result of this function double dist_covered = 0; while (n > 0) { // after ever fuel/n km we are discarding one bike and filling // all the other bikes with fuel/n liters of fuel i.e. to their // maximum limit (100 litre) dist_covered += (double)fuel / n; n -= 1; // reduce number of bikes } return dist_covered; } // driver program public static void main (String[] args) { int n = 3; // number of bikes int fuel = 100; System.out.println(\"Maximum distance possible with \" + n + \" bikes is \" + maxDistance(n, fuel)); }} // Contributed by Pramod Kumar", "e": 4597, "s": 3583, "text": null }, { "code": "# Python 3 program to find the maximum# distance covered using n bikes # Returns maximum distance that can be# traveled by n bikes and given fuel# in every bikedef maxDistance(n, fuel): # dist_covered is the result # of this function dist_covered = 0 while (n > 0): # after ever fuel/n km we are # discarding one bike and filling # all the other bikes with fuel/n # liters of fuel i.e. to their # maximum limit (100 litre) dist_covered = dist_covered + (fuel / n) # reduce number of bikes n = n - 1 return dist_covered # Driver Codeif __name__ =='__main__': n = 3 # number of bikes fuel = 100 print(\"Maximum distance possible with\", n, \"bikes is\", maxDistance(n, fuel)) # This code is contributed by# Surendra_Gangwar", "e": 5434, "s": 4597, "text": null }, { "code": "// C# program to find the maximum// distance covered using n bikesusing System; class GFG { // Function that returns maximum distance // that can be travelled by n bikes // and given fuel in every bike static double maxDistance(int n, int fuel) { // dist_covered is the result of this function double dist_covered = 0; while (n > 0) { // after ever fuel/n km we are discarding // one bike and filling all the other bikes // with fuel/n liters of fuel i.e. to their // maximum limit (100 litre) dist_covered += (double)fuel / n; n -= 1; // reduce number of bikes } return dist_covered; } // driver program public static void Main() { // number of bikes int n = 3; int fuel = 100; Console.WriteLine(\"Maximum distance possible with \" + n + \" bikes is \" + maxDistance(n, fuel)); }} // This code is contributed by Sam007", "e": 6451, "s": 5434, "text": null }, { "code": "<?php// Returns maximum distance that can// be traveled by n bikes and given// fuel in every bike function maxDistance($n, $fuel){ // dist_covered is the result // of this function $dist_covered = 0; while ($n > 0) { // after ever fuel/n km we are // discarding one bike and filling // all the other bikes with fuel/n // liters of fuel i.e. to their // maximum limit (100 litre) $dist_covered += (double)$fuel / $n; // reduce number of bikes $n -= 1; } return $dist_covered;} // Driver Code // number of bikes$n = 3;$fuel = 100;echo \"Maximum distance possible with \", $n, \" bikes is \", maxDistance($n, $fuel); // This code is contributed by ajit?>", "e": 7215, "s": 6451, "text": null }, { "code": "<script> // Javascript program to find the maximum// distance covered using n bikes // Function that returns maximum distance// that can be travelled by n bikes// and given fuel in every bikefunction maxDistance(n, fuel){ // dist_covered is the result of this function let dist_covered = 0; while (n > 0) { // After ever fuel/n km we are discarding // one bike and filling all the other bikes // with fuel/n liters of fuel i.e. to their // maximum limit (100 litre) dist_covered += fuel / n; // Reduce number of bikes n -= 1; } return dist_covered.toFixed(6);} // Driver code // Number of bikeslet n = 3;let fuel = 100; document.write(\"Maximum distance possible with \" + n + \" bikes is \" + maxDistance(n, fuel)); // This code is contributed by divyesh072019 </script>", "e": 8103, "s": 7215, "text": null }, { "code": null, "e": 8113, "s": 8103, "text": "Output : " }, { "code": null, "e": 8166, "s": 8113, "text": "Maximum distance possible with 3 bikes is 183.333333" }, { "code": null, "e": 8379, "s": 8166, "text": "Time Complexity: O(N)Auxiliary Space: O(1) This article is contributed by Shamik Mitra. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 8385, "s": 8379, "text": "jit_t" }, { "code": null, "e": 8402, "s": 8385, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 8416, "s": 8402, "text": "divyesh072019" }, { "code": null, "e": 8432, "s": 8416, "text": "pankajsharmagfg" }, { "code": null, "e": 8443, "s": 8432, "text": "Algorithms" }, { "code": null, "e": 8456, "s": 8443, "text": "Mathematical" }, { "code": null, "e": 8469, "s": 8456, "text": "Mathematical" }, { "code": null, "e": 8480, "s": 8469, "text": "Algorithms" } ]
TCS Coding Practice Question | Average of 2 Numbers
09 Apr, 2019 Given two numbers, the task is to find the average of two numbers using Command Line Arguments. Examples: Input: n1 = 10, n2 = 20 Output: 15 Input: n1 = 100, n2 = 200 Output: 150 Approach: Since the numbers are entered as Command line Arguments, there is no need for a dedicated input line Extract the input numbers from the command line argument This extracted numbers will be in String type. Convert these numbers into integer type and store it in variables, say num1 and num2 Find the average of the numbers using the formula ((num1 + num2)/2) Print or return the average Program: C Java // C program to compute the average of two numbers// using command line arguments #include <stdio.h>#include <stdlib.h> /* atoi */ // Function to compute the average of two numbersint average(int a, int b){ return (a + b) / 2;} // Driver codeint main(int argc, char* argv[]){ int num1, num2; // Check if the length of args array is 1 if (argc == 1) printf("No command line arguments found.\n"); else { // Get the command line argument and // Convert it from string type to integer type // using function "atoi( argument)" num1 = atoi(argv[1]); num2 = atoi(argv[2]); // Find the average and print it printf("%d\n", average(num1, num2)); } return 0;} // Java program to compute the average of two numbers// using command line arguments class GFG { // Function to compute the average of two numbers static int average(int a, int b) { return (a + b) / 2; } // Driver code public static void main(String[] args) { // Check if length of args array is // greater than 0 if (args.length > 0) { // Get the command line argument and // Convert it from string type to integer type int num1 = Integer.parseInt(args[0]); int num2 = Integer.parseInt(args[1]); // Find the average int res = average(num1, num2); // Print the average System.out.println(res); } else System.out.println("No command line " + "arguments found."); }} In C: In Java: TCS TCS-coding-questions C++ Programs Java Programs Placements TCS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to implement Singly Linked List in C++ using class Passing a function as a parameter in C++ Const keyword in C++ cout in C++ Dynamic _Cast in C++ MD5 hash in Java Java Programming Examples Convert a String to Character Array in Java Initializing a List in Java How to Sort a LinkedList in Java?
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Apr, 2019" }, { "code": null, "e": 150, "s": 54, "text": "Given two numbers, the task is to find the average of two numbers using Command Line Arguments." }, { "code": null, "e": 160, "s": 150, "text": "Examples:" }, { "code": null, "e": 235, "s": 160, "text": "Input: n1 = 10, n2 = 20\nOutput: 15\n\nInput: n1 = 100, n2 = 200\nOutput: 150\n" }, { "code": null, "e": 245, "s": 235, "text": "Approach:" }, { "code": null, "e": 346, "s": 245, "text": "Since the numbers are entered as Command line Arguments, there is no need for a dedicated input line" }, { "code": null, "e": 403, "s": 346, "text": "Extract the input numbers from the command line argument" }, { "code": null, "e": 450, "s": 403, "text": "This extracted numbers will be in String type." }, { "code": null, "e": 535, "s": 450, "text": "Convert these numbers into integer type and store it in variables, say num1 and num2" }, { "code": null, "e": 603, "s": 535, "text": "Find the average of the numbers using the formula ((num1 + num2)/2)" }, { "code": null, "e": 631, "s": 603, "text": "Print or return the average" }, { "code": null, "e": 640, "s": 631, "text": "Program:" }, { "code": null, "e": 642, "s": 640, "text": "C" }, { "code": null, "e": 647, "s": 642, "text": "Java" }, { "code": "// C program to compute the average of two numbers// using command line arguments #include <stdio.h>#include <stdlib.h> /* atoi */ // Function to compute the average of two numbersint average(int a, int b){ return (a + b) / 2;} // Driver codeint main(int argc, char* argv[]){ int num1, num2; // Check if the length of args array is 1 if (argc == 1) printf(\"No command line arguments found.\\n\"); else { // Get the command line argument and // Convert it from string type to integer type // using function \"atoi( argument)\" num1 = atoi(argv[1]); num2 = atoi(argv[2]); // Find the average and print it printf(\"%d\\n\", average(num1, num2)); } return 0;}", "e": 1386, "s": 647, "text": null }, { "code": "// Java program to compute the average of two numbers// using command line arguments class GFG { // Function to compute the average of two numbers static int average(int a, int b) { return (a + b) / 2; } // Driver code public static void main(String[] args) { // Check if length of args array is // greater than 0 if (args.length > 0) { // Get the command line argument and // Convert it from string type to integer type int num1 = Integer.parseInt(args[0]); int num2 = Integer.parseInt(args[1]); // Find the average int res = average(num1, num2); // Print the average System.out.println(res); } else System.out.println(\"No command line \" + \"arguments found.\"); }}", "e": 2259, "s": 1386, "text": null }, { "code": null, "e": 2265, "s": 2259, "text": "In C:" }, { "code": null, "e": 2274, "s": 2265, "text": "In Java:" }, { "code": null, "e": 2278, "s": 2274, "text": "TCS" }, { "code": null, "e": 2299, "s": 2278, "text": "TCS-coding-questions" }, { "code": null, "e": 2312, "s": 2299, "text": "C++ Programs" }, { "code": null, "e": 2326, "s": 2312, "text": "Java Programs" }, { "code": null, "e": 2337, "s": 2326, "text": "Placements" }, { "code": null, "e": 2341, "s": 2337, "text": "TCS" }, { "code": null, "e": 2439, "s": 2341, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2498, "s": 2439, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 2539, "s": 2498, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 2560, "s": 2539, "text": "Const keyword in C++" }, { "code": null, "e": 2572, "s": 2560, "text": "cout in C++" }, { "code": null, "e": 2593, "s": 2572, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 2610, "s": 2593, "text": "MD5 hash in Java" }, { "code": null, "e": 2636, "s": 2610, "text": "Java Programming Examples" }, { "code": null, "e": 2680, "s": 2636, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 2708, "s": 2680, "text": "Initializing a List in Java" } ]