title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
puts() vs printf() for printing a string in C language
The function puts() and printf() are declared in stdio.h header file and are used to send the text to the output stream. Both have different usages and syntax. The function puts() is used to print the string on the output stream with the additional new line character ‘\n’. It moves the cursor to the next line. Implementation of puts() is easier than printf(). Here is the syntax of puts() in C language, puts(“string”); If you do not want the cursor to be moved to the new line, use the following syntax. fputs(string, stdout) Here is an example of puts() in C language, Live Demo #include<stdio.h> int main() { puts("This is a demo."); fputs("No new Line.", stdout); puts(" Welcome!"); getchar(); return 0; } This is a demo. No new Line. Welcome! The function printf() is used to print the text long with the values of variables. The implementation of printf() is complex, that is why it is expensive than puts(). Here is the syntax of printf() in C language, printf(“string”); Here is an example of printf() in C language, Live Demo #include<stdio.h> int main() { int a = 10; printf("Hello world! \n"); printf("The value of a : %d",a); getchar(); return 0; } Hello world! The value of a : 10
[ { "code": null, "e": 1222, "s": 1062, "text": "The function puts() and printf() are declared in stdio.h header file and are used to send the text to the output stream. Both have different usages and syntax." }, { "code": null, "e": 1424, "s": 1222, "text": "The function puts() is used to print the string on the output stream with the additional new line character ‘\\n’. It moves the cursor to the next line. Implementation of puts() is easier than printf()." }, { "code": null, "e": 1468, "s": 1424, "text": "Here is the syntax of puts() in C language," }, { "code": null, "e": 1484, "s": 1468, "text": "puts(“string”);" }, { "code": null, "e": 1569, "s": 1484, "text": "If you do not want the cursor to be moved to the new line, use the following syntax." }, { "code": null, "e": 1591, "s": 1569, "text": "fputs(string, stdout)" }, { "code": null, "e": 1635, "s": 1591, "text": "Here is an example of puts() in C language," }, { "code": null, "e": 1646, "s": 1635, "text": " Live Demo" }, { "code": null, "e": 1790, "s": 1646, "text": "#include<stdio.h>\nint main() {\n puts(\"This is a demo.\");\n fputs(\"No new Line.\", stdout);\n puts(\" Welcome!\");\n getchar();\n return 0;\n}" }, { "code": null, "e": 1828, "s": 1790, "text": "This is a demo.\nNo new Line. Welcome!" }, { "code": null, "e": 1995, "s": 1828, "text": "The function printf() is used to print the text long with the values of variables. The implementation of printf() is complex, that is why it is expensive than puts()." }, { "code": null, "e": 2041, "s": 1995, "text": "Here is the syntax of printf() in C language," }, { "code": null, "e": 2059, "s": 2041, "text": "printf(“string”);" }, { "code": null, "e": 2105, "s": 2059, "text": "Here is an example of printf() in C language," }, { "code": null, "e": 2116, "s": 2105, "text": " Live Demo" }, { "code": null, "e": 2257, "s": 2116, "text": "#include<stdio.h>\nint main() {\n int a = 10;\n printf(\"Hello world! \\n\");\n printf(\"The value of a : %d\",a);\n getchar();\n return 0;\n}" }, { "code": null, "e": 2290, "s": 2257, "text": "Hello world!\nThe value of a : 10" } ]
Matplotlib - Axes Class
Axes object is the region of the image with the data space. A given figure can contain many Axes, but a given Axes object can only be in one Figure. The Axes contains two (or three in the case of 3D) Axis objects. The Axes class and its member functions are the primary entry point to working with the OO interface. Axes object is added to figure by calling the add_axes() method. It returns the axes object and adds an axes at position rect [left, bottom, width, height] where all quantities are in fractions of figure width and height. Following is the parameter for the Axes class − rect − A 4-length sequence of [left, bottom, width, height] quantities. rect − A 4-length sequence of [left, bottom, width, height] quantities. ax=fig.add_axes([0,0,1,1]) The following member functions of axes class add different elements to plot − The legend() method of axes class adds a legend to the plot figure. It takes three parameters − ax.legend(handles, labels, loc) Where labels is a sequence of strings and handles a sequence of Line2D or Patch instances. loc can be a string or an integer specifying the legend location. This is the basic method of axes class that plots values of one array versus another as lines or markers. The plot() method can have an optional format string argument to specify color, style and size of line and marker. Following example shows the advertisement expenses and sales figures of TV and smartphone in the form of line plots. Line representing TV is a solid line with yellow colour and square markers whereas smartphone line is a dashed line with green colour and circle marker. import matplotlib.pyplot as plt y = [1, 4, 9, 16, 25,36,49, 64] x1 = [1, 16, 30, 42,55, 68, 77,88] x2 = [1,6,12,18,28, 40, 52, 65] fig = plt.figure() ax = fig.add_axes([0,0,1,1]) l1 = ax.plot(x1,y,'ys-') # solid line with yellow colour and square marker l2 = ax.plot(x2,y,'go--') # dash line with green colour and circle marker ax.legend(labels = ('tv', 'Smartphone'), loc = 'lower right') # legend placed at lower right ax.set_title("Advertisement effect on sales") ax.set_xlabel('medium') ax.set_ylabel('sales') plt.show() When the above line of code is executed, it produces the following plot − 63 Lectures 6 hours Abhilash Nelson 11 Lectures 4 hours DATAhill Solutions Srinivas Reddy 9 Lectures 2.5 hours DATAhill Solutions Srinivas Reddy 32 Lectures 4 hours Aipython 10 Lectures 2.5 hours Akbar Khan 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2832, "s": 2516, "text": "Axes object is the region of the image with the data space. A given figure can contain many Axes, but a given Axes object can only be in one Figure. The Axes contains two (or three in the case of 3D) Axis objects. The Axes class and its member functions are the primary entry point to working with the OO interface." }, { "code": null, "e": 3054, "s": 2832, "text": "Axes object is added to figure by calling the add_axes() method. It returns the axes object and adds an axes at position rect [left, bottom, width, height] where all quantities are in fractions of figure width and height." }, { "code": null, "e": 3102, "s": 3054, "text": "Following is the parameter for the Axes class −" }, { "code": null, "e": 3174, "s": 3102, "text": "rect − A 4-length sequence of [left, bottom, width, height] quantities." }, { "code": null, "e": 3246, "s": 3174, "text": "rect − A 4-length sequence of [left, bottom, width, height] quantities." }, { "code": null, "e": 3273, "s": 3246, "text": "ax=fig.add_axes([0,0,1,1])" }, { "code": null, "e": 3351, "s": 3273, "text": "The following member functions of axes class add different elements to plot −" }, { "code": null, "e": 3447, "s": 3351, "text": "The legend() method of axes class adds a legend to the plot figure. It takes three parameters −" }, { "code": null, "e": 3479, "s": 3447, "text": "ax.legend(handles, labels, loc)" }, { "code": null, "e": 3636, "s": 3479, "text": "Where labels is a sequence of strings and handles a sequence of Line2D or Patch instances. loc can be a string or an integer specifying the legend location." }, { "code": null, "e": 3857, "s": 3636, "text": "This is the basic method of axes class that plots values of one array versus another as lines or markers. The plot() method can have an optional format string argument to specify color, style and size of line and marker." }, { "code": null, "e": 4127, "s": 3857, "text": "Following example shows the advertisement expenses and sales figures of TV and smartphone in the form of line plots. Line representing TV is a solid line with yellow colour and square markers whereas smartphone line is a dashed line with green colour and circle marker." }, { "code": null, "e": 4652, "s": 4127, "text": "import matplotlib.pyplot as plt\ny = [1, 4, 9, 16, 25,36,49, 64]\nx1 = [1, 16, 30, 42,55, 68, 77,88]\nx2 = [1,6,12,18,28, 40, 52, 65]\nfig = plt.figure()\nax = fig.add_axes([0,0,1,1])\nl1 = ax.plot(x1,y,'ys-') # solid line with yellow colour and square marker\nl2 = ax.plot(x2,y,'go--') # dash line with green colour and circle marker\nax.legend(labels = ('tv', 'Smartphone'), loc = 'lower right') # legend placed at lower right\nax.set_title(\"Advertisement effect on sales\")\nax.set_xlabel('medium')\nax.set_ylabel('sales')\nplt.show()" }, { "code": null, "e": 4726, "s": 4652, "text": "When the above line of code is executed, it produces the following plot −" }, { "code": null, "e": 4759, "s": 4726, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4776, "s": 4759, "text": " Abhilash Nelson" }, { "code": null, "e": 4809, "s": 4776, "text": "\n 11 Lectures \n 4 hours \n" }, { "code": null, "e": 4844, "s": 4809, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 4878, "s": 4844, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4913, "s": 4878, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 4946, "s": 4913, "text": "\n 32 Lectures \n 4 hours \n" }, { "code": null, "e": 4956, "s": 4946, "text": " Aipython" }, { "code": null, "e": 4991, "s": 4956, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5003, "s": 4991, "text": " Akbar Khan" }, { "code": null, "e": 5036, "s": 5003, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5043, "s": 5036, "text": " Anmol" }, { "code": null, "e": 5050, "s": 5043, "text": " Print" }, { "code": null, "e": 5061, "s": 5050, "text": " Add Notes" } ]
Objective-C Strings
The string in Objective-C programming language is represented using NSString and its subclass NSMutableString provides several ways for creating string objects. The simplest way to create a string object is to use the Objective-C @"..." construct − NSString *greeting = @"Hello"; A simple example for creating and printing a string is shown below. #import <Foundation/Foundation.h> int main () { NSString *greeting = @"Hello"; NSLog(@"Greeting message: %@\n", greeting ); return 0; } When the above code is compiled and executed, it produces result something as follows − 2013-09-11 01:21:39.922 demo[23926] Greeting message: Hello Objective-C supports a wide range of methods for manipulate strings − - (NSString *)capitalizedString; Returns a capitalized representation of the receiver. - (unichar)characterAtIndex:(NSUInteger)index; Returns the character at a given array position. - (double)doubleValue; Returns the floating-point value of the receiver’s text as a double. - (float)floatValue; Returns the floating-point value of the receiver’s text as a float. - (BOOL)hasPrefix:(NSString *)aString; Returns a Boolean value that indicates whether a given string matches the beginning characters of the receiver. - (BOOL)hasSuffix:(NSString *)aString; Returns a Boolean value that indicates whether a given string matches the ending characters of the receiver. - (id)initWithFormat:(NSString *)format ...; Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted. - (NSInteger)integerValue; Returns the NSInteger value of the receiver’s text. - (BOOL)isEqualToString:(NSString *)aString; Returns a Boolean value that indicates whether a given string is equal to the receiver using a literal Unicode-based comparison. - (NSUInteger)length; Returns the number of Unicode characters in the receiver. - (NSString *)lowercaseString; Returns lowercased representation of the receiver. - (NSRange)rangeOfString:(NSString *)aString; Finds and returns the range of the first occurrence of a given string within the receiver. - (NSString *)stringByAppendingFormat:(NSString *)format ...; Returns a string made by appending to the receiver a string constructed from a given format string and the following arguments. - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set; Returns a new string made by removing from both ends of the receiver characters contained in a given character set. - (NSString *)substringFromIndex:(NSUInteger)anIndex; Returns a new string containing the characters of the receiver from the one at a given index to the end. Following example makes use of few of the above-mentioned functions − #import <Foundation/Foundation.h> int main () { NSString *str1 = @"Hello"; NSString *str2 = @"World"; NSString *str3; int len ; NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; /* uppercase string */ str3 = [str2 uppercaseString]; NSLog(@"Uppercase String : %@\n", str3 ); /* concatenates str1 and str2 */ str3 = [str1 stringByAppendingFormat:@"World"]; NSLog(@"Concatenated string: %@\n", str3 ); /* total length of str3 after concatenation */ len = [str3 length]; NSLog(@"Length of Str3 : %d\n", len ); /* InitWithFormat */ str3 = [[NSString alloc] initWithFormat:@"%@ %@",str1,str2]; NSLog(@"Using initWithFormat: %@\n", str3 ); [pool drain]; return 0; } When the above code is compiled and executed, it produces result something as follows − 2013-09-11 01:15:45.069 demo[30378] Uppercase String : WORLD 2013-09-11 01:15:45.070 demo[30378] Concatenated string: HelloWorld 2013-09-11 01:15:45.070 demo[30378] Length of Str3 : 10 2013-09-11 01:15:45.070 demo[30378] Using initWithFormat: Hello World You can find a complete list of Objective-C NSString related methods in NSString Class Reference. 18 Lectures 1 hours PARTHA MAJUMDAR 6 Lectures 25 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2810, "s": 2560, "text": "The string in Objective-C programming language is represented using NSString and its subclass NSMutableString provides several ways for creating string objects. The simplest way to create a string object is to use the Objective-C @\"...\" construct −" }, { "code": null, "e": 2841, "s": 2810, "text": "NSString *greeting = @\"Hello\";" }, { "code": null, "e": 2909, "s": 2841, "text": "A simple example for creating and printing a string is shown below." }, { "code": null, "e": 3056, "s": 2909, "text": "#import <Foundation/Foundation.h>\n\nint main () {\n NSString *greeting = @\"Hello\";\n NSLog(@\"Greeting message: %@\\n\", greeting );\n\n return 0;\n}" }, { "code": null, "e": 3144, "s": 3056, "text": "When the above code is compiled and executed, it produces result something as follows −" }, { "code": null, "e": 3205, "s": 3144, "text": "2013-09-11 01:21:39.922 demo[23926] Greeting message: Hello\n" }, { "code": null, "e": 3275, "s": 3205, "text": "Objective-C supports a wide range of methods for manipulate strings −" }, { "code": null, "e": 3308, "s": 3275, "text": "- (NSString *)capitalizedString;" }, { "code": null, "e": 3362, "s": 3308, "text": "Returns a capitalized representation of the receiver." }, { "code": null, "e": 3409, "s": 3362, "text": "- (unichar)characterAtIndex:(NSUInteger)index;" }, { "code": null, "e": 3458, "s": 3409, "text": "Returns the character at a given array position." }, { "code": null, "e": 3481, "s": 3458, "text": "- (double)doubleValue;" }, { "code": null, "e": 3550, "s": 3481, "text": "Returns the floating-point value of the receiver’s text as a double." }, { "code": null, "e": 3571, "s": 3550, "text": "- (float)floatValue;" }, { "code": null, "e": 3639, "s": 3571, "text": "Returns the floating-point value of the receiver’s text as a float." }, { "code": null, "e": 3678, "s": 3639, "text": "- (BOOL)hasPrefix:(NSString *)aString;" }, { "code": null, "e": 3790, "s": 3678, "text": "Returns a Boolean value that indicates whether a given string matches the beginning characters of the receiver." }, { "code": null, "e": 3829, "s": 3790, "text": "- (BOOL)hasSuffix:(NSString *)aString;" }, { "code": null, "e": 3938, "s": 3829, "text": "Returns a Boolean value that indicates whether a given string matches the ending characters of the receiver." }, { "code": null, "e": 3983, "s": 3938, "text": "- (id)initWithFormat:(NSString *)format ...;" }, { "code": null, "e": 4125, "s": 3983, "text": "Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted." }, { "code": null, "e": 4152, "s": 4125, "text": "- (NSInteger)integerValue;" }, { "code": null, "e": 4204, "s": 4152, "text": "Returns the NSInteger value of the receiver’s text." }, { "code": null, "e": 4249, "s": 4204, "text": "- (BOOL)isEqualToString:(NSString *)aString;" }, { "code": null, "e": 4378, "s": 4249, "text": "Returns a Boolean value that indicates whether a given string is equal to the receiver using a literal Unicode-based comparison." }, { "code": null, "e": 4400, "s": 4378, "text": "- (NSUInteger)length;" }, { "code": null, "e": 4458, "s": 4400, "text": "Returns the number of Unicode characters in the receiver." }, { "code": null, "e": 4489, "s": 4458, "text": "- (NSString *)lowercaseString;" }, { "code": null, "e": 4540, "s": 4489, "text": "Returns lowercased representation of the receiver." }, { "code": null, "e": 4586, "s": 4540, "text": "- (NSRange)rangeOfString:(NSString *)aString;" }, { "code": null, "e": 4677, "s": 4586, "text": "Finds and returns the range of the first occurrence of a given string within the receiver." }, { "code": null, "e": 4739, "s": 4677, "text": "- (NSString *)stringByAppendingFormat:(NSString *)format ...;" }, { "code": null, "e": 4867, "s": 4739, "text": "Returns a string made by appending to the receiver a string constructed from a given format string and the following arguments." }, { "code": null, "e": 4936, "s": 4867, "text": "- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;" }, { "code": null, "e": 5052, "s": 4936, "text": "Returns a new string made by removing from both ends of the receiver characters contained in a given character set." }, { "code": null, "e": 5106, "s": 5052, "text": "- (NSString *)substringFromIndex:(NSUInteger)anIndex;" }, { "code": null, "e": 5211, "s": 5106, "text": "Returns a new string containing the characters of the receiver from the one at a given index to the end." }, { "code": null, "e": 5281, "s": 5211, "text": "Following example makes use of few of the above-mentioned functions −" }, { "code": null, "e": 6023, "s": 5281, "text": "#import <Foundation/Foundation.h>\n\nint main () {\n NSString *str1 = @\"Hello\";\n NSString *str2 = @\"World\";\n NSString *str3;\n int len ;\n\n NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n\n /* uppercase string */\n str3 = [str2 uppercaseString];\n NSLog(@\"Uppercase String : %@\\n\", str3 );\n\n /* concatenates str1 and str2 */\n str3 = [str1 stringByAppendingFormat:@\"World\"];\n NSLog(@\"Concatenated string: %@\\n\", str3 );\n\n /* total length of str3 after concatenation */\n len = [str3 length];\n NSLog(@\"Length of Str3 : %d\\n\", len );\n\n /* InitWithFormat */\n str3 = [[NSString alloc] initWithFormat:@\"%@ %@\",str1,str2];\t\n NSLog(@\"Using initWithFormat: %@\\n\", str3 );\n [pool drain];\n\n return 0;\n}" }, { "code": null, "e": 6111, "s": 6023, "text": "When the above code is compiled and executed, it produces result something as follows −" }, { "code": null, "e": 6373, "s": 6111, "text": "2013-09-11 01:15:45.069 demo[30378] Uppercase String : WORLD\n2013-09-11 01:15:45.070 demo[30378] Concatenated string: HelloWorld\n2013-09-11 01:15:45.070 demo[30378] Length of Str3 : 10\n2013-09-11 01:15:45.070 demo[30378] Using initWithFormat: Hello World\n" }, { "code": null, "e": 6471, "s": 6373, "text": "You can find a complete list of Objective-C NSString related methods in NSString Class Reference." }, { "code": null, "e": 6504, "s": 6471, "text": "\n 18 Lectures \n 1 hours \n" }, { "code": null, "e": 6521, "s": 6504, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 6552, "s": 6521, "text": "\n 6 Lectures \n 25 mins\n" }, { "code": null, "e": 6563, "s": 6552, "text": " Ken Burke" }, { "code": null, "e": 6570, "s": 6563, "text": " Print" }, { "code": null, "e": 6581, "s": 6570, "text": " Add Notes" } ]
How to use Cookies in CGI in Perl?
HTTP protocol is a stateless protocol. But for a commercial website it is required to maintain session information among different pages. For example one user registration ends after transactions which spans through many pages. But how to maintain user's session information across all the web pages? In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics. Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored. Cookies are a plain text data record of 5 variable-length fields − Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser. Domain − The domain name of your site. Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page. Secure − If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists. Name = Value − Cookies are set and retrviewed in the form of key and value pairs. It is very easy to send cookies to browser. These cookies will be sent along with the HTTP Header. Assuming you want to set UserID and Password as cookies. So it will be done as follows − #!/usr/bin/perl print "Set-Cookie:UserID = XYZ;\n"; print "Set-Cookie:Password = XYZ123;\n"; print "Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT";\n"; print "Set-Cookie:Domain = www.tutorialspoint.com;\n"; print "Set-Cookie:Path = /perl;\n"; print "Content-type:text/html\r\n\r\n"; ...........Rest of the HTML Content goes here.... Here we used Set-Cookie HTTP header to set cookies. It is optional to set cookies attributes like Expires, Domain, and Path. It is important to note that cookies are set before sending magic line "Content-type:text/html\r\n\r\n. It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form. key1 = value1;key2 = value2;key3 = value3.... Here is an example of how to retrieve cookies. #!/usr/bin/perl $rcvd_cookies = $ENV{'HTTP_COOKIE'}; @cookies = split /;/, $rcvd_cookies; foreach $cookie ( @cookies ) { ($key, $val) = split(/=/, $cookie); # splits on the first =. $key =~ s/^\s+//; $val =~ s/^\s+//; $key =~ s/\s+$//; $val =~ s/\s+$//; if( $key eq "UserID" ) { $user_id = $val; } elsif($key eq "Password") { $password = $val; } } print "User ID = $user_id\n"; print "Password = $password\n"; This will produce the following result, provided above cookies have been set before calling retrieval cookies script. User ID = XYZ Password = XYZ123
[ { "code": null, "e": 1363, "s": 1062, "text": "HTTP protocol is a stateless protocol. But for a commercial website it is required to maintain session information among different pages. For example one user registration ends after transactions which spans through many pages. But how to maintain user's session information across all the web pages?" }, { "code": null, "e": 1572, "s": 1363, "text": "In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics." }, { "code": null, "e": 1922, "s": 1572, "text": "Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored." }, { "code": null, "e": 1989, "s": 1922, "text": "Cookies are a plain text data record of 5 variable-length fields −" }, { "code": null, "e": 2109, "s": 1989, "text": "Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser." }, { "code": null, "e": 2148, "s": 2109, "text": "Domain − The domain name of your site." }, { "code": null, "e": 2295, "s": 2148, "text": "Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page." }, { "code": null, "e": 2457, "s": 2295, "text": "Secure − If this field contains the word \"secure\" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists." }, { "code": null, "e": 2539, "s": 2457, "text": "Name = Value − Cookies are set and retrviewed in the form of key and value pairs." }, { "code": null, "e": 2727, "s": 2539, "text": "It is very easy to send cookies to browser. These cookies will be sent along with the HTTP Header. Assuming you want to set UserID and Password as cookies. So it will be done as follows −" }, { "code": null, "e": 3069, "s": 2727, "text": "#!/usr/bin/perl\nprint \"Set-Cookie:UserID = XYZ;\\n\";\nprint \"Set-Cookie:Password = XYZ123;\\n\";\nprint \"Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT\";\\n\";\nprint \"Set-Cookie:Domain = www.tutorialspoint.com;\\n\";\nprint \"Set-Cookie:Path = /perl;\\n\";\nprint \"Content-type:text/html\\r\\n\\r\\n\";\n...........Rest of the HTML Content goes here...." }, { "code": null, "e": 3298, "s": 3069, "text": "Here we used Set-Cookie HTTP header to set cookies. It is optional to set cookies attributes like Expires, Domain, and Path. It is important to note that cookies are set before sending magic line \"Content-type:text/html\\r\\n\\r\\n." }, { "code": null, "e": 3441, "s": 3298, "text": "It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form." }, { "code": null, "e": 3487, "s": 3441, "text": "key1 = value1;key2 = value2;key3 = value3...." }, { "code": null, "e": 3534, "s": 3487, "text": "Here is an example of how to retrieve cookies." }, { "code": null, "e": 3980, "s": 3534, "text": "#!/usr/bin/perl\n$rcvd_cookies = $ENV{'HTTP_COOKIE'};\n@cookies = split /;/, $rcvd_cookies;\nforeach $cookie ( @cookies ) {\n ($key, $val) = split(/=/, $cookie); # splits on the first =.\n $key =~ s/^\\s+//;\n $val =~ s/^\\s+//;\n $key =~ s/\\s+$//;\n $val =~ s/\\s+$//;\n if( $key eq \"UserID\" ) {\n $user_id = $val;\n } elsif($key eq \"Password\") {\n $password = $val;\n }\n}\nprint \"User ID = $user_id\\n\";\nprint \"Password = $password\\n\";" }, { "code": null, "e": 4098, "s": 3980, "text": "This will produce the following result, provided above cookies have been set before calling retrieval cookies script." }, { "code": null, "e": 4130, "s": 4098, "text": "User ID = XYZ\nPassword = XYZ123" } ]
How to add Social Share Buttons in NextJS ? - GeeksforGeeks
29 Oct, 2021 In this article, we are going to learn how we can add Social Share buttons in NextJs. Using the social share button user can share your content in different social media sites. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally. Approach: To add our Social Share buttons we are going to use the next-share package. The next-share package helps us to integrate 19 social media sites in which users can share your content within a click. So first, we will install the next-share package and then we will add different social share buttons on our homepage using the next-share package. Create NextJS Application: You can create a new NextJs project using the below command: npx create-next-app gfg Install the required package: Now we will install the next-share package using the below command: npm i next-share Project Structure: It will look like this. Adding the Social Share Buttons: After installing the next-share package we can easily add different social share buttons on any page in our app. For this example, we are going to add social share buttons to our homepage. Add the below content in the index.js file: index.js import React from 'react'import { FacebookShareButton, FacebookIcon, PinterestShareButton, PinterestIcon, RedditShareButton, RedditIcon, WhatsappShareButton, WhatsappIcon, LinkedinShareButton, LinkedinIcon,} from 'next-share'; export default function Text() { return ( <div> <h1>Social Share - GeeksforGeeks</h1> <FacebookShareButton {/* Url you want to share */} url={'http://localhost:3000'} > <FacebookIcon size={32} round /> </FacebookShareButton> <PinterestShareButton {/* Url you want to share */} url={'http://localhost:3000'} > <PinterestIcon size={32} round /> </PinterestShareButton> <RedditShareButton {/* Url you want to share */} url={'http://localhost:3000'} > <RedditIcon size={32} round /> </RedditShareButton> <WhatsappShareButton {/* Url you want to share */} url={'http://localhost:3000'} > <WhatsappIcon size={32} round /> </WhatsappShareButton> <LinkedinShareButton {/* Url you want to share */} url={'http://localhost:3000'} > <LinkedinIcon size={32} round /> </LinkedinShareButton> </div> )} Explanation: In the above example first, we are importing different social share buttons from our next-share package and then we are using those buttons in our Text component. You can add the URL you want to share in the URL parameter of every button. Steps to run the application: Run the below command in the terminal to run the app. npm run dev Nextjs React-Questions JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript 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? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 25312, "s": 25284, "text": "\n29 Oct, 2021" }, { "code": null, "e": 25489, "s": 25312, "text": "In this article, we are going to learn how we can add Social Share buttons in NextJs. Using the social share button user can share your content in different social media sites." }, { "code": null, "e": 25719, "s": 25489, "text": "NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally." }, { "code": null, "e": 26073, "s": 25719, "text": "Approach: To add our Social Share buttons we are going to use the next-share package. The next-share package helps us to integrate 19 social media sites in which users can share your content within a click. So first, we will install the next-share package and then we will add different social share buttons on our homepage using the next-share package." }, { "code": null, "e": 26163, "s": 26075, "text": "Create NextJS Application: You can create a new NextJs project using the below command:" }, { "code": null, "e": 26187, "s": 26163, "text": "npx create-next-app gfg" }, { "code": null, "e": 26285, "s": 26187, "text": "Install the required package: Now we will install the next-share package using the below command:" }, { "code": null, "e": 26302, "s": 26285, "text": "npm i next-share" }, { "code": null, "e": 26345, "s": 26302, "text": "Project Structure: It will look like this." }, { "code": null, "e": 26567, "s": 26345, "text": "Adding the Social Share Buttons: After installing the next-share package we can easily add different social share buttons on any page in our app. For this example, we are going to add social share buttons to our homepage." }, { "code": null, "e": 26611, "s": 26567, "text": "Add the below content in the index.js file:" }, { "code": null, "e": 26620, "s": 26611, "text": "index.js" }, { "code": "import React from 'react'import { FacebookShareButton, FacebookIcon, PinterestShareButton, PinterestIcon, RedditShareButton, RedditIcon, WhatsappShareButton, WhatsappIcon, LinkedinShareButton, LinkedinIcon,} from 'next-share'; export default function Text() { return ( <div> <h1>Social Share - GeeksforGeeks</h1> <FacebookShareButton {/* Url you want to share */} url={'http://localhost:3000'} > <FacebookIcon size={32} round /> </FacebookShareButton> <PinterestShareButton {/* Url you want to share */} url={'http://localhost:3000'} > <PinterestIcon size={32} round /> </PinterestShareButton> <RedditShareButton {/* Url you want to share */} url={'http://localhost:3000'} > <RedditIcon size={32} round /> </RedditShareButton> <WhatsappShareButton {/* Url you want to share */} url={'http://localhost:3000'} > <WhatsappIcon size={32} round /> </WhatsappShareButton> <LinkedinShareButton {/* Url you want to share */} url={'http://localhost:3000'} > <LinkedinIcon size={32} round /> </LinkedinShareButton> </div> )}", "e": 27814, "s": 26620, "text": null }, { "code": null, "e": 28066, "s": 27814, "text": "Explanation: In the above example first, we are importing different social share buttons from our next-share package and then we are using those buttons in our Text component. You can add the URL you want to share in the URL parameter of every button." }, { "code": null, "e": 28150, "s": 28066, "text": "Steps to run the application: Run the below command in the terminal to run the app." }, { "code": null, "e": 28162, "s": 28150, "text": "npm run dev" }, { "code": null, "e": 28169, "s": 28162, "text": "Nextjs" }, { "code": null, "e": 28185, "s": 28169, "text": "React-Questions" }, { "code": null, "e": 28196, "s": 28185, "text": "JavaScript" }, { "code": null, "e": 28204, "s": 28196, "text": "ReactJS" }, { "code": null, "e": 28221, "s": 28204, "text": "Web Technologies" }, { "code": null, "e": 28319, "s": 28221, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28380, "s": 28319, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28421, "s": 28380, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28475, "s": 28421, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28515, "s": 28475, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28563, "s": 28515, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 28606, "s": 28563, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28651, "s": 28606, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 28716, "s": 28651, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 28784, "s": 28716, "text": "How to pass data from one component to other component in ReactJS ?" } ]
Algorithmic Beauty: An Introduction to Cellular Automata | by Evan Kozliner | Towards Data Science
If you’re interested in the philosophical implications of cellular automata, check out my post here. Cellular Automata (CA) are simultaneously one of the simplest and most fascinating ideas I’ve ever encountered. In this post I’ll go over some famous CAs and their properties, focusing on the “elementary” cellular automata, and the famous “Game of Life”. You won’t need to know coding to read this post, but for more technical readers I provide endnotes and Github repos. I’ve also written a library in Python to generate the CAs which I use throughout the post. I didn’t like many of the ones I was encountering elsewhere on the internet because I felt they weren’t beginner friendly enough [1]. All the code is on Github, so you can read through it: Link to elementary CA library Link to Game of Life library CAs are computational models that are typically represented by a grid with values (cells). A cell is a particular location on a grid with a value, like a cell on a spreadsheet you’d see in Microsoft Excel. Each cell in the grid evolves based on its neighbors and some rule. Elementary CAs are visualized by drawing a row of cells, then evolving that row according to a rule, and displaying the evolved row below its predecessor. All this being said, they’re easiest to understand by example: Rule / Key: *** **- *-* *-- -*- --* --- -** - - - * * * - * $ python3 Main.py --evolutions 8 --rule 30 -------*-------- ------***------- -----**--*------ ----**-****----- ---**--*---*---- --**-****-***--- -**--*----*--*-- **-****--******- The above is an example of a CA. Here’s how it was generated: First, we start at the top row of cells. The top row of cells is a hand-chosen initial configuration. The values of the top row could be anything: they could be random, or just have 1 star in the middle, as we have here. The CA will do drastically different things based on the initial conditions, but typically the same sorts of shapes will appear. Each cell from the 2nd row onwards is computed based on its own shape and the shape of its neighbors above according to the key on the top. Cutoffs are counted as “-”s. For example, row 2 column 2 is a “-” because there is a “-” “-” “-” above it, as described in the 2nd to last rule of the “Rule” above. Note that all the cells in the row evolve in parallel. The elementary CAs are often referred to as “rules” (reason why at [2]). The above CA is rule 30. Remarkably, it turns into the pattern at the top of the page if you run it for enough iterations. What’s more perplexing to experts is that despite the simple, deterministic, rules used to build the automata up, the results never converge. In other words, rule 30 never begins to exhibit any pattern in its behavior that would allow someone to predict what cells were in what state at an arbitrary row without computing all the iterations prior by brute-force. Throw any statistical tool you want at it, you won’t find anything of interest. This is interesting because most other patterns like it can be expressed algebraically, so when scientists want to know what will happen in a particular row, they can do some quick math and find out almost instantly. However, with rule 30, if we wanted to figure out what happens on the billionth row, we would actually have to generate all 1 billion rows, one by one! For this reason, rule 30 actually served as the random number generator in Mathematica for a long time. This pseudo-random behavior is what makes rule 30 so fascinating. How could something built from deterministic rules be both so beautifully ordered and impossible to predict? We’ll see this behavior in CAs that move “in time” as well; these exhibit almost lifelike behavior. Most CAs don’t have this random behavior; they converge to well-defined patterns. Take rule 94: Another CA that can produce random behavior is Rule 90. There are a lot of special things about rule 90; one of them is that is can behave predictably, or randomly based on its initial conditions. Check it out. Rule/key *** **- *-* *-- -** -*- --* --- - * - * * - * - python3 Main.py --evolutions 8 --rule 90 -------*-------- ------*-*------- -----*---*------ ----*-*-*-*----- ---*-------*---- --*-*-----*-*--- -*---*---*---*-- *-*-*-*-*-*-*-*- Notice how in the above diagram a single star in the middle produces highly self-similar behavior. Here’s an expanded of the same pattern. You’ll probably recognize this Sierpiński triangle fractal. In this configuration rule 90 is predictable. But let’s see what happens when we give it a random initial configuration instead: This is what mathematicians and philosophers mean by sensitivity to initial conditions. Most of the functions you’ve studied in school don’t behave this way. These three should give you a good idea of what elementary CAs are like. They’re only called elementary because each cell only has two states: colored, and not colored (I use * and “-” for colored and not colored, but in principle, this is the same). CAs were originally discovered by John Von Neumann and Stanislav Ulam in the 40s, but many of the CAs I talk about here weren’t found until modern computers allowed researchers to explore the space of potential CAs quickly. More contemporarily, Stephan Wolfram, the founder of Wolfram Alpha, has studied the elementary CAs exhaustively [3]. He’s shown that random patterns like the one exhibited in rule 30 don’t become any more likely when the CAs are no longer elementary. If you’re looking for more resources on elementary CAs, his book, A New Kind of Science, is probably the best resource I’ve found. Now that you know what elementary CAs are, you’ll start noticing them everywhere. Pretty amazing for such a recent discovery. Now that you’re familiar with the basic “1D” CAs, I want to show you what you can do with 2D CAs. The results are remarkable because the CAs look to be “alive”. Whenever I run these programs I feel like I have a petri dish living inside my computer. The 2D CA I want to show you is called “Conway’s Game of Life”, or just Life, as it’s referred to often in the literature. Its name and appearance are not an accident. The creator of Life, John Horton Conway, built it with the intention that it satisfied John von Neumann’s two criteria for life. (As I mention in the introduction, I wrote a library to run the game of life in the terminal that you can use to play around with these quickly if you have basic programming expertise.) Von Neumann viewed something as being ‘alive’ if it could do two things: Reproduce itselfSimulate a Turing machine Reproduce itself Simulate a Turing machine Conway succeeded in finding a CA that fit these criteria. The “creatures” in the game seem to reproduce, and, after some efforts, researchers have proven that Life is, in fact, a universal Turing machine. In other words, Life can compute anything that is possibly computable, satisfying item 2 [4]. As we saw with the elementary CAs, the rules of Life are simple to implement. But instead of considering neighbors in the row above the cell-like we did with the elementary CAs, Life counts the neighbors surrounding a cell to decide the state of the cell in the middle. Unlike elementary CAs, the next generation of cells is displayed as a “game tick” instead of another row of cells beneath the previous. Here are the rules: Any live cell with fewer than two live neighbors dies, as if by underpopulation.Any live cell with two or three live neighbors lives on to the next generation.Any live cell with more than three live neighbors dies, as if by overpopulation.Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. Any live cell with fewer than two live neighbors dies, as if by underpopulation. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies, as if by overpopulation. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. It’s worth noting that typically the grid that the cells live on will have a toroidal geometry — think pac-man style —where cells will “loop around” to look for neighbors. Amazingly, the above rules generate the complex patterns above. Here’s another example of Life, this time earlier in its evolution, and made using the Github repo I mentioned earlier: We aren’t limited to random-looking shapes though. There are a number of patterns, or “attractor states” that Life tends towards. Below is a collision between two of them. I love how the rules above can generate a sort of collision detection by themselves. These are just a few of the properties of Life. If you’re interested, definitely play around with the library I provide and read more. Also, keep in mind that Life is also far from the only 2D CA out there. If you want to check another out another 2D CA, I’d recommend Brian’s Brain. I want to leave you with a video of some of the most astounding configurations of Life. I hope it leaves you with the same feeling of mystery it left me with. [1] Much of the audience for CAs are philosophers, biologists, and high schoolers with only basic coding backgrounds. Most of the libraries I found had dependencies that could be complex for a beginner to install. I’d rather have something that people can run in the shell and see what’s going on immediately. [2] What is this numbering system? (The Wolfram Code) Wolfram also invented the numerical code that we’re using to name each rule. The numbering system requires you to understand binary, so feel free to skip this section if you don’t know binary. The number of the given rule tells you how it should react to different inputs. Here’s an example: rule 90 is 01011010 in binary. The ith digit of the binary encoding tells you how the rule behaves for input i. So rule 90 outputs a 0 for input 111 because its digit in the 8th’s place is 0 when converted to binary. Note that *** is 111 in the diagram below, which is 8 in decimal. This is easier to see visually: [3] Admittedly, I haven’t finished his 1,200-page book “A New Kind of Science”. It’s sitting in my apartment, looking at me kind of eerily. Most of it is pictures, so I’m about 200 pages through though. I’d probably finish it if it wasn’t so heavy. [4] I know this is a big statement to gloss over in a single sentence. I may do another post on Turing machines and their relationship to CAs and philosophy in another post.
[ { "code": null, "e": 273, "s": 172, "text": "If you’re interested in the philosophical implications of cellular automata, check out my post here." }, { "code": null, "e": 645, "s": 273, "text": "Cellular Automata (CA) are simultaneously one of the simplest and most fascinating ideas I’ve ever encountered. In this post I’ll go over some famous CAs and their properties, focusing on the “elementary” cellular automata, and the famous “Game of Life”. You won’t need to know coding to read this post, but for more technical readers I provide endnotes and Github repos." }, { "code": null, "e": 925, "s": 645, "text": "I’ve also written a library in Python to generate the CAs which I use throughout the post. I didn’t like many of the ones I was encountering elsewhere on the internet because I felt they weren’t beginner friendly enough [1]. All the code is on Github, so you can read through it:" }, { "code": null, "e": 955, "s": 925, "text": "Link to elementary CA library" }, { "code": null, "e": 984, "s": 955, "text": "Link to Game of Life library" }, { "code": null, "e": 1258, "s": 984, "text": "CAs are computational models that are typically represented by a grid with values (cells). A cell is a particular location on a grid with a value, like a cell on a spreadsheet you’d see in Microsoft Excel. Each cell in the grid evolves based on its neighbors and some rule." }, { "code": null, "e": 1476, "s": 1258, "text": "Elementary CAs are visualized by drawing a row of cells, then evolving that row according to a rule, and displaying the evolved row below its predecessor. All this being said, they’re easiest to understand by example:" }, { "code": null, "e": 1986, "s": 1476, "text": "Rule / Key:\n\n*** **- *-* *-- -*- --* --- -**\n - - - * * * - * \n\n$ python3 Main.py --evolutions 8 --rule 30\n -------*--------\n ------***-------\n -----**--*------\n ----**-****-----\n ---**--*---*----\n --**-****-***---\n -**--*----*--*--\n **-****--******- \n" }, { "code": null, "e": 2048, "s": 1986, "text": "The above is an example of a CA. Here’s how it was generated:" }, { "code": null, "e": 2398, "s": 2048, "text": "First, we start at the top row of cells. The top row of cells is a hand-chosen initial configuration. The values of the top row could be anything: they could be random, or just have 1 star in the middle, as we have here. The CA will do drastically different things based on the initial conditions, but typically the same sorts of shapes will appear." }, { "code": null, "e": 2758, "s": 2398, "text": "Each cell from the 2nd row onwards is computed based on its own shape and the shape of its neighbors above according to the key on the top. Cutoffs are counted as “-”s. For example, row 2 column 2 is a “-” because there is a “-” “-” “-” above it, as described in the 2nd to last rule of the “Rule” above. Note that all the cells in the row evolve in parallel." }, { "code": null, "e": 3870, "s": 2758, "text": "The elementary CAs are often referred to as “rules” (reason why at [2]). The above CA is rule 30. Remarkably, it turns into the pattern at the top of the page if you run it for enough iterations. What’s more perplexing to experts is that despite the simple, deterministic, rules used to build the automata up, the results never converge. In other words, rule 30 never begins to exhibit any pattern in its behavior that would allow someone to predict what cells were in what state at an arbitrary row without computing all the iterations prior by brute-force. Throw any statistical tool you want at it, you won’t find anything of interest. This is interesting because most other patterns like it can be expressed algebraically, so when scientists want to know what will happen in a particular row, they can do some quick math and find out almost instantly. However, with rule 30, if we wanted to figure out what happens on the billionth row, we would actually have to generate all 1 billion rows, one by one! For this reason, rule 30 actually served as the random number generator in Mathematica for a long time." }, { "code": null, "e": 4145, "s": 3870, "text": "This pseudo-random behavior is what makes rule 30 so fascinating. How could something built from deterministic rules be both so beautifully ordered and impossible to predict? We’ll see this behavior in CAs that move “in time” as well; these exhibit almost lifelike behavior." }, { "code": null, "e": 4241, "s": 4145, "text": "Most CAs don’t have this random behavior; they converge to well-defined patterns. Take rule 94:" }, { "code": null, "e": 4452, "s": 4241, "text": "Another CA that can produce random behavior is Rule 90. There are a lot of special things about rule 90; one of them is that is can behave predictably, or randomly based on its initial conditions. Check it out." }, { "code": null, "e": 4883, "s": 4452, "text": "Rule/key\n*** **- *-* *-- -** -*- --* ---\n - * - * * - * - \n\npython3 Main.py --evolutions 8 --rule 90\n -------*--------\n ------*-*-------\n -----*---*------\n ----*-*-*-*-----\n ---*-------*----\n --*-*-----*-*---\n -*---*---*---*--\n *-*-*-*-*-*-*-*-\n\n" }, { "code": null, "e": 5083, "s": 4883, "text": "Notice how in the above diagram a single star in the middle produces highly self-similar behavior. Here’s an expanded of the same pattern. You’ll probably recognize this Sierpiński triangle fractal." }, { "code": null, "e": 5212, "s": 5083, "text": "In this configuration rule 90 is predictable. But let’s see what happens when we give it a random initial configuration instead:" }, { "code": null, "e": 5370, "s": 5212, "text": "This is what mathematicians and philosophers mean by sensitivity to initial conditions. Most of the functions you’ve studied in school don’t behave this way." }, { "code": null, "e": 5621, "s": 5370, "text": "These three should give you a good idea of what elementary CAs are like. They’re only called elementary because each cell only has two states: colored, and not colored (I use * and “-” for colored and not colored, but in principle, this is the same)." }, { "code": null, "e": 6227, "s": 5621, "text": "CAs were originally discovered by John Von Neumann and Stanislav Ulam in the 40s, but many of the CAs I talk about here weren’t found until modern computers allowed researchers to explore the space of potential CAs quickly. More contemporarily, Stephan Wolfram, the founder of Wolfram Alpha, has studied the elementary CAs exhaustively [3]. He’s shown that random patterns like the one exhibited in rule 30 don’t become any more likely when the CAs are no longer elementary. If you’re looking for more resources on elementary CAs, his book, A New Kind of Science, is probably the best resource I’ve found." }, { "code": null, "e": 6353, "s": 6227, "text": "Now that you know what elementary CAs are, you’ll start noticing them everywhere. Pretty amazing for such a recent discovery." }, { "code": null, "e": 6603, "s": 6353, "text": "Now that you’re familiar with the basic “1D” CAs, I want to show you what you can do with 2D CAs. The results are remarkable because the CAs look to be “alive”. Whenever I run these programs I feel like I have a petri dish living inside my computer." }, { "code": null, "e": 6900, "s": 6603, "text": "The 2D CA I want to show you is called “Conway’s Game of Life”, or just Life, as it’s referred to often in the literature. Its name and appearance are not an accident. The creator of Life, John Horton Conway, built it with the intention that it satisfied John von Neumann’s two criteria for life." }, { "code": null, "e": 7086, "s": 6900, "text": "(As I mention in the introduction, I wrote a library to run the game of life in the terminal that you can use to play around with these quickly if you have basic programming expertise.)" }, { "code": null, "e": 7159, "s": 7086, "text": "Von Neumann viewed something as being ‘alive’ if it could do two things:" }, { "code": null, "e": 7201, "s": 7159, "text": "Reproduce itselfSimulate a Turing machine" }, { "code": null, "e": 7218, "s": 7201, "text": "Reproduce itself" }, { "code": null, "e": 7244, "s": 7218, "text": "Simulate a Turing machine" }, { "code": null, "e": 7543, "s": 7244, "text": "Conway succeeded in finding a CA that fit these criteria. The “creatures” in the game seem to reproduce, and, after some efforts, researchers have proven that Life is, in fact, a universal Turing machine. In other words, Life can compute anything that is possibly computable, satisfying item 2 [4]." }, { "code": null, "e": 7969, "s": 7543, "text": "As we saw with the elementary CAs, the rules of Life are simple to implement. But instead of considering neighbors in the row above the cell-like we did with the elementary CAs, Life counts the neighbors surrounding a cell to decide the state of the cell in the middle. Unlike elementary CAs, the next generation of cells is displayed as a “game tick” instead of another row of cells beneath the previous. Here are the rules:" }, { "code": null, "e": 8300, "s": 7969, "text": "Any live cell with fewer than two live neighbors dies, as if by underpopulation.Any live cell with two or three live neighbors lives on to the next generation.Any live cell with more than three live neighbors dies, as if by overpopulation.Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction." }, { "code": null, "e": 8381, "s": 8300, "text": "Any live cell with fewer than two live neighbors dies, as if by underpopulation." }, { "code": null, "e": 8461, "s": 8381, "text": "Any live cell with two or three live neighbors lives on to the next generation." }, { "code": null, "e": 8542, "s": 8461, "text": "Any live cell with more than three live neighbors dies, as if by overpopulation." }, { "code": null, "e": 8634, "s": 8542, "text": "Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction." }, { "code": null, "e": 8806, "s": 8634, "text": "It’s worth noting that typically the grid that the cells live on will have a toroidal geometry — think pac-man style —where cells will “loop around” to look for neighbors." }, { "code": null, "e": 8990, "s": 8806, "text": "Amazingly, the above rules generate the complex patterns above. Here’s another example of Life, this time earlier in its evolution, and made using the Github repo I mentioned earlier:" }, { "code": null, "e": 9247, "s": 8990, "text": "We aren’t limited to random-looking shapes though. There are a number of patterns, or “attractor states” that Life tends towards. Below is a collision between two of them. I love how the rules above can generate a sort of collision detection by themselves." }, { "code": null, "e": 9531, "s": 9247, "text": "These are just a few of the properties of Life. If you’re interested, definitely play around with the library I provide and read more. Also, keep in mind that Life is also far from the only 2D CA out there. If you want to check another out another 2D CA, I’d recommend Brian’s Brain." }, { "code": null, "e": 9690, "s": 9531, "text": "I want to leave you with a video of some of the most astounding configurations of Life. I hope it leaves you with the same feeling of mystery it left me with." }, { "code": null, "e": 10000, "s": 9690, "text": "[1] Much of the audience for CAs are philosophers, biologists, and high schoolers with only basic coding backgrounds. Most of the libraries I found had dependencies that could be complex for a beginner to install. I’d rather have something that people can run in the shell and see what’s going on immediately." }, { "code": null, "e": 10054, "s": 10000, "text": "[2] What is this numbering system? (The Wolfram Code)" }, { "code": null, "e": 10629, "s": 10054, "text": "Wolfram also invented the numerical code that we’re using to name each rule. The numbering system requires you to understand binary, so feel free to skip this section if you don’t know binary. The number of the given rule tells you how it should react to different inputs. Here’s an example: rule 90 is 01011010 in binary. The ith digit of the binary encoding tells you how the rule behaves for input i. So rule 90 outputs a 0 for input 111 because its digit in the 8th’s place is 0 when converted to binary. Note that *** is 111 in the diagram below, which is 8 in decimal." }, { "code": null, "e": 10661, "s": 10629, "text": "This is easier to see visually:" }, { "code": null, "e": 10910, "s": 10661, "text": "[3] Admittedly, I haven’t finished his 1,200-page book “A New Kind of Science”. It’s sitting in my apartment, looking at me kind of eerily. Most of it is pictures, so I’m about 200 pages through though. I’d probably finish it if it wasn’t so heavy." } ]
MIDI Music Data Extraction using Music21 and Word2Vec on Kaggle | by Waldecir Faria | Towards Data Science
Kaggle is a community site for data scientists and machine learners which offers several features to support their work and research. One of those feature is an online editor of scripts and notebooks which are called of “Kernel” by them. Users can create and edit Kernels online to share knowledge about some topic like machine learning algorithms or Python data structures. I was taking a look there to see if I could find anything related with music or MIDI files but I didn’t find anything. There are few databases and kernels and most of them are focused on analyzing music recommendation and preferences. This way I decided to create a new kernel there to learn more about MIDI files and play with the Word2Vec over harmonic sequences. In this article I’ll describe in high level some results which I achieved. You can find all code on my Kaggle Kernel link. Once I was reading about music generation using neural networks and remembered another article about Explainable Artificial Intelligence. Since neural networks have “hidden layers”, it becomes harder to understand why the machine “choose” to create the music using a specific structure. Then I thought, instead of letting the machine do everything, we could use the computer just to help music students to understand better musical compositions. Of course, a lot of people thought the same thing. For example, on Youtube you can find several program videos that shows which chords are being played at the music. My idea was to create a Kernel where you could choose a set of MIDI musics, analyze them and extract knowledge focused on those compositions. This way I could answer questions like “which chord Beethoven would use here?” or “which Key Signatures are more used on Sega Genesis Sonic games?” Usually when we are talking about music files, we think on files extensions like MP3 extension, which is an audio coding format for digital audio. Since they represent the music’s audio final format to be listened, concepts like “notes” or “chords” became hard to visualize. Another way of representing a music is a MIDI file. They are a very compact way of representing a sequence of notes being used on different instruments. Nowadays it is pretty easy to download a MIDI file from your favorite artist and start to play with it, transforming a piano solo into a guitar one or isolating that bass section which you love. Usually a MIDI file has less than 20kb while a MP3 one can have more than 4MBs according to the compression configurations. Moreover, MIDI files describes all notes from a composition, so we can check easily the music structure using any MIDI editor. Finally, after extracting any relevant information, we can export a common audio file from the MIDI file and apply other audio processing techniques on it, combining the better from both worlds. There are several libraries to manipulate MIDI files programmatically. Music21 is one of them. Quoting the definition from their site: Music 21 is a Python-based toolkit for computer-aided musicology. People use music21 to answer questions from musicology using computers, to study large datasets of music, to generate musical examples, to teach fundamentals of music theory, to edit musical notation, study music and the brain, and to compose music (both algorithmically and directly). I choose to use it in this project because: It uses Python code It looks pretty robust and there are people working on its code since 2006 until now It supports MIDI files well It has music analysis methods based on note sequences It can draw plots and music sheets easily Music21 makes easy to extract notes from a MIDI file. You can get all notes from each instrument and work over them as you wish. I used a Sonic’s Green Hill MIDI file for the next pictures: This library offer lots of methods to handle note sequences, in this project I mainly used a method to analyze key signatures and a method to get a chord from a note combination. For example, a note sequence [C, E, G] would result the First chord from the C-major scale. A single music can have hundreds of notes which makes it harder to analyze it. We can simplify it based on its harmony to make it easier to understand while losing some details like the melody. From Wikipedia: In music, a reduction is an arrangement or transcription of an existing score or composition in which complexity is lessened to make analysis, performance, or practice easier or clearer; the number of parts may be reduced or rhythm may be simplified, such as through the use of block chords. Manually there are several ways of doing that, considering the context on the measure being analyzed, the music’s current key signature and the set of notes on the current measure. In this project I followed these steps: Find the music key signature For each measure, sum the time which each note is pressed and choose the 4 most frequent ones Use Music21 to find the Chord and its function based on the key signature Simplify Chord names to avoid names like “bII#86#6#5”, even if it means to lose chord information Consider Bach’s Prelude in C-Major, I was able to get the following sequence using my method on it: ['I', 'ii42', 'vii53', 'I', 'vi6', 'ii42', 'V6', 'i42', ...] My method isn’t perfect, guessing several wrong chords, but now we can describe a Bach’s Prelude harmony using a string for each measure. Since that Prelude has 32 measures, in the end we get a list of 32 words describing its harmonic progression. If we could get all Bach’s works and do the same, we would end with a sequence of harmonic sequences which we could analyze and find some interesting relationships like which chord Bach would replace by another one in a composition. Word2Vec is a technique to do that with texts, citing a quote from this article: The idea behind Word2Vec is pretty simple. We’re making an assumption that the meaning of a word can be inferred by the company it keeps. This is analogous to the saying, “show me your friends, and I’ll tell who you are.” If you have two words that have very similar neighbors (meaning: the context in which its used is about the same), then these words are probably quite similar in meaning or are at least related. For example, the words shocked, appalled, and astonished are usually used in a similar context. In my Kaggle Kernel I downloaded 450 Sonic MIDI files from Sega Genesis games and generated a harmonic reduction sequence for each file. Then I trained a word2vec model to extract more information about the chord use there. With the trained model I was able to answer several questions based only on Sonic compositions, some examples: Finally, I created a method to compare several musics using my model. The word2vec trained model transforms each harmonic reduction sequence into a numeric vector and we compare them using cosine similarity. I chose this Green Hill MIDI file as the base and compared with all available versions of: Emerald Hill Theme (Sonic 2) — most similar version got score 0.990 Hydrocity Theme (Sonic 3) — most similar version got score 0.991 Sandopolis (Sonic & Knuckles) — most similar version got score 0.963 Then we could say that Sandopolis theme has the most different harmonic structure when compared with Green Hill theme. I hope that you enjoyed this article and learned more about music theory and Sonic themes. Regarding word2vec use, I need to find a good way to measure the model’s accuracy but the tests which I demonstrated previously based on music theory presented nice results. There are also a lot of space to improve on the other methods and I have several ideas to play more with that data when I have more free time. Please comment if you have questions or feedback. See you!
[ { "code": null, "e": 547, "s": 172, "text": "Kaggle is a community site for data scientists and machine learners which offers several features to support their work and research. One of those feature is an online editor of scripts and notebooks which are called of “Kernel” by them. Users can create and edit Kernels online to share knowledge about some topic like machine learning algorithms or Python data structures." }, { "code": null, "e": 782, "s": 547, "text": "I was taking a look there to see if I could find anything related with music or MIDI files but I didn’t find anything. There are few databases and kernels and most of them are focused on analyzing music recommendation and preferences." }, { "code": null, "e": 1036, "s": 782, "text": "This way I decided to create a new kernel there to learn more about MIDI files and play with the Word2Vec over harmonic sequences. In this article I’ll describe in high level some results which I achieved. You can find all code on my Kaggle Kernel link." }, { "code": null, "e": 1323, "s": 1036, "text": "Once I was reading about music generation using neural networks and remembered another article about Explainable Artificial Intelligence. Since neural networks have “hidden layers”, it becomes harder to understand why the machine “choose” to create the music using a specific structure." }, { "code": null, "e": 1648, "s": 1323, "text": "Then I thought, instead of letting the machine do everything, we could use the computer just to help music students to understand better musical compositions. Of course, a lot of people thought the same thing. For example, on Youtube you can find several program videos that shows which chords are being played at the music." }, { "code": null, "e": 1938, "s": 1648, "text": "My idea was to create a Kernel where you could choose a set of MIDI musics, analyze them and extract knowledge focused on those compositions. This way I could answer questions like “which chord Beethoven would use here?” or “which Key Signatures are more used on Sega Genesis Sonic games?”" }, { "code": null, "e": 2213, "s": 1938, "text": "Usually when we are talking about music files, we think on files extensions like MP3 extension, which is an audio coding format for digital audio. Since they represent the music’s audio final format to be listened, concepts like “notes” or “chords” became hard to visualize." }, { "code": null, "e": 2561, "s": 2213, "text": "Another way of representing a music is a MIDI file. They are a very compact way of representing a sequence of notes being used on different instruments. Nowadays it is pretty easy to download a MIDI file from your favorite artist and start to play with it, transforming a piano solo into a guitar one or isolating that bass section which you love." }, { "code": null, "e": 3007, "s": 2561, "text": "Usually a MIDI file has less than 20kb while a MP3 one can have more than 4MBs according to the compression configurations. Moreover, MIDI files describes all notes from a composition, so we can check easily the music structure using any MIDI editor. Finally, after extracting any relevant information, we can export a common audio file from the MIDI file and apply other audio processing techniques on it, combining the better from both worlds." }, { "code": null, "e": 3142, "s": 3007, "text": "There are several libraries to manipulate MIDI files programmatically. Music21 is one of them. Quoting the definition from their site:" }, { "code": null, "e": 3208, "s": 3142, "text": "Music 21 is a Python-based toolkit for computer-aided musicology." }, { "code": null, "e": 3494, "s": 3208, "text": "People use music21 to answer questions from musicology using computers, to study large datasets of music, to generate musical examples, to teach fundamentals of music theory, to edit musical notation, study music and the brain, and to compose music (both algorithmically and directly)." }, { "code": null, "e": 3538, "s": 3494, "text": "I choose to use it in this project because:" }, { "code": null, "e": 3558, "s": 3538, "text": "It uses Python code" }, { "code": null, "e": 3643, "s": 3558, "text": "It looks pretty robust and there are people working on its code since 2006 until now" }, { "code": null, "e": 3671, "s": 3643, "text": "It supports MIDI files well" }, { "code": null, "e": 3725, "s": 3671, "text": "It has music analysis methods based on note sequences" }, { "code": null, "e": 3767, "s": 3725, "text": "It can draw plots and music sheets easily" }, { "code": null, "e": 3957, "s": 3767, "text": "Music21 makes easy to extract notes from a MIDI file. You can get all notes from each instrument and work over them as you wish. I used a Sonic’s Green Hill MIDI file for the next pictures:" }, { "code": null, "e": 4228, "s": 3957, "text": "This library offer lots of methods to handle note sequences, in this project I mainly used a method to analyze key signatures and a method to get a chord from a note combination. For example, a note sequence [C, E, G] would result the First chord from the C-major scale." }, { "code": null, "e": 4438, "s": 4228, "text": "A single music can have hundreds of notes which makes it harder to analyze it. We can simplify it based on its harmony to make it easier to understand while losing some details like the melody. From Wikipedia:" }, { "code": null, "e": 4730, "s": 4438, "text": "In music, a reduction is an arrangement or transcription of an existing score or composition in which complexity is lessened to make analysis, performance, or practice easier or clearer; the number of parts may be reduced or rhythm may be simplified, such as through the use of block chords." }, { "code": null, "e": 4951, "s": 4730, "text": "Manually there are several ways of doing that, considering the context on the measure being analyzed, the music’s current key signature and the set of notes on the current measure. In this project I followed these steps:" }, { "code": null, "e": 4980, "s": 4951, "text": "Find the music key signature" }, { "code": null, "e": 5074, "s": 4980, "text": "For each measure, sum the time which each note is pressed and choose the 4 most frequent ones" }, { "code": null, "e": 5148, "s": 5074, "text": "Use Music21 to find the Chord and its function based on the key signature" }, { "code": null, "e": 5246, "s": 5148, "text": "Simplify Chord names to avoid names like “bII#86#6#5”, even if it means to lose chord information" }, { "code": null, "e": 5346, "s": 5246, "text": "Consider Bach’s Prelude in C-Major, I was able to get the following sequence using my method on it:" }, { "code": null, "e": 5407, "s": 5346, "text": "['I', 'ii42', 'vii53', 'I', 'vi6', 'ii42', 'V6', 'i42', ...]" }, { "code": null, "e": 5655, "s": 5407, "text": "My method isn’t perfect, guessing several wrong chords, but now we can describe a Bach’s Prelude harmony using a string for each measure. Since that Prelude has 32 measures, in the end we get a list of 32 words describing its harmonic progression." }, { "code": null, "e": 5888, "s": 5655, "text": "If we could get all Bach’s works and do the same, we would end with a sequence of harmonic sequences which we could analyze and find some interesting relationships like which chord Bach would replace by another one in a composition." }, { "code": null, "e": 5969, "s": 5888, "text": "Word2Vec is a technique to do that with texts, citing a quote from this article:" }, { "code": null, "e": 6191, "s": 5969, "text": "The idea behind Word2Vec is pretty simple. We’re making an assumption that the meaning of a word can be inferred by the company it keeps. This is analogous to the saying, “show me your friends, and I’ll tell who you are.”" }, { "code": null, "e": 6482, "s": 6191, "text": "If you have two words that have very similar neighbors (meaning: the context in which its used is about the same), then these words are probably quite similar in meaning or are at least related. For example, the words shocked, appalled, and astonished are usually used in a similar context." }, { "code": null, "e": 6706, "s": 6482, "text": "In my Kaggle Kernel I downloaded 450 Sonic MIDI files from Sega Genesis games and generated a harmonic reduction sequence for each file. Then I trained a word2vec model to extract more information about the chord use there." }, { "code": null, "e": 6817, "s": 6706, "text": "With the trained model I was able to answer several questions based only on Sonic compositions, some examples:" }, { "code": null, "e": 7116, "s": 6817, "text": "Finally, I created a method to compare several musics using my model. The word2vec trained model transforms each harmonic reduction sequence into a numeric vector and we compare them using cosine similarity. I chose this Green Hill MIDI file as the base and compared with all available versions of:" }, { "code": null, "e": 7184, "s": 7116, "text": "Emerald Hill Theme (Sonic 2) — most similar version got score 0.990" }, { "code": null, "e": 7249, "s": 7184, "text": "Hydrocity Theme (Sonic 3) — most similar version got score 0.991" }, { "code": null, "e": 7318, "s": 7249, "text": "Sandopolis (Sonic & Knuckles) — most similar version got score 0.963" }, { "code": null, "e": 7437, "s": 7318, "text": "Then we could say that Sandopolis theme has the most different harmonic structure when compared with Green Hill theme." }, { "code": null, "e": 7528, "s": 7437, "text": "I hope that you enjoyed this article and learned more about music theory and Sonic themes." } ]
5 Hidden Python Libraries For Cyber Security | by Pranjal Saxena | Towards Data Science
Python is now one of the most popular and fastest-growing programming languages. Its utility has been demonstrated in the fields of artificial intelligence and business analytics. Building cybersecurity solutions is yet another important application of technology. Python has some amazing libraries that can be utilised in cybersecurity. The good thing is that most of these libraries are currently being utilised in the cybersecurity area. They are using python because it is much simple to learn and user-friendly. In his article, I will share some useful libraries for creating cybersecurity solutions using python. Nmap is an open-source tool analyser that is widely used in cybersecurity. This library enables you to integrate Nmap with your Python scripts, allowing you to leverage Nmap’s capabilities to scan hosts and then interact with the results within your Python script. Nmap is a great tool for system administrators since it specialises in automating scanning operations by modifying Nmap scan findings. Nmap is a tool used by pen testers to analyse scan results and launch tailored attacks against hosts. pip install python-nmap You can learn more about Nmap on its official website here. Scapy is a sophisticated Python package that may be used for scanning, probing, unit testing, and tracerouting in penetration testing. The program’s purpose is to sniff, transmit, analyse, and modify network packets. Many modules disregard packets that the target network/host does not respond to. Scapy, on the other hand, gives the user all of the information by producing an additional list of mismatched (unanswered) packets. Scapy may also transmit incorrect frames to the target host, inject 802.11 frames, decode WEP-encrypted VOIP packets, and so on, in addition to probing packets. pip install scapy You can learn more about Scapy on its official website here. The collection of data is a crucial part of penetration testing. Penetration testers may need to extract data from HTML/XML sites on occasion. In big projects, writing a tool from the start or even doing the procedure manually might take hours or days. Beautiful Soup is a Python module that may be used to automate data scraping operations. For example, the library can read data from HTML and XML files and parse them. pip install beautifulsoup4 Let’s have a look at a glimpse of code snippets to use Beautiful Soup using Python. from bs4 import BeautifulSoupsoup = BeautifulSoup(html_doc, 'html.parser')for tag in soup.find_all('b') print(tag.name)# b You can learn more about Beautiful Soup on its official website here. It contains high-level recipes and reduced gateways to popular cryptographic methods, including symmetrical cyphers, message digests, and key derivation algorithms. Cryptographic primitives at a low level. These are frequently hazardous and can be misused. This layer is known as the “hazardous materials” or “hazmat” layer because of the risk potential when operating at this level. These are found in the cryptography.hazmat package and their explanation will always include a warning. pip install cryptography You can learn more about Cryptography on its official website here. VirusTotal’s Yara is a tool for quickly identifying patterns in data. It’s like a supercharged version of Ctrl+F. You can provide strings or regex patterns and whether or not a condition or several criteria should be satisfied. This module makes it simple to integrate Yara into your scripts. We can use it to extract data from API requests that matched on yara criteria. pip install yara-python Let’s have a look at a glimpse of code snippets to use Yara using Python. print(matches)>>[foo] You can learn more about Yara on its official website here. The given packages are very useful in your cybersecurity and will help you defend your system and effectively carry out cybersecurity measures. In addition, python’s strong libraries have made it the language of choice for programmers. These Python libraries/modules can assist developers in creating the most sophisticated Cybersecurity tools without having to write separate code for each aspect of the product. Before you go... If you liked this article and want to stay tuned with more exciting articles on Python & Data Science — do consider becoming a medium member by clicking here https://pranjalai.medium.com/membership. Please do consider signing up using my referral link. In this way, the portion of the membership fee goes to me, which motivates me to write more exciting stuff on Python and Data Science. Also, feel free to subscribe to my free newsletter: Pranjal’s Newsletter.
[ { "code": null, "e": 437, "s": 172, "text": "Python is now one of the most popular and fastest-growing programming languages. Its utility has been demonstrated in the fields of artificial intelligence and business analytics. Building cybersecurity solutions is yet another important application of technology." }, { "code": null, "e": 689, "s": 437, "text": "Python has some amazing libraries that can be utilised in cybersecurity. The good thing is that most of these libraries are currently being utilised in the cybersecurity area. They are using python because it is much simple to learn and user-friendly." }, { "code": null, "e": 791, "s": 689, "text": "In his article, I will share some useful libraries for creating cybersecurity solutions using python." }, { "code": null, "e": 1056, "s": 791, "text": "Nmap is an open-source tool analyser that is widely used in cybersecurity. This library enables you to integrate Nmap with your Python scripts, allowing you to leverage Nmap’s capabilities to scan hosts and then interact with the results within your Python script." }, { "code": null, "e": 1293, "s": 1056, "text": "Nmap is a great tool for system administrators since it specialises in automating scanning operations by modifying Nmap scan findings. Nmap is a tool used by pen testers to analyse scan results and launch tailored attacks against hosts." }, { "code": null, "e": 1317, "s": 1293, "text": "pip install python-nmap" }, { "code": null, "e": 1377, "s": 1317, "text": "You can learn more about Nmap on its official website here." }, { "code": null, "e": 1675, "s": 1377, "text": "Scapy is a sophisticated Python package that may be used for scanning, probing, unit testing, and tracerouting in penetration testing. The program’s purpose is to sniff, transmit, analyse, and modify network packets. Many modules disregard packets that the target network/host does not respond to." }, { "code": null, "e": 1968, "s": 1675, "text": "Scapy, on the other hand, gives the user all of the information by producing an additional list of mismatched (unanswered) packets. Scapy may also transmit incorrect frames to the target host, inject 802.11 frames, decode WEP-encrypted VOIP packets, and so on, in addition to probing packets." }, { "code": null, "e": 1986, "s": 1968, "text": "pip install scapy" }, { "code": null, "e": 2047, "s": 1986, "text": "You can learn more about Scapy on its official website here." }, { "code": null, "e": 2300, "s": 2047, "text": "The collection of data is a crucial part of penetration testing. Penetration testers may need to extract data from HTML/XML sites on occasion. In big projects, writing a tool from the start or even doing the procedure manually might take hours or days." }, { "code": null, "e": 2468, "s": 2300, "text": "Beautiful Soup is a Python module that may be used to automate data scraping operations. For example, the library can read data from HTML and XML files and parse them." }, { "code": null, "e": 2495, "s": 2468, "text": "pip install beautifulsoup4" }, { "code": null, "e": 2579, "s": 2495, "text": "Let’s have a look at a glimpse of code snippets to use Beautiful Soup using Python." }, { "code": null, "e": 2706, "s": 2579, "text": "from bs4 import BeautifulSoupsoup = BeautifulSoup(html_doc, 'html.parser')for tag in soup.find_all('b') print(tag.name)# b" }, { "code": null, "e": 2776, "s": 2706, "text": "You can learn more about Beautiful Soup on its official website here." }, { "code": null, "e": 3033, "s": 2776, "text": "It contains high-level recipes and reduced gateways to popular cryptographic methods, including symmetrical cyphers, message digests, and key derivation algorithms. Cryptographic primitives at a low level. These are frequently hazardous and can be misused." }, { "code": null, "e": 3264, "s": 3033, "text": "This layer is known as the “hazardous materials” or “hazmat” layer because of the risk potential when operating at this level. These are found in the cryptography.hazmat package and their explanation will always include a warning." }, { "code": null, "e": 3289, "s": 3264, "text": "pip install cryptography" }, { "code": null, "e": 3357, "s": 3289, "text": "You can learn more about Cryptography on its official website here." }, { "code": null, "e": 3585, "s": 3357, "text": "VirusTotal’s Yara is a tool for quickly identifying patterns in data. It’s like a supercharged version of Ctrl+F. You can provide strings or regex patterns and whether or not a condition or several criteria should be satisfied." }, { "code": null, "e": 3729, "s": 3585, "text": "This module makes it simple to integrate Yara into your scripts. We can use it to extract data from API requests that matched on yara criteria." }, { "code": null, "e": 3753, "s": 3729, "text": "pip install yara-python" }, { "code": null, "e": 3827, "s": 3753, "text": "Let’s have a look at a glimpse of code snippets to use Yara using Python." }, { "code": null, "e": 3849, "s": 3827, "text": "print(matches)>>[foo]" }, { "code": null, "e": 3909, "s": 3849, "text": "You can learn more about Yara on its official website here." }, { "code": null, "e": 4145, "s": 3909, "text": "The given packages are very useful in your cybersecurity and will help you defend your system and effectively carry out cybersecurity measures. In addition, python’s strong libraries have made it the language of choice for programmers." }, { "code": null, "e": 4323, "s": 4145, "text": "These Python libraries/modules can assist developers in creating the most sophisticated Cybersecurity tools without having to write separate code for each aspect of the product." }, { "code": null, "e": 4340, "s": 4323, "text": "Before you go..." }, { "code": null, "e": 4539, "s": 4340, "text": "If you liked this article and want to stay tuned with more exciting articles on Python & Data Science — do consider becoming a medium member by clicking here https://pranjalai.medium.com/membership." }, { "code": null, "e": 4728, "s": 4539, "text": "Please do consider signing up using my referral link. In this way, the portion of the membership fee goes to me, which motivates me to write more exciting stuff on Python and Data Science." } ]
Convert Long Values into Byte Using Explicit Casting in Java - GeeksforGeeks
29 Oct, 2020 In Java, a byte can contain only values from -128 to 127, if we try to cast a long value above or below the limits of the byte then there will be a precision loss. 1. byte: The byte data type is an 8-bit signed two’s complement integer. Syntax: byte varName; // Default value 0 Values: 1 byte (8 bits) : -128 to 127 2. long: The long data type is a 64-bit two’s complement integer. Syntax: long varName; // Default value 0 Values: 8 byte (64 bits): -9223372036854775808 to 9223372036854775807 Example 1: In limits Java // Java Program to Convert Long (under Byte limit)// Values into Byte using explicit castingimport java.io.*; class GFG { public static void main(String[] args) { long firstLong = 45; long secondLong = -90; // explicit type conversion from long to byte byte firstByte = (byte)firstLong; byte secondByte = (byte)secondLong; // printing typecasted value System.out.println(firstByte); System.out.println(secondByte); }} 45 -90 Example 2: Out of limits Java // Java Program to Convert Long (out of the// limits of Byte) Values into Byte using // explicit casting import java.io.*; class GFG { public static void main(String[] args) { long firstLong = 150; long secondLong = -130; // explicit type conversion from long to byte byte firstByte = (byte)firstLong; byte secondByte = (byte)secondLong; // printing typecasted value System.out.println(firstByte); System.out.println(secondByte); }} -106 126 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23557, "s": 23529, "text": "\n29 Oct, 2020" }, { "code": null, "e": 23721, "s": 23557, "text": "In Java, a byte can contain only values from -128 to 127, if we try to cast a long value above or below the limits of the byte then there will be a precision loss." }, { "code": null, "e": 23794, "s": 23721, "text": "1. byte: The byte data type is an 8-bit signed two’s complement integer." }, { "code": null, "e": 23802, "s": 23794, "text": "Syntax:" }, { "code": null, "e": 23836, "s": 23802, "text": "byte varName; // Default value 0\n" }, { "code": null, "e": 23844, "s": 23836, "text": "Values:" }, { "code": null, "e": 23876, "s": 23844, "text": "1 byte (8 bits) : \n-128 to 127\n" }, { "code": null, "e": 23943, "s": 23876, "text": "2. long: The long data type is a 64-bit two’s complement integer. " }, { "code": null, "e": 23951, "s": 23943, "text": "Syntax:" }, { "code": null, "e": 23985, "s": 23951, "text": "long varName; // Default value 0\n" }, { "code": null, "e": 23993, "s": 23985, "text": "Values:" }, { "code": null, "e": 24056, "s": 23993, "text": "8 byte (64 bits):\n-9223372036854775808 to 9223372036854775807\n" }, { "code": null, "e": 24077, "s": 24056, "text": "Example 1: In limits" }, { "code": null, "e": 24082, "s": 24077, "text": "Java" }, { "code": "// Java Program to Convert Long (under Byte limit)// Values into Byte using explicit castingimport java.io.*; class GFG { public static void main(String[] args) { long firstLong = 45; long secondLong = -90; // explicit type conversion from long to byte byte firstByte = (byte)firstLong; byte secondByte = (byte)secondLong; // printing typecasted value System.out.println(firstByte); System.out.println(secondByte); }}", "e": 24586, "s": 24082, "text": null }, { "code": null, "e": 24595, "s": 24586, "text": "45\n-90\n\n" }, { "code": null, "e": 24620, "s": 24595, "text": "Example 2: Out of limits" }, { "code": null, "e": 24625, "s": 24620, "text": "Java" }, { "code": "// Java Program to Convert Long (out of the// limits of Byte) Values into Byte using // explicit casting import java.io.*; class GFG { public static void main(String[] args) { long firstLong = 150; long secondLong = -130; // explicit type conversion from long to byte byte firstByte = (byte)firstLong; byte secondByte = (byte)secondLong; // printing typecasted value System.out.println(firstByte); System.out.println(secondByte); }}", "e": 25141, "s": 24625, "text": null }, { "code": null, "e": 25152, "s": 25141, "text": "-106\n126\n\n" }, { "code": null, "e": 25157, "s": 25152, "text": "Java" }, { "code": null, "e": 25171, "s": 25157, "text": "Java Programs" }, { "code": null, "e": 25176, "s": 25171, "text": "Java" }, { "code": null, "e": 25274, "s": 25176, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25283, "s": 25274, "text": "Comments" }, { "code": null, "e": 25296, "s": 25283, "text": "Old Comments" }, { "code": null, "e": 25326, "s": 25296, "text": "Functional Interfaces in Java" }, { "code": null, "e": 25341, "s": 25326, "text": "Stream In Java" }, { "code": null, "e": 25362, "s": 25341, "text": "Constructors in Java" }, { "code": null, "e": 25408, "s": 25362, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 25427, "s": 25408, "text": "Exceptions in Java" }, { "code": null, "e": 25471, "s": 25427, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 25497, "s": 25471, "text": "Java Programming Examples" }, { "code": null, "e": 25531, "s": 25497, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 25578, "s": 25531, "text": "Implementing a Linked List in Java using Class" } ]
Puppet - RESTful API
Puppet uses RESTful API’s as the communication channel between both Puppet master and Puppet agents. Following is the basic URL to access this RESTful API. https://brcleprod001:8140/{environment}/{resource}/{key} https://brcleprod001:8139/{environment}/{resource}/{key} Puppet usually takes care of security and SSL certificate management. However, if one wishes to use the RESTful API outside the cluster one needs to manage the certificate on their own, when trying to connect to a machine. The security policy for Puppet can be configured through the rest authconfig file. Curl utility can be used as a basic utility to rest RESTful API connectivity. Following is an example of how we can retrieve the catalog of node using REST API curl command. curl --cert /etc/puppet/ssl/certs/brcleprod001.pem --key /etc/puppet/ssl/private_keys/brcleprod001.pem In the following set of commands we are just setting the SSL certificate, which will be different depending on where the SSL directory is and the name of the node being used. For example, let’s look at the following command. curl --insecure -H 'Accept: yaml' https://brcleprod002:8140/production/catalog/brcleprod001 In the above command, we just send a header specifying the format or formats we want back and a RESTful URL for generating a catalog of brcleprod001 in production environment, will generate a the following output. --- &id001 !ruby/object:Puppet::Resource::Catalog aliases: {} applying: false classes: [] ... Let’s assume another example, where we want to get the CA certificate back from Puppet master. It doesn’t require to be authenticated with own signed SSL certificate since that is something which is required before being authenticated. curl --insecure -H 'Accept: s' https://brcleprod001:8140/production/certificate/ca -----BEGIN CERTIFICATE----- MIICHTCCAYagAwIBAgIBATANBgkqhkiG9w0BAQUFADAXMRUwEwYDVQQDDAxwdXBw GET /certificate/{ca, other} curl -k -H "Accept: s" https://brcelprod001:8140/production/certificate/ca curl -k -H "Accept: s" https://brcleprod002:8139/production/certificate/brcleprod002 Authenticated Resources (Valid, signed certificate required). GET /{environment}/catalog/{node certificate name} curl -k -H "Accept: pson" https://brcelprod001:8140/production/catalog/myclient GET /certificate_revocation_list/ca curl -k -H "Accept: s" https://brcleprod001:8140/production/certificate/ca GET /{environment}/certificate_requests/{anything} GET /{environment}/certificate_request/{node certificate name} curl -k -H "Accept: yaml" https://brcelprod001:8140/production/certificate_requests/all curl -k -H "Accept: yaml" https://brcleprod001:8140/production/certificate_request/puppetclient PUT /{environment}/report/{node certificate name} curl -k -X PUT -H "Content-Type: text/yaml" -d "{key:value}" https://brcleprod002:8139/production GET /{environment}/node/{node certificate name} curl -k -H "Accept: yaml" https://brcleprod002:8140/production/node/puppetclient GET /{environment}/status/{anything} curl -k -H "Accept: pson" https://brcleprod002:8140/production/certificate_request/puppetclient When a new agent is set up on any machine, by default Puppet agent does not listen to HTTP request. It needs to be enabled in Puppet by adding “listen=true” in puppet.conf file. This will enable Puppet agents to listen to HTTP request when the Puppet agent is starting up. GET /{environment}/facts/{anything} curl -k -H "Accept: yaml" https://brcelprod002:8139/production/facts/{anything} Run − Causes the client to update like puppetturn or puppet kick. PUT /{environment}/run/{node certificate name} curl -k -X PUT -H "Content-Type: text/pson" -d "{}" https://brcleprod002:8139/production/run/{anything} Print Add Notes Bookmark this page
[ { "code": null, "e": 2329, "s": 2173, "text": "Puppet uses RESTful API’s as the communication channel between both Puppet master and Puppet agents. Following is the basic URL to access this RESTful API." }, { "code": null, "e": 2445, "s": 2329, "text": "https://brcleprod001:8140/{environment}/{resource}/{key} \nhttps://brcleprod001:8139/{environment}/{resource}/{key}\n" }, { "code": null, "e": 2751, "s": 2445, "text": "Puppet usually takes care of security and SSL certificate management. However, if one wishes to use the RESTful API outside the cluster one needs to manage the certificate on their own, when trying to connect to a machine. The security policy for Puppet can be configured through the rest authconfig file." }, { "code": null, "e": 2925, "s": 2751, "text": "Curl utility can be used as a basic utility to rest RESTful API connectivity. Following is an example of how we can retrieve the catalog of node using REST API curl command." }, { "code": null, "e": 3033, "s": 2925, "text": "curl --cert /etc/puppet/ssl/certs/brcleprod001.pem --key \n /etc/puppet/ssl/private_keys/brcleprod001.pem\n" }, { "code": null, "e": 3258, "s": 3033, "text": "In the following set of commands we are just setting the SSL certificate, which will be different depending on where the SSL directory is and the name of the node being used. For example, let’s look at the following command." }, { "code": null, "e": 3353, "s": 3258, "text": "curl --insecure -H 'Accept: yaml' \nhttps://brcleprod002:8140/production/catalog/brcleprod001 \n" }, { "code": null, "e": 3567, "s": 3353, "text": "In the above command, we just send a header specifying the format or formats we want back and a RESTful URL for generating a catalog of brcleprod001 in production environment, will generate a the following output." }, { "code": null, "e": 3666, "s": 3567, "text": "--- &id001 !ruby/object:Puppet::Resource::Catalog \naliases: {} \napplying: false \nclasses: [] \n...\n" }, { "code": null, "e": 3902, "s": 3666, "text": "Let’s assume another example, where we want to get the CA certificate back from Puppet master. It doesn’t require to be authenticated with own signed SSL certificate since that is something which is required before being authenticated." }, { "code": null, "e": 4083, "s": 3902, "text": "curl --insecure -H 'Accept: s' https://brcleprod001:8140/production/certificate/ca \n\n-----BEGIN CERTIFICATE----- \nMIICHTCCAYagAwIBAgIBATANBgkqhkiG9w0BAQUFADAXMRUwEwYDVQQDDAxwdXBw\n" }, { "code": null, "e": 4278, "s": 4083, "text": "GET /certificate/{ca, other} \n\ncurl -k -H \"Accept: s\" https://brcelprod001:8140/production/certificate/ca \ncurl -k -H \"Accept: s\" https://brcleprod002:8139/production/certificate/brcleprod002 \n" }, { "code": null, "e": 4340, "s": 4278, "text": "Authenticated Resources (Valid, signed certificate required)." }, { "code": null, "e": 4474, "s": 4340, "text": "GET /{environment}/catalog/{node certificate name} \n\ncurl -k -H \"Accept: pson\" https://brcelprod001:8140/production/catalog/myclient\n" }, { "code": null, "e": 4589, "s": 4474, "text": "GET /certificate_revocation_list/ca \n\ncurl -k -H \"Accept: s\" https://brcleprod001:8140/production/certificate/ca \n" }, { "code": null, "e": 4894, "s": 4589, "text": "GET /{environment}/certificate_requests/{anything} GET \n/{environment}/certificate_request/{node certificate name} \n\ncurl -k -H \"Accept: yaml\" https://brcelprod001:8140/production/certificate_requests/all \ncurl -k -H \"Accept: yaml\" https://brcleprod001:8140/production/certificate_request/puppetclient \n" }, { "code": null, "e": 5045, "s": 4894, "text": "PUT /{environment}/report/{node certificate name} \ncurl -k -X PUT -H \"Content-Type: text/yaml\" -d \"{key:value}\" https://brcleprod002:8139/production\n" }, { "code": null, "e": 5179, "s": 5045, "text": "GET /{environment}/node/{node certificate name} \n\ncurl -k -H \"Accept: yaml\" https://brcleprod002:8140/production/node/puppetclient \n" }, { "code": null, "e": 5316, "s": 5179, "text": "GET /{environment}/status/{anything} \n\ncurl -k -H \"Accept: pson\" https://brcleprod002:8140/production/certificate_request/puppetclient\n" }, { "code": null, "e": 5589, "s": 5316, "text": "When a new agent is set up on any machine, by default Puppet agent does not listen to HTTP request. It needs to be enabled in Puppet by adding “listen=true” in puppet.conf file. This will enable Puppet agents to listen to HTTP request when the Puppet agent is starting up." }, { "code": null, "e": 5709, "s": 5589, "text": "GET /{environment}/facts/{anything} \n\ncurl -k -H \"Accept: yaml\" https://brcelprod002:8139/production/facts/{anything}\n" }, { "code": null, "e": 5775, "s": 5709, "text": "Run − Causes the client to update like puppetturn or puppet kick." }, { "code": null, "e": 5932, "s": 5775, "text": "PUT /{environment}/run/{node certificate name} \n\ncurl -k -X PUT -H \"Content-Type: text/pson\" -d \"{}\" \nhttps://brcleprod002:8139/production/run/{anything}\n" }, { "code": null, "e": 5939, "s": 5932, "text": " Print" }, { "code": null, "e": 5950, "s": 5939, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: HTML article element
[]
How to print a formatted text using printf() method in Java?
The printf() method allows us to format output to a java.io.PrintStream or java.io.PrintWriter. These classes also contain a method called format() which can produce the same results, so whatever we read here for the printf() method can also be applied to the format() method. System.out.printf(“format-string” [, arg1, arg2, ... ]); import java.io.PrintStream; public class PrintfTest1 { public static void main(String[] args) { int i = 1234; System.out.printf("Decimal: %1$,d Octal: %1$o Hex: %1$x"\n, i); String str = "Tutorials Point"; System.out.printf("%15s", str); } } Decimal: 1,234 Octal: 2322 Hex: 4d2 Tutorials Point public class PrintfTest2 { public static void main(String[] args) { String name = "Adithya"; int age= 30; System.out.format("%-10s - %4d\n", name, age); } } Adithya - 30
[ { "code": null, "e": 1339, "s": 1062, "text": "The printf() method allows us to format output to a java.io.PrintStream or java.io.PrintWriter. These classes also contain a method called format() which can produce the same results, so whatever we read here for the printf() method can also be applied to the format() method." }, { "code": null, "e": 1396, "s": 1339, "text": "System.out.printf(“format-string” [, arg1, arg2, ... ]);" }, { "code": null, "e": 1668, "s": 1396, "text": "import java.io.PrintStream;\npublic class PrintfTest1 {\n public static void main(String[] args) {\n int i = 1234;\n System.out.printf(\"Decimal: %1$,d Octal: %1$o Hex: %1$x\"\\n, i);\n String str = \"Tutorials Point\";\n System.out.printf(\"%15s\", str);\n }\n}" }, { "code": null, "e": 1720, "s": 1668, "text": "Decimal: 1,234 Octal: 2322 Hex: 4d2\nTutorials Point" }, { "code": null, "e": 1901, "s": 1720, "text": "public class PrintfTest2 {\n public static void main(String[] args) {\n String name = \"Adithya\";\n int age= 30;\n System.out.format(\"%-10s - %4d\\n\", name, age);\n }\n}" }, { "code": null, "e": 1919, "s": 1901, "text": "Adithya - 30" } ]
C library function - sin()
The C library function double sin(double x) returns the sine of a radian angle x. Following is the declaration for sin() function. double sin(double x) x − This is the floating point value representing an angle expressed in radians. x − This is the floating point value representing an angle expressed in radians. This function returns sine of x. The following example shows the usage of sin() function. #include <stdio.h> #include <math.h> #define PI 3.14159265 int main () { double x, ret, val; x = 45.0; val = PI / 180; ret = sin(x*val); printf("The sine of %lf is %lf degrees", x, ret); return(0); } Let us compile and run the above program to produce the following result − The sine of 45.000000 degrees is 0.707107 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2089, "s": 2007, "text": "The C library function double sin(double x) returns the sine of a radian angle x." }, { "code": null, "e": 2138, "s": 2089, "text": "Following is the declaration for sin() function." }, { "code": null, "e": 2159, "s": 2138, "text": "double sin(double x)" }, { "code": null, "e": 2240, "s": 2159, "text": "x − This is the floating point value representing an angle expressed in radians." }, { "code": null, "e": 2321, "s": 2240, "text": "x − This is the floating point value representing an angle expressed in radians." }, { "code": null, "e": 2354, "s": 2321, "text": "This function returns sine of x." }, { "code": null, "e": 2411, "s": 2354, "text": "The following example shows the usage of sin() function." }, { "code": null, "e": 2636, "s": 2411, "text": "#include <stdio.h>\n#include <math.h>\n\n#define PI 3.14159265\n\nint main () {\n double x, ret, val;\n\n x = 45.0;\n val = PI / 180;\n ret = sin(x*val);\n printf(\"The sine of %lf is %lf degrees\", x, ret);\n \n return(0);\n}" }, { "code": null, "e": 2711, "s": 2636, "text": "Let us compile and run the above program to produce the following result −" }, { "code": null, "e": 2754, "s": 2711, "text": "The sine of 45.000000 degrees is 0.707107\n" }, { "code": null, "e": 2787, "s": 2754, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2802, "s": 2787, "text": " Nishant Malik" }, { "code": null, "e": 2837, "s": 2802, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2852, "s": 2837, "text": " Nishant Malik" }, { "code": null, "e": 2887, "s": 2852, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 2901, "s": 2887, "text": " Asif Hussain" }, { "code": null, "e": 2934, "s": 2901, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2952, "s": 2934, "text": " Richa Maheshwari" }, { "code": null, "e": 2987, "s": 2952, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3006, "s": 2987, "text": " Vandana Annavaram" }, { "code": null, "e": 3039, "s": 3006, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3051, "s": 3039, "text": " Amit Diwan" }, { "code": null, "e": 3058, "s": 3051, "text": " Print" }, { "code": null, "e": 3069, "s": 3058, "text": " Add Notes" } ]
Hadoop with GCP Dataproc. An introduction to Hadoop, its services... | by Varuni Punchihewa | Towards Data Science
Today, big data analytics is one of the most rapidly growing fields in the world because of the vast amount of benefits one can gain through it. With its tremendous growth and tons of benefits, also comes its own set of issues. One of the major issues in storing big data is, you need a large space to store thousands of terabytes of data, which you cannot achieve via your personal computer. Even if you managed to store a part of your big data, it would take years to process it. As a solution to this, Hadoop was developed by Apache Software Foundation. Let’s start with: What is Hadoop? Hadoop is an open-source framework designed for storing and processing big data. Thus, Hadoop offers two major functionalities, storing big data and processing big data. We use HDFS (Hadoop Distributed File System) for storing big data and MapReduce for processing big data. We will be talking more about HDFS throughout the rest of this article. Before talking about HDFS, let’s first take a look at DFS. In a Distributed File System (DFS), you split your data into small chunks and store them across several machines separately. HDFS is a specially designed distributed file system for storing a large data set in a cluster of commodity hardware. NOTE: Commodity hardware is cheap hardware. For example, laptops you use daily are commodity hardware. Generally, you store your files and directories in your computer machine’s Hard Disk (HD). An HD is divided into Tracks, then Sectors, and finally Blocks. Generally, the size of one such block in your HD is 4 KB. NOTE: A block is a group of sectors that the operating system can point to. If I want to store a file of size 2 KB in my HD, it is stored inside one block, but there is going to be a remaining 2 KB of empty space. HD cannot use this remaining space again for some other file. Therefore that space will be wasted. Now on top of this HD, we are going to install Hadoop with HDFS. HDFS is given a block size of 128 MB by default in Hadoop 2.x (64 MB in Hadoop 1.x) If I want to store a file (example.txt) of size 300 MB in HDFS, it will be stored across three blocks as shown below. In block 3, only 44 MB will be used. It will have 84 MB of free space, and this remaining space will be released for the use of some other file. Thus, Hadoop manages data storage more efficiently than HD. NOTE: Here I have taken a file of size 300 MB for the mere benefit of explaining the concept. Usually, Hadoop deals with very large files of size terabytes! HDFS has two main services, namely NameNode and Datanode. NameNode: A master daemon that runs on the master machine which is a high-end machine. DataNode: A slave daemon that runs on commodity hardware. NOTE: Why we use a high-end machine for the NameNode is, because all the metadata is stored at the NameNode. If the NameNode fails, we lose all the information regarding where each part of the file is stored, which ultimately could lead to the loss of access to the entire Hadoop cluster. Thus, there would be no usage of the cluster anymore even the DataNodes are active because we will not be able to access the data stored there. The most common practice that is being followed to overcome this issue is to use a secondary NameNode as a backup. Master daemon Maintains and manages DataNodes Records metadata (e.g. location of blocks stored, the size of the files, permissions, hierarchy, etc.) Receives heartbeats and block reports from all the DataNodes NOTE: Heartbeat tells the NameNode that this DataNode is still alive. Slave daemons Store actual data Serve read and write requests made by the client In order to be fault-tolerant, Hadoop stores replicas of the blocks across different DataNodes. By default, the replication factor is 3. That is, it is going to keep three copies of any block in the cluster across DataNodes. Let’s take our previous example of a 300 MB file. How does Hadoop decide where to store the replicas of the blocks created? It uses Rack Awareness Algorithm. When a client requests for a read/write in a Hadoop cluster, in order to minimize the traffic, the NameNode chooses a DataNode that is closer to it. This is called Rack Aware. The replica/s of a block should not be created in the same rack where the original copy resides. Here, the replicas of block 1 should not be created in rack 1. They can be created in any other rack apart from rack 1. If I store the replicas of block 1 in rack 1 and if rack 1 fails, then I am going to lose my data in block 1. NOTE: A rack is a collection of 30 or 40 nodes that are physically stored close together and are all connected to the same network switch. Network bandwidth between any two nodes in a rack is greater than the bandwidth between two nodes on different racks. Why store the two replicas of block 1 on the same rack (rack 2)? There are two reasons for this. Firstly, the chances of both the racks (rack 1 & rack 2) failing at the same time are minimum. Secondly, the network bandwidth required to move a data file from one DataNode present in a rack to a DataNode in the same rack is very less compared to moving a data file from a DataNode present in another rack. There is no point in consuming extra bandwidth when it is not required. Taking our previous example back again, let’s say we have a client who wants to store a file called example.txt which is of size 300 MB. Since he does not have enough space in the local machine he wants to put it into the Hadoop cluster but the client does not know what are the DataNodes that are having free space to store his data. So the client first contacts the NameNode. The client sends a request to the NameNode saying that he wants to put the example.txt file into the cluster. Now the NameNode looks into the file size of the example.txt, calculates how many blocks are needed and how to split that file into a number of 128 MB of blocks. So the 300 MB file will be split into 3 blocks each holding 128 MB, 128 MB, and 44 MB respectively. Let’s call each split of the file as a.txt, b.txt, and c.txt. After that, NameNode does a quick check-up on which DataNodes are having free spaces and then gives a response back to the client saying, please go store your 300 MB file in DataNode 1, 3, and 5. Now the client first approaches DataNode1 directly to store a.txt file there. The cluster is going to keep two more backup files of the a.txt by default. Once the a.txt is stored, DataNode1 sends a copy of that file to another DataNode which is having some free space, let’s say DataNode2. And similarly, DataNode2 gives a copy of that file to another DataNode, let’s say DataNode4. Once DataNode4 stores that file with him, he sends an acknowledgment to DataNode2 saying that the file you have sent has been stored in my local DataNode. Same way, DataNode2 gives an acknowledgment to DataNode1 saying that the file you have sent has been stored in my DataNode2 as well as in DataNode4. Now, DataNode1 will give an acknowledgment back to the client saying that the sent file has been stored in the DataNode1, 2 and 4. But how does the NameNode know where the a.txt file has exactly been stored? All the DataNodes give block reports to the NameNode for every short period of time which tells the NameNode how many blocks have been occupied in the respective DataNodes. NOTE: A block report contains the block ID, the generation stamp, and the length for each block replica the server hosts. Through these block reports, the NameNode updates the information at the metadata accordingly. Same way, b.txt file, and the c.txt file will be stored in the cluster. What happens when one DataNode goes down? All the DataNodes give a heartbeat to the NameNode from time to time, which helps the NameNode to figure out whether the DataNode is alive or not. If any of the DataNode is not giving a proper heartbeat, then the NameNode considers that DataNode dead. Let’s say DataNode1 dies. Then the NameNode will remove it from the a.txt file in metadata and allocate that file to another DataNode which has free space. Let’s say it is sent to DataNode7. Then the DataNode7 sends a block report back to the NameNode, and the NameNode will update the metadata for a.txt. Let’s say the client wants to read the example.txt file he has stored previously. The client first contacts the NameNode saying that he wants to read the example.txt file. The NameNode will look into the metadata it has regarding the said file, selects the closest replica of each stored split to the client, and send the relevant IP addresses of those DataNodes back to the client. Then the client will directly reach out to those DataNodes where the blocks are stored and read the data. Once the client gets all the required file blocks, it will combine these blocks to form the file, example.txt. NOTE: While serving the read request of the client, HDFS selects the replica which is closest to the client. This reduces read latency and network bandwidth consumption. Before moving on to the hands-on, let me briefly tell you about Dataproc. Dataproc is a managed service for running Hadoop & Spark jobs (It now supports more than 30+ open source tools and frameworks). It can be used for Big Data Processing and Machine Learning. The below hands-on is about using GCP Dataproc to create a cloud cluster and run a Hadoop job on it. I will be using the Google Cloud Platform and Ubuntu 18.04.1 for this practical. First, you need to set up a Hadoop cluster. Select or create a Google Cloud Platform project You need a create a Cloud Bigtable instance. For that first, enable the Cloud Bigtable and Cloud Bigtable Admin APIs Now create a Cloud Bigtable instance via GCloud shell gcloud bigtable instances create INSTANCE_ID \ --cluster=CLUSTER_ID \ --cluster-zone=CLUSTER_ZONE \ --display-name=DISPLAY_NAME \ [--cluster-num-nodes=CLUSTER_NUM_NODES] \ [--cluster-storage-type=CLUSTER_STORAGE_TYPE] \ [--instance-type=INSTANCE_TYPE] NOTE: Make sure to use a cluster-zone where Cloud Bigtable is available. Enable the Cloud Bigtable, Cloud Bigtable Admin, Cloud Dataproc, and Cloud Storage JSON APIs. Install the gsutil tool by running gcloud components install gsutil Install Apache Maven, which will be used to run a sample Hadoop job. sudo apt-get install maven Clone the GitHub repository GoogleCloudPlatform/cloud-bigtable-examples, which contains an example of a Hadoop job that uses Cloud Bigtable. git clone https://github.com/GoogleCloudPlatform/cloud-bigtable-examples.git Now creates a Cloud Storage bucket. Cloud Dataproc uses a Cloud Storage bucket to store temporary files.gsutil mb -p [PROJECT_ID] gs://[BUCKET_NAME] NOTE: Cloud Storage bucket names must be globally unique across all buckets. Make sure you use a unique name for this. If you get a ServiceException: 409 Bucket hadoop-bucket already exists, that means the given bucket name is already being used. You can check the created buckets in a project by running gsutil ls Create a Cloud Dataproc cluster with three worker nodes. Go to the Navigation Menu, under “BIG DATA” group category you can find “Dataproc” label. Click it and select “clusters”. Click the “create cluster” button. Give a suitable name to your cluster, change the Worker nodes into 3. Click the “Advanced options” at the bottom of the page, find “Cloud Storage staging bucket section”, click “Browse” and select the bucket you have made previously. If all completed, click “create cluster” and wait for few minutes till the cluster is created. Once the cluster is created successfully, it will be displayed as follows. You can go inside the created cluster and click on the “VM Instances” tab. There you can find a list of nodes created for your cluster. Go to the directory java/dataproc-wordcount Build the project with Maven mvn clean package -Dbigtable.projectID=[PROJECT_ID] \ -Dbigtable.instanceID=[BIGTABLE_INSTANCE_ID] Once the project is fully built, you will see a “build successful” message. Now start the Hadoop job ./cluster.sh start [DATAPROC_CLUSTER_NAME] gcloud dataproc jobs submit pig --cluster test-hadoop --execute ‘fs -ls /’ You can delete the Cloud Dataproc cluster by gcloud dataproc clusters delete [DATAPROC_CLUSTER_NAME] [1] GCP Dataproc documentation [2] GCP Big Table Examples
[ { "code": null, "e": 729, "s": 172, "text": "Today, big data analytics is one of the most rapidly growing fields in the world because of the vast amount of benefits one can gain through it. With its tremendous growth and tons of benefits, also comes its own set of issues. One of the major issues in storing big data is, you need a large space to store thousands of terabytes of data, which you cannot achieve via your personal computer. Even if you managed to store a part of your big data, it would take years to process it. As a solution to this, Hadoop was developed by Apache Software Foundation." }, { "code": null, "e": 763, "s": 729, "text": "Let’s start with: What is Hadoop?" }, { "code": null, "e": 844, "s": 763, "text": "Hadoop is an open-source framework designed for storing and processing big data." }, { "code": null, "e": 1110, "s": 844, "text": "Thus, Hadoop offers two major functionalities, storing big data and processing big data. We use HDFS (Hadoop Distributed File System) for storing big data and MapReduce for processing big data. We will be talking more about HDFS throughout the rest of this article." }, { "code": null, "e": 1294, "s": 1110, "text": "Before talking about HDFS, let’s first take a look at DFS. In a Distributed File System (DFS), you split your data into small chunks and store them across several machines separately." }, { "code": null, "e": 1412, "s": 1294, "text": "HDFS is a specially designed distributed file system for storing a large data set in a cluster of commodity hardware." }, { "code": null, "e": 1515, "s": 1412, "text": "NOTE: Commodity hardware is cheap hardware. For example, laptops you use daily are commodity hardware." }, { "code": null, "e": 1728, "s": 1515, "text": "Generally, you store your files and directories in your computer machine’s Hard Disk (HD). An HD is divided into Tracks, then Sectors, and finally Blocks. Generally, the size of one such block in your HD is 4 KB." }, { "code": null, "e": 1804, "s": 1728, "text": "NOTE: A block is a group of sectors that the operating system can point to." }, { "code": null, "e": 2041, "s": 1804, "text": "If I want to store a file of size 2 KB in my HD, it is stored inside one block, but there is going to be a remaining 2 KB of empty space. HD cannot use this remaining space again for some other file. Therefore that space will be wasted." }, { "code": null, "e": 2106, "s": 2041, "text": "Now on top of this HD, we are going to install Hadoop with HDFS." }, { "code": null, "e": 2190, "s": 2106, "text": "HDFS is given a block size of 128 MB by default in Hadoop 2.x (64 MB in Hadoop 1.x)" }, { "code": null, "e": 2453, "s": 2190, "text": "If I want to store a file (example.txt) of size 300 MB in HDFS, it will be stored across three blocks as shown below. In block 3, only 44 MB will be used. It will have 84 MB of free space, and this remaining space will be released for the use of some other file." }, { "code": null, "e": 2513, "s": 2453, "text": "Thus, Hadoop manages data storage more efficiently than HD." }, { "code": null, "e": 2670, "s": 2513, "text": "NOTE: Here I have taken a file of size 300 MB for the mere benefit of explaining the concept. Usually, Hadoop deals with very large files of size terabytes!" }, { "code": null, "e": 2728, "s": 2670, "text": "HDFS has two main services, namely NameNode and Datanode." }, { "code": null, "e": 2815, "s": 2728, "text": "NameNode: A master daemon that runs on the master machine which is a high-end machine." }, { "code": null, "e": 2873, "s": 2815, "text": "DataNode: A slave daemon that runs on commodity hardware." }, { "code": null, "e": 3421, "s": 2873, "text": "NOTE: Why we use a high-end machine for the NameNode is, because all the metadata is stored at the NameNode. If the NameNode fails, we lose all the information regarding where each part of the file is stored, which ultimately could lead to the loss of access to the entire Hadoop cluster. Thus, there would be no usage of the cluster anymore even the DataNodes are active because we will not be able to access the data stored there. The most common practice that is being followed to overcome this issue is to use a secondary NameNode as a backup." }, { "code": null, "e": 3435, "s": 3421, "text": "Master daemon" }, { "code": null, "e": 3467, "s": 3435, "text": "Maintains and manages DataNodes" }, { "code": null, "e": 3570, "s": 3467, "text": "Records metadata (e.g. location of blocks stored, the size of the files, permissions, hierarchy, etc.)" }, { "code": null, "e": 3631, "s": 3570, "text": "Receives heartbeats and block reports from all the DataNodes" }, { "code": null, "e": 3701, "s": 3631, "text": "NOTE: Heartbeat tells the NameNode that this DataNode is still alive." }, { "code": null, "e": 3715, "s": 3701, "text": "Slave daemons" }, { "code": null, "e": 3733, "s": 3715, "text": "Store actual data" }, { "code": null, "e": 3782, "s": 3733, "text": "Serve read and write requests made by the client" }, { "code": null, "e": 4007, "s": 3782, "text": "In order to be fault-tolerant, Hadoop stores replicas of the blocks across different DataNodes. By default, the replication factor is 3. That is, it is going to keep three copies of any block in the cluster across DataNodes." }, { "code": null, "e": 4057, "s": 4007, "text": "Let’s take our previous example of a 300 MB file." }, { "code": null, "e": 4131, "s": 4057, "text": "How does Hadoop decide where to store the replicas of the blocks created?" }, { "code": null, "e": 4165, "s": 4131, "text": "It uses Rack Awareness Algorithm." }, { "code": null, "e": 4341, "s": 4165, "text": "When a client requests for a read/write in a Hadoop cluster, in order to minimize the traffic, the NameNode chooses a DataNode that is closer to it. This is called Rack Aware." }, { "code": null, "e": 4668, "s": 4341, "text": "The replica/s of a block should not be created in the same rack where the original copy resides. Here, the replicas of block 1 should not be created in rack 1. They can be created in any other rack apart from rack 1. If I store the replicas of block 1 in rack 1 and if rack 1 fails, then I am going to lose my data in block 1." }, { "code": null, "e": 4925, "s": 4668, "text": "NOTE: A rack is a collection of 30 or 40 nodes that are physically stored close together and are all connected to the same network switch. Network bandwidth between any two nodes in a rack is greater than the bandwidth between two nodes on different racks." }, { "code": null, "e": 4990, "s": 4925, "text": "Why store the two replicas of block 1 on the same rack (rack 2)?" }, { "code": null, "e": 5402, "s": 4990, "text": "There are two reasons for this. Firstly, the chances of both the racks (rack 1 & rack 2) failing at the same time are minimum. Secondly, the network bandwidth required to move a data file from one DataNode present in a rack to a DataNode in the same rack is very less compared to moving a data file from a DataNode present in another rack. There is no point in consuming extra bandwidth when it is not required." }, { "code": null, "e": 5890, "s": 5402, "text": "Taking our previous example back again, let’s say we have a client who wants to store a file called example.txt which is of size 300 MB. Since he does not have enough space in the local machine he wants to put it into the Hadoop cluster but the client does not know what are the DataNodes that are having free space to store his data. So the client first contacts the NameNode. The client sends a request to the NameNode saying that he wants to put the example.txt file into the cluster." }, { "code": null, "e": 6410, "s": 5890, "text": "Now the NameNode looks into the file size of the example.txt, calculates how many blocks are needed and how to split that file into a number of 128 MB of blocks. So the 300 MB file will be split into 3 blocks each holding 128 MB, 128 MB, and 44 MB respectively. Let’s call each split of the file as a.txt, b.txt, and c.txt. After that, NameNode does a quick check-up on which DataNodes are having free spaces and then gives a response back to the client saying, please go store your 300 MB file in DataNode 1, 3, and 5." }, { "code": null, "e": 7228, "s": 6410, "text": "Now the client first approaches DataNode1 directly to store a.txt file there. The cluster is going to keep two more backup files of the a.txt by default. Once the a.txt is stored, DataNode1 sends a copy of that file to another DataNode which is having some free space, let’s say DataNode2. And similarly, DataNode2 gives a copy of that file to another DataNode, let’s say DataNode4. Once DataNode4 stores that file with him, he sends an acknowledgment to DataNode2 saying that the file you have sent has been stored in my local DataNode. Same way, DataNode2 gives an acknowledgment to DataNode1 saying that the file you have sent has been stored in my DataNode2 as well as in DataNode4. Now, DataNode1 will give an acknowledgment back to the client saying that the sent file has been stored in the DataNode1, 2 and 4." }, { "code": null, "e": 7478, "s": 7228, "text": "But how does the NameNode know where the a.txt file has exactly been stored? All the DataNodes give block reports to the NameNode for every short period of time which tells the NameNode how many blocks have been occupied in the respective DataNodes." }, { "code": null, "e": 7600, "s": 7478, "text": "NOTE: A block report contains the block ID, the generation stamp, and the length for each block replica the server hosts." }, { "code": null, "e": 7767, "s": 7600, "text": "Through these block reports, the NameNode updates the information at the metadata accordingly. Same way, b.txt file, and the c.txt file will be stored in the cluster." }, { "code": null, "e": 7809, "s": 7767, "text": "What happens when one DataNode goes down?" }, { "code": null, "e": 8367, "s": 7809, "text": "All the DataNodes give a heartbeat to the NameNode from time to time, which helps the NameNode to figure out whether the DataNode is alive or not. If any of the DataNode is not giving a proper heartbeat, then the NameNode considers that DataNode dead. Let’s say DataNode1 dies. Then the NameNode will remove it from the a.txt file in metadata and allocate that file to another DataNode which has free space. Let’s say it is sent to DataNode7. Then the DataNode7 sends a block report back to the NameNode, and the NameNode will update the metadata for a.txt." }, { "code": null, "e": 8967, "s": 8367, "text": "Let’s say the client wants to read the example.txt file he has stored previously. The client first contacts the NameNode saying that he wants to read the example.txt file. The NameNode will look into the metadata it has regarding the said file, selects the closest replica of each stored split to the client, and send the relevant IP addresses of those DataNodes back to the client. Then the client will directly reach out to those DataNodes where the blocks are stored and read the data. Once the client gets all the required file blocks, it will combine these blocks to form the file, example.txt." }, { "code": null, "e": 9137, "s": 8967, "text": "NOTE: While serving the read request of the client, HDFS selects the replica which is closest to the client. This reduces read latency and network bandwidth consumption." }, { "code": null, "e": 9211, "s": 9137, "text": "Before moving on to the hands-on, let me briefly tell you about Dataproc." }, { "code": null, "e": 9400, "s": 9211, "text": "Dataproc is a managed service for running Hadoop & Spark jobs (It now supports more than 30+ open source tools and frameworks). It can be used for Big Data Processing and Machine Learning." }, { "code": null, "e": 9501, "s": 9400, "text": "The below hands-on is about using GCP Dataproc to create a cloud cluster and run a Hadoop job on it." }, { "code": null, "e": 9582, "s": 9501, "text": "I will be using the Google Cloud Platform and Ubuntu 18.04.1 for this practical." }, { "code": null, "e": 9626, "s": 9582, "text": "First, you need to set up a Hadoop cluster." }, { "code": null, "e": 9675, "s": 9626, "text": "Select or create a Google Cloud Platform project" }, { "code": null, "e": 9792, "s": 9675, "text": "You need a create a Cloud Bigtable instance. For that first, enable the Cloud Bigtable and Cloud Bigtable Admin APIs" }, { "code": null, "e": 9846, "s": 9792, "text": "Now create a Cloud Bigtable instance via GCloud shell" }, { "code": null, "e": 10116, "s": 9846, "text": "gcloud bigtable instances create INSTANCE_ID \\ --cluster=CLUSTER_ID \\ --cluster-zone=CLUSTER_ZONE \\ --display-name=DISPLAY_NAME \\ [--cluster-num-nodes=CLUSTER_NUM_NODES] \\ [--cluster-storage-type=CLUSTER_STORAGE_TYPE] \\ [--instance-type=INSTANCE_TYPE]" }, { "code": null, "e": 10189, "s": 10116, "text": "NOTE: Make sure to use a cluster-zone where Cloud Bigtable is available." }, { "code": null, "e": 10283, "s": 10189, "text": "Enable the Cloud Bigtable, Cloud Bigtable Admin, Cloud Dataproc, and Cloud Storage JSON APIs." }, { "code": null, "e": 10351, "s": 10283, "text": "Install the gsutil tool by running gcloud components install gsutil" }, { "code": null, "e": 10447, "s": 10351, "text": "Install Apache Maven, which will be used to run a sample Hadoop job. sudo apt-get install maven" }, { "code": null, "e": 10665, "s": 10447, "text": "Clone the GitHub repository GoogleCloudPlatform/cloud-bigtable-examples, which contains an example of a Hadoop job that uses Cloud Bigtable. git clone https://github.com/GoogleCloudPlatform/cloud-bigtable-examples.git" }, { "code": null, "e": 10814, "s": 10665, "text": "Now creates a Cloud Storage bucket. Cloud Dataproc uses a Cloud Storage bucket to store temporary files.gsutil mb -p [PROJECT_ID] gs://[BUCKET_NAME]" }, { "code": null, "e": 11061, "s": 10814, "text": "NOTE: Cloud Storage bucket names must be globally unique across all buckets. Make sure you use a unique name for this. If you get a ServiceException: 409 Bucket hadoop-bucket already exists, that means the given bucket name is already being used." }, { "code": null, "e": 11129, "s": 11061, "text": "You can check the created buckets in a project by running gsutil ls" }, { "code": null, "e": 11186, "s": 11129, "text": "Create a Cloud Dataproc cluster with three worker nodes." }, { "code": null, "e": 11672, "s": 11186, "text": "Go to the Navigation Menu, under “BIG DATA” group category you can find “Dataproc” label. Click it and select “clusters”. Click the “create cluster” button. Give a suitable name to your cluster, change the Worker nodes into 3. Click the “Advanced options” at the bottom of the page, find “Cloud Storage staging bucket section”, click “Browse” and select the bucket you have made previously. If all completed, click “create cluster” and wait for few minutes till the cluster is created." }, { "code": null, "e": 11747, "s": 11672, "text": "Once the cluster is created successfully, it will be displayed as follows." }, { "code": null, "e": 11883, "s": 11747, "text": "You can go inside the created cluster and click on the “VM Instances” tab. There you can find a list of nodes created for your cluster." }, { "code": null, "e": 11927, "s": 11883, "text": "Go to the directory java/dataproc-wordcount" }, { "code": null, "e": 11956, "s": 11927, "text": "Build the project with Maven" }, { "code": null, "e": 12058, "s": 11956, "text": "mvn clean package -Dbigtable.projectID=[PROJECT_ID] \\ -Dbigtable.instanceID=[BIGTABLE_INSTANCE_ID]" }, { "code": null, "e": 12134, "s": 12058, "text": "Once the project is fully built, you will see a “build successful” message." }, { "code": null, "e": 12202, "s": 12134, "text": "Now start the Hadoop job ./cluster.sh start [DATAPROC_CLUSTER_NAME]" }, { "code": null, "e": 12277, "s": 12202, "text": "gcloud dataproc jobs submit pig --cluster test-hadoop --execute ‘fs -ls /’" }, { "code": null, "e": 12322, "s": 12277, "text": "You can delete the Cloud Dataproc cluster by" }, { "code": null, "e": 12378, "s": 12322, "text": "gcloud dataproc clusters delete [DATAPROC_CLUSTER_NAME]" }, { "code": null, "e": 12409, "s": 12378, "text": "[1] GCP Dataproc documentation" } ]
Assembly - Recursion
A recursive procedure is one that calls itself. There are two kind of recursion: direct and indirect. In direct recursion, the procedure calls itself and in indirect recursion, the first procedure calls a second procedure, which in turn calls the first procedure. Recursion could be observed in numerous mathematical algorithms. For example, consider the case of calculating the factorial of a number. Factorial of a number is given by the equation − Fact (n) = n * fact (n-1) for n > 0 For example: factorial of 5 is 1 x 2 x 3 x 4 x 5 = 5 x factorial of 4 and this can be a good example of showing a recursive procedure. Every recursive algorithm must have an ending condition, i.e., the recursive calling of the program should be stopped when a condition is fulfilled. In the case of factorial algorithm, the end condition is reached when n is 0. The following program shows how factorial n is implemented in assembly language. To keep the program simple, we will calculate factorial 3. section .text global _start ;must be declared for using gcc _start: ;tell linker entry point mov bx, 3 ;for calculating factorial 3 call proc_fact add ax, 30h mov [fact], ax 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 mov edx,1 ;message length mov ecx,fact ;message to write mov ebx,1 ;file descriptor (stdout) mov eax,4 ;system call number (sys_write) int 0x80 ;call kernel mov eax,1 ;system call number (sys_exit) int 0x80 ;call kernel proc_fact: cmp bl, 1 jg do_calculation mov ax, 1 ret do_calculation: dec bl call proc_fact inc bl mul bl ;ax = al * bl ret section .data msg db 'Factorial 3 is:',0xa len equ $ - msg section .bss fact resb 1 When the above code is compiled and executed, it produces the following result − Factorial 3 is: 6 46 Lectures 2 hours Frahaan Hussain 23 Lectures 12 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2349, "s": 2085, "text": "A recursive procedure is one that calls itself. There are two kind of recursion: direct and indirect. In direct recursion, the procedure calls itself and in indirect recursion, the first procedure calls a second procedure, which in turn calls the first procedure." }, { "code": null, "e": 2536, "s": 2349, "text": "Recursion could be observed in numerous mathematical algorithms. For example, consider the case of calculating the factorial of a number. Factorial of a number is given by the equation −" }, { "code": null, "e": 2572, "s": 2536, "text": "Fact (n) = n * fact (n-1) for n > 0" }, { "code": null, "e": 2934, "s": 2572, "text": "For example: factorial of 5 is 1 x 2 x 3 x 4 x 5 = 5 x factorial of 4 and this can be a good example of showing a recursive procedure. Every recursive algorithm must have an ending condition, i.e., the recursive calling of the program should be stopped when a condition is fulfilled. In the case of factorial algorithm, the end condition is reached when n is 0." }, { "code": null, "e": 3074, "s": 2934, "text": "The following program shows how factorial n is implemented in assembly language. To keep the program simple, we will calculate factorial 3." }, { "code": null, "e": 4127, "s": 3074, "text": "section\t.text\n global _start ;must be declared for using gcc\n\t\n_start: ;tell linker entry point\n\n mov bx, 3 ;for calculating factorial 3\n call proc_fact\n add ax, 30h\n mov [fact], ax\n \n mov\t edx,len ;message length\n mov\t ecx,msg ;message to write\n mov\t ebx,1 ;file descriptor (stdout)\n mov\t eax,4 ;system call number (sys_write)\n int\t 0x80 ;call kernel\n\n mov edx,1 ;message length\n mov\t ecx,fact ;message to write\n mov\t ebx,1 ;file descriptor (stdout)\n mov\t eax,4 ;system call number (sys_write)\n int\t 0x80 ;call kernel\n \n mov\t eax,1 ;system call number (sys_exit)\n int\t 0x80 ;call kernel\n\t\nproc_fact:\n cmp bl, 1\n jg do_calculation\n mov ax, 1\n ret\n\t\ndo_calculation:\n dec bl\n call proc_fact\n inc bl\n mul bl ;ax = al * bl\n ret\n\nsection\t.data\nmsg db 'Factorial 3 is:',0xa\t\nlen equ $ - msg\t\t\t\n\nsection .bss\nfact resb 1" }, { "code": null, "e": 4208, "s": 4127, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4227, "s": 4208, "text": "Factorial 3 is:\n6\n" }, { "code": null, "e": 4260, "s": 4227, "text": "\n 46 Lectures \n 2 hours \n" }, { "code": null, "e": 4277, "s": 4260, "text": " Frahaan Hussain" }, { "code": null, "e": 4311, "s": 4277, "text": "\n 23 Lectures \n 12 hours \n" }, { "code": null, "e": 4319, "s": 4311, "text": " Uplatz" }, { "code": null, "e": 4326, "s": 4319, "text": " Print" }, { "code": null, "e": 4337, "s": 4326, "text": " Add Notes" } ]
How to remove an item from a C# list by using an index?
To remove an item from a list in C# using index, use the RemoveAt() method. Firstly, set the list − List<string> list1 = new List<string>() { "Hanks", "Lawrence", "Beckham", "Cooper", }; Now remove the element at 2nd position i.e. index 1 list1.RemoveAt(1); Let us see the complete example − Live Demo using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<string> list1 = new List<string>() { "Hanks", "Lawrence", "Beckham", "Cooper", }; Console.Write("Initial list..."); foreach (string list in list1) { Console.WriteLine(list); } Console.Write("Removing element from the list..."); list1.RemoveAt(1); foreach (string list in list1) { Console.WriteLine(list); } } } Initial list... Hanks Lawrence Beckham Cooper Removing element from the list... Hanks Beckham Cooper
[ { "code": null, "e": 1138, "s": 1062, "text": "To remove an item from a list in C# using index, use the RemoveAt() method." }, { "code": null, "e": 1162, "s": 1138, "text": "Firstly, set the list −" }, { "code": null, "e": 1261, "s": 1162, "text": "List<string> list1 = new List<string>() {\n \"Hanks\",\n \"Lawrence\",\n \"Beckham\",\n \"Cooper\",\n};" }, { "code": null, "e": 1313, "s": 1261, "text": "Now remove the element at 2nd position i.e. index 1" }, { "code": null, "e": 1332, "s": 1313, "text": "list1.RemoveAt(1);" }, { "code": null, "e": 1366, "s": 1332, "text": "Let us see the complete example −" }, { "code": null, "e": 1377, "s": 1366, "text": " Live Demo" }, { "code": null, "e": 1918, "s": 1377, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program {\n static void Main() {\n List<string> list1 = new List<string>() {\n \"Hanks\",\n \"Lawrence\",\n \"Beckham\",\n \"Cooper\",\n };\n\n Console.Write(\"Initial list...\");\n foreach (string list in list1) {\n Console.WriteLine(list);\n }\n\n Console.Write(\"Removing element from the list...\");\n list1.RemoveAt(1);\n \n foreach (string list in list1) {\n Console.WriteLine(list);\n }\n }\n}" }, { "code": null, "e": 2019, "s": 1918, "text": "Initial list...\nHanks\nLawrence\nBeckham\nCooper\nRemoving element from the list...\nHanks\nBeckham\nCooper" } ]
Create a selectable list in HTML
Use the <select> tag to create a selectable list. The HTML <select> tag is used within a form for defining a select list. The HTML <select> tag also supports the following additional attributes − You can try to run the following code to create a selectable list in HTML − <!DOCTYPE html> <html> <head> <title>HTML select Tag</title> </head> <body> <form action = "/cgi-bin/dropdown.cgi" method = "post"> <select name = "dropdown"> <option value = "Data Structures" selected>Data Structures</option> <option value = "Data Mining">Data Mining</option> </select> <input type = "submit" value = "Submit" /> </form> </body> </html>
[ { "code": null, "e": 1184, "s": 1062, "text": "Use the <select> tag to create a selectable list. The HTML <select> tag is used within a form for defining a select list." }, { "code": null, "e": 1258, "s": 1184, "text": "The HTML <select> tag also supports the following additional attributes −" }, { "code": null, "e": 1334, "s": 1258, "text": "You can try to run the following code to create a selectable list in HTML −" }, { "code": null, "e": 1770, "s": 1334, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML select Tag</title>\n </head>\n <body>\n <form action = \"/cgi-bin/dropdown.cgi\" method = \"post\">\n <select name = \"dropdown\">\n <option value = \"Data Structures\" selected>Data Structures</option>\n <option value = \"Data Mining\">Data Mining</option>\n </select>\n <input type = \"submit\" value = \"Submit\" />\n </form>\n </body>\n</html>" } ]
OpenCV Python Program to blur an image?
OpenCV is one of the best python package for image processing. Also like signals carry noise attached to it, images too contain different types of noise mainly from the source itself (Camera sensor). Python OpenCV package provides ways for image smoothing also called blurring. This is what we are going to do in this section. One of the common technique is using Gaussian filter (Gf) for image blurring. With this, any sharp edges in images are smoothed while minimizing too much blurring. cv.GaussianBlur(src, ksize, sigmaX[, dst[, sigmaY[, borderType=BORDER_DEFAULT]]] ) Where− src – input image src – input image dst – output image dst – output image ksize – Gaussian kernel size[ height width]. If ksize is set to [0 0], then ksize is computed from sigma values. ksize – Gaussian kernel size[ height width]. If ksize is set to [0 0], then ksize is computed from sigma values. sigmaX – Kernel standard deviation along X-axis(horizontal direction). sigmaX – Kernel standard deviation along X-axis(horizontal direction). sigmaY – kernel standard deviation along Y-axis(Vertical direction). sigmaY – kernel standard deviation along Y-axis(Vertical direction). Bordertype – Specifies iage boundaries while kernel is applied on image borders. Few possible values are: cv.BORDER_CONSTANT, cv.BORDER_REPLICATE, cv.BORDER_REFLECT, cv.BORDER_WRAP, cv.BORDER_DEFAULT, cv.BORDER_ISOLATED, cv.BORDER_TRANSPARENT etc. Bordertype – Specifies iage boundaries while kernel is applied on image borders. Few possible values are: cv.BORDER_CONSTANT, cv.BORDER_REPLICATE, cv.BORDER_REFLECT, cv.BORDER_WRAP, cv.BORDER_DEFAULT, cv.BORDER_ISOLATED, cv.BORDER_TRANSPARENT etc. Below is the program to Gaussian blur an image using OpenCV package. import cv2 import numpy # read image src = cv2.imread('LionKing.jpeg', cv2.IMREAD_UNCHANGED) # apply guassian blur on src image dst = cv2.GaussianBlur(src,(3,3),cv2.BORDER_DEFAULT) # display input and output image cv2.imshow("Gaussian Blur",numpy.hstack((src, dst))) cv2.waitKey(0) # waits until a key is pressed cv2.destroyAllWindows() # destroys the window showing image The two images looks almost similar (original/blur). Now let us increase the kernel size and observe the result. dst = cv2.GaussianBlur(src,(13,13),cv2.BORDER_DEFAULT) Now there is a clear distinction between the two images.
[ { "code": null, "e": 1553, "s": 1062, "text": "OpenCV is one of the best python package for image processing. Also like signals carry noise attached to it, images too contain different types of noise mainly from the source itself (Camera sensor). Python OpenCV package provides ways for image smoothing also called blurring. This is what we are going to do in this section. One of the common technique is using Gaussian filter (Gf) for image blurring. With this, any sharp edges in images are smoothed while minimizing too much blurring." }, { "code": null, "e": 1636, "s": 1553, "text": "cv.GaussianBlur(src, ksize, sigmaX[, dst[, sigmaY[, borderType=BORDER_DEFAULT]]] )" }, { "code": null, "e": 1643, "s": 1636, "text": "Where−" }, { "code": null, "e": 1661, "s": 1643, "text": "src – input image" }, { "code": null, "e": 1679, "s": 1661, "text": "src – input image" }, { "code": null, "e": 1698, "s": 1679, "text": "dst – output image" }, { "code": null, "e": 1717, "s": 1698, "text": "dst – output image" }, { "code": null, "e": 1830, "s": 1717, "text": "ksize – Gaussian kernel size[ height width]. If ksize is set to [0 0], then ksize is computed from sigma values." }, { "code": null, "e": 1943, "s": 1830, "text": "ksize – Gaussian kernel size[ height width]. If ksize is set to [0 0], then ksize is computed from sigma values." }, { "code": null, "e": 2014, "s": 1943, "text": "sigmaX – Kernel standard deviation along X-axis(horizontal direction)." }, { "code": null, "e": 2085, "s": 2014, "text": "sigmaX – Kernel standard deviation along X-axis(horizontal direction)." }, { "code": null, "e": 2154, "s": 2085, "text": "sigmaY – kernel standard deviation along Y-axis(Vertical direction)." }, { "code": null, "e": 2223, "s": 2154, "text": "sigmaY – kernel standard deviation along Y-axis(Vertical direction)." }, { "code": null, "e": 2471, "s": 2223, "text": "Bordertype – Specifies iage boundaries while kernel is applied on image borders. Few possible values are: cv.BORDER_CONSTANT, cv.BORDER_REPLICATE, cv.BORDER_REFLECT, cv.BORDER_WRAP, cv.BORDER_DEFAULT, cv.BORDER_ISOLATED, cv.BORDER_TRANSPARENT etc." }, { "code": null, "e": 2719, "s": 2471, "text": "Bordertype – Specifies iage boundaries while kernel is applied on image borders. Few possible values are: cv.BORDER_CONSTANT, cv.BORDER_REPLICATE, cv.BORDER_REFLECT, cv.BORDER_WRAP, cv.BORDER_DEFAULT, cv.BORDER_ISOLATED, cv.BORDER_TRANSPARENT etc." }, { "code": null, "e": 2788, "s": 2719, "text": "Below is the program to Gaussian blur an image using OpenCV package." }, { "code": null, "e": 3164, "s": 2788, "text": "import cv2\nimport numpy\n\n# read image\nsrc = cv2.imread('LionKing.jpeg', cv2.IMREAD_UNCHANGED)\n\n# apply guassian blur on src image\ndst = cv2.GaussianBlur(src,(3,3),cv2.BORDER_DEFAULT)\n\n# display input and output image\ncv2.imshow(\"Gaussian Blur\",numpy.hstack((src, dst)))\ncv2.waitKey(0) # waits until a key is pressed\ncv2.destroyAllWindows() # destroys the window showing image" }, { "code": null, "e": 3277, "s": 3164, "text": "The two images looks almost similar (original/blur). Now let us increase the kernel size and observe the result." }, { "code": null, "e": 3332, "s": 3277, "text": "dst = cv2.GaussianBlur(src,(13,13),cv2.BORDER_DEFAULT)" }, { "code": null, "e": 3389, "s": 3332, "text": "Now there is a clear distinction between the two images." } ]
Object Detection with Python & YOLO | by Mauro Di Pietro | Towards Data Science
In this article, I will show how to play with computer vision and have a lot of fun with a few lines of code. Computer vision is the field of Artificial Intelligence that studies how computers can gain high-level understanding from digital images or videos in order to produce numerical or symbolic information. The main tasks of computer vision are image classification and object detection. The first one recognizes what an image is about and classifies it with a label. The best example would be to classify photos of dogs and cats. But what if the task is to count how many dogs and cats are in a picture? That would be an object detection problem. Object detection deals with detecting instances of semantic objects of a certain class in digital images and videos. YOLO (You Only Look Once) is the fastest and therefore most used real-time object detection system. Basically, it applies a single neural network to the full image dividing it into regions, then the network predicts bounding boxes and probabilities for each region. In this article I will use a pre-trained YOLO model to do object detection, therefore if you want to know more about the neural network structure and how to train it, I recommend reading the original paper. There are several ways to use a pre-trained model for computer vision, the most popular frameworks are Tensorflow and Keras. However, I think that ImageAI is the most convenient tool for a lazy programmer like I am. This package facilitates the usage of deep learning and computer vision as it provides very powerful and easy functions to perform object detection and image classification. First of all, I will download the weights of the pre-trained YOLO from here (file “yolo.h5”) and store the file in some folder on my computer. modelpath = "mycomputer/myfolder/yolo.h5" Then, I can load the model very easily using ImageAI: from imageai import Detectionyolo = Detection.ObjectDetection()yolo.setModelTypeAsYOLOv3()yolo.setModelPath(modelpath)yolo.loadModel() Now the model is ready to make predictions, we just need data. I shall use the live video stream from my webcam to feed the model with real-world images. You can access your device cameras with the package OpenCV, which provides a video capture object that handles everything related to the opening and closing of the webcam. import cv2cam = cv2.VideoCapture(0) #0=front-cam, 1=back-camcam.set(cv2.CAP_PROP_FRAME_WIDTH, 1300)cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 1500) Now we can start playing with YOLO. The model will be used to predict frame by frame as they are captured by the camera until the loop gets interrupted. while True: ## read frames ret, img = cam.read() ## predict yolo img, preds = yolo.detectCustomObjectsFromImage(input_image=img, custom_objects=None, input_type="array", output_type="array", minimum_percentage_probability=70, display_percentage_probability=False, display_object_name=True) ## display predictions cv2.imshow("", img) ## press q or Esc to quit if (cv2.waitKey(1) & 0xFF == ord("q")) or (cv2.waitKey(1)==27): break## close cameracam.release()cv2.destroyAllWindows() Fun, right? And the model is doing pretty well too, even though it recognizes an orange as a “sports ball”. I’m using a minimum percentage probability of 0.70, which means that we’re able to detect objects only when the model is at least 70% sure. Lowering the value shows more objects while increasing the value ensures objects with the highest accuracy are detected. I hope you enjoyed it! Feel free to contact me for questions and feedback or just to share your interesting projects. 👉 Let’s Connect 👈
[ { "code": null, "e": 282, "s": 172, "text": "In this article, I will show how to play with computer vision and have a lot of fun with a few lines of code." }, { "code": null, "e": 484, "s": 282, "text": "Computer vision is the field of Artificial Intelligence that studies how computers can gain high-level understanding from digital images or videos in order to produce numerical or symbolic information." }, { "code": null, "e": 942, "s": 484, "text": "The main tasks of computer vision are image classification and object detection. The first one recognizes what an image is about and classifies it with a label. The best example would be to classify photos of dogs and cats. But what if the task is to count how many dogs and cats are in a picture? That would be an object detection problem. Object detection deals with detecting instances of semantic objects of a certain class in digital images and videos." }, { "code": null, "e": 1415, "s": 942, "text": "YOLO (You Only Look Once) is the fastest and therefore most used real-time object detection system. Basically, it applies a single neural network to the full image dividing it into regions, then the network predicts bounding boxes and probabilities for each region. In this article I will use a pre-trained YOLO model to do object detection, therefore if you want to know more about the neural network structure and how to train it, I recommend reading the original paper." }, { "code": null, "e": 1805, "s": 1415, "text": "There are several ways to use a pre-trained model for computer vision, the most popular frameworks are Tensorflow and Keras. However, I think that ImageAI is the most convenient tool for a lazy programmer like I am. This package facilitates the usage of deep learning and computer vision as it provides very powerful and easy functions to perform object detection and image classification." }, { "code": null, "e": 1948, "s": 1805, "text": "First of all, I will download the weights of the pre-trained YOLO from here (file “yolo.h5”) and store the file in some folder on my computer." }, { "code": null, "e": 1990, "s": 1948, "text": "modelpath = \"mycomputer/myfolder/yolo.h5\"" }, { "code": null, "e": 2044, "s": 1990, "text": "Then, I can load the model very easily using ImageAI:" }, { "code": null, "e": 2179, "s": 2044, "text": "from imageai import Detectionyolo = Detection.ObjectDetection()yolo.setModelTypeAsYOLOv3()yolo.setModelPath(modelpath)yolo.loadModel()" }, { "code": null, "e": 2333, "s": 2179, "text": "Now the model is ready to make predictions, we just need data. I shall use the live video stream from my webcam to feed the model with real-world images." }, { "code": null, "e": 2505, "s": 2333, "text": "You can access your device cameras with the package OpenCV, which provides a video capture object that handles everything related to the opening and closing of the webcam." }, { "code": null, "e": 2645, "s": 2505, "text": "import cv2cam = cv2.VideoCapture(0) #0=front-cam, 1=back-camcam.set(cv2.CAP_PROP_FRAME_WIDTH, 1300)cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 1500)" }, { "code": null, "e": 2798, "s": 2645, "text": "Now we can start playing with YOLO. The model will be used to predict frame by frame as they are captured by the camera until the loop gets interrupted." }, { "code": null, "e": 3419, "s": 2798, "text": "while True: ## read frames ret, img = cam.read() ## predict yolo img, preds = yolo.detectCustomObjectsFromImage(input_image=img, custom_objects=None, input_type=\"array\", output_type=\"array\", minimum_percentage_probability=70, display_percentage_probability=False, display_object_name=True) ## display predictions cv2.imshow(\"\", img) ## press q or Esc to quit if (cv2.waitKey(1) & 0xFF == ord(\"q\")) or (cv2.waitKey(1)==27): break## close cameracam.release()cv2.destroyAllWindows()" }, { "code": null, "e": 3527, "s": 3419, "text": "Fun, right? And the model is doing pretty well too, even though it recognizes an orange as a “sports ball”." }, { "code": null, "e": 3788, "s": 3527, "text": "I’m using a minimum percentage probability of 0.70, which means that we’re able to detect objects only when the model is at least 70% sure. Lowering the value shows more objects while increasing the value ensures objects with the highest accuracy are detected." }, { "code": null, "e": 3906, "s": 3788, "text": "I hope you enjoyed it! Feel free to contact me for questions and feedback or just to share your interesting projects." } ]
Minimum number with digits as 4 and 7 only and given sum - GeeksforGeeks
14 Mar, 2022 Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. What minimum lucky number has the sum of digits equal to n. Examples: Input : sum = 11 Output : 47 Sum of digits in 47 is 11 and 47 is the smallest number with given sum. Input : sum = 10 Output : -1 The approach is based on below facts : Since digits are 4 and 7 only, given digit sum can be written as a*4 + b*7 = sum where a and b are some positive integers (greater than or equal to 0) representing number of 4s and 7s respectively.Since we need to find minimum number, the result would always be in the form which has all 4s first, then all 7s, i.e., 44...477...7. Since digits are 4 and 7 only, given digit sum can be written as a*4 + b*7 = sum where a and b are some positive integers (greater than or equal to 0) representing number of 4s and 7s respectively. Since we need to find minimum number, the result would always be in the form which has all 4s first, then all 7s, i.e., 44...477...7. We basically need to find values of ‘a’ and ‘b’. We find these values using below facts: If sum is multiple of 4, then result has all 4s.If sum is multiple of 7, then result has all 7s.If sum is not multiple of 4 or 7, then we can subtract one of them till sum becomes multiple of other. If sum is multiple of 4, then result has all 4s. If sum is multiple of 7, then result has all 7s. If sum is not multiple of 4 or 7, then we can subtract one of them till sum becomes multiple of other. C++ Java Python3 C# PHP Javascript // C++ program to find smallest number// with given sum of digits.#include <bits/stdc++.h>using namespace std; // Prints minimum number with given digit// sum and only allowed digits as 4 and 7.void findMin(int sum){ int a = 0, b = 0; while (sum > 0) { // Cases where all remaining digits // are 4 or 7 (Remaining sum of digits // should be multiple of 4 or 7) if (sum % 7 == 0) { b++; sum -= 7; } else if (sum % 4 == 0) { a++; sum -= 4; } // If both 4s and 7s are there // in digit sum, we subtract a 4. else { a++; sum -= 4; } } if (sum < 0) { printf("-1n"); return; } for (int i=0; i<a; i++) printf("4"); for (int i=0; i<b; i++) printf("7"); printf("n");} // Driver codeint main(){ findMin(15); return 0;} // Java program to find smallest number// with given sum of digits.import java.io.*; class GFG { // Prints minimum number with given digit // sum and only allowed digits as 4 and 7. static void findMin(int sum) { int a = 0, b = 0; while (sum > 0) { // Cases where all remaining digits // are 4 or 7 (Remaining sum of digits // should be multiple of 4 or 7) if (sum % 7 == 0) { b++; sum -= 7; } else if (sum % 4 == 0) { a++; sum -= 4; } // If both 4s and 7s are there // in digit sum, we subtract a 4. else { a++; sum -= 4; } } if (sum < 0) { System.out.print("-1n"); return; } for (int i = 0; i < a; i++) System.out.print("4"); for (int i = 0; i < b; i++) System.out.print("7"); System.out.println(); } // Driver code public static void main(String args[]) throws IOException { findMin(15); }} /* This code is contributed by Nikita tiwari.*/ # Python program to find smallest number# with given sum of digits. # Prints minimum number with given digit# sum and only allowed digits as 4 and 7.def findMin(s): a, b = 0, 0 while (s > 0): # Cases where all remaining digits # are 4 or 7 (Remaining sum of digits # should be multiple of 4 or 7) if (s % 7 == 0): b += 1 s -= 7 else if (s % 4 == 0): a += 1 s -= 4 # If both 4s and 7s are there # in digit sum, we subtract a 4. else: a += 1 s -= 4 string = "" if (s < 0): string = "-1" return string string += "4" * a string += "7" * b return string # Driver codeprint(findMin(15)) # This code is contributed by Sachin Bisht // C# program to find smallest number// with given sum of digits.using System; class GFG { // Prints minimum number with given digit // sum and only allowed digits as 4 and 7. static void findMin(int sum) { int a = 0, b = 0; while (sum > 0) { // Cases where all remaining digits // are 4 or 7 (Remaining sum of digits // should be multiple of 4 or 7) if (sum % 7 == 0) { b++; sum -= 7; } else if (sum % 4 == 0) { a++; sum -= 4; } // If both 4s and 7s are there // in digit sum, we subtract a 4. else { a++; sum -= 4; } } if (sum < 0) { Console.Write("-1n"); return; } for (int i = 0; i < a; i++) Console.Write("4"); for (int i = 0; i < b; i++) Console.Write("7"); Console.WriteLine(); } // Driver code public static void Main() { findMin(15); }} // This code is contributed by Nitin Mittal. <?php// PHP program to find smallest number// with given sum of digits. // Prints minimum number with given digit// sum and only allowed digits as 4 and 7.function findMin($sum){ $a = 0; $b = 0; while ($sum > 0) { // Cases where all remaining digits // are 4 or 7 (Remaining sum of digits // should be multiple of 4 or 7) if ($sum % 7 == 0) { $b++; $sum -= 7; } else if ($sum % 4 == 0) { $a++; $sum -= 4; } // If both 4s and 7s are there // in digit sum, we subtract a 4. else { $a++; $sum -= 4; } } if ($sum < 0) { echo("-1n"); return; } for ($i = 0; $i < $a; $i++) echo("4"); for ($i = 0; $i < $b; $i++) echo("7"); echo("\n");} // Driver code findMin(15); // This code is contributed by nitin mittal?> <script> // Javascript program to find smallest number// with given sum of digits. // Prints minimum number with given digit// sum and only allowed digits as 4 and 7.function findMin(sum){ var a = 0, b = 0; while (sum > 0) { // Cases where all remaining digits // are 4 or 7 (Remaining sum of digits // should be multiple of 4 or 7) if (sum % 7 == 0) { b++; sum -= 7; } else if (sum % 4 == 0) { a++; sum -= 4; } // If both 4s and 7s are there // in digit sum, we subtract a 4. else { a++; sum -= 4; } } if (sum < 0) { document.write("-1n"); return; } for(i = 0; i < a; i++) document.write("4"); for(i = 0; i < b; i++) document.write("7"); document.write();} // Driver codefindMin(15); // This code is contributed by todaysgaurav </script> Output: 447 Time Complexity: O(sum). This article is contributed by Amit. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal todaysgaurav amartyaghoshgfg surinderdawra388 number-digits Numbers Mathematical Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Modulo 10^9+7 (1000000007) Find all factors of a natural number | Set 1 Program to find sum of elements in a given array The Knight's tour problem | Backtracking-1 Program for factorial of a number Minimum number of jumps to reach end Operators in C / C++ Efficient program to print all prime factors of a given number
[ { "code": null, "e": 23903, "s": 23875, "text": "\n14 Mar, 2022" }, { "code": null, "e": 24073, "s": 23903, "text": "Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. What minimum lucky number has the sum of digits equal to n. " }, { "code": null, "e": 24084, "s": 24073, "text": "Examples: " }, { "code": null, "e": 24220, "s": 24084, "text": "Input : sum = 11\nOutput : 47\nSum of digits in 47 is 11 and 47\nis the smallest number with given sum.\n\nInput : sum = 10\nOutput : -1 " }, { "code": null, "e": 24261, "s": 24220, "text": "The approach is based on below facts : " }, { "code": null, "e": 24592, "s": 24261, "text": "Since digits are 4 and 7 only, given digit sum can be written as a*4 + b*7 = sum where a and b are some positive integers (greater than or equal to 0) representing number of 4s and 7s respectively.Since we need to find minimum number, the result would always be in the form which has all 4s first, then all 7s, i.e., 44...477...7." }, { "code": null, "e": 24790, "s": 24592, "text": "Since digits are 4 and 7 only, given digit sum can be written as a*4 + b*7 = sum where a and b are some positive integers (greater than or equal to 0) representing number of 4s and 7s respectively." }, { "code": null, "e": 24924, "s": 24790, "text": "Since we need to find minimum number, the result would always be in the form which has all 4s first, then all 7s, i.e., 44...477...7." }, { "code": null, "e": 25015, "s": 24924, "text": "We basically need to find values of ‘a’ and ‘b’. We find these values using below facts: " }, { "code": null, "e": 25214, "s": 25015, "text": "If sum is multiple of 4, then result has all 4s.If sum is multiple of 7, then result has all 7s.If sum is not multiple of 4 or 7, then we can subtract one of them till sum becomes multiple of other." }, { "code": null, "e": 25263, "s": 25214, "text": "If sum is multiple of 4, then result has all 4s." }, { "code": null, "e": 25312, "s": 25263, "text": "If sum is multiple of 7, then result has all 7s." }, { "code": null, "e": 25415, "s": 25312, "text": "If sum is not multiple of 4 or 7, then we can subtract one of them till sum becomes multiple of other." }, { "code": null, "e": 25419, "s": 25415, "text": "C++" }, { "code": null, "e": 25424, "s": 25419, "text": "Java" }, { "code": null, "e": 25432, "s": 25424, "text": "Python3" }, { "code": null, "e": 25435, "s": 25432, "text": "C#" }, { "code": null, "e": 25439, "s": 25435, "text": "PHP" }, { "code": null, "e": 25450, "s": 25439, "text": "Javascript" }, { "code": "// C++ program to find smallest number// with given sum of digits.#include <bits/stdc++.h>using namespace std; // Prints minimum number with given digit// sum and only allowed digits as 4 and 7.void findMin(int sum){ int a = 0, b = 0; while (sum > 0) { // Cases where all remaining digits // are 4 or 7 (Remaining sum of digits // should be multiple of 4 or 7) if (sum % 7 == 0) { b++; sum -= 7; } else if (sum % 4 == 0) { a++; sum -= 4; } // If both 4s and 7s are there // in digit sum, we subtract a 4. else { a++; sum -= 4; } } if (sum < 0) { printf(\"-1n\"); return; } for (int i=0; i<a; i++) printf(\"4\"); for (int i=0; i<b; i++) printf(\"7\"); printf(\"n\");} // Driver codeint main(){ findMin(15); return 0;}", "e": 26392, "s": 25450, "text": null }, { "code": "// Java program to find smallest number// with given sum of digits.import java.io.*; class GFG { // Prints minimum number with given digit // sum and only allowed digits as 4 and 7. static void findMin(int sum) { int a = 0, b = 0; while (sum > 0) { // Cases where all remaining digits // are 4 or 7 (Remaining sum of digits // should be multiple of 4 or 7) if (sum % 7 == 0) { b++; sum -= 7; } else if (sum % 4 == 0) { a++; sum -= 4; } // If both 4s and 7s are there // in digit sum, we subtract a 4. else { a++; sum -= 4; } } if (sum < 0) { System.out.print(\"-1n\"); return; } for (int i = 0; i < a; i++) System.out.print(\"4\"); for (int i = 0; i < b; i++) System.out.print(\"7\"); System.out.println(); } // Driver code public static void main(String args[]) throws IOException { findMin(15); }} /* This code is contributed by Nikita tiwari.*/", "e": 27704, "s": 26392, "text": null }, { "code": "# Python program to find smallest number# with given sum of digits. # Prints minimum number with given digit# sum and only allowed digits as 4 and 7.def findMin(s): a, b = 0, 0 while (s > 0): # Cases where all remaining digits # are 4 or 7 (Remaining sum of digits # should be multiple of 4 or 7) if (s % 7 == 0): b += 1 s -= 7 else if (s % 4 == 0): a += 1 s -= 4 # If both 4s and 7s are there # in digit sum, we subtract a 4. else: a += 1 s -= 4 string = \"\" if (s < 0): string = \"-1\" return string string += \"4\" * a string += \"7\" * b return string # Driver codeprint(findMin(15)) # This code is contributed by Sachin Bisht", "e": 28511, "s": 27704, "text": null }, { "code": "// C# program to find smallest number// with given sum of digits.using System; class GFG { // Prints minimum number with given digit // sum and only allowed digits as 4 and 7. static void findMin(int sum) { int a = 0, b = 0; while (sum > 0) { // Cases where all remaining digits // are 4 or 7 (Remaining sum of digits // should be multiple of 4 or 7) if (sum % 7 == 0) { b++; sum -= 7; } else if (sum % 4 == 0) { a++; sum -= 4; } // If both 4s and 7s are there // in digit sum, we subtract a 4. else { a++; sum -= 4; } } if (sum < 0) { Console.Write(\"-1n\"); return; } for (int i = 0; i < a; i++) Console.Write(\"4\"); for (int i = 0; i < b; i++) Console.Write(\"7\"); Console.WriteLine(); } // Driver code public static void Main() { findMin(15); }} // This code is contributed by Nitin Mittal.", "e": 29758, "s": 28511, "text": null }, { "code": "<?php// PHP program to find smallest number// with given sum of digits. // Prints minimum number with given digit// sum and only allowed digits as 4 and 7.function findMin($sum){ $a = 0; $b = 0; while ($sum > 0) { // Cases where all remaining digits // are 4 or 7 (Remaining sum of digits // should be multiple of 4 or 7) if ($sum % 7 == 0) { $b++; $sum -= 7; } else if ($sum % 4 == 0) { $a++; $sum -= 4; } // If both 4s and 7s are there // in digit sum, we subtract a 4. else { $a++; $sum -= 4; } } if ($sum < 0) { echo(\"-1n\"); return; } for ($i = 0; $i < $a; $i++) echo(\"4\"); for ($i = 0; $i < $b; $i++) echo(\"7\"); echo(\"\\n\");} // Driver code findMin(15); // This code is contributed by nitin mittal?>", "e": 30712, "s": 29758, "text": null }, { "code": "<script> // Javascript program to find smallest number// with given sum of digits. // Prints minimum number with given digit// sum and only allowed digits as 4 and 7.function findMin(sum){ var a = 0, b = 0; while (sum > 0) { // Cases where all remaining digits // are 4 or 7 (Remaining sum of digits // should be multiple of 4 or 7) if (sum % 7 == 0) { b++; sum -= 7; } else if (sum % 4 == 0) { a++; sum -= 4; } // If both 4s and 7s are there // in digit sum, we subtract a 4. else { a++; sum -= 4; } } if (sum < 0) { document.write(\"-1n\"); return; } for(i = 0; i < a; i++) document.write(\"4\"); for(i = 0; i < b; i++) document.write(\"7\"); document.write();} // Driver codefindMin(15); // This code is contributed by todaysgaurav </script>", "e": 31692, "s": 30712, "text": null }, { "code": null, "e": 31701, "s": 31692, "text": "Output: " }, { "code": null, "e": 31705, "s": 31701, "text": "447" }, { "code": null, "e": 31730, "s": 31705, "text": "Time Complexity: O(sum)." }, { "code": null, "e": 32143, "s": 31730, "text": "This article is contributed by Amit. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32156, "s": 32143, "text": "nitin mittal" }, { "code": null, "e": 32169, "s": 32156, "text": "todaysgaurav" }, { "code": null, "e": 32185, "s": 32169, "text": "amartyaghoshgfg" }, { "code": null, "e": 32202, "s": 32185, "text": "surinderdawra388" }, { "code": null, "e": 32216, "s": 32202, "text": "number-digits" }, { "code": null, "e": 32224, "s": 32216, "text": "Numbers" }, { "code": null, "e": 32237, "s": 32224, "text": "Mathematical" }, { "code": null, "e": 32250, "s": 32237, "text": "Mathematical" }, { "code": null, "e": 32258, "s": 32250, "text": "Numbers" }, { "code": null, "e": 32356, "s": 32258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32365, "s": 32356, "text": "Comments" }, { "code": null, "e": 32378, "s": 32365, "text": "Old Comments" }, { "code": null, "e": 32402, "s": 32378, "text": "Merge two sorted arrays" }, { "code": null, "e": 32445, "s": 32402, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 32472, "s": 32445, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 32517, "s": 32472, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 32566, "s": 32517, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32609, "s": 32566, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 32643, "s": 32609, "text": "Program for factorial of a number" }, { "code": null, "e": 32680, "s": 32643, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 32701, "s": 32680, "text": "Operators in C / C++" } ]
Python - Test if Values Sum is Greater than Keys Sum in dictionary - GeeksforGeeks
12 Nov, 2020 Given a Dictionary, check if the summation of values is greater than Keys sum. Input : test_dict = {5:3, 1:3, 10:4, 7:3, 8:1, 9:5} Output : False Explanation : Values sum = 19 < 40, which is key sum, i.e false. Input : test_dict = {5:3, 1:4} Output : True Explanation : Values sum = 7 > 6, which is key sum, i.e true. Method #1: Using loop In this, we compute keys and values sum in separate counter, and after the loop equate the values, if values are greater than Keys summation, True is returned. Python3 # Python3 code to demonstrate working of# Test if Values Sum is Greater than Keys Sum in dictionary# Using loop # initializing dictionarytest_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) key_sum = 0val_sum = 0 for key in test_dict: # getting sum key_sum += key val_sum += test_dict[key] # checking if val_sum greater than key sumres = val_sum > key_sum # printing resultprint("The required result : " + str(res)) The original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5} The required result : False Method #2 : Using sum() + values() + keys() In this way, keys sum and values sum is extracted using keys(), values() and summation using sum(), the required condition is checked and verdict is computed. Python3 # Python3 code to demonstrate working of# Test if Values Sum is Greater than Keys Sum in dictionary# Using sum() + values() + keys() # initializing dictionarytest_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) res = sum(list(test_dict.keys())) < sum(list(test_dict.values())) # printing resultprint("The required result : " + str(res)) The original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5} The required result : False Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 24390, "s": 24362, "text": "\n12 Nov, 2020" }, { "code": null, "e": 24469, "s": 24390, "text": "Given a Dictionary, check if the summation of values is greater than Keys sum." }, { "code": null, "e": 24601, "s": 24469, "text": "Input : test_dict = {5:3, 1:3, 10:4, 7:3, 8:1, 9:5} Output : False Explanation : Values sum = 19 < 40, which is key sum, i.e false." }, { "code": null, "e": 24709, "s": 24601, "text": "Input : test_dict = {5:3, 1:4} Output : True Explanation : Values sum = 7 > 6, which is key sum, i.e true. " }, { "code": null, "e": 24731, "s": 24709, "text": "Method #1: Using loop" }, { "code": null, "e": 24891, "s": 24731, "text": "In this, we compute keys and values sum in separate counter, and after the loop equate the values, if values are greater than Keys summation, True is returned." }, { "code": null, "e": 24899, "s": 24891, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Test if Values Sum is Greater than Keys Sum in dictionary# Using loop # initializing dictionarytest_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) key_sum = 0val_sum = 0 for key in test_dict: # getting sum key_sum += key val_sum += test_dict[key] # checking if val_sum greater than key sumres = val_sum > key_sum # printing resultprint(\"The required result : \" + str(res))", "e": 25415, "s": 24899, "text": null }, { "code": null, "e": 25511, "s": 25415, "text": "The original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}\nThe required result : False\n" }, { "code": null, "e": 25556, "s": 25511, "text": "Method #2 : Using sum() + values() + keys()" }, { "code": null, "e": 25715, "s": 25556, "text": "In this way, keys sum and values sum is extracted using keys(), values() and summation using sum(), the required condition is checked and verdict is computed." }, { "code": null, "e": 25723, "s": 25715, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Test if Values Sum is Greater than Keys Sum in dictionary# Using sum() + values() + keys() # initializing dictionarytest_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) res = sum(list(test_dict.keys())) < sum(list(test_dict.values())) # printing resultprint(\"The required result : \" + str(res))", "e": 26148, "s": 25723, "text": null }, { "code": null, "e": 26244, "s": 26148, "text": "The original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}\nThe required result : False\n" }, { "code": null, "e": 26271, "s": 26244, "text": "Python dictionary-programs" }, { "code": null, "e": 26278, "s": 26271, "text": "Python" }, { "code": null, "e": 26294, "s": 26278, "text": "Python Programs" }, { "code": null, "e": 26392, "s": 26294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26424, "s": 26392, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26466, "s": 26424, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26508, "s": 26466, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26564, "s": 26508, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26586, "s": 26564, "text": "Defaultdict in Python" }, { "code": null, "e": 26608, "s": 26586, "text": "Defaultdict in Python" }, { "code": null, "e": 26647, "s": 26608, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26693, "s": 26647, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26731, "s": 26693, "text": "Python | Convert a list to dictionary" } ]
Food & Beverage Services - Food Garnishing
The guests’ experience of food and beverage starts when the serving staff brings beautifully garnished food with the appropriate accompaniments on their table. The service staff turns a guiding hand to the guests in suggesting which accompaniment will go well with the main food the guest is interested in having. There are numerous interesting pairs of foods with their garnishes or accompaniments. Let us see in detail about garnishing, food accompaniments, and some typical food-garnishing paired with accompaniments. It is the way of decorating the food or beverage so that it is aesthetically appealing for the guests/customers. It works on the plate. Garnishing also harmonizes color, flavor, and taste of the main dish. Chopped herbs or small twigs of herbs, leafy vegetables, twirls of carrots or tomatoes, swirls of fresh cream, fruit glaze, chopped nuts, seedless berries, and lemon zest or slices are used for garnishing. Desserts are garnished with dried fruits, fresh fruit zests, glazes, roasted or candied nuts, frostings, chocolate curls, chocolate coated buts, or small pieces of sugar arts. Drinks like cocktails and mocktails are garnished using fruit pieces and zests, mint leaves, and castor sugar. Milk based drinks are garnished mostly with fruit pieces, cherries, chocolates, or nuts. The following are some important Dos and Don’ts to be understood in food garnishing − Place it where it seems just perfect. Contrast color schemes work best for garnishing. Do not overdo garnishing; this overshadows the main food. Do not reuse the garnish. Avoid being too elaborate. There are dishes that come along with accompaniments. These accompaniments complement the main food and enrich its taste. It provides an aesthetic value to the main dish. The accompanying food or beverage itself can have a garnish of its own. An accompaniment can be inside the main dish or in a separate bowl. The following are a few different types of accompaniments − Sauces and Dips Pickles Dressings Chips and Wedges Salads Gravies Beverages such as soft drinks or wines Breads For example, grilled Hake fish served with potato chips and Pizza served with garlic bread, cheese dip, and a carbonated beverage. The following are a few popular food items with their garnishing and accompaniments − There are no stringent rules for which wine goes well with which cheese but one must observe the following guidelines while pairing wines with cheese − Select wine and cheese originating from the same region. Dessert wines accompanying the desserts must be sweeter than the dessert itself. Cheeses go well with wines of contrast taste. Lighter chocolates contain more milk based-products and less chocolate. Chocolates with light and elegant tastes are paired best with light-bodied wines. The ones with more bitter taste are paired with intense flavored full-bodied wines. A critical standardized recipe is one that, “has been tried, adapted, and retried several times for use by a given food service operation and has been found to yield the same good results under same procedures, equipment, and quantity and quality of ingredients.” Generally, popular menu items are developed using standard recipes, ingredients, and presentation. A standardized recipe can bring in the following benefits − Consistency in food quality. Consistency in nutrients per unit serving. Increase in customer satisfaction. Control on cost of food. Prediction of accurate yield. Reduction in food leftover and record keeping. Increase in the confidence of employees. A typical standardized recipe is composed of the following description − Recipe name/title − It is the name that describes the recipe in brief. Recipe name/title − It is the name that describes the recipe in brief. Recipe section − It is the section that the recipe should be classified under (grains, starters, desserts, etc.) Recipe section − It is the section that the recipe should be classified under (grains, starters, desserts, etc.) Ingredients − Types (fresh/canned/cooked/uncooked/ground, etc.) Ingredients − Types (fresh/canned/cooked/uncooked/ground, etc.) Weight and measures of ingredients Weight and measures of ingredients Method − This is a set of instructions to prepare a particular recipe. A method includes guidelines for steps such as mixing, selecting pans, and setting the right cooking temperature. Method − This is a set of instructions to prepare a particular recipe. A method includes guidelines for steps such as mixing, selecting pans, and setting the right cooking temperature. Time − This includes preparation time, cooking time, and serving time. Time − This includes preparation time, cooking time, and serving time. Serving size − It is the portion of food to be served. Serving size − It is the portion of food to be served. Critical Control Points (CCP) − They are control measures taken to avoid food safety hazards. Every CCP includes control of time, preparation, and cooking temperature. Critical Control Points (CCP) − They are control measures taken to avoid food safety hazards. Every CCP includes control of time, preparation, and cooking temperature. Predicting the total yield for a particular number of customers and calculating weights of ingredients accordingly is important in standardized recipes. For recipe to be prepared for new lot of customers, the total yield changes. The new yield can be calculated in the following two steps − Step 1 − Calculate conversion factor as − Conversion Factor = New Yield / Old Yield Step 2 − Multiply the measure of each ingredient by the conversion factor to obtain the new yield − New Yield = Old ingredient quantity x Conversion factor 18 Lectures 2 hours Manish Gupta 185 Lectures 46.5 hours Nikhil Agarwal 10 Lectures 34 mins Faiq Ismayilov 7 Lectures 52 mins Dr. Harris Print Add Notes Bookmark this page
[ { "code": null, "e": 2618, "s": 2304, "text": "The guests’ experience of food and beverage starts when the serving staff brings beautifully garnished food with the appropriate accompaniments on their table. The service staff turns a guiding hand to the guests in suggesting which accompaniment will go well with the main food the guest is interested in having." }, { "code": null, "e": 2825, "s": 2618, "text": "There are numerous interesting pairs of foods with their garnishes or accompaniments. Let us see in detail about garnishing, food accompaniments, and some typical food-garnishing paired with accompaniments." }, { "code": null, "e": 3031, "s": 2825, "text": "It is the way of decorating the food or beverage so that it is aesthetically appealing for the guests/customers. It works on the plate. Garnishing also harmonizes color, flavor, and taste of the main dish." }, { "code": null, "e": 3237, "s": 3031, "text": "Chopped herbs or small twigs of herbs, leafy vegetables, twirls of carrots or tomatoes, swirls of fresh cream, fruit glaze, chopped nuts, seedless berries, and lemon zest or slices are used for garnishing." }, { "code": null, "e": 3413, "s": 3237, "text": "Desserts are garnished with dried fruits, fresh fruit zests, glazes, roasted or candied nuts, frostings, chocolate curls, chocolate coated buts, or small pieces of sugar arts." }, { "code": null, "e": 3613, "s": 3413, "text": "Drinks like cocktails and mocktails are garnished using fruit pieces and zests, mint leaves, and castor sugar. Milk based drinks are garnished mostly with fruit pieces, cherries, chocolates, or nuts." }, { "code": null, "e": 3699, "s": 3613, "text": "The following are some important Dos and Don’ts to be understood in food garnishing −" }, { "code": null, "e": 3737, "s": 3699, "text": "Place it where it seems just perfect." }, { "code": null, "e": 3786, "s": 3737, "text": "Contrast color schemes work best for garnishing." }, { "code": null, "e": 3844, "s": 3786, "text": "Do not overdo garnishing; this overshadows the main food." }, { "code": null, "e": 3870, "s": 3844, "text": "Do not reuse the garnish." }, { "code": null, "e": 3897, "s": 3870, "text": "Avoid being too elaborate." }, { "code": null, "e": 4208, "s": 3897, "text": "There are dishes that come along with accompaniments. These accompaniments complement the main food and enrich its taste. It provides an aesthetic value to the main dish. The accompanying food or beverage itself can have a garnish of its own. An accompaniment can be inside the main dish or in a separate bowl." }, { "code": null, "e": 4268, "s": 4208, "text": "The following are a few different types of accompaniments −" }, { "code": null, "e": 4284, "s": 4268, "text": "Sauces and Dips" }, { "code": null, "e": 4292, "s": 4284, "text": "Pickles" }, { "code": null, "e": 4302, "s": 4292, "text": "Dressings" }, { "code": null, "e": 4319, "s": 4302, "text": "Chips and Wedges" }, { "code": null, "e": 4326, "s": 4319, "text": "Salads" }, { "code": null, "e": 4334, "s": 4326, "text": "Gravies" }, { "code": null, "e": 4373, "s": 4334, "text": "Beverages such as soft drinks or wines" }, { "code": null, "e": 4380, "s": 4373, "text": "Breads" }, { "code": null, "e": 4511, "s": 4380, "text": "For example, grilled Hake fish served with potato chips and Pizza served with garlic bread, cheese dip, and a carbonated beverage." }, { "code": null, "e": 4597, "s": 4511, "text": "The following are a few popular food items with their garnishing and accompaniments −" }, { "code": null, "e": 4749, "s": 4597, "text": "There are no stringent rules for which wine goes well with which cheese but one must observe the following guidelines while pairing wines with cheese −" }, { "code": null, "e": 4806, "s": 4749, "text": "Select wine and cheese originating from the same region." }, { "code": null, "e": 4887, "s": 4806, "text": "Dessert wines accompanying the desserts must be sweeter than the dessert itself." }, { "code": null, "e": 4933, "s": 4887, "text": "Cheeses go well with wines of contrast taste." }, { "code": null, "e": 5171, "s": 4933, "text": "Lighter chocolates contain more milk based-products and less chocolate. Chocolates with light and elegant tastes are paired best with light-bodied wines. The ones with more bitter taste are paired with intense flavored full-bodied wines." }, { "code": null, "e": 5435, "s": 5171, "text": "A critical standardized recipe is one that, “has been tried, adapted, and retried several times for use by a given food service operation and has been found to yield the same good results under same procedures, equipment, and quantity and quality of ingredients.”" }, { "code": null, "e": 5534, "s": 5435, "text": "Generally, popular menu items are developed using standard recipes, ingredients, and presentation." }, { "code": null, "e": 5594, "s": 5534, "text": "A standardized recipe can bring in the following benefits −" }, { "code": null, "e": 5623, "s": 5594, "text": "Consistency in food quality." }, { "code": null, "e": 5666, "s": 5623, "text": "Consistency in nutrients per unit serving." }, { "code": null, "e": 5701, "s": 5666, "text": "Increase in customer satisfaction." }, { "code": null, "e": 5726, "s": 5701, "text": "Control on cost of food." }, { "code": null, "e": 5756, "s": 5726, "text": "Prediction of accurate yield." }, { "code": null, "e": 5803, "s": 5756, "text": "Reduction in food leftover and record keeping." }, { "code": null, "e": 5844, "s": 5803, "text": "Increase in the confidence of employees." }, { "code": null, "e": 5917, "s": 5844, "text": "A typical standardized recipe is composed of the following description −" }, { "code": null, "e": 5988, "s": 5917, "text": "Recipe name/title − It is the name that describes the recipe in brief." }, { "code": null, "e": 6059, "s": 5988, "text": "Recipe name/title − It is the name that describes the recipe in brief." }, { "code": null, "e": 6172, "s": 6059, "text": "Recipe section − It is the section that the recipe should be classified under (grains, starters, desserts, etc.)" }, { "code": null, "e": 6285, "s": 6172, "text": "Recipe section − It is the section that the recipe should be classified under (grains, starters, desserts, etc.)" }, { "code": null, "e": 6349, "s": 6285, "text": "Ingredients − Types (fresh/canned/cooked/uncooked/ground, etc.)" }, { "code": null, "e": 6413, "s": 6349, "text": "Ingredients − Types (fresh/canned/cooked/uncooked/ground, etc.)" }, { "code": null, "e": 6448, "s": 6413, "text": "Weight and measures of ingredients" }, { "code": null, "e": 6483, "s": 6448, "text": "Weight and measures of ingredients" }, { "code": null, "e": 6668, "s": 6483, "text": "Method − This is a set of instructions to prepare a particular recipe. A method includes guidelines for steps such as mixing, selecting pans, and setting the right cooking temperature." }, { "code": null, "e": 6853, "s": 6668, "text": "Method − This is a set of instructions to prepare a particular recipe. A method includes guidelines for steps such as mixing, selecting pans, and setting the right cooking temperature." }, { "code": null, "e": 6924, "s": 6853, "text": "Time − This includes preparation time, cooking time, and serving time." }, { "code": null, "e": 6995, "s": 6924, "text": "Time − This includes preparation time, cooking time, and serving time." }, { "code": null, "e": 7050, "s": 6995, "text": "Serving size − It is the portion of food to be served." }, { "code": null, "e": 7105, "s": 7050, "text": "Serving size − It is the portion of food to be served." }, { "code": null, "e": 7273, "s": 7105, "text": "Critical Control Points (CCP) − They are control measures taken to avoid food safety hazards. Every CCP includes control of time, preparation, and cooking temperature." }, { "code": null, "e": 7441, "s": 7273, "text": "Critical Control Points (CCP) − They are control measures taken to avoid food safety hazards. Every CCP includes control of time, preparation, and cooking temperature." }, { "code": null, "e": 7594, "s": 7441, "text": "Predicting the total yield for a particular number of customers and calculating weights of ingredients accordingly is important in standardized recipes." }, { "code": null, "e": 7732, "s": 7594, "text": "For recipe to be prepared for new lot of customers, the total yield changes. The new yield can be calculated in the following two steps −" }, { "code": null, "e": 7774, "s": 7732, "text": "Step 1 − Calculate conversion factor as −" }, { "code": null, "e": 7817, "s": 7774, "text": "Conversion Factor = New Yield / Old Yield\n" }, { "code": null, "e": 7917, "s": 7817, "text": "Step 2 − Multiply the measure of each ingredient by the conversion factor to obtain the new yield −" }, { "code": null, "e": 7974, "s": 7917, "text": "New Yield = Old ingredient quantity x Conversion factor\n" }, { "code": null, "e": 8007, "s": 7974, "text": "\n 18 Lectures \n 2 hours \n" }, { "code": null, "e": 8021, "s": 8007, "text": " Manish Gupta" }, { "code": null, "e": 8058, "s": 8021, "text": "\n 185 Lectures \n 46.5 hours \n" }, { "code": null, "e": 8074, "s": 8058, "text": " Nikhil Agarwal" }, { "code": null, "e": 8106, "s": 8074, "text": "\n 10 Lectures \n 34 mins\n" }, { "code": null, "e": 8122, "s": 8106, "text": " Faiq Ismayilov" }, { "code": null, "e": 8153, "s": 8122, "text": "\n 7 Lectures \n 52 mins\n" }, { "code": null, "e": 8165, "s": 8153, "text": " Dr. Harris" }, { "code": null, "e": 8172, "s": 8165, "text": " Print" }, { "code": null, "e": 8183, "s": 8172, "text": " Add Notes" } ]
Move all occurrences of an element to end in a linked list - GeeksforGeeks
10 Mar, 2022 Given a linked list and a key in it, the task is to move all occurrences of the given key to the end of the linked list, keeping the order of all other elements the same. Examples: Input : 1 -> 2 -> 2 -> 4 -> 3 key = 2 Output : 1 -> 4 -> 3 -> 2 -> 2 Input : 6 -> 6 -> 7 -> 6 -> 3 -> 10 key = 6 Output : 7 -> 3 -> 10 -> 6 -> 6 -> 6 A simple solution is to one by one find all occurrences of a given key in the linked list. For every found occurrence, insert it at the end. We do it till all occurrences of the given key are moved to the end. Time Complexity: O(n2) Efficient Solution 1: is to keep two pointers: pCrawl => Pointer to traverse the whole list one by one. pKey => Pointer to an occurrence of the key if a key is found. Else same as pCrawl.We start both of the above pointers from the head of the linked list. We move pKey only when pKey is not pointing to a key. We always move pCrawl. So, when pCrawl and pKey are not the same, we must have found a key that lies before pCrawl, so we swap between pCrawl and pKey, and move pKey to the next location. The loop invariant is, after swapping of data, all elements from pKey to pCrawl are keys. Below is the implementation of this approach. C++ Java Python3 C# Javascript // C++ program to move all occurrences of a// given key to end.#include <bits/stdc++.h> // A Linked list Nodestruct Node { int data; struct Node* next;}; // A utility function to create a new node.struct Node* newNode(int x){ Node* temp = new Node; temp->data = x; temp->next = NULL;} // Utility function to print the elements// in Linked listvoid printList(Node* head){ struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n");} // Moves all occurrences of given key to// end of linked list.void moveToEnd(Node* head, int key){ // Keeps track of locations where key // is present. struct Node* pKey = head; // Traverse list struct Node* pCrawl = head; while (pCrawl != NULL) { // If current pointer is not same as pointer // to a key location, then we must have found // a key in linked list. We swap data of pCrawl // and pKey and move pKey to next position. if (pCrawl != pKey && pCrawl->data != key) { pKey->data = pCrawl->data; pCrawl->data = key; pKey = pKey->next; } // Find next position where key is present if (pKey->data != key) pKey = pKey->next; // Moving to next Node pCrawl = pCrawl->next; }} // Driver codeint main(){ Node* head = newNode(10); head->next = newNode(20); head->next->next = newNode(10); head->next->next->next = newNode(30); head->next->next->next->next = newNode(40); head->next->next->next->next->next = newNode(10); head->next->next->next->next->next->next = newNode(60); printf("Before moveToEnd(), the Linked list is\n"); printList(head); int key = 10; moveToEnd(head, key); printf("\nAfter moveToEnd(), the Linked list is\n"); printList(head); return 0;} // Java program to move all occurrences of a// given key to end.class GFG { // A Linked list Node static class Node { int data; Node next; } // A utility function to create a new node. static Node newNode(int x) { Node temp = new Node(); temp.data = x; temp.next = null; return temp; } // Utility function to print the elements // in Linked list static void printList(Node head) { Node temp = head; while (temp != null) { System.out.printf("%d ", temp.data); temp = temp.next; } System.out.printf("\n"); } // Moves all occurrences of given key to // end of linked list. static void moveToEnd(Node head, int key) { // Keeps track of locations where key // is present. Node pKey = head; // Traverse list Node pCrawl = head; while (pCrawl != null) { // If current pointer is not same as pointer // to a key location, then we must have found // a key in linked list. We swap data of pCrawl // and pKey and move pKey to next position. if (pCrawl != pKey && pCrawl.data != key) { pKey.data = pCrawl.data; pCrawl.data = key; pKey = pKey.next; } // Find next position where key is present if (pKey.data != key) pKey = pKey.next; // Moving to next Node pCrawl = pCrawl.next; } } // Driver code public static void main(String args[]) { Node head = newNode(10); head.next = newNode(20); head.next.next = newNode(10); head.next.next.next = newNode(30); head.next.next.next.next = newNode(40); head.next.next.next.next.next = newNode(10); head.next.next.next.next.next.next = newNode(60); System.out.printf("Before moveToEnd(), the Linked list is\n"); printList(head); int key = 10; moveToEnd(head, key); System.out.printf("\nAfter moveToEnd(), the Linked list is\n"); printList(head); }} // This code is contributed by Arnab Kundu # Python3 program to move all occurrences of a# given key to end. # Linked List nodeclass Node: def __init__(self, data): self.data = data self.next = None # A utility function to create a new node.def newNode(x): temp = Node(0) temp.data = x temp.next = None return temp # Utility function to print the elements# in Linked listdef printList( head): temp = head while (temp != None) : print( temp.data,end = " ") temp = temp.next print() # Moves all occurrences of given key to# end of linked list.def moveToEnd(head, key): # Keeps track of locations where key # is present. pKey = head # Traverse list pCrawl = head while (pCrawl != None) : # If current pointer is not same as pointer # to a key location, then we must have found # a key in linked list. We swap data of pCrawl # and pKey and move pKey to next position. if (pCrawl != pKey and pCrawl.data != key) : pKey.data = pCrawl.data pCrawl.data = key pKey = pKey.next # Find next position where key is present if (pKey.data != key): pKey = pKey.next # Moving to next Node pCrawl = pCrawl.next return head # Driver codehead = newNode(10)head.next = newNode(20)head.next.next = newNode(10)head.next.next.next = newNode(30)head.next.next.next.next = newNode(40)head.next.next.next.next.next = newNode(10)head.next.next.next.next.next.next = newNode(60) print("Before moveToEnd(), the Linked list is\n")printList(head) key = 10head = moveToEnd(head, key) print("\nAfter moveToEnd(), the Linked list is\n")printList(head) # This code is contributed by Arnab Kundu // C# program to move all occurrences of a// given key to end.using System; class GFG { // A Linked list Node public class Node { public int data; public Node next; } // A utility function to create a new node. static Node newNode(int x) { Node temp = new Node(); temp.data = x; temp.next = null; return temp; } // Utility function to print the elements // in Linked list static void printList(Node head) { Node temp = head; while (temp != null) { Console.Write("{0} ", temp.data); temp = temp.next; } Console.Write("\n"); } // Moves all occurrences of given key to // end of linked list. static void moveToEnd(Node head, int key) { // Keeps track of locations where key // is present. Node pKey = head; // Traverse list Node pCrawl = head; while (pCrawl != null) { // If current pointer is not same as pointer // to a key location, then we must have found // a key in linked list. We swap data of pCrawl // and pKey and move pKey to next position. if (pCrawl != pKey && pCrawl.data != key) { pKey.data = pCrawl.data; pCrawl.data = key; pKey = pKey.next; } // Find next position where key is present if (pKey.data != key) pKey = pKey.next; // Moving to next Node pCrawl = pCrawl.next; } } // Driver code public static void Main(String[] args) { Node head = newNode(10); head.next = newNode(20); head.next.next = newNode(10); head.next.next.next = newNode(30); head.next.next.next.next = newNode(40); head.next.next.next.next.next = newNode(10); head.next.next.next.next.next.next = newNode(60); Console.Write("Before moveToEnd(), the Linked list is\n"); printList(head); int key = 10; moveToEnd(head, key); Console.Write("\nAfter moveToEnd(), the Linked list is\n"); printList(head); }} // This code has been contributed by 29AjayKumar <script> // Javascript program to move all occurrences of a// given key to end. // A Linked list Node class Node { constructor() { this.data = 0; this.next = null; } } // A utility function to create a new node. function newNode(x) { var temp = new Node(); temp.data = x; temp.next = null; return temp; } // Utility function to print the elements // in Linked list function printList(head) { var temp = head; while (temp != null) { document.write( temp.data+" "); temp = temp.next; } document.write("<br/>"); } // Moves all occurrences of given key to // end of linked list. function moveToEnd(head , key) { // Keeps track of locations where key // is present. var pKey = head; // Traverse list var pCrawl = head; while (pCrawl != null) { // If current pointer is not same as pointer // to a key location, then we must have found // a key in linked list. We swap data of pCrawl // and pKey and move pKey to next position. if (pCrawl != pKey && pCrawl.data != key) { pKey.data = pCrawl.data; pCrawl.data = key; pKey = pKey.next; } // Find next position where key is present if (pKey.data != key) pKey = pKey.next; // Moving to next Node pCrawl = pCrawl.next; } } // Driver code var head = newNode(10); head.next = newNode(20); head.next.next = newNode(10); head.next.next.next = newNode(30); head.next.next.next.next = newNode(40); head.next.next.next.next.next = newNode(10); head.next.next.next.next.next.next = newNode(60); document.write( "Before moveToEnd(), the Linked list is<br/>" ); printList(head); var key = 10; moveToEnd(head, key); document.write( "<br/>After moveToEnd(), the Linked list is<br/>" ); printList(head); // This code contributed by umadevi9616 </script> Output: Before moveToEnd(), the Linked list is 10 20 10 30 40 10 60 After moveToEnd(), the Linked list is 20 30 40 60 10 10 10 Time Complexity: O(n) requires only one traversal of the list. Efficient Solution 2 : 1. Traverse the linked list and take a pointer at the tail. 2. Now, check for the key and node->data. If they are equal, move the node to last-next, else move ahead. C++ Java Python3 C# Javascript // C++ code to remove key element to end of linked list#include<bits/stdc++.h>using namespace std; // A Linked list Nodestruct Node{ int data; struct Node* next;}; // A utility function to create a new node.struct Node* newNode(int x){ Node* temp = new Node; temp->data = x; temp->next = NULL;} // Function to remove key to endNode *keyToEnd(Node* head, int key){ // Node to keep pointing to tail Node* tail = head; if (head == NULL) { return NULL; } while (tail->next != NULL) { tail = tail->next; } // Node to point to last of linked list Node* last = tail; Node* current = head; Node* prev = NULL; // Node prev2 to point to previous when head.data!=key Node* prev2 = NULL; // loop to perform operations to remove key to end while (current != tail) { if (current->data == key && prev2 == NULL) { prev = current; current = current->next; head = current; last->next = prev; last = last->next; last->next = NULL; prev = NULL; } else { if (current->data == key && prev2 != NULL) { prev = current; current = current->next; prev2->next = current; last->next = prev; last = last->next; last->next = NULL; } else if (current != tail) { prev2 = current; current = current->next; } } } return head;} // Function to display linked listvoid printList(Node* head){ struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n");} // Driver Codeint main(){ Node* root = newNode(5); root->next = newNode(2); root->next->next = newNode(2); root->next->next->next = newNode(7); root->next->next->next->next = newNode(2); root->next->next->next->next->next = newNode(2); root->next->next->next->next->next->next = newNode(2); int key = 2; cout << "Linked List before operations :"; printList(root); cout << "\nLinked List after operations :"; root = keyToEnd(root, key); printList(root); return 0;} // This code is contributed by Rajout-Ji // Java code to remove key element to end of linked listimport java.util.*; // Node classclass Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; }} class gfg { static Node root; // Function to remove key to end public static Node keyToEnd(Node head, int key) { // Node to keep pointing to tail Node tail = head; if (head == null) { return null; } while (tail.next != null) { tail = tail.next; } // Node to point to last of linked list Node last = tail; Node current = head; Node prev = null; // Node prev2 to point to previous when head.data!=key Node prev2 = null; // loop to perform operations to remove key to end while (current != tail) { if (current.data == key && prev2 == null) { prev = current; current = current.next; head = current; last.next = prev; last = last.next; last.next = null; prev = null; } else { if (current.data == key && prev2 != null) { prev = current; current = current.next; prev2.next = current; last.next = prev; last = last.next; last.next = null; } else if (current != tail) { prev2 = current; current = current.next; } } } return head; } // Function to display linked list public static void display(Node root) { while (root != null) { System.out.print(root.data + " "); root = root.next; } } // Driver Code public static void main(String args[]) { root = new Node(5); root.next = new Node(2); root.next.next = new Node(2); root.next.next.next = new Node(7); root.next.next.next.next = new Node(2); root.next.next.next.next.next = new Node(2); root.next.next.next.next.next.next = new Node(2); int key = 2; System.out.println("Linked List before operations :"); display(root); System.out.println("\nLinked List after operations :"); root = keyToEnd(root, key); display(root); }} # Python3 code to remove key element to# end of linked list # A Linked list Nodeclass Node: def __init__(self, data): self.data = data self.next = None # A utility function to create a new node.def newNode(x): temp = Node(x) return temp # Function to remove key to enddef keyToEnd(head, key): # Node to keep pointing to tail tail = head if (head == None): return None while (tail.next != None): tail = tail.next # Node to point to last of linked list last = tail current = head prev = None # Node prev2 to point to previous # when head.data!=key prev2 = None # Loop to perform operations to # remove key to end while (current != tail): if (current.data == key and prev2 == None): prev = current current = current.next head = current last.next = prev last = last.next last.next = None prev = None else: if (current.data == key and prev2 != None): prev = current current = current.next prev2.next = current last.next = prev last = last.next last.next = None else if (current != tail): prev2 = current current = current.next return head # Function to display linked listdef printList(head): temp = head while (temp != None): print(temp.data, end = ' ') temp = temp.next print() # Driver Codeif __name__=='__main__': root = newNode(5) root.next = newNode(2) root.next.next = newNode(2) root.next.next.next = newNode(7) root.next.next.next.next = newNode(2) root.next.next.next.next.next = newNode(2) root.next.next.next.next.next.next = newNode(2) key = 2 print("Linked List before operations :") printList(root) print("Linked List after operations :") root = keyToEnd(root, key) printList(root) # This code is contributed by rutvik_56 // C# code to remove key// element to end of linked listusing System; // Node classpublic class Node { public int data; public Node next; public Node(int data) { this.data = data; this.next = null; }} class GFG { static Node root; // Function to remove key to end public static Node keyToEnd(Node head, int key) { // Node to keep pointing to tail Node tail = head; if (head == null) { return null; } while (tail.next != null) { tail = tail.next; } // Node to point to last of linked list Node last = tail; Node current = head; Node prev = null; // Node prev2 to point to // previous when head.data!=key Node prev2 = null; // loop to perform operations // to remove key to end while (current != tail) { if (current.data == key && prev2 == null) { prev = current; current = current.next; head = current; last.next = prev; last = last.next; last.next = null; prev = null; } else { if (current.data == key && prev2 != null) { prev = current; current = current.next; prev2.next = current; last.next = prev; last = last.next; last.next = null; } else if (current != tail) { prev2 = current; current = current.next; } } } return head; } // Function to display linked list public static void display(Node root) { while (root != null) { Console.Write(root.data + " "); root = root.next; } } // Driver Code public static void Main() { root = new Node(5); root.next = new Node(2); root.next.next = new Node(2); root.next.next.next = new Node(7); root.next.next.next.next = new Node(2); root.next.next.next.next.next = new Node(2); root.next.next.next.next.next.next = new Node(2); int key = 2; Console.WriteLine("Linked List before operations :"); display(root); Console.WriteLine("\nLinked List after operations :"); root = keyToEnd(root, key); display(root); }} // This code is contributed by PrinciRaj1992 <script>// javascript code to remove key element to end of linked list// Node class class Node { constructor(val) { this.data = val; this.next = null; } } var root; // Function to remove key to end function keyToEnd(head , key) { // Node to keep pointing to tail var tail = head; if (head == null) { return null; } while (tail.next != null) { tail = tail.next; } // Node to point to last of linked list var last = tail; var current = head; var prev = null; // Node prev2 to point to previous when head.data!=key var prev2 = null; // loop to perform operations to remove key to end while (current != tail) { if (current.data == key && prev2 == null) { prev = current; current = current.next; head = current; last.next = prev; last = last.next; last.next = null; prev = null; } else { if (current.data == key && prev2 != null) { prev = current; current = current.next; prev2.next = current; last.next = prev; last = last.next; last.next = null; } else if (current != tail) { prev2 = current; current = current.next; } } } return head; } // Function to display linked list function display(root) { while (root != null) { document.write(root.data + " "); root = root.next; } } // Driver Code root = new Node(5); root.next = new Node(2); root.next.next = new Node(2); root.next.next.next = new Node(7); root.next.next.next.next = new Node(2); root.next.next.next.next.next = new Node(2); root.next.next.next.next.next.next = new Node(2); var key = 2; document.write("Linked List before operations :<br/>"); display(root); document.write("<br/>Linked List after operations :<br/>"); root = keyToEnd(root, key); display(root); // This code contributed by aashish1995</script> Output: Linked List before operations : 5 2 2 7 2 2 2 Linked List after operations : 5 7 2 2 2 2 2 Thanks to Ravinder Kumar for suggesting this method. Efficient Solution 3: is to maintain a separate list of keys. We initialize this list of keys as empty. We traverse the given list. For every key found, we remove it from the original list and insert it into a separate list of keys. We finally link the list of keys at the end of the remaining given list. The time complexity of this solution is also O(n) and it also requires only one traversal of the list. This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. princiraj1992 andrew1234 29AjayKumar Rajput-Ji rutvik_56 umadevi9616 aashish1995 khushboogoyal499 gulshankumarar231 surinderdawra388 Linked List Searching Linked List Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Delete a Linked List node at a given position Implementing a Linked List in Java using Class Circular Linked List | Set 1 (Introduction and Applications) Find Length of a Linked List (Iterative and Recursive) Merge Sort for Linked Lists Binary Search Linear Search Maximum and minimum of an array using minimum number of comparisons Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1
[ { "code": null, "e": 24678, "s": 24650, "text": "\n10 Mar, 2022" }, { "code": null, "e": 24849, "s": 24678, "text": "Given a linked list and a key in it, the task is to move all occurrences of the given key to the end of the linked list, keeping the order of all other elements the same." }, { "code": null, "e": 24861, "s": 24849, "text": "Examples: " }, { "code": null, "e": 25033, "s": 24861, "text": "Input : 1 -> 2 -> 2 -> 4 -> 3\n key = 2 \nOutput : 1 -> 4 -> 3 -> 2 -> 2\n\nInput : 6 -> 6 -> 7 -> 6 -> 3 -> 10\n key = 6\nOutput : 7 -> 3 -> 10 -> 6 -> 6 -> 6" }, { "code": null, "e": 25243, "s": 25033, "text": "A simple solution is to one by one find all occurrences of a given key in the linked list. For every found occurrence, insert it at the end. We do it till all occurrences of the given key are moved to the end." }, { "code": null, "e": 25266, "s": 25243, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 25855, "s": 25266, "text": "Efficient Solution 1: is to keep two pointers: pCrawl => Pointer to traverse the whole list one by one. pKey => Pointer to an occurrence of the key if a key is found. Else same as pCrawl.We start both of the above pointers from the head of the linked list. We move pKey only when pKey is not pointing to a key. We always move pCrawl. So, when pCrawl and pKey are not the same, we must have found a key that lies before pCrawl, so we swap between pCrawl and pKey, and move pKey to the next location. The loop invariant is, after swapping of data, all elements from pKey to pCrawl are keys." }, { "code": null, "e": 25903, "s": 25855, "text": "Below is the implementation of this approach. " }, { "code": null, "e": 25907, "s": 25903, "text": "C++" }, { "code": null, "e": 25912, "s": 25907, "text": "Java" }, { "code": null, "e": 25920, "s": 25912, "text": "Python3" }, { "code": null, "e": 25923, "s": 25920, "text": "C#" }, { "code": null, "e": 25934, "s": 25923, "text": "Javascript" }, { "code": "// C++ program to move all occurrences of a// given key to end.#include <bits/stdc++.h> // A Linked list Nodestruct Node { int data; struct Node* next;}; // A utility function to create a new node.struct Node* newNode(int x){ Node* temp = new Node; temp->data = x; temp->next = NULL;} // Utility function to print the elements// in Linked listvoid printList(Node* head){ struct Node* temp = head; while (temp != NULL) { printf(\"%d \", temp->data); temp = temp->next; } printf(\"\\n\");} // Moves all occurrences of given key to// end of linked list.void moveToEnd(Node* head, int key){ // Keeps track of locations where key // is present. struct Node* pKey = head; // Traverse list struct Node* pCrawl = head; while (pCrawl != NULL) { // If current pointer is not same as pointer // to a key location, then we must have found // a key in linked list. We swap data of pCrawl // and pKey and move pKey to next position. if (pCrawl != pKey && pCrawl->data != key) { pKey->data = pCrawl->data; pCrawl->data = key; pKey = pKey->next; } // Find next position where key is present if (pKey->data != key) pKey = pKey->next; // Moving to next Node pCrawl = pCrawl->next; }} // Driver codeint main(){ Node* head = newNode(10); head->next = newNode(20); head->next->next = newNode(10); head->next->next->next = newNode(30); head->next->next->next->next = newNode(40); head->next->next->next->next->next = newNode(10); head->next->next->next->next->next->next = newNode(60); printf(\"Before moveToEnd(), the Linked list is\\n\"); printList(head); int key = 10; moveToEnd(head, key); printf(\"\\nAfter moveToEnd(), the Linked list is\\n\"); printList(head); return 0;}", "e": 27804, "s": 25934, "text": null }, { "code": "// Java program to move all occurrences of a// given key to end.class GFG { // A Linked list Node static class Node { int data; Node next; } // A utility function to create a new node. static Node newNode(int x) { Node temp = new Node(); temp.data = x; temp.next = null; return temp; } // Utility function to print the elements // in Linked list static void printList(Node head) { Node temp = head; while (temp != null) { System.out.printf(\"%d \", temp.data); temp = temp.next; } System.out.printf(\"\\n\"); } // Moves all occurrences of given key to // end of linked list. static void moveToEnd(Node head, int key) { // Keeps track of locations where key // is present. Node pKey = head; // Traverse list Node pCrawl = head; while (pCrawl != null) { // If current pointer is not same as pointer // to a key location, then we must have found // a key in linked list. We swap data of pCrawl // and pKey and move pKey to next position. if (pCrawl != pKey && pCrawl.data != key) { pKey.data = pCrawl.data; pCrawl.data = key; pKey = pKey.next; } // Find next position where key is present if (pKey.data != key) pKey = pKey.next; // Moving to next Node pCrawl = pCrawl.next; } } // Driver code public static void main(String args[]) { Node head = newNode(10); head.next = newNode(20); head.next.next = newNode(10); head.next.next.next = newNode(30); head.next.next.next.next = newNode(40); head.next.next.next.next.next = newNode(10); head.next.next.next.next.next.next = newNode(60); System.out.printf(\"Before moveToEnd(), the Linked list is\\n\"); printList(head); int key = 10; moveToEnd(head, key); System.out.printf(\"\\nAfter moveToEnd(), the Linked list is\\n\"); printList(head); }} // This code is contributed by Arnab Kundu", "e": 29999, "s": 27804, "text": null }, { "code": "# Python3 program to move all occurrences of a# given key to end. # Linked List nodeclass Node: def __init__(self, data): self.data = data self.next = None # A utility function to create a new node.def newNode(x): temp = Node(0) temp.data = x temp.next = None return temp # Utility function to print the elements# in Linked listdef printList( head): temp = head while (temp != None) : print( temp.data,end = \" \") temp = temp.next print() # Moves all occurrences of given key to# end of linked list.def moveToEnd(head, key): # Keeps track of locations where key # is present. pKey = head # Traverse list pCrawl = head while (pCrawl != None) : # If current pointer is not same as pointer # to a key location, then we must have found # a key in linked list. We swap data of pCrawl # and pKey and move pKey to next position. if (pCrawl != pKey and pCrawl.data != key) : pKey.data = pCrawl.data pCrawl.data = key pKey = pKey.next # Find next position where key is present if (pKey.data != key): pKey = pKey.next # Moving to next Node pCrawl = pCrawl.next return head # Driver codehead = newNode(10)head.next = newNode(20)head.next.next = newNode(10)head.next.next.next = newNode(30)head.next.next.next.next = newNode(40)head.next.next.next.next.next = newNode(10)head.next.next.next.next.next.next = newNode(60) print(\"Before moveToEnd(), the Linked list is\\n\")printList(head) key = 10head = moveToEnd(head, key) print(\"\\nAfter moveToEnd(), the Linked list is\\n\")printList(head) # This code is contributed by Arnab Kundu", "e": 31728, "s": 29999, "text": null }, { "code": "// C# program to move all occurrences of a// given key to end.using System; class GFG { // A Linked list Node public class Node { public int data; public Node next; } // A utility function to create a new node. static Node newNode(int x) { Node temp = new Node(); temp.data = x; temp.next = null; return temp; } // Utility function to print the elements // in Linked list static void printList(Node head) { Node temp = head; while (temp != null) { Console.Write(\"{0} \", temp.data); temp = temp.next; } Console.Write(\"\\n\"); } // Moves all occurrences of given key to // end of linked list. static void moveToEnd(Node head, int key) { // Keeps track of locations where key // is present. Node pKey = head; // Traverse list Node pCrawl = head; while (pCrawl != null) { // If current pointer is not same as pointer // to a key location, then we must have found // a key in linked list. We swap data of pCrawl // and pKey and move pKey to next position. if (pCrawl != pKey && pCrawl.data != key) { pKey.data = pCrawl.data; pCrawl.data = key; pKey = pKey.next; } // Find next position where key is present if (pKey.data != key) pKey = pKey.next; // Moving to next Node pCrawl = pCrawl.next; } } // Driver code public static void Main(String[] args) { Node head = newNode(10); head.next = newNode(20); head.next.next = newNode(10); head.next.next.next = newNode(30); head.next.next.next.next = newNode(40); head.next.next.next.next.next = newNode(10); head.next.next.next.next.next.next = newNode(60); Console.Write(\"Before moveToEnd(), the Linked list is\\n\"); printList(head); int key = 10; moveToEnd(head, key); Console.Write(\"\\nAfter moveToEnd(), the Linked list is\\n\"); printList(head); }} // This code has been contributed by 29AjayKumar", "e": 33940, "s": 31728, "text": null }, { "code": "<script> // Javascript program to move all occurrences of a// given key to end. // A Linked list Node class Node { constructor() { this.data = 0; this.next = null; } } // A utility function to create a new node. function newNode(x) { var temp = new Node(); temp.data = x; temp.next = null; return temp; } // Utility function to print the elements // in Linked list function printList(head) { var temp = head; while (temp != null) { document.write( temp.data+\" \"); temp = temp.next; } document.write(\"<br/>\"); } // Moves all occurrences of given key to // end of linked list. function moveToEnd(head , key) { // Keeps track of locations where key // is present. var pKey = head; // Traverse list var pCrawl = head; while (pCrawl != null) { // If current pointer is not same as pointer // to a key location, then we must have found // a key in linked list. We swap data of pCrawl // and pKey and move pKey to next position. if (pCrawl != pKey && pCrawl.data != key) { pKey.data = pCrawl.data; pCrawl.data = key; pKey = pKey.next; } // Find next position where key is present if (pKey.data != key) pKey = pKey.next; // Moving to next Node pCrawl = pCrawl.next; } } // Driver code var head = newNode(10); head.next = newNode(20); head.next.next = newNode(10); head.next.next.next = newNode(30); head.next.next.next.next = newNode(40); head.next.next.next.next.next = newNode(10); head.next.next.next.next.next.next = newNode(60); document.write( \"Before moveToEnd(), the Linked list is<br/>\" ); printList(head); var key = 10; moveToEnd(head, key); document.write( \"<br/>After moveToEnd(), the Linked list is<br/>\" ); printList(head); // This code contributed by umadevi9616 </script>", "e": 36135, "s": 33940, "text": null }, { "code": null, "e": 36144, "s": 36135, "text": "Output: " }, { "code": null, "e": 36265, "s": 36144, "text": "Before moveToEnd(), the Linked list is\n10 20 10 30 40 10 60 \n\nAfter moveToEnd(), the Linked list is\n20 30 40 60 10 10 10" }, { "code": null, "e": 36328, "s": 36265, "text": "Time Complexity: O(n) requires only one traversal of the list." }, { "code": null, "e": 36517, "s": 36328, "text": "Efficient Solution 2 : 1. Traverse the linked list and take a pointer at the tail. 2. Now, check for the key and node->data. If they are equal, move the node to last-next, else move ahead." }, { "code": null, "e": 36521, "s": 36517, "text": "C++" }, { "code": null, "e": 36526, "s": 36521, "text": "Java" }, { "code": null, "e": 36534, "s": 36526, "text": "Python3" }, { "code": null, "e": 36537, "s": 36534, "text": "C#" }, { "code": null, "e": 36548, "s": 36537, "text": "Javascript" }, { "code": "// C++ code to remove key element to end of linked list#include<bits/stdc++.h>using namespace std; // A Linked list Nodestruct Node{ int data; struct Node* next;}; // A utility function to create a new node.struct Node* newNode(int x){ Node* temp = new Node; temp->data = x; temp->next = NULL;} // Function to remove key to endNode *keyToEnd(Node* head, int key){ // Node to keep pointing to tail Node* tail = head; if (head == NULL) { return NULL; } while (tail->next != NULL) { tail = tail->next; } // Node to point to last of linked list Node* last = tail; Node* current = head; Node* prev = NULL; // Node prev2 to point to previous when head.data!=key Node* prev2 = NULL; // loop to perform operations to remove key to end while (current != tail) { if (current->data == key && prev2 == NULL) { prev = current; current = current->next; head = current; last->next = prev; last = last->next; last->next = NULL; prev = NULL; } else { if (current->data == key && prev2 != NULL) { prev = current; current = current->next; prev2->next = current; last->next = prev; last = last->next; last->next = NULL; } else if (current != tail) { prev2 = current; current = current->next; } } } return head;} // Function to display linked listvoid printList(Node* head){ struct Node* temp = head; while (temp != NULL) { printf(\"%d \", temp->data); temp = temp->next; } printf(\"\\n\");} // Driver Codeint main(){ Node* root = newNode(5); root->next = newNode(2); root->next->next = newNode(2); root->next->next->next = newNode(7); root->next->next->next->next = newNode(2); root->next->next->next->next->next = newNode(2); root->next->next->next->next->next->next = newNode(2); int key = 2; cout << \"Linked List before operations :\"; printList(root); cout << \"\\nLinked List after operations :\"; root = keyToEnd(root, key); printList(root); return 0;} // This code is contributed by Rajout-Ji", "e": 38899, "s": 36548, "text": null }, { "code": "// Java code to remove key element to end of linked listimport java.util.*; // Node classclass Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; }} class gfg { static Node root; // Function to remove key to end public static Node keyToEnd(Node head, int key) { // Node to keep pointing to tail Node tail = head; if (head == null) { return null; } while (tail.next != null) { tail = tail.next; } // Node to point to last of linked list Node last = tail; Node current = head; Node prev = null; // Node prev2 to point to previous when head.data!=key Node prev2 = null; // loop to perform operations to remove key to end while (current != tail) { if (current.data == key && prev2 == null) { prev = current; current = current.next; head = current; last.next = prev; last = last.next; last.next = null; prev = null; } else { if (current.data == key && prev2 != null) { prev = current; current = current.next; prev2.next = current; last.next = prev; last = last.next; last.next = null; } else if (current != tail) { prev2 = current; current = current.next; } } } return head; } // Function to display linked list public static void display(Node root) { while (root != null) { System.out.print(root.data + \" \"); root = root.next; } } // Driver Code public static void main(String args[]) { root = new Node(5); root.next = new Node(2); root.next.next = new Node(2); root.next.next.next = new Node(7); root.next.next.next.next = new Node(2); root.next.next.next.next.next = new Node(2); root.next.next.next.next.next.next = new Node(2); int key = 2; System.out.println(\"Linked List before operations :\"); display(root); System.out.println(\"\\nLinked List after operations :\"); root = keyToEnd(root, key); display(root); }}", "e": 41352, "s": 38899, "text": null }, { "code": "# Python3 code to remove key element to# end of linked list # A Linked list Nodeclass Node: def __init__(self, data): self.data = data self.next = None # A utility function to create a new node.def newNode(x): temp = Node(x) return temp # Function to remove key to enddef keyToEnd(head, key): # Node to keep pointing to tail tail = head if (head == None): return None while (tail.next != None): tail = tail.next # Node to point to last of linked list last = tail current = head prev = None # Node prev2 to point to previous # when head.data!=key prev2 = None # Loop to perform operations to # remove key to end while (current != tail): if (current.data == key and prev2 == None): prev = current current = current.next head = current last.next = prev last = last.next last.next = None prev = None else: if (current.data == key and prev2 != None): prev = current current = current.next prev2.next = current last.next = prev last = last.next last.next = None else if (current != tail): prev2 = current current = current.next return head # Function to display linked listdef printList(head): temp = head while (temp != None): print(temp.data, end = ' ') temp = temp.next print() # Driver Codeif __name__=='__main__': root = newNode(5) root.next = newNode(2) root.next.next = newNode(2) root.next.next.next = newNode(7) root.next.next.next.next = newNode(2) root.next.next.next.next.next = newNode(2) root.next.next.next.next.next.next = newNode(2) key = 2 print(\"Linked List before operations :\") printList(root) print(\"Linked List after operations :\") root = keyToEnd(root, key) printList(root) # This code is contributed by rutvik_56", "e": 43479, "s": 41352, "text": null }, { "code": "// C# code to remove key// element to end of linked listusing System; // Node classpublic class Node { public int data; public Node next; public Node(int data) { this.data = data; this.next = null; }} class GFG { static Node root; // Function to remove key to end public static Node keyToEnd(Node head, int key) { // Node to keep pointing to tail Node tail = head; if (head == null) { return null; } while (tail.next != null) { tail = tail.next; } // Node to point to last of linked list Node last = tail; Node current = head; Node prev = null; // Node prev2 to point to // previous when head.data!=key Node prev2 = null; // loop to perform operations // to remove key to end while (current != tail) { if (current.data == key && prev2 == null) { prev = current; current = current.next; head = current; last.next = prev; last = last.next; last.next = null; prev = null; } else { if (current.data == key && prev2 != null) { prev = current; current = current.next; prev2.next = current; last.next = prev; last = last.next; last.next = null; } else if (current != tail) { prev2 = current; current = current.next; } } } return head; } // Function to display linked list public static void display(Node root) { while (root != null) { Console.Write(root.data + \" \"); root = root.next; } } // Driver Code public static void Main() { root = new Node(5); root.next = new Node(2); root.next.next = new Node(2); root.next.next.next = new Node(7); root.next.next.next.next = new Node(2); root.next.next.next.next.next = new Node(2); root.next.next.next.next.next.next = new Node(2); int key = 2; Console.WriteLine(\"Linked List before operations :\"); display(root); Console.WriteLine(\"\\nLinked List after operations :\"); root = keyToEnd(root, key); display(root); }} // This code is contributed by PrinciRaj1992", "e": 45994, "s": 43479, "text": null }, { "code": "<script>// javascript code to remove key element to end of linked list// Node class class Node { constructor(val) { this.data = val; this.next = null; } } var root; // Function to remove key to end function keyToEnd(head , key) { // Node to keep pointing to tail var tail = head; if (head == null) { return null; } while (tail.next != null) { tail = tail.next; } // Node to point to last of linked list var last = tail; var current = head; var prev = null; // Node prev2 to point to previous when head.data!=key var prev2 = null; // loop to perform operations to remove key to end while (current != tail) { if (current.data == key && prev2 == null) { prev = current; current = current.next; head = current; last.next = prev; last = last.next; last.next = null; prev = null; } else { if (current.data == key && prev2 != null) { prev = current; current = current.next; prev2.next = current; last.next = prev; last = last.next; last.next = null; } else if (current != tail) { prev2 = current; current = current.next; } } } return head; } // Function to display linked list function display(root) { while (root != null) { document.write(root.data + \" \"); root = root.next; } } // Driver Code root = new Node(5); root.next = new Node(2); root.next.next = new Node(2); root.next.next.next = new Node(7); root.next.next.next.next = new Node(2); root.next.next.next.next.next = new Node(2); root.next.next.next.next.next.next = new Node(2); var key = 2; document.write(\"Linked List before operations :<br/>\"); display(root); document.write(\"<br/>Linked List after operations :<br/>\"); root = keyToEnd(root, key); display(root); // This code contributed by aashish1995</script>", "e": 48341, "s": 45994, "text": null }, { "code": null, "e": 48350, "s": 48341, "text": "Output: " }, { "code": null, "e": 48442, "s": 48350, "text": "Linked List before operations :\n5 2 2 7 2 2 2 \nLinked List after operations :\n5 7 2 2 2 2 2" }, { "code": null, "e": 48495, "s": 48442, "text": "Thanks to Ravinder Kumar for suggesting this method." }, { "code": null, "e": 48904, "s": 48495, "text": "Efficient Solution 3: is to maintain a separate list of keys. We initialize this list of keys as empty. We traverse the given list. For every key found, we remove it from the original list and insert it into a separate list of keys. We finally link the list of keys at the end of the remaining given list. The time complexity of this solution is also O(n) and it also requires only one traversal of the list." }, { "code": null, "e": 49329, "s": 48904, "text": "This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 49343, "s": 49329, "text": "princiraj1992" }, { "code": null, "e": 49354, "s": 49343, "text": "andrew1234" }, { "code": null, "e": 49366, "s": 49354, "text": "29AjayKumar" }, { "code": null, "e": 49376, "s": 49366, "text": "Rajput-Ji" }, { "code": null, "e": 49386, "s": 49376, "text": "rutvik_56" }, { "code": null, "e": 49398, "s": 49386, "text": "umadevi9616" }, { "code": null, "e": 49410, "s": 49398, "text": "aashish1995" }, { "code": null, "e": 49427, "s": 49410, "text": "khushboogoyal499" }, { "code": null, "e": 49445, "s": 49427, "text": "gulshankumarar231" }, { "code": null, "e": 49462, "s": 49445, "text": "surinderdawra388" }, { "code": null, "e": 49474, "s": 49462, "text": "Linked List" }, { "code": null, "e": 49484, "s": 49474, "text": "Searching" }, { "code": null, "e": 49496, "s": 49484, "text": "Linked List" }, { "code": null, "e": 49506, "s": 49496, "text": "Searching" }, { "code": null, "e": 49604, "s": 49506, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49613, "s": 49604, "text": "Comments" }, { "code": null, "e": 49626, "s": 49613, "text": "Old Comments" }, { "code": null, "e": 49672, "s": 49626, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 49719, "s": 49672, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 49780, "s": 49719, "text": "Circular Linked List | Set 1 (Introduction and Applications)" }, { "code": null, "e": 49835, "s": 49780, "text": "Find Length of a Linked List (Iterative and Recursive)" }, { "code": null, "e": 49863, "s": 49835, "text": "Merge Sort for Linked Lists" }, { "code": null, "e": 49877, "s": 49863, "text": "Binary Search" }, { "code": null, "e": 49891, "s": 49877, "text": "Linear Search" }, { "code": null, "e": 49959, "s": 49891, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 49983, "s": 49959, "text": "Find the Missing Number" } ]
Generate Pythagorean Triplets - GeeksforGeeks
09 Feb, 2022 A Pythagorean triplet is a set of three positive integers a, b and c such that a2 + b2 = c2. Given a limit, generate all Pythagorean Triples with values smaller than given limit. Input : limit = 20 Output : 3 4 5 8 6 10 5 12 13 15 8 17 12 16 20 A Simple Solution is to generate these triplets smaller than given limit using three nested loop. For every triplet, check if Pythagorean condition is true, if true, then print the triplet. Time complexity of this solution is O(limit3) where ‘limit’ is given limit. An Efficient Solution can print all triplets in O(k) time where k is number of triplets printed. The idea is to use square sum relation of Pythagorean triplet, i.e., addition of squares of a and b is equal to square of c, we can write these number in terms of m and n such that, a = m2 - n2 b = 2 * m * n c = m2 + n2 because, a2 = m4 + n4 – 2 * m2 * n2 b2 = 4 * m2 * n2 c2 = m4 + n4 + 2* m2 * n2 We can see that a2 + b2 = c2, so instead of iterating for a, b and c we can iterate for m and n and can generate these triplets. Below is the implementation of above idea : C++ Java Python3 C# PHP Javascript // C++ program to generate pythagorean// triplets smaller than a given limit#include <bits/stdc++.h> // Function to generate pythagorean// triplets smaller than limitvoid pythagoreanTriplets(int limit){ // triplet: a^2 + b^2 = c^2 int a, b, c = 0; // loop from 2 to max_limit int m = 2; // Limiting c would limit // all a, b and c while (c < limit) { // now loop on j from 1 to i-1 for (int n = 1; n < m; ++n) { // Evaluate and print triplets using // the relation between a, b and c a = m * m - n * n; b = 2 * m * n; c = m * m + n * n; if (c > limit) break; printf("%d %d %d\n", a, b, c); } m++; }} // Driver Codeint main(){ int limit = 20; pythagoreanTriplets(limit); return 0;} // Java program to generate pythagorean// triplets smaller than a given limitimport java.io.*;import java.util.*; class GFG { // Function to generate pythagorean // triplets smaller than limit static void pythagoreanTriplets(int limit) { // triplet: a^2 + b^2 = c^2 int a, b, c = 0; // loop from 2 to max_limit int m = 2; // Limiting c would limit // all a, b and c while (c < limit) { // now loop on j from 1 to i-1 for (int n = 1; n < m; ++n) { // Evaluate and print // triplets using // the relation between // a, b and c a = m * m - n * n; b = 2 * m * n; c = m * m + n * n; if (c > limit) break; System.out.println(a + " " + b + " " + c); } m++; } } // Driver Code public static void main(String args[]) { int limit = 20; pythagoreanTriplets(limit); }} // This code is contributed by Manish. # Python3 program to generate pythagorean# triplets smaller than a given limit # Function to generate pythagorean# triplets smaller than limitdef pythagoreanTriplets(limits) : c, m = 0, 2 # Limiting c would limit # all a, b and c while c < limits : # Now loop on n from 1 to m-1 for n in range(1, m) : a = m * m - n * n b = 2 * m * n c = m * m + n * n # if c is greater than # limit then break it if c > limits : break print(a, b, c) m = m + 1 # Driver Codeif __name__ == '__main__' : limit = 20 pythagoreanTriplets(limit) # This code is contributed by Shrikant13. // C# program to generate pythagorean// triplets smaller than a given limitusing System; class GFG { // Function to generate pythagorean // triplets smaller than limit static void pythagoreanTriplets(int limit) { // triplet: a^2 + b^2 = c^2 int a, b, c = 0; // loop from 2 to max_limit int m = 2; // Limiting c would limit // all a, b and c while (c < limit) { // now loop on j from 1 to i-1 for (int n = 1; n < m; ++n) { // Evaluate and print // triplets using // the relation between // a, b and c a = m * m - n * n; b = 2 * m * n; c = m * m + n * n; if (c > limit) break; Console.WriteLine(a + " " + b + " " + c); } m++; } } // Driver Code public static void Main() { int limit = 20; pythagoreanTriplets(limit); }} // This code is contributed by anuj_67. <?php// PHP program to generate pythagorean// triplets smaller than a given limit // Function to generate pythagorean// triplets smaller than limitfunction pythagoreanTriplets($limit){ // triplet: a^2 + b^2 = c^2 $a; $b; $c=0; // loop from 2 to max_limit $m = 2; // Limiting c would limit // all a, b and c while ($c < $limit) { // now loop on j from 1 to i-1 for ($n = 1; $n < $m; ++$n) { // Evaluate and print // triplets using the // relation between a, // b and c $a = $m *$m - $n * $n; $b = 2 * $m * $n; $c = $m * $m + $n * $n; if ($c > $limit) break; echo $a, " ", $b, " ", $c, "\n"; } $m++; }} // Driver Code $limit = 20; pythagoreanTriplets($limit); // This code is contributed by ajit.?> <script> // Javascript program to generate pythagorean// triplets smaller than a given limit // Function to generate pythagorean// triplets smaller than limitfunction pythagoreanTriplets(limit){ // Triplet: a^2 + b^2 = c^2 let a, b, c = 0; // Loop from 2 to max_limit let m = 2; // Limiting c would limit // all a, b and c while (c < limit) { // Now loop on j from 1 to i-1 for(let n = 1; n < m; ++n) { // Evaluate and print // triplets using // the relation between // a, b and c a = m * m - n * n; b = 2 * m * n; c = m * m + n * n; if (c > limit) break; document.write(a + " " + b + " " + c + "</br>"); } m++; }} // Driver codelet limit = 20;pythagoreanTriplets(limit); // This code is contributed by divyesh072019 </script> Output : 3 4 5 8 6 10 5 12 13 15 8 17 12 16 20 Time complexity of this approach is O(k) where k is number of triplets printed for a given limit (We iterate for m and n only and every iteration prints a triplet) Note: The above method doesn’t generate all triplets smaller than a given limit. For example “9 12 15” which is a valid triplet is not printed by above method. Thanks to Sid Agrawal for pointing this out. References: https://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Manish_100 jit_t vt_m Shubham Mishra 22 divyesh072019 rkbhola5 surinderdawra388 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Find minimum number of coins that make a given value Program for factorial of a number Sieve of Eratosthenes The Knight's tour problem | Backtracking-1 Operators in C / C++
[ { "code": null, "e": 25120, "s": 25092, "text": "\n09 Feb, 2022" }, { "code": null, "e": 25299, "s": 25120, "text": "A Pythagorean triplet is a set of three positive integers a, b and c such that a2 + b2 = c2. Given a limit, generate all Pythagorean Triples with values smaller than given limit." }, { "code": null, "e": 25401, "s": 25299, "text": "Input : limit = 20\nOutput : 3 4 5\n 8 6 10\n 5 12 13\n 15 8 17\n 12 16 20" }, { "code": null, "e": 25667, "s": 25401, "text": "A Simple Solution is to generate these triplets smaller than given limit using three nested loop. For every triplet, check if Pythagorean condition is true, if true, then print the triplet. Time complexity of this solution is O(limit3) where ‘limit’ is given limit." }, { "code": null, "e": 25948, "s": 25667, "text": "An Efficient Solution can print all triplets in O(k) time where k is number of triplets printed. The idea is to use square sum relation of Pythagorean triplet, i.e., addition of squares of a and b is equal to square of c, we can write these number in terms of m and n such that, " }, { "code": null, "e": 26108, "s": 25948, "text": " a = m2 - n2\n b = 2 * m * n\n c = m2 + n2\nbecause,\n a2 = m4 + n4 – 2 * m2 * n2\n b2 = 4 * m2 * n2\n c2 = m4 + n4 + 2* m2 * n2" }, { "code": null, "e": 26238, "s": 26108, "text": "We can see that a2 + b2 = c2, so instead of iterating for a, b and c we can iterate for m and n and can generate these triplets. " }, { "code": null, "e": 26284, "s": 26238, "text": "Below is the implementation of above idea : " }, { "code": null, "e": 26288, "s": 26284, "text": "C++" }, { "code": null, "e": 26293, "s": 26288, "text": "Java" }, { "code": null, "e": 26301, "s": 26293, "text": "Python3" }, { "code": null, "e": 26304, "s": 26301, "text": "C#" }, { "code": null, "e": 26308, "s": 26304, "text": "PHP" }, { "code": null, "e": 26319, "s": 26308, "text": "Javascript" }, { "code": "// C++ program to generate pythagorean// triplets smaller than a given limit#include <bits/stdc++.h> // Function to generate pythagorean// triplets smaller than limitvoid pythagoreanTriplets(int limit){ // triplet: a^2 + b^2 = c^2 int a, b, c = 0; // loop from 2 to max_limit int m = 2; // Limiting c would limit // all a, b and c while (c < limit) { // now loop on j from 1 to i-1 for (int n = 1; n < m; ++n) { // Evaluate and print triplets using // the relation between a, b and c a = m * m - n * n; b = 2 * m * n; c = m * m + n * n; if (c > limit) break; printf(\"%d %d %d\\n\", a, b, c); } m++; }} // Driver Codeint main(){ int limit = 20; pythagoreanTriplets(limit); return 0;}", "e": 27160, "s": 26319, "text": null }, { "code": "// Java program to generate pythagorean// triplets smaller than a given limitimport java.io.*;import java.util.*; class GFG { // Function to generate pythagorean // triplets smaller than limit static void pythagoreanTriplets(int limit) { // triplet: a^2 + b^2 = c^2 int a, b, c = 0; // loop from 2 to max_limit int m = 2; // Limiting c would limit // all a, b and c while (c < limit) { // now loop on j from 1 to i-1 for (int n = 1; n < m; ++n) { // Evaluate and print // triplets using // the relation between // a, b and c a = m * m - n * n; b = 2 * m * n; c = m * m + n * n; if (c > limit) break; System.out.println(a + \" \" + b + \" \" + c); } m++; } } // Driver Code public static void main(String args[]) { int limit = 20; pythagoreanTriplets(limit); }} // This code is contributed by Manish.", "e": 28259, "s": 27160, "text": null }, { "code": "# Python3 program to generate pythagorean# triplets smaller than a given limit # Function to generate pythagorean# triplets smaller than limitdef pythagoreanTriplets(limits) : c, m = 0, 2 # Limiting c would limit # all a, b and c while c < limits : # Now loop on n from 1 to m-1 for n in range(1, m) : a = m * m - n * n b = 2 * m * n c = m * m + n * n # if c is greater than # limit then break it if c > limits : break print(a, b, c) m = m + 1 # Driver Codeif __name__ == '__main__' : limit = 20 pythagoreanTriplets(limit) # This code is contributed by Shrikant13.", "e": 28975, "s": 28259, "text": null }, { "code": "// C# program to generate pythagorean// triplets smaller than a given limitusing System; class GFG { // Function to generate pythagorean // triplets smaller than limit static void pythagoreanTriplets(int limit) { // triplet: a^2 + b^2 = c^2 int a, b, c = 0; // loop from 2 to max_limit int m = 2; // Limiting c would limit // all a, b and c while (c < limit) { // now loop on j from 1 to i-1 for (int n = 1; n < m; ++n) { // Evaluate and print // triplets using // the relation between // a, b and c a = m * m - n * n; b = 2 * m * n; c = m * m + n * n; if (c > limit) break; Console.WriteLine(a + \" \" + b + \" \" + c); } m++; } } // Driver Code public static void Main() { int limit = 20; pythagoreanTriplets(limit); }} // This code is contributed by anuj_67.", "e": 30091, "s": 28975, "text": null }, { "code": "<?php// PHP program to generate pythagorean// triplets smaller than a given limit // Function to generate pythagorean// triplets smaller than limitfunction pythagoreanTriplets($limit){ // triplet: a^2 + b^2 = c^2 $a; $b; $c=0; // loop from 2 to max_limit $m = 2; // Limiting c would limit // all a, b and c while ($c < $limit) { // now loop on j from 1 to i-1 for ($n = 1; $n < $m; ++$n) { // Evaluate and print // triplets using the // relation between a, // b and c $a = $m *$m - $n * $n; $b = 2 * $m * $n; $c = $m * $m + $n * $n; if ($c > $limit) break; echo $a, \" \", $b, \" \", $c, \"\\n\"; } $m++; }} // Driver Code $limit = 20; pythagoreanTriplets($limit); // This code is contributed by ajit.?>", "e": 31011, "s": 30091, "text": null }, { "code": "<script> // Javascript program to generate pythagorean// triplets smaller than a given limit // Function to generate pythagorean// triplets smaller than limitfunction pythagoreanTriplets(limit){ // Triplet: a^2 + b^2 = c^2 let a, b, c = 0; // Loop from 2 to max_limit let m = 2; // Limiting c would limit // all a, b and c while (c < limit) { // Now loop on j from 1 to i-1 for(let n = 1; n < m; ++n) { // Evaluate and print // triplets using // the relation between // a, b and c a = m * m - n * n; b = 2 * m * n; c = m * m + n * n; if (c > limit) break; document.write(a + \" \" + b + \" \" + c + \"</br>\"); } m++; }} // Driver codelet limit = 20;pythagoreanTriplets(limit); // This code is contributed by divyesh072019 </script>", "e": 31975, "s": 31011, "text": null }, { "code": null, "e": 31985, "s": 31975, "text": "Output : " }, { "code": null, "e": 32023, "s": 31985, "text": "3 4 5\n8 6 10\n5 12 13\n15 8 17\n12 16 20" }, { "code": null, "e": 32187, "s": 32023, "text": "Time complexity of this approach is O(k) where k is number of triplets printed for a given limit (We iterate for m and n only and every iteration prints a triplet)" }, { "code": null, "e": 32479, "s": 32187, "text": "Note: The above method doesn’t generate all triplets smaller than a given limit. For example “9 12 15” which is a valid triplet is not printed by above method. Thanks to Sid Agrawal for pointing this out. References: https://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples " }, { "code": null, "e": 32652, "s": 32479, "text": "This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 32663, "s": 32652, "text": "Manish_100" }, { "code": null, "e": 32669, "s": 32663, "text": "jit_t" }, { "code": null, "e": 32674, "s": 32669, "text": "vt_m" }, { "code": null, "e": 32692, "s": 32674, "text": "Shubham Mishra 22" }, { "code": null, "e": 32706, "s": 32692, "text": "divyesh072019" }, { "code": null, "e": 32715, "s": 32706, "text": "rkbhola5" }, { "code": null, "e": 32732, "s": 32715, "text": "surinderdawra388" }, { "code": null, "e": 32745, "s": 32732, "text": "Mathematical" }, { "code": null, "e": 32758, "s": 32745, "text": "Mathematical" }, { "code": null, "e": 32856, "s": 32758, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32880, "s": 32856, "text": "Merge two sorted arrays" }, { "code": null, "e": 32923, "s": 32880, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 32937, "s": 32923, "text": "Prime Numbers" }, { "code": null, "e": 32979, "s": 32937, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 33052, "s": 32979, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 33105, "s": 33052, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 33139, "s": 33105, "text": "Program for factorial of a number" }, { "code": null, "e": 33161, "s": 33139, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 33204, "s": 33161, "text": "The Knight's tour problem | Backtracking-1" } ]
Check if a Palindromic String can be formed by concatenating Substrings of two given Strings - GeeksforGeeks
07 Jun, 2021 Given two strings str1 and str2, the task is to check if it is possible to form a Palindromic String by concatenation of two substrings of str1 and str2. Examples: Input: str1 = “abcd”, str2 = “acba”Output: YesExplanation:There are five possible cases where concatenation of two substrings from str1 and str2 gives palindromic string:“ab” + “a” = “aba”“ab” + “ba” = “abba”“bc” + “cb” = “bccb”“bc” + “b” = “bcb”“cd” + “c” = “cdc” Input: str1 = “pqrs”, str2 = “abcd”Output: NoExplanation:There is no possible concatenation of sub-strings from given strings which gives palindromic string. Naive Approach:The simplest approach to solve the problem is to generate every possible substring of str1 and str2 and combine them to generate all possible concatenations. For each concatenation, check if it is palindromic or not. If found to be true, print “Yes”. Otherwise, print “No”.Time Complexity: O(N2* M2 * (N+M)), where N and M are the lengths of str1 and str2 respectively.Auxiliary Space: O(1) Efficient Approach:To optimize the above approach, the following observation needs to be made: If the given strings possess at least one common character, then they will always form a palindromic string on concatenation of the common character from both the strings. Illustration:str1 = “abc”, str2 = “fad” Since ‘a’ is common in both strings, a palindromic string “aa” can be obtained. Follow the steps below to solve the problem: Initialize a boolean array to mark the presence of each alphabet in the two strings. Traverse str1 and mark the index (str1[i] – ‘a’) as true. Now, traverse str2 and check if any index (str2[i] – ‘a’) is already marked as true, print “Yes”. After complete traversal of str2, if no common character is found, print “No”. 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; // Function to check if a palindromic// string can be formed from the// substring of given stringsbool check(string str1, string str2){ // Boolean array to mark // presence of characters vector<bool> mark(26, false); int n = str1.size(), m = str2.size(); for (int i = 0; i < n; i++) { mark[str1[i] - 'a'] = true; } // Check if any of the character // of str2 is already marked for (int i = 0; i < m; i++) { // If a common character // is found if (mark[str2[i] - 'a']) return true; } // If no common character // is found return false;} // Driver Codeint main(){ string str1 = "abca", str2 = "efad"; if (check(str1, str2)) cout << "Yes"; else cout << "No"; return 0;} // Java program to implement// the above approachimport java.util.Arrays; class GFG{ // Function to check if a palindromic// string can be formed from the// substring of given stringspublic static boolean check(String str1, String str2){ // Boolean array to mark // presence of characters boolean[] mark = new boolean[26]; Arrays.fill(mark, false); int n = str1.length(), m = str2.length(); for(int i = 0; i < n; i++) { mark[str1.charAt(i) - 'a'] = true; } // Check if any of the character // of str2 is already marked for(int i = 0; i < m; i++) { // If a common character // is found if (mark[str2.charAt(i) - 'a']) return true; } // If no common character // is found return false;} // Driver codepublic static void main(String[] args){ String str1 = "abca", str2 = "efad"; if (check(str1, str2)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by divyeshrabadiya07 # Python3 program to implement# the above approach # Function to check if a palindromic# string can be formed from the# substring of given stringsdef check(str1, str2): # Boolean array to mark # presence of characters mark = [False for i in range(26)] n = len(str1) m = len(str2) for i in range(n): mark[ord(str1[i]) - ord('a')] = True # Check if any of the character # of str2 is already marked for i in range(m): # If a common character # is found if (mark[ord(str2[i]) - ord('a')]): return True; # If no common character # is found return False # Driver codeif __name__=="__main__": str1 = "abca" str2 = "efad" if (check(str1, str2)): print("Yes"); else: print("No"); # This code is contributed by rutvik_56 // C# program to implement// the above approachusing System; class GFG{ // Function to check if a palindromic// string can be formed from the// substring of given stringspublic static bool check(String str1, String str2){ // Boolean array to mark // presence of characters bool[] mark = new bool[26]; int n = str1.Length, m = str2.Length; for(int i = 0; i < n; i++) { mark[str1[i] - 'a'] = true; } // Check if any of the character // of str2 is already marked for(int i = 0; i < m; i++) { // If a common character // is found if (mark[str2[i] - 'a']) return true; } // If no common character // is found return false;} // Driver codepublic static void Main(String[] args){ String str1 = "abca", str2 = "efad"; if (check(str1, str2)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by amal kumar choubey <script> // Javascript Program to implement// the above approach // Function to check if a palindromic// string can be formed from the// substring of given stringsfunction check(str1, str2){ // Boolean array to mark // presence of characters var mark = Array(26).fill(false); var n = str1.length, m = str2.length; for (var i = 0; i < n; i++) { mark[str1[i] - 'a'] = true; } // Check if any of the character // of str2 is already marked for (var i = 0; i < m; i++) { // If a common character // is found if (mark[str2[i] - 'a']) return true; } // If no common character // is found return false;} // Driver Codevar str1 = "abca", str2 = "efad";if (check(str1, str2)) document.write( "Yes");else document.write( "No"); // This code is contributed by noob2000.</script> Yes Time Complexity: O(max(N, M)) where N and M are the lengths of str1 and str2 respectively. Auxiliary Space: O(1) divyeshrabadiya07 Amal Kumar Choubey rutvik_56 noob2000 frequency-counting palindrome substring Searching Strings Searching Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Search an element in a sorted and rotated array Program to find largest element in an array k largest(or smallest) elements in an array Given an array of size n and a number k, find all elements that appear more than n/k times Median of two sorted arrays of different sizes Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 C++ Data Types Write a program to print all permutations of a given string
[ { "code": null, "e": 25198, "s": 25170, "text": "\n07 Jun, 2021" }, { "code": null, "e": 25352, "s": 25198, "text": "Given two strings str1 and str2, the task is to check if it is possible to form a Palindromic String by concatenation of two substrings of str1 and str2." }, { "code": null, "e": 25362, "s": 25352, "text": "Examples:" }, { "code": null, "e": 25627, "s": 25362, "text": "Input: str1 = “abcd”, str2 = “acba”Output: YesExplanation:There are five possible cases where concatenation of two substrings from str1 and str2 gives palindromic string:“ab” + “a” = “aba”“ab” + “ba” = “abba”“bc” + “cb” = “bccb”“bc” + “b” = “bcb”“cd” + “c” = “cdc”" }, { "code": null, "e": 25785, "s": 25627, "text": "Input: str1 = “pqrs”, str2 = “abcd”Output: NoExplanation:There is no possible concatenation of sub-strings from given strings which gives palindromic string." }, { "code": null, "e": 26191, "s": 25785, "text": "Naive Approach:The simplest approach to solve the problem is to generate every possible substring of str1 and str2 and combine them to generate all possible concatenations. For each concatenation, check if it is palindromic or not. If found to be true, print “Yes”. Otherwise, print “No”.Time Complexity: O(N2* M2 * (N+M)), where N and M are the lengths of str1 and str2 respectively.Auxiliary Space: O(1)" }, { "code": null, "e": 26286, "s": 26191, "text": "Efficient Approach:To optimize the above approach, the following observation needs to be made:" }, { "code": null, "e": 26579, "s": 26286, "text": "If the given strings possess at least one common character, then they will always form a palindromic string on concatenation of the common character from both the strings. Illustration:str1 = “abc”, str2 = “fad” Since ‘a’ is common in both strings, a palindromic string “aa” can be obtained. " }, { "code": null, "e": 26624, "s": 26579, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 26709, "s": 26624, "text": "Initialize a boolean array to mark the presence of each alphabet in the two strings." }, { "code": null, "e": 26767, "s": 26709, "text": "Traverse str1 and mark the index (str1[i] – ‘a’) as true." }, { "code": null, "e": 26865, "s": 26767, "text": "Now, traverse str2 and check if any index (str2[i] – ‘a’) is already marked as true, print “Yes”." }, { "code": null, "e": 26944, "s": 26865, "text": "After complete traversal of str2, if no common character is found, print “No”." }, { "code": null, "e": 26995, "s": 26944, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26999, "s": 26995, "text": "C++" }, { "code": null, "e": 27004, "s": 26999, "text": "Java" }, { "code": null, "e": 27012, "s": 27004, "text": "Python3" }, { "code": null, "e": 27015, "s": 27012, "text": "C#" }, { "code": null, "e": 27026, "s": 27015, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to check if a palindromic// string can be formed from the// substring of given stringsbool check(string str1, string str2){ // Boolean array to mark // presence of characters vector<bool> mark(26, false); int n = str1.size(), m = str2.size(); for (int i = 0; i < n; i++) { mark[str1[i] - 'a'] = true; } // Check if any of the character // of str2 is already marked for (int i = 0; i < m; i++) { // If a common character // is found if (mark[str2[i] - 'a']) return true; } // If no common character // is found return false;} // Driver Codeint main(){ string str1 = \"abca\", str2 = \"efad\"; if (check(str1, str2)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 27914, "s": 27026, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.Arrays; class GFG{ // Function to check if a palindromic// string can be formed from the// substring of given stringspublic static boolean check(String str1, String str2){ // Boolean array to mark // presence of characters boolean[] mark = new boolean[26]; Arrays.fill(mark, false); int n = str1.length(), m = str2.length(); for(int i = 0; i < n; i++) { mark[str1.charAt(i) - 'a'] = true; } // Check if any of the character // of str2 is already marked for(int i = 0; i < m; i++) { // If a common character // is found if (mark[str2.charAt(i) - 'a']) return true; } // If no common character // is found return false;} // Driver codepublic static void main(String[] args){ String str1 = \"abca\", str2 = \"efad\"; if (check(str1, str2)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by divyeshrabadiya07", "e": 28988, "s": 27914, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to check if a palindromic# string can be formed from the# substring of given stringsdef check(str1, str2): # Boolean array to mark # presence of characters mark = [False for i in range(26)] n = len(str1) m = len(str2) for i in range(n): mark[ord(str1[i]) - ord('a')] = True # Check if any of the character # of str2 is already marked for i in range(m): # If a common character # is found if (mark[ord(str2[i]) - ord('a')]): return True; # If no common character # is found return False # Driver codeif __name__==\"__main__\": str1 = \"abca\" str2 = \"efad\" if (check(str1, str2)): print(\"Yes\"); else: print(\"No\"); # This code is contributed by rutvik_56", "e": 29844, "s": 28988, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to check if a palindromic// string can be formed from the// substring of given stringspublic static bool check(String str1, String str2){ // Boolean array to mark // presence of characters bool[] mark = new bool[26]; int n = str1.Length, m = str2.Length; for(int i = 0; i < n; i++) { mark[str1[i] - 'a'] = true; } // Check if any of the character // of str2 is already marked for(int i = 0; i < m; i++) { // If a common character // is found if (mark[str2[i] - 'a']) return true; } // If no common character // is found return false;} // Driver codepublic static void Main(String[] args){ String str1 = \"abca\", str2 = \"efad\"; if (check(str1, str2)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by amal kumar choubey", "e": 30844, "s": 29844, "text": null }, { "code": "<script> // Javascript Program to implement// the above approach // Function to check if a palindromic// string can be formed from the// substring of given stringsfunction check(str1, str2){ // Boolean array to mark // presence of characters var mark = Array(26).fill(false); var n = str1.length, m = str2.length; for (var i = 0; i < n; i++) { mark[str1[i] - 'a'] = true; } // Check if any of the character // of str2 is already marked for (var i = 0; i < m; i++) { // If a common character // is found if (mark[str2[i] - 'a']) return true; } // If no common character // is found return false;} // Driver Codevar str1 = \"abca\", str2 = \"efad\";if (check(str1, str2)) document.write( \"Yes\");else document.write( \"No\"); // This code is contributed by noob2000.</script>", "e": 31711, "s": 30844, "text": null }, { "code": null, "e": 31715, "s": 31711, "text": "Yes" }, { "code": null, "e": 31829, "s": 31715, "text": "Time Complexity: O(max(N, M)) where N and M are the lengths of str1 and str2 respectively. Auxiliary Space: O(1) " }, { "code": null, "e": 31847, "s": 31829, "text": "divyeshrabadiya07" }, { "code": null, "e": 31866, "s": 31847, "text": "Amal Kumar Choubey" }, { "code": null, "e": 31876, "s": 31866, "text": "rutvik_56" }, { "code": null, "e": 31885, "s": 31876, "text": "noob2000" }, { "code": null, "e": 31904, "s": 31885, "text": "frequency-counting" }, { "code": null, "e": 31915, "s": 31904, "text": "palindrome" }, { "code": null, "e": 31925, "s": 31915, "text": "substring" }, { "code": null, "e": 31935, "s": 31925, "text": "Searching" }, { "code": null, "e": 31943, "s": 31935, "text": "Strings" }, { "code": null, "e": 31953, "s": 31943, "text": "Searching" }, { "code": null, "e": 31961, "s": 31953, "text": "Strings" }, { "code": null, "e": 31972, "s": 31961, "text": "palindrome" }, { "code": null, "e": 32070, "s": 31972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32118, "s": 32070, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 32162, "s": 32118, "text": "Program to find largest element in an array" }, { "code": null, "e": 32206, "s": 32162, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 32297, "s": 32206, "text": "Given an array of size n and a number k, find all elements that appear more than n/k times" }, { "code": null, "e": 32344, "s": 32297, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 32390, "s": 32344, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 32415, "s": 32390, "text": "Reverse a string in Java" }, { "code": null, "e": 32449, "s": 32415, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 32464, "s": 32449, "text": "C++ Data Types" } ]
Which PHP function is used to establish MySQL database connection using PHP script?
PHP provides mysql_connect() function to open a database connection. This function takes five parameters and returns a MySQL link identifier on success or FALSE on failure. Its syntax is as follows − connection mysql_connect(server,user,passwd,new_link,client_flag); Following table give us the parameters used in the syntax above − MYSQL_CLIENT_SSL − Use SSL encryption.MYSQL_CLIENT_COMPRESS − Use compression protocol.MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names.MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of inactivity before closing the connection. MYSQL_CLIENT_SSL − Use SSL encryption. MYSQL_CLIENT_COMPRESS − Use compression protocol. MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names. MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of inactivity before closing the connection.
[ { "code": null, "e": 1262, "s": 1062, "text": "PHP provides mysql_connect() function to open a database connection. This function takes five parameters and returns a MySQL link identifier on success or FALSE on failure. Its syntax is as follows −" }, { "code": null, "e": 1329, "s": 1262, "text": "connection mysql_connect(server,user,passwd,new_link,client_flag);" }, { "code": null, "e": 1395, "s": 1329, "text": "Following table give us the parameters used in the syntax above −" }, { "code": null, "e": 1649, "s": 1395, "text": "MYSQL_CLIENT_SSL − Use SSL encryption.MYSQL_CLIENT_COMPRESS − Use compression protocol.MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names.MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of inactivity before closing the connection." }, { "code": null, "e": 1688, "s": 1649, "text": "MYSQL_CLIENT_SSL − Use SSL encryption." }, { "code": null, "e": 1738, "s": 1688, "text": "MYSQL_CLIENT_COMPRESS − Use compression protocol." }, { "code": null, "e": 1800, "s": 1738, "text": "MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names." }, { "code": null, "e": 1906, "s": 1800, "text": "MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of inactivity before closing the connection." } ]
Java Examples - Array to Collection
How to convert an array into a collection ? Following example demonstrates to convert an array into a collection Arrays.asList(name) method of Java Util class. import java.util.*; import java.io.*; public class ArrayToCollection{ public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader (new InputStreamReader(System.in)); System.out.println("How many elements you want to add to the array: "); int n = Integer.parseInt(in.readLine()); String[] name = new String[n]; for(int i = 0; i < n; i++) { name[i] = in.readLine(); } List<String> list = Arrays.asList(name); System.out.println(); for(String li: list) { String str = li; System.out.print(str + " "); } } } The above code sample will produce the following result. How many elements you want to add to the array: red white green red white green Print Add Notes Bookmark this page
[ { "code": null, "e": 2112, "s": 2068, "text": "How to convert an array into a collection ?" }, { "code": null, "e": 2228, "s": 2112, "text": "Following example demonstrates to convert an array into a collection Arrays.asList(name) method of Java Util class." }, { "code": null, "e": 2880, "s": 2228, "text": "import java.util.*;\nimport java.io.*;\n\npublic class ArrayToCollection{\n public static void main(String args[]) throws IOException {\n BufferedReader in = new BufferedReader (new InputStreamReader(System.in));\n System.out.println(\"How many elements you want to add to the array: \");\n int n = Integer.parseInt(in.readLine());\n String[] name = new String[n];\n \n for(int i = 0; i < n; i++) {\n name[i] = in.readLine();\n }\n List<String> list = Arrays.asList(name); \n System.out.println();\n \n for(String li: list) {\n String str = li;\n System.out.print(str + \" \");\n }\n }\n}" }, { "code": null, "e": 2937, "s": 2880, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3019, "s": 2937, "text": "How many elements you want to add to the array:\nred white green\n\nred white green\n" }, { "code": null, "e": 3026, "s": 3019, "text": " Print" }, { "code": null, "e": 3037, "s": 3026, "text": " Add Notes" } ]
Ngx-Bootstrap - Quick Guide
The ngx-bootstrap is a very popular library to use bootstrap components in Angular Based projects. It contains almost all core components of Bootstrap. ngx-bootstrap components are by design modular,extensible and adaptable. Following are the key highlighting points of this bootstrap library. All components are modular by design. Custom templates, Styles can be applied easily. All components are modular by design. Custom templates, Styles can be applied easily. All components are extensible and adaptable and works on desktop and mobile with same ease and performance. All components are extensible and adaptable and works on desktop and mobile with same ease and performance. All components uses latest style guides and guidelines for code maintainability and readablity. All components uses latest style guides and guidelines for code maintainability and readablity. All components are fully unit tested and supports latest angular versions. All components are fully unit tested and supports latest angular versions. All components are richly documented and well written. All components are richly documented and well written. All components are have multiple working demos to exihibits multiple types of functionalities. All components are have multiple working demos to exihibits multiple types of functionalities. ngx-bootstrap is open source project. It is backed by MIT License. ngx-bootstrap is open source project. It is backed by MIT License. In this chapter, you will learn in detail about setting up the working environment of ngx-bootstrap on your local computer. As ngx-bootstrap is primarily for angular projects, make sure you have Node.js and npm and angular installed on your system. First create a angular project to test ngx-bootstrap components using following commands. ng new ngxbootstrap It will create an angular project named ngxbootstrap. You can use the following command to install ngx-bootstrap in newly created project− npm install ngx-bootstrap You can observe the following output once ngx-bootstrap is successfully installed − + [email protected] added 1 package from 1 contributor and audited 1454 packages in 16.743s Now, to test if bootstrap works fine with Node.js, create the test component using following command − ng g component test CREATE src/app/test/test.component.html (19 bytes) CREATE src/app/test/test.component.spec.ts (614 bytes) CREATE src/app/test/test.component.ts (267 bytes) CREATE src/app/test/test.component.css (0 bytes) UPDATE src/app/app.module.ts (388 bytes) Clear content of app.component.html and update it following contents. app.component.html <app-test></app-test> Update content of app.module.ts to include ngx-bootstrap accordion module. We'll add other module in subsequent chapters. Update it following contents. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion' @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule.forRoot() ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Update content of index.html to include bootstrap.css. Update it following contents. index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Ngxbootstrap</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <app-root></app-root> </body> </html> In next chapter, we'll update test component to use ngx-bootstrap components. Accordion is a control to display collapsible panels and it is used to display information in limited space. Displays collapsible content panels for presenting information in a limited amount of space. accordion accordion closeOthers − boolean, if true expanding one item will close all others closeOthers − boolean, if true expanding one item will close all others isAnimated − boolean, turn on/off animation, default: false isAnimated − boolean, turn on/off animation, default: false Instead of using heading attribute on the accordion-group, you can use an accordion-heading attribute on any element inside of a group that will be used as group's header template. accordion-group, accordion-panel accordion-group, accordion-panel heading − string, Clickable text in accordion's group header heading − string, Clickable text in accordion's group header isDisabled − boolean, enables/disables accordion group isDisabled − boolean, enables/disables accordion group isOpen − boolean, Is accordion group open or closed. This property supports two-way binding isOpen − boolean, Is accordion group open or closed. This property supports two-way binding panelClass − string, Provides an ability to use Bootstrap's contextual panel classes (panel-primary, panel-success, panel-info, etc...). panelClass − string, Provides an ability to use Bootstrap's contextual panel classes (panel-primary, panel-success, panel-info, etc...). isOpenChange − Emits when the opened state changes isOpenChange − Emits when the opened state changes Configuration service, provides default values for the AccordionComponent. closeOthers − boolean, Whether the other panels should be closed when a panel is opened. Default: false closeOthers − boolean, Whether the other panels should be closed when a panel is opened. Default: false isAnimated − boolean, turn on/off animation isAnimated − boolean, turn on/off animation As we're going to use accordion, We've updated app.module.ts to use AccordionModule as in ngx-bootstrap Environment Setup chapter. Update test.component.html to use the accordion. test.component.html <accordion> <accordion-group heading="Open By Default" [isOpen]="open"> <p>Open By Default</p> </accordion-group> <accordion-group heading="Disabled" [isDisabled]="disabled"> <p>Disabled</p> </accordion-group> <accordion-group heading="with isOpenChange" (isOpenChange)="log($event)"> <p>Open Event</p> </accordion-group> </accordion> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { open: boolean = true; disabled: boolean = true; constructor() { } ngOnInit(): void { } log(isOpened: boolean){ console.log(isOpened); } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200 and verify the following output. Alerts provides contextual messages for typical user actions like info, error with available and flexible alert messages. Displays collapsible content panels for presenting information in a limited amount of space. alert,bs-alert alert,bs-alert dismissible − boolean, If set, displays an inline "Close" button, default: false dismissible − boolean, If set, displays an inline "Close" button, default: false dismissOnTimeout − string | number, Number in milliseconds, after which alert will be closed dismissOnTimeout − string | number, Number in milliseconds, after which alert will be closed isOpen − boolean, Is alert visible, default: true isOpen − boolean, Is alert visible, default: true type − string, alert type. Provides one of four bootstrap supported contextual classes: success, info, warning and danger, default: warning type − string, alert type. Provides one of four bootstrap supported contextual classes: success, info, warning and danger, default: warning onClose − This event fires immediately after close instance method is called, $event is an instance of Alert component. onClose − This event fires immediately after close instance method is called, $event is an instance of Alert component. onClosed − This event fires when alert closed, $event is an instance of Alert component onClosed − This event fires when alert closed, $event is an instance of Alert component dismissible − boolean, is alerts are dismissible by default, default: false dismissible − boolean, is alerts are dismissible by default, default: false dismissOnTimeout − number, default time before alert will dismiss, default: undefined dismissOnTimeout − number, default time before alert will dismiss, default: undefined type − string, default alert type, default: warning type − string, default alert type, default: warning As we're going to use alerts, We've to update app.module.ts used in ngx-bootstrap Accordion chapter to use AlertModule and AlertConfig. Update app.module.ts to use the AlertModule and AlertConfig. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule, AlertConfig } from 'ngx-bootstrap/alert'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule ], providers: [AlertConfig], bootstrap: [AppComponent] }) export class AppModule { } Update test.component.html to use the alerts. test.component.html <alert type="success" [dismissible]="dismissible" [isOpen]="open" (onClosed)="log($event)" [dismissOnTimeout]="timeout"> <h4 class="alert-heading">Well done!</h4> <p>Success Message</p> </alert> <alert type="info"> <strong>Heads up!</strong> Info </alert> <alert type="warning"> <strong>Warning!</strong> Warning </alert> <alert type="danger"> <strong>Oh snap!</strong> Error </alert> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { open: boolean = true; dismissible: boolean = true; timeout: number = 10000; constructor() { } ngOnInit(): void { } log(alert){ console.log('alert message closed'); } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200 and verify the following output. ngx-bootstrap buttons have two specific directives which makes a group of buttons to behave as checkbox or radio buttons or hybrid where a radio button can be unchecked. Add checkbox functionality to any element. [btnCheckbox] [btnCheckbox] btnCheckboxFalse − boolean, Falsy value, will be set to ngModel, default: false btnCheckboxFalse − boolean, Falsy value, will be set to ngModel, default: false btnCheckboxTrue − boolean, Truthy value, will be set to ngModel, default: true btnCheckboxTrue − boolean, Truthy value, will be set to ngModel, default: true Create radio buttons or groups of buttons. A value of a selected button is bound to a variable specified via ngModel. [btnRadio] [btnRadio] btnRadio − string, Radio button value, will be set to ngModel btnRadio − string, Radio button value, will be set to ngModel disabled − boolean, If true - radio button is disabled disabled − boolean, If true - radio button is disabled uncheckable − boolean, If true - radio button can be unchecked uncheckable − boolean, If true - radio button can be unchecked value − string, Current value of radio component or group value − string, Current value of radio component or group A group of radio buttons. A value of a selected button is bound to a variable specified via ngModel. [btnRadioGroup] [btnRadioGroup] As we're going to use buttons, We've to update app.module.ts used in ngx-bootstrap Alerts chapter to use ButtonsModule. We're also adding support for input controls using FormModule. Update app.module.ts to use the AlertModule and AlertConfig. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule ], providers: [AlertConfig], bootstrap: [AppComponent] }) export class AppModule { } Update test.component.html to use the buttons. test.component.html <button type="button" class="btn btn-primary" (click)="clicked()"> Single Button </button> <pre class="card card-block card-header"> {{clickCounter}} </pre> <p>Button as Checkbox</p> <div class="btn-group"> <label class="btn btn-primary" [(ngModel)]="checkModel.left" btnCheckbox tabindex="0" role="button">Left</label> <label class="btn btn-primary" [(ngModel)]="checkModel.right" btnCheckbox tabindex="0" role="button">Right</label> </div> <pre class="card card-block card-header"> {{checkModel | json}} </pre> <p>Button as RadionButton</p> <div class="form-inline"> <div class="btn-group" btnRadioGroup [(ngModel)]="radioModel"> <label class="btn btn-success" btnRadio="Left">Left</label> <label class="btn btn-success" btnRadio="Right">Right</label> </div> </div> <pre class="card card-block card-header"> {{radioModel}} </pre> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { checkModel = { left: false, right: false }; radioModel = 'Left'; clickCounter = 0; constructor() { } ngOnInit(): void { } clicked(): void { this.clickCounter++; } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200 and verify the following output. ngx-bootstrap Carousel is used to create slide show of images or text Base element to create carousel. carousel carousel activeSlide − number, Index of currently displayed slide(started for 0) activeSlide − number, Index of currently displayed slide(started for 0) indicatorsByChunk − boolean, default: false indicatorsByChunk − boolean, default: false interval − number, Delay of item cycling in milliseconds. If false, carousel won't cycle automatically. interval − number, Delay of item cycling in milliseconds. If false, carousel won't cycle automatically. isAnimated − boolean, Turn on/off animation. Animation doesn't work for multilist carousel, default: false isAnimated − boolean, Turn on/off animation. Animation doesn't work for multilist carousel, default: false itemsPerSlide − number, default: 1 itemsPerSlide − number, default: 1 noPause − boolean noPause − boolean noWrap − boolean noWrap − boolean pauseOnFocus − boolean pauseOnFocus − boolean showIndicators − boolean showIndicators − boolean singleSlideOffset − boolean singleSlideOffset − boolean startFromIndex − number, default: 0 startFromIndex − number, default: 0 activeSlideChange − Will be emitted when active slide has been changed. Part of two-way-bindable [(activeSlide)] property activeSlideChange − Will be emitted when active slide has been changed. Part of two-way-bindable [(activeSlide)] property slideRangeChange − Will be emitted when active slides has been changed in multilist mode slideRangeChange − Will be emitted when active slides has been changed in multilist mode slide slide active − boolean, Is current slide active active − boolean, Is current slide active As we're going to use carousel, We've to update app.module.ts used in ngx-bootstrap Buttons chapter to use CarouselModule. Update app.module.ts to use the CarouselModule. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule ], providers: [AlertConfig], bootstrap: [AppComponent] }) export class AppModule { } Update test.component.html to use the Carousel. test.component.html <div style="width: 500px; height: 500px;"> <carousel [noWrap]="noWrapSlides" [showIndicators]="showIndicator"> <slide *ngFor="let slide of slides; let index=index"> <img [src]="slide.image" alt="image slide" style="display: block; width: 100%;"> <div class="carousel-caption"> <h4>Slide {{index}}</h4> <p>{{slide.text}}</p> </div> </slide> </carousel> <br/> <div> <div class="checkbox"> <label><input type="checkbox" [(ngModel)]="noWrapSlides">Disable Slide Looping</label> <label><input type="checkbox" [(ngModel)]="showIndicator">Enable Indicator</label> </div> </div> </div> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; import { CarouselConfig } from 'ngx-bootstrap/carousel'; @Component({ selector: 'app-test', templateUrl: './test.component.html', providers: [ { provide: CarouselConfig, useValue: { interval: 1500, noPause: false, showIndicators: true } } ], styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { slides = [ {image: 'assets/images/nature/1.jpg', text: 'First'}, {image: 'assets/images/nature/2.jpg',text: 'Second'}, {image: 'assets/images/nature/3.jpg',text: 'Third'} ]; noWrapSlides = false; showIndicator = true; constructor() { } ngOnInit(): void { } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200 and verify the following output. ngx-bootstrap Collapse directive helps to show/hide a container content. [collapse] [collapse] collapse − boolean, A flag indicating visibility of content (shown or hidden) collapse − boolean, A flag indicating visibility of content (shown or hidden) display − string display − string isAnimated − boolean, turn on/off animation. default: false isAnimated − boolean, turn on/off animation. default: false collapsed − This event fires as soon as content collapses collapsed − This event fires as soon as content collapses collapses − This event fires when collapsing is started collapses − This event fires when collapsing is started expanded − This event fires as soon as content becomes visible expanded − This event fires as soon as content becomes visible expands − This event fires when expansion is started expands − This event fires when expansion is started toggle() − allows to manually toggle content visibility toggle() − allows to manually toggle content visibility hide − allows to manually hide content hide − allows to manually hide content show − allows to manually show collapsed content show − allows to manually show collapsed content As we're going to use collapse, We've to update app.module.ts used in ngx-bootstrap Carousel chapter to use CollapseModule. Update app.module.ts to use the CollapseModule. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { CollapseModule } from 'ngx-bootstrap/collapse'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule, CollapseModule ], providers: [AlertConfig], bootstrap: [AppComponent] }) export class AppModule { } Update test.component.html to use the Collapse. test.component.html <div> <div class="checkbox"> <label><input type="checkbox" [(ngModel)]="isCollapsed">Collapse</label> </div> </div> <div [collapse]="isCollapsed" [isAnimated]="true"> <div class="well well-lg card card-block card-header">Welcome to Tutorialspoint.</div> </div> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { isCollapsed: boolean = false; constructor() { } ngOnInit(): void { } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200 and verify the following output. Check the collapse check box and then content will be collapsed. ngx-bootstrap DatePicker component is highly configurable and customizable as per our need. It provides various options to select date or date range. [bsDatepicker] [bsDatepicker] bsConfig − Partial<BsDatepickerConfig>, Config object for datepicker bsConfig − Partial<BsDatepickerConfig>, Config object for datepicker bsValue − Date, Initial value of datepicker bsValue − Date, Initial value of datepicker container − string, A selector specifying the element the datepicker should be appended to. default: body container − string, A selector specifying the element the datepicker should be appended to. default: body dateCustomClasses − DatepickerDateCustomClasses[], Date custom classes dateCustomClasses − DatepickerDateCustomClasses[], Date custom classes datesDisabled − Date[], Disable specific dates datesDisabled − Date[], Disable specific dates datesEnabled − Date[], Enable specific dates datesEnabled − Date[], Enable specific dates dateTooltipTexts − DatepickerDateTooltipText[], Date tooltip text dateTooltipTexts − DatepickerDateTooltipText[], Date tooltip text daysDisabled − number[], Disable Certain days in the week daysDisabled − number[], Disable Certain days in the week isDisabled − boolean, Indicates whether datepicker's content is enabled or not isDisabled − boolean, Indicates whether datepicker's content is enabled or not isOpen − boolean, Returns whether or not the datepicker is currently being shown isOpen − boolean, Returns whether or not the datepicker is currently being shown maxDate − boolean, Maximum date which is available for selection maxDate − boolean, Maximum date which is available for selection minDate − boolean, Minimum date which is available for selection minDate − boolean, Minimum date which is available for selection minMode − BsDatepickerViewMode, Minimum view mode : day, month, or year minMode − BsDatepickerViewMode, Minimum view mode : day, month, or year outsideClick − boolean, Close datepicker on outside click, default: true outsideClick − boolean, Close datepicker on outside click, default: true outsideEsc − boolean, Close datepicker on escape click, default: true outsideEsc − boolean, Close datepicker on escape click, default: true placement − "top" | "bottom" | "left" | "right", Placement of a datepicker. Accepts: "top", "bottom", "left", "right", default: bottom placement − "top" | "bottom" | "left" | "right", Placement of a datepicker. Accepts: "top", "bottom", "left", "right", default: bottom triggers − string, Specifies events that should trigger. Supports a space separated list of event names., default: click triggers − string, Specifies events that should trigger. Supports a space separated list of event names., default: click bsValueChange − Emits when datepicker value has been changed bsValueChange − Emits when datepicker value has been changed onHidden − Emits an event when the datepicker is hidden onHidden − Emits an event when the datepicker is hidden onShown − Emits an event when the datepicker is shown onShown − Emits an event when the datepicker is shown show() − Opens an element's datepicker. This is considered a 'manual' triggering of the datepicker. show() − Opens an element's datepicker. This is considered a 'manual' triggering of the datepicker. hide() − Closes an element's datepicker. This is considered a 'manual' triggering of the datepicker. hide() − Closes an element's datepicker. This is considered a 'manual' triggering of the datepicker. toggle() − Toggles an element's datepicker. This is considered a 'manual' triggering of the datepicker. toggle() − Toggles an element's datepicker. This is considered a 'manual' triggering of the datepicker. setConfig() − Set config for datepicker setConfig() − Set config for datepicker [bsDaterangepicker] [bsDaterangepicker] bsConfig − Partial<BsDaterangepickerConfig>, Config object for daterangepicker bsConfig − Partial<BsDaterangepickerConfig>, Config object for daterangepicker bsValue − Date, Initial value of daterangepicker bsValue − Date, Initial value of daterangepicker container − string, A selector specifying the element the daterangepicker should be appended to. default: body container − string, A selector specifying the element the daterangepicker should be appended to. default: body dateCustomClasses − DatepickerDateCustomClasses[], Date custom classes dateCustomClasses − DatepickerDateCustomClasses[], Date custom classes datesDisabled − Date[], Disable specific dates datesDisabled − Date[], Disable specific dates datesEnabled − Date[], Enable specific dates datesEnabled − Date[], Enable specific dates dateTooltipTexts − DatepickerDateTooltipText[], Date tooltip text dateTooltipTexts − DatepickerDateTooltipText[], Date tooltip text daysDisabled − number[], Disable Certain days in the week daysDisabled − number[], Disable Certain days in the week isDisabled − boolean, Indicates whether daterangepicker's content is enabled or not isDisabled − boolean, Indicates whether daterangepicker's content is enabled or not isOpen − boolean, Returns whether or not the daterangepicker is currently being shown isOpen − boolean, Returns whether or not the daterangepicker is currently being shown maxDate − boolean, Maximum date which is available for selection maxDate − boolean, Maximum date which is available for selection minDate − boolean, Minimum date which is available for selection minDate − boolean, Minimum date which is available for selection minMode − BsDatepickerViewMode, Minimum view mode : day, month, or year minMode − BsDatepickerViewMode, Minimum view mode : day, month, or year outsideClick − boolean, Close daterangepicker on outside click, default: true outsideClick − boolean, Close daterangepicker on outside click, default: true outsideEsc − boolean, Close daterangepicker on escape click, default: true outsideEsc − boolean, Close daterangepicker on escape click, default: true placement − "top" | "bottom" | "left" | "right", Placement of a daterangepicker. Accepts: "top", "bottom", "left", "right", default: bottom placement − "top" | "bottom" | "left" | "right", Placement of a daterangepicker. Accepts: "top", "bottom", "left", "right", default: bottom triggers − string, Specifies events that should trigger. Supports a space separated list of event names., default: click triggers − string, Specifies events that should trigger. Supports a space separated list of event names., default: click bsValueChange − Emits when daterangepicker value has been changed bsValueChange − Emits when daterangepicker value has been changed onHidden − Emits an event when the daterangepicker is hidden onHidden − Emits an event when the daterangepicker is hidden onShown − Emits an event when the daterangepicker is shown onShown − Emits an event when the daterangepicker is shown show() − Opens an element's datepicker. This is considered a 'manual' triggering of the datepicker. show() − Opens an element's datepicker. This is considered a 'manual' triggering of the datepicker. hide() − Closes an element's datepicker. This is considered a 'manual' triggering of the datepicker. hide() − Closes an element's datepicker. This is considered a 'manual' triggering of the datepicker. toggle() − Toggles an element's datepicker. This is considered a 'manual' triggering of the datepicker. toggle() − Toggles an element's datepicker. This is considered a 'manual' triggering of the datepicker. setConfig() − Set config for datepicker setConfig() − Set config for datepicker As we're going to use DatePicker and DateRangePicker, We've to update app.module.ts used in ngx-bootstrap Collapse chapter to use BsDatepickerModule and BsDatepickerConfig. Update app.module.ts to use the BsDatepickerModule and BsDatepickerConfig. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { CollapseModule } from 'ngx-bootstrap/collapse'; import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule, CollapseModule, BsDatepickerModule.forRoot() ], providers: [AlertConfig, BsDatepickerConfig], bootstrap: [AppComponent] }) export class AppModule { } Update index.html to use the bs-datepicker.css. app.module.ts <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Ngxbootstrap</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"> <link href="https://unpkg.com/ngx-bootstrap/datepicker/bs-datepicker.css" rel="stylesheet" > </head> <body> <app-root></app-root> </body> </html> Update test.component.html to use the datepickers. test.component.html <div class="row"> <div class="col-xs-12 col-12 col-md-4 form-group"> <input type="text" placeholder="Datepicker" class="form-control" bsDatepicker [bsValue]="bsValue" [minDate]="minDate" [maxDate]="maxDate" [daysDisabled]="[6,0]" [datesDisabled]="disabledDates" [bsConfig]="{ isAnimated: true, dateInputFormat: 'YYYY-MM-DD' }"> </div> <div class="col-xs-12 col-12 col-md-4 form-group"> <input type="text" placeholder="Daterangepicker" class="form-control" bsDaterangepicker [(ngModel)]="bsRangeValue" [datesEnabled]="enabledDates" [bsConfig]="{ isAnimated: true }"> </div> </div> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { bsValue = new Date(); bsRangeValue: Date[]; maxDate = new Date(); minDate = new Date(); constructor() { this.minDate.setDate(this.minDate.getDate() - 1); this.maxDate.setDate(this.maxDate.getDate() + 7); this.bsRangeValue = [this.bsValue, this.maxDate]; } ngOnInit(): void { } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200 and verify the following output. ngx-bootstrap dropdown component is toggleable and provides contextual overlay to display list of links etc. With dropdown directives we can make dropdowns interactive. [bsDropdown],[dropdown] [bsDropdown],[dropdown] autoClose − boolean, Indicates that dropdown will be closed on item or document click, and after pressing ESC autoClose − boolean, Indicates that dropdown will be closed on item or document click, and after pressing ESC container − string, A selector specifying the element the popover should be appended to. container − string, A selector specifying the element the popover should be appended to. dropup − boolean, This attribute indicates that the dropdown should be opened upwards. dropup − boolean, This attribute indicates that the dropdown should be opened upwards. insideClick − boolean, This attribute indicates that the dropdown shouldn't close on inside click when autoClose is set to true. insideClick − boolean, This attribute indicates that the dropdown shouldn't close on inside click when autoClose is set to true. isAnimated − boolean, Indicates that dropdown will be animated isAnimated − boolean, Indicates that dropdown will be animated isDisabled − boolean, Disables dropdown toggle and hides dropdown menu if opened isDisabled − boolean, Disables dropdown toggle and hides dropdown menu if opened isOpen − boolean, Returns whether or not the popover is currently being shown isOpen − boolean, Returns whether or not the popover is currently being shown placement − string, Placement of a popover. Accepts: "top", "bottom", "left", "right" placement − string, Placement of a popover. Accepts: "top", "bottom", "left", "right" triggers − string, Specifies events that should trigger. Supports a space separated list of event names. triggers − string, Specifies events that should trigger. Supports a space separated list of event names. isOpenChange − Emits an event when isOpen change isOpenChange − Emits an event when isOpen change onHidden − Emits an event when the popover is hidden onHidden − Emits an event when the popover is hidden onShown − Emits an event when the popover is shown onShown − Emits an event when the popover is shown show() − Opens an element's popover. This is considered a 'manual' triggering of the popover. show() − Opens an element's popover. This is considered a 'manual' triggering of the popover. hide() − Closes an element's popover. This is considered a 'manual' triggering of the popover. hide() − Closes an element's popover. This is considered a 'manual' triggering of the popover. toggle() − Toggles an element's popover. This is considered a 'manual' triggering of the popover. toggle() − Toggles an element's popover. This is considered a 'manual' triggering of the popover. setConfig() − Set config for popover setConfig() − Set config for popover As we're going to use dropdowns, We've to update app.module.ts used in ngx-bootstrap DatePicker chapter to use BsDropdownModule and BsDropdownConfig. Update app.module.ts to use the BsDropdownModule and BsDropdownConfig. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { CollapseModule } from 'ngx-bootstrap/collapse'; import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker'; import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule, CollapseModule, BsDatepickerModule.forRoot(), BsDropdownModule ], providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig], bootstrap: [AppComponent] }) export class AppModule { } Update test.component.html to use the dropdowns. test.component.html <div class="btn-group" dropdown #dropdown="bs-dropdown" [autoClose]="false"> <button id="button-basic" dropdownToggle type="button" class="btn btn-primary dropdown-toggle" aria-controls="dropdown-basic"> Menu <span class="caret"></span> </button> <ul id="dropdown-basic" *dropdownMenu class="dropdown-menu" role="menu" aria-labelledby="button-basic"> <li role="menuitem"><a class="dropdown-item" href="#">File</a></li> <li role="menuitem"><a class="dropdown-item" href="#">Edit</a></li> <li role="menuitem"><a class="dropdown-item" href="#">Search</a></li> <li class="divider dropdown-divider"></li> <li role="menuitem"><a class="dropdown-item" href="#">Recents</a> </li> </ul> </div> <button type="button" class="btn btn-primary" (click)="dropdown.isOpen = !dropdown.isOpen">Show/Hide </button> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { constructor() {} ngOnInit(): void {} } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200 and verify the following output. ngx-bootstrap modal component is a flexible and highly configurable dialog prompt and provides multiple defaults and can be used with minimum code. [bsModal] [bsModal] config − ModalOptions, allows to set modal configuration via element property config − ModalOptions, allows to set modal configuration via element property onHidden − This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete). onHidden − This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete). onHide − This event is fired immediately when the hide instance method has been called. onHide − This event is fired immediately when the hide instance method has been called. onShow − This event fires immediately when the show instance method is called. onShow − This event fires immediately when the show instance method is called. onShown − This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete). onShown − This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete). show() − Allows to manually open modal. show() − Allows to manually open modal. hide() − Allows to manually close modal. hide() − Allows to manually close modal. toggle() − Allows to manually toggle modal visibility. toggle() − Allows to manually toggle modal visibility. showElement() − Show dialog. showElement() − Show dialog. focusOtherModal() − Events tricks. focusOtherModal() − Events tricks. As we're going to use a modal, We've to update app.module.ts used in ngx-bootstrap Dropdowns chapter to use ModalModule and BsModalService. Update app.module.ts to use the ModalModule and BsModalService. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { CollapseModule } from 'ngx-bootstrap/collapse'; import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker'; import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown'; import { ModalModule, BsModalService } from 'ngx-bootstrap/modal'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule, CollapseModule, BsDatepickerModule.forRoot(), BsDropdownModule, ModalModule ], providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig,BsModalService], bootstrap: [AppComponent] }) export class AppModule { } Update test.component.html to use the modal. test.component.html <button type="button" class="btn btn-primary" (click)="openModal(template)">Open modal</button> <ng-template #template> <div class="modal-header"> <h4 class="modal-title pull-left">Modal</h4> <button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> This is a sample modal dialog box. </div> <div class="modal-footer"> <button type="button" class="btn btn-default" (click)="modalRef.hide()">Close</button> </div> </ng-template> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit, TemplateRef } from '@angular/core'; import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { modalRef: BsModalRef; constructor(private modalService: BsModalService) {} openModal(template: TemplateRef<any>) { this.modalRef = this.modalService.show(template); } ngOnInit(): void { } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output. ngx-bootstrap pagination component provides pagination links or a pager component to your site or component. pagination pagination align − boolean, if true aligns each link to the sides of pager align − boolean, if true aligns each link to the sides of pager boundaryLinks − boolean, if false first and last buttons will be hidden boundaryLinks − boolean, if false first and last buttons will be hidden customFirstTemplate − TemplateRef<PaginationLinkContext>, custom template for first link customFirstTemplate − TemplateRef<PaginationLinkContext>, custom template for first link customLastTemplate − TemplateRef<PaginationLinkContext>, custom template for last link customLastTemplate − TemplateRef<PaginationLinkContext>, custom template for last link customNextTemplate − TemplateRef<PaginationLinkContext>, custom template for next link customNextTemplate − TemplateRef<PaginationLinkContext>, custom template for next link customPageTemplate − TemplateRef<PaginationLinkContext>, custom template for page link customPageTemplate − TemplateRef<PaginationLinkContext>, custom template for page link customPreviousTemplate − TemplateRef<PaginationLinkContext>, custom template for previous link customPreviousTemplate − TemplateRef<PaginationLinkContext>, custom template for previous link directionLinks − boolean, if false previous and next buttons will be hidden directionLinks − boolean, if false previous and next buttons will be hidden disabled − boolean, if true pagination component will be disabled disabled − boolean, if true pagination component will be disabled firstText − boolean, first button text firstText − boolean, first button text itemsPerPage − number, maximum number of items per page. If value less than 1 will display all items on one page itemsPerPage − number, maximum number of items per page. If value less than 1 will display all items on one page lastText − string, last button text lastText − string, last button text maxSize − number, limit number for page links in pager maxSize − number, limit number for page links in pager nextText − string, next button text nextText − string, next button text pageBtnClass − string, add class to <li> pageBtnClass − string, add class to <li> previousText − string, previous button text previousText − string, previous button text rotate − boolean, if true current page will in the middle of pages list rotate − boolean, if true current page will in the middle of pages list totalItems − number, total number of items in all pages totalItems − number, total number of items in all pages numPages − fired when total pages count changes, $event:number equals to total pages count. numPages − fired when total pages count changes, $event:number equals to total pages count. pageChanged − fired when page was changed, $event:{page, itemsPerPage} equals to object with current page index and number of items per page. pageChanged − fired when page was changed, $event:{page, itemsPerPage} equals to object with current page index and number of items per page. As we're going to use a pagination, We've to update app.module.ts used in ngx-bootstrap Modals chapter to use PaginationModule and PaginationConfig. Update app.module.ts to use the PaginationModule and PaginationConfig. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { CollapseModule } from 'ngx-bootstrap/collapse'; import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker'; import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown'; import { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule, CollapseModule, BsDatepickerModule.forRoot(), BsDropdownModule, ModalModule, PaginationModule ], providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig, BsModalService, PaginationConfig], bootstrap: [AppComponent] }) export class AppModule { } Update test.component.html to use the modal. test.component.html <div class="row"> <div class="col-xs-12 col-12"> <div class="content-wrapper"> <p class="content-item" *ngFor="let content of returnedArray">{{content}}</p> </div> <pagination [boundaryLinks]="showBoundaryLinks" [directionLinks]="showDirectionLinks" [totalItems]="contentArray.length" [itemsPerPage]="5" (pageChanged)="pageChanged($event)"></pagination> </div> </div> <div> <div class="checkbox"> <label><input type="checkbox" [(ngModel)]="showBoundaryLinks">Show Boundary Links</label> <br/> <label><input type="checkbox" [(ngModel)]="showDirectionLinks">Show Direction Links</label> </div> </div> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; import { BsModalService } from 'ngx-bootstrap/modal'; import { PageChangedEvent } from 'ngx-bootstrap/pagination'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { contentArray: string[] = new Array(50).fill(''); returnedArray: string[]; showBoundaryLinks: boolean = true; showDirectionLinks: boolean = true; constructor() {} pageChanged(event: PageChangedEvent): void { const startItem = (event.page - 1) * event.itemsPerPage; const endItem = event.page * event.itemsPerPage; this.returnedArray = this.contentArray.slice(startItem, endItem); } ngOnInit(): void { this.contentArray = this.contentArray.map((v: string, i: number) => { return 'Line '+ (i + 1); }); this.returnedArray = this.contentArray.slice(0, 5); } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output. ngx-bootstrap popover component provides a small overlay component to provide small information about a component. popover popover adaptivePosition − boolean, sets disable adaptive position. adaptivePosition − boolean, sets disable adaptive position. container − string, A selector specifying the element the popover should be appended to. container − string, A selector specifying the element the popover should be appended to. containerClass − string, Css class for popover container containerClass − string, Css class for popover container delay − number, Delay before showing the tooltip delay − number, Delay before showing the tooltip isOpen − boolean, Returns whether or not the popover is currently being shown isOpen − boolean, Returns whether or not the popover is currently being shown outsideClick − boolean, Close popover on outside click, default: false outsideClick − boolean, Close popover on outside click, default: false placement − "top" | "bottom" | "left" | "right" | "auto" | "top left" | "top right" | "right top" | "right bottom" | "bottom right" | "bottom left" | "left bottom" | "left top", Placement of a popover. Accepts: "top", "bottom", "left", "right". placement − "top" | "bottom" | "left" | "right" | "auto" | "top left" | "top right" | "right top" | "right bottom" | "bottom right" | "bottom left" | "left bottom" | "left top", Placement of a popover. Accepts: "top", "bottom", "left", "right". popover − string | TemplateRef<any>, Content to be displayed as popover. popover − string | TemplateRef<any>, Content to be displayed as popover. popoverContext − any, Context to be used if popover is a template. popoverContext − any, Context to be used if popover is a template. popoverTitle − string, Title of a popover. popoverTitle − string, Title of a popover. triggers − string, Specifies events that should trigger. Supports a space separated list of event names. triggers − string, Specifies events that should trigger. Supports a space separated list of event names. onHidden − Emits an event when the popover is hidden. onHidden − Emits an event when the popover is hidden. onShown − Emits an event when the popover is shown. onShown − Emits an event when the popover is shown. setAriaDescribedBy() − Set attribute aria-describedBy for element directive and set id for the popover. setAriaDescribedBy() − Set attribute aria-describedBy for element directive and set id for the popover. show() − Opens an element's popover. This is considered a "manual" triggering of the popover. show() − Opens an element's popover. This is considered a "manual" triggering of the popover. hide() − Closes an element's popover. This is considered a "manual" triggering of the popover. hide() − Closes an element's popover. This is considered a "manual" triggering of the popover. toggle() − Toggles an element's popover. This is considered a "manual" triggering of the popover. toggle() − Toggles an element's popover. This is considered a "manual" triggering of the popover. As we're going to use a popover, We've to update app.module.ts used in ngx-bootstrap Pagination chapter to use PopoverModule and PopoverConfig. Update app.module.ts to use the PopoverModule and PopoverConfig. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { CollapseModule } from 'ngx-bootstrap/collapse'; import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker'; import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown'; import { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination'; import { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule, CollapseModule, BsDatepickerModule.forRoot(), BsDropdownModule, ModalModule, PaginationModule, PopoverModule ], providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig, BsModalService, PaginationConfig], bootstrap: [AppComponent] }) export class AppModule { } Update test.component.html to use the modal. test.component.html <button type="button" class="btn btn-default btn-primary" popover="Welcome to Tutorialspoint." [outsideClick]="true"> Default Popover </button> <button type="button" class="btn btn-default btn-primary" popover="Welcome to Tutorialspoint." popoverTitle="Tutorialspoint" [outsideClick]="true" placement="right"> Right Aligned popover </button> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; import { BsModalService } from 'ngx-bootstrap/modal'; import { PageChangedEvent } from 'ngx-bootstrap/pagination'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { constructor() {} ngOnInit(): void { } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output. ngx-bootstrap progress bar component provides a progress component to show progress of a workflow with flexible bars. progressbar progressbar animate − boolean, if true changing value of progress bar will be animated. animate − boolean, if true changing value of progress bar will be animated. max − number, maximum total value of progress element. max − number, maximum total value of progress element. striped − boolean, If true, striped classes are applied. striped − boolean, If true, striped classes are applied. type − ProgressbarType, provide one of the four supported contextual classes: success, info, warning, danger. type − ProgressbarType, provide one of the four supported contextual classes: success, info, warning, danger. value − number | any[], current value of progress bar. Could be a number or array of objects like {"value":15,"type":"info","label":"15 %"}. value − number | any[], current value of progress bar. Could be a number or array of objects like {"value":15,"type":"info","label":"15 %"}. As we're going to use a progressbar, We've to update app.module.ts used in ngx-bootstrap Popover chapter to use ProgressbarModule and ProgressbarConfig. Update app.module.ts to use the ProgressbarModule and ProgressbarConfig. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { CollapseModule } from 'ngx-bootstrap/collapse'; import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker'; import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown'; import { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination'; import { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover'; import { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule, CollapseModule, BsDatepickerModule.forRoot(), BsDropdownModule, ModalModule, PaginationModule, PopoverModule, ProgressbarModule ], providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig, BsModalService, PaginationConfig, ProgressbarConfig], bootstrap: [AppComponent] }) export class AppModule { } Update test.component.html to use the modal. test.component.html <div class="row"> <div class="col-sm-4"> <div class="mb-2"> <progressbar [value]="value"></progressbar> </div> </div> <div class="col-sm-4"> <div class="mb-2"> <progressbar [value]="value" type="warning" [striped]="true">{{value}}%</progressbar> </div> </div> <div class="col-sm-4"> <div class="mb-2"> <progressbar [value]="value" type="danger" [striped]="true" [animate]="true" ><i>{{value}} / {{max}}</i></progressbar> </div> </div> </div> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { max: number = 100; value: number = 25; constructor() {} ngOnInit(): void { } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200. ngx-bootstrap rating component provides a configurable rating component, a star bar by default. rating rating customTemplate − TemplateRef<any>, custom template for icons. customTemplate − TemplateRef<any>, custom template for icons. max − number, no. of icons, default: 5. max − number, no. of icons, default: 5. readonly − boolean, if true will not react on any user events. readonly − boolean, if true will not react on any user events. titles − string[], array of icons titles, default: ([1, 2, 3, 4, 5]) titles − string[], array of icons titles, default: ([1, 2, 3, 4, 5]) onHover − fired when icon selected, $event:number equals to selected rating. onHover − fired when icon selected, $event:number equals to selected rating. onLeave − fired when icon selected, $event:number equals to previous rating value. onLeave − fired when icon selected, $event:number equals to previous rating value. As we're going to use a rating, We've to update app.module.ts used in ngx-bootstrap ProgressBar chapter to use RatingModule, RatingConfig. Update app.module.ts to use the RatingModule and RatingConfig. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { CollapseModule } from 'ngx-bootstrap/collapse'; import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker'; import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown'; import { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination'; import { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover'; import { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar'; import { RatingModule, RatingConfig } from 'ngx-bootstrap/rating'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule, CollapseModule, BsDatepickerModule.forRoot(), BsDropdownModule, ModalModule, PaginationModule, PopoverModule, ProgressbarModule, RatingModule ], providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig, BsModalService, PaginationConfig, ProgressbarConfig, RatingConfig], bootstrap: [AppComponent] }) export class AppModule { } Update test.component.html to use the rating. test.component.html <rating [(ngModel)]="value" [max]="max" [readonly]="false" [titles]="['one','two','three','four']"></rating> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { max: number = 10; value: number = 5; constructor() {} ngOnInit(): void { } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output. ngx-bootstrap sortable component provides a configurable sortable component, with drag drop support. bs-sortable bs-sortable fieldName − string, field name if input array consists of objects. fieldName − string, field name if input array consists of objects. itemActiveClass − string, class name for active item. itemActiveClass − string, class name for active item. itemActiveStyle − { [key: string]: string; }, style object for active item. itemActiveStyle − { [key: string]: string; }, style object for active item. itemClass − string, class name for item itemClass − string, class name for item itemStyle − string, class name for item itemStyle − string, class name for item itemTemplate − TemplateRef<any>, used to specify a custom item template. Template variables: item and index; itemTemplate − TemplateRef<any>, used to specify a custom item template. Template variables: item and index; placeholderClass − string, class name for placeholder placeholderClass − string, class name for placeholder placeholderItem − string, placeholder item which will be shown if collection is empty placeholderItem − string, placeholder item which will be shown if collection is empty placeholderStyle − string, style object for placeholder placeholderStyle − string, style object for placeholder wrapperClass − string, class name for items wrapper wrapperClass − string, class name for items wrapper wrapperStyle − { [key: string]: string; }, style object for items wrapper wrapperStyle − { [key: string]: string; }, style object for items wrapper onChange − fired on array change (reordering, insert, remove), same as ngModelChange. Returns new items collection as a payload. onChange − fired on array change (reordering, insert, remove), same as ngModelChange. Returns new items collection as a payload. As we're going to use a sortable, We've to update app.module.ts used in ngx-bootstrap Rating chapter to use SortableModule and DraggableItemService. Update app.module.ts to use the SortableModule and DraggableItemService. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { CollapseModule } from 'ngx-bootstrap/collapse'; import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker'; import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown'; import { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination'; import { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover'; import { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar'; import { RatingModule, RatingConfig } from 'ngx-bootstrap/rating'; import { SortableModule, DraggableItemService } from 'ngx-bootstrap/sortable'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule, CollapseModule, BsDatepickerModule.forRoot(), BsDropdownModule, ModalModule, PaginationModule, PopoverModule, ProgressbarModule, RatingModule, SortableModule ], providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig, BsModalService, PaginationConfig, ProgressbarConfig, RatingConfig, DraggableItemService], bootstrap: [AppComponent] }) export class AppModule { } Update styles.css to use styles for sortable component. Styles.css .sortableItem { padding: 6px 12px; margin-bottom: 4px; font-size: 14px; line-height: 1.4em; text-align: center; cursor: grab; border: 1px solid transparent; border-radius: 4px; border-color: #adadad; } .sortableItemActive { background-color: #e6e6e6; box-shadow: inset 0 3px 5px rgba(0,0,0,.125); } .sortableWrapper { min-height: 150px; } Update test.component.html to use the sortable component. test.component.html <bs-sortable [(ngModel)]="items" fieldName="name" itemClass="sortableItem" itemActiveClass="sortableItemActive" wrapperClass="sortableWrapper"> </bs-sortable> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { items = [ { id: 1, name: 'Apple' }, { id: 2, name: 'Orange' }, { id: 3, name: 'Mango' } ]; constructor() {} ngOnInit(): void { } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200. ngx-bootstrap tabs component provides a easy to use and highly configurable Tab component. tabset tabset justified − boolean, if true tabs fill the container and have a consistent width. justified − boolean, if true tabs fill the container and have a consistent width. type − string, navigation context class: 'tabs' or 'pills'. type − string, navigation context class: 'tabs' or 'pills'. vertical − if true tabs will be placed vertically. vertical − if true tabs will be placed vertically. tab, [tab] tab, [tab] active − boolean, tab active state toggle. active − boolean, tab active state toggle. customClass − string, if set, will be added to the tab's class attribute. Multiple classes are supported. customClass − string, if set, will be added to the tab's class attribute. Multiple classes are supported. disabled − boolean, if true tab can not be activated. disabled − boolean, if true tab can not be activated. heading − string, tab header text. heading − string, tab header text. id − string, tab id. The same id with suffix '-link' will be added to the corresponding id − string, tab id. The same id with suffix '-link' will be added to the corresponding element. removable − boolean, if true tab can be removable, additional button will appear. removable − boolean, if true tab can be removable, additional button will appear. deselect − fired when tab became inactive, $event:Tab equals to deselected instance of Tab component. deselect − fired when tab became inactive, $event:Tab equals to deselected instance of Tab component. removed − fired before tab will be removed, $event:Tab equals to instance of removed tab. removed − fired before tab will be removed, $event:Tab equals to instance of removed tab. selectTab − fired when tab became active, $event:Tab equals to selected instance of Tab component. selectTab − fired when tab became active, $event:Tab equals to selected instance of Tab component. As we're going to use a Tab, We've to update app.module.ts used in ngx-bootstrap Sortable chapter to use TabsModule and TabsetConfig. Update app.module.ts to use the TabsModule and TabsetConfig. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { CollapseModule } from 'ngx-bootstrap/collapse'; import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker'; import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown'; import { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination'; import { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover'; import { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar'; import { RatingModule, RatingConfig } from 'ngx-bootstrap/rating'; import { SortableModule, DraggableItemService } from 'ngx-bootstrap/sortable'; import { TabsModule, TabsetConfig } from 'ngx-bootstrap/tabs'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule, CollapseModule, BsDatepickerModule.forRoot(), BsDropdownModule, ModalModule, PaginationModule, PopoverModule, ProgressbarModule, RatingModule, SortableModule, TabsModule ], providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig, BsModalService, PaginationConfig, ProgressbarConfig, RatingConfig, DraggableItemService, TabsetConfig], bootstrap: [AppComponent] }) export class AppModule { } Update test.component.html to use the tabs component. test.component.html <tabset> <tab heading="Home">Home</tab> <tab *ngFor="let tabz of tabs" [heading]="tabz.title" [active]="tabz.active" (selectTab)="tabz.active = true" [disabled]="tabz.disabled"> {{tabz?.content}} </tab> </tabset> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { tabs = [ { title: 'First', content: 'First Tab Content' }, { title: 'Second', content: 'Second Tab Content', active: true }, { title: 'Third', content: 'Third Tab Content', removable: true }, { title: 'Four', content: 'Fourth Tab Content', disabled: true } ]; constructor() {} ngOnInit(): void { } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output. ngx-bootstrap timepicker component provides a easy to use and highly configurable Time Picker component. timepicker timepicker arrowkeys − boolean, if true the values of hours and minutes can be changed using the up/down arrow keys on the keyboard. arrowkeys − boolean, if true the values of hours and minutes can be changed using the up/down arrow keys on the keyboard. disabled − boolean, if true hours and minutes fields will be disabled. disabled − boolean, if true hours and minutes fields will be disabled. hoursPlaceholder − string, placeholder for hours field in timepicker. hoursPlaceholder − string, placeholder for hours field in timepicker. hourStep − number, hours change step. hourStep − number, hours change step. max − Date, maximum time user can select. max − Date, maximum time user can select. meridians − string[], meridian labels based on locale. meridians − string[], meridian labels based on locale. min − Date, minimum time user can select. min − Date, minimum time user can select. minutesPlaceholder − string, placeholder for minutes field in timepicker. minutesPlaceholder − string, placeholder for minutes field in timepicker. minuteStep − number, hours change step. minuteStep − number, hours change step. mousewheel − boolean, if true scroll inside hours and minutes inputs will change time. mousewheel − boolean, if true scroll inside hours and minutes inputs will change time. readonlyInput − boolean, if true hours and minutes fields will be readonly. readonlyInput − boolean, if true hours and minutes fields will be readonly. secondsPlaceholder − string, placeholder for seconds field in timepicker. secondsPlaceholder − string, placeholder for seconds field in timepicker. secondsStep − number, seconds change step. secondsStep − number, seconds change step. showMeridian − boolean, if true meridian button will be shown. showMeridian − boolean, if true meridian button will be shown. showMinutes − boolean, show minutes in timepicker. showMinutes − boolean, show minutes in timepicker. showSeconds − boolean, show seconds in timepicker. showSeconds − boolean, show seconds in timepicker. showSpinners − boolean, if true spinner arrows above and below the inputs will be shown. showSpinners − boolean, if true spinner arrows above and below the inputs will be shown. isValid − emits true if value is a valid date. isValid − emits true if value is a valid date. As we're going to use a TimePicker, We've to update app.module.ts used in ngx-bootstrap Tabs chapter to use TimepickerModule. Update app.module.ts to use the TimepickerModule. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { CollapseModule } from 'ngx-bootstrap/collapse'; import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker'; import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown'; import { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination'; import { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover'; import { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar'; import { RatingModule, RatingConfig } from 'ngx-bootstrap/rating'; import { SortableModule, DraggableItemService } from 'ngx-bootstrap/sortable'; import { TabsModule, TabsetConfig } from 'ngx-bootstrap/tabs'; import { TimepickerModule } from 'ngx-bootstrap/timepicker'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule, CollapseModule, BsDatepickerModule.forRoot(), BsDropdownModule, ModalModule, PaginationModule, PopoverModule, ProgressbarModule, RatingModule, SortableModule, TabsModule, TimepickerModule.forRoot() ], providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig, BsModalService, PaginationConfig, ProgressbarConfig, RatingConfig, DraggableItemService, TabsetConfig], bootstrap: [AppComponent] }) export class AppModule { } Update test.component.html to use the timepicker component. test.component.html <timepicker [(ngModel)]="time"></timepicker> <pre class="alert alert-info">Time is: {{time}}</pre> <timepicker [(ngModel)]="time" [showMeridian]="false"></timepicker> <pre class="alert alert-info">Time is: {{time}}</pre> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { time: Date = new Date(); constructor() {} ngOnInit(): void { } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output. ngx-bootstrap tooltip component provides a easy to use and highly configurable Tooltip component. [tooltip], [tooltipHtml] [tooltip], [tooltipHtml] adaptivePosition − boolean, sets disable adaptive position. adaptivePosition − boolean, sets disable adaptive position. container − string, A selector specifying the element the tooltip should be appended to. container − string, A selector specifying the element the tooltip should be appended to. containerClass − string, Css class for tooltip container. containerClass − string, Css class for tooltip container. delay − number, Delay before showing the tooltip. delay − number, Delay before showing the tooltip. isDisabled − boolean, Allows to disable tooltip. isDisabled − boolean, Allows to disable tooltip. isOpen − boolean, Returns whether or not the tooltip is currently being shown. isOpen − boolean, Returns whether or not the tooltip is currently being shown. placement − string, Placement of a tooltip. Accepts: "top", "bottom", "left", "right". placement − string, Placement of a tooltip. Accepts: "top", "bottom", "left", "right". tooltip − string | TemplateRef<any>, Content to be displayed as tooltip. tooltip − string | TemplateRef<any>, Content to be displayed as tooltip. tooltipAnimation − boolean, default: true. tooltipAnimation − boolean, default: true. tooltipAppendToBody − boolean. tooltipAppendToBody − boolean. tooltipClass − string. tooltipClass − string. tooltipContext − any. tooltipContext − any. tooltipEnable − boolean. tooltipEnable − boolean. tooltipFadeDuration − number, default: 150. tooltipFadeDuration − number, default: 150. tooltipHtml − string | TemplateRef<any>. tooltipHtml − string | TemplateRef<any>. tooltipIsOpen − boolean. tooltipIsOpen − boolean. tooltipPlacement − string tooltipPlacement − string tooltipPopupDelay − number tooltipPopupDelay − number tooltipTrigger − string | string[] tooltipTrigger − string | string[] triggers − string, Specifies events that should trigger. Supports a space separated list of event names. triggers − string, Specifies events that should trigger. Supports a space separated list of event names. onHidden − Emits an event when the tooltip is hidden. onHidden − Emits an event when the tooltip is hidden. onShown − Emits an event when the tooltip is shown. onShown − Emits an event when the tooltip is shown. tooltipChange − Fired when tooltip content changes. tooltipChange − Fired when tooltip content changes. tooltipStateChanged − Fired when tooltip state changes. tooltipStateChanged − Fired when tooltip state changes. As we're going to use Tooltip, We've to update app.module.ts used in ngx-bootstrap TimePicker chapter to use TooltipModule. Update app.module.ts to use the TooltipModule. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { CollapseModule } from 'ngx-bootstrap/collapse'; import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker'; import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown'; import { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination'; import { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover'; import { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar'; import { RatingModule, RatingConfig } from 'ngx-bootstrap/rating'; import { SortableModule, DraggableItemService } from 'ngx-bootstrap/sortable'; import { TabsModule, TabsetConfig } from 'ngx-bootstrap/tabs'; import { TimepickerModule } from 'ngx-bootstrap/timepicker'; import { TooltipModule } from 'ngx-bootstrap/tooltip'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule, CollapseModule, BsDatepickerModule.forRoot(), BsDropdownModule, ModalModule, PaginationModule, PopoverModule, ProgressbarModule, RatingModule, SortableModule, TabsModule, TimepickerModule.forRoot(), TooltipModule.forRoot() ], providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig, BsModalService, PaginationConfig, ProgressbarConfig, RatingConfig, DraggableItemService, TabsetConfig], bootstrap: [AppComponent] }) export class AppModule { } Update test.component.html to use the timepicker component. test.component.html <timepicker [(ngModel)]="time"></timepicker> <pre class="alert alert-info">Time is: {{time}}</pre> <timepicker [(ngModel)]="time" [showMeridian]="false"></timepicker> <pre class="alert alert-info">Time is: {{time}}</pre> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { time: Date = new Date(); constructor() {} ngOnInit(): void { } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output. ngx-bootstrap Typeahead directive provides a easy to use and highly configurable, easy to use Typeahead component. [typeahead] [typeahead] adaptivePosition − boolean, sets use adaptive position. adaptivePosition − boolean, sets use adaptive position. container − string, A selector specifying the element the typeahead should be appended to. container − string, A selector specifying the element the typeahead should be appended to. dropup − boolean, This attribute indicates that the dropdown should be opened upwards, default:false. dropup − boolean, This attribute indicates that the dropdown should be opened upwards, default:false. isAnimated − boolean, turn on/off animation, default:false. isAnimated − boolean, turn on/off animation, default:false. optionsListTemplate − TemplateRef<TypeaheadOptionListContext>, used to specify a custom options list template. Template variables: matches, itemTemplate, query. optionsListTemplate − TemplateRef<TypeaheadOptionListContext>, used to specify a custom options list template. Template variables: matches, itemTemplate, query. typeahead − Typeahead, options source, can be Array of strings, objects or an Observable for external matching process. typeahead − Typeahead, options source, can be Array of strings, objects or an Observable for external matching process. typeaheadAsync − boolean, should be used only in case of typeahead attribute is Observable of array. If true - loading of options will be async, otherwise - sync. true make sense if options array is large. typeaheadAsync − boolean, should be used only in case of typeahead attribute is Observable of array. If true - loading of options will be async, otherwise - sync. true make sense if options array is large. typeaheadGroupField − string, when options source is an array of objects, the name of field that contains the group value, matches are grouped by this field when set. typeaheadGroupField − string, when options source is an array of objects, the name of field that contains the group value, matches are grouped by this field when set. typeaheadHideResultsOnBlur − boolean, used to hide result on blur. typeaheadHideResultsOnBlur − boolean, used to hide result on blur. typeaheadIsFirstItemActive − boolean, makes active first item in a list. Default:true. typeaheadIsFirstItemActive − boolean, makes active first item in a list. Default:true. typeaheadItemTemplate − TemplateRef<TypeaheadOptionItemContext>, used to specify a custom item template. Template variables exposed are called item and index. typeaheadItemTemplate − TemplateRef<TypeaheadOptionItemContext>, used to specify a custom item template. Template variables exposed are called item and index. typeaheadLatinize − boolean, match latin symbols. If true the word s�per would match super and vice versa.Default: true. typeaheadLatinize − boolean, match latin symbols. If true the word s�per would match super and vice versa.Default: true. typeaheadMinLength − number, minimal no of characters that needs to be entered before typeahead kicks-in. When set to 0, typeahead shows on focus with full list of options (limited as normal by typeaheadOptionsLimit) typeaheadMinLength − number, minimal no of characters that needs to be entered before typeahead kicks-in. When set to 0, typeahead shows on focus with full list of options (limited as normal by typeaheadOptionsLimit) typeaheadMultipleSearch − boolean, Can be used to conduct a search of multiple items and have suggestion not for the whole value of the input but for the value that comes after a delimiter provided via typeaheadMultipleSearchDelimiters attribute. This option can only be used together with typeaheadSingleWords option if typeaheadWordDelimiters and typeaheadPhraseDelimiters are different from typeaheadMultipleSearchDelimiters to avoid conflict in determining when to delimit multiple searches and when a single word. typeaheadMultipleSearch − boolean, Can be used to conduct a search of multiple items and have suggestion not for the whole value of the input but for the value that comes after a delimiter provided via typeaheadMultipleSearchDelimiters attribute. This option can only be used together with typeaheadSingleWords option if typeaheadWordDelimiters and typeaheadPhraseDelimiters are different from typeaheadMultipleSearchDelimiters to avoid conflict in determining when to delimit multiple searches and when a single word. typeaheadMultipleSearchDelimiters − string, should be used only in case typeaheadMultipleSearch attribute is true. Sets the multiple search delimiter to know when to start a new search. Defaults to comma. If space needs to be used, then explicitly set typeaheadWordDelimiters to something else than space because space is used by default OR set typeaheadSingleWords attribute to false if you don't need to use it together with multiple search. typeaheadMultipleSearchDelimiters − string, should be used only in case typeaheadMultipleSearch attribute is true. Sets the multiple search delimiter to know when to start a new search. Defaults to comma. If space needs to be used, then explicitly set typeaheadWordDelimiters to something else than space because space is used by default OR set typeaheadSingleWords attribute to false if you don't need to use it together with multiple search. typeaheadOptionField − string, when options source is an array of objects, the name of field that contains the options value, we use array item as option in case of this field is missing. Supports nested properties and methods. typeaheadOptionField − string, when options source is an array of objects, the name of field that contains the options value, we use array item as option in case of this field is missing. Supports nested properties and methods. typeaheadOptionsInScrollableView − number, Default value: 5,specifies number of options to show in scroll view typeaheadOptionsInScrollableView − number, Default value: 5,specifies number of options to show in scroll view typeaheadOptionsLimit − number, maximum length of options items list. The default value is 20. typeaheadOptionsLimit − number, maximum length of options items list. The default value is 20. typeaheadOrderBy − TypeaheadOrder, Used to specify a custom order of matches. When options source is an array of objects a field for sorting has to be set up. In case of options source is an array of string, a field for sorting is absent. The ordering direction could be changed to ascending or descending. typeaheadOrderBy − TypeaheadOrder, Used to specify a custom order of matches. When options source is an array of objects a field for sorting has to be set up. In case of options source is an array of string, a field for sorting is absent. The ordering direction could be changed to ascending or descending. typeaheadPhraseDelimiters − string, should be used only in case typeaheadSingleWords attribute is true. Sets the word delimiter to match exact phrase. Defaults to simple and double quotes. typeaheadPhraseDelimiters − string, should be used only in case typeaheadSingleWords attribute is true. Sets the word delimiter to match exact phrase. Defaults to simple and double quotes. typeaheadScrollable − boolean, Default value: false, specifies if typeahead is scrollable typeaheadScrollable − boolean, Default value: false, specifies if typeahead is scrollable typeaheadSelectFirstItem − boolean, Default value: true, fired when an options list was opened and the user clicked Tab If a value equal true, it will be chosen first or active item in the list If value equal false, it will be chosen an active item in the list or nothing typeaheadSelectFirstItem − boolean, Default value: true, fired when an options list was opened and the user clicked Tab If a value equal true, it will be chosen first or active item in the list If value equal false, it will be chosen an active item in the list or nothing typeaheadSingleWords − boolean, Default value: true, Can be use to search words by inserting a single white space between each characters for example 'C a l i f o r n i a' will match 'California'. typeaheadSingleWords − boolean, Default value: true, Can be use to search words by inserting a single white space between each characters for example 'C a l i f o r n i a' will match 'California'. typeaheadWaitMs − number, minimal wait time after last character typed before typeahead kicks-in typeaheadWaitMs − number, minimal wait time after last character typed before typeahead kicks-in typeaheadWordDelimiters − string, should be used only in case typeaheadSingleWords attribute is true. Sets the word delimiter to break words. Defaults to space. typeaheadWordDelimiters − string, should be used only in case typeaheadSingleWords attribute is true. Sets the word delimiter to break words. Defaults to space. typeaheadLoading − fired when 'busy' state of this component was changed, fired on async mode only, returns boolean. typeaheadLoading − fired when 'busy' state of this component was changed, fired on async mode only, returns boolean. typeaheadNoResults − fired on every key event and returns true in case of matches are not detected. typeaheadNoResults − fired on every key event and returns true in case of matches are not detected. typeaheadOnBlur − fired when blur event occurs. returns the active item. typeaheadOnBlur − fired when blur event occurs. returns the active item. typeaheadOnSelect − fired when option was selected, return object with data of this option. typeaheadOnSelect − fired when option was selected, return object with data of this option. As we're going to use a Typeahead, We've to update app.module.ts used in ngx-bootstrap Timepicker chapter to use TypeaheadModule. Update app.module.ts to use the TypeaheadModule. app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { AccordionModule } from 'ngx-bootstrap/accordion'; import { AlertModule,AlertConfig } from 'ngx-bootstrap/alert'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import { FormsModule } from '@angular/forms'; import { CarouselModule } from 'ngx-bootstrap/carousel'; import { CollapseModule } from 'ngx-bootstrap/collapse'; import { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker'; import { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown'; import { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination'; import { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover'; import { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar'; import { RatingModule, RatingConfig } from 'ngx-bootstrap/rating'; import { SortableModule, DraggableItemService } from 'ngx-bootstrap/sortable'; import { TabsModule, TabsetConfig } from 'ngx-bootstrap/tabs'; import { TimepickerModule } from 'ngx-bootstrap/timepicker'; import { TypeaheadModule } from 'ngx-bootstrap/typeahead'; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserAnimationsModule, BrowserModule, AccordionModule, AlertModule, ButtonsModule, FormsModule, CarouselModule, CollapseModule, BsDatepickerModule.forRoot(), BsDropdownModule, ModalModule, PaginationModule, PopoverModule, ProgressbarModule, RatingModule, SortableModule, TabsModule, TimepickerModule.forRoot(), TypeaheadModule.forRoot() ], providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig, BsModalService, PaginationConfig, ProgressbarConfig, RatingConfig, DraggableItemService, TabsetConfig], bootstrap: [AppComponent] }) export class AppModule { } Update test.component.html to use the timepicker component. test.component.html <input [(ngModel)]="selectedState" [typeahead]="states" class="form-control"> <pre class="card card-block card-header mb-3">Model: {{selectedState | json}}</pre> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { selectedState: string; states: string[] = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado', 'Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois', 'Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine', 'Maryland','Massachusetts','Michigan','Minnesota','Mississippi', 'Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey', 'New Mexico','New York','North Dakota','North Carolina','Ohio', 'Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina', 'South Dakota','Tennessee','Texas','Utah','Vermont', 'Virginia','Washington','West Virginia','Wisconsin','Wyoming']; constructor() {} ngOnInit(): void { } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output. Print Add Notes Bookmark this page
[ { "code": null, "e": 2394, "s": 2100, "text": "The ngx-bootstrap is a very popular library to use bootstrap components in Angular Based projects. It contains almost all core components of Bootstrap. ngx-bootstrap components are by design modular,extensible and adaptable. Following are the key highlighting points of this bootstrap library." }, { "code": null, "e": 2480, "s": 2394, "text": "All components are modular by design. Custom templates, Styles can be applied easily." }, { "code": null, "e": 2566, "s": 2480, "text": "All components are modular by design. Custom templates, Styles can be applied easily." }, { "code": null, "e": 2674, "s": 2566, "text": "All components are extensible and adaptable and works on desktop and mobile with same ease and performance." }, { "code": null, "e": 2782, "s": 2674, "text": "All components are extensible and adaptable and works on desktop and mobile with same ease and performance." }, { "code": null, "e": 2878, "s": 2782, "text": "All components uses latest style guides and guidelines for code maintainability and readablity." }, { "code": null, "e": 2974, "s": 2878, "text": "All components uses latest style guides and guidelines for code maintainability and readablity." }, { "code": null, "e": 3049, "s": 2974, "text": "All components are fully unit tested and supports latest angular versions." }, { "code": null, "e": 3124, "s": 3049, "text": "All components are fully unit tested and supports latest angular versions." }, { "code": null, "e": 3179, "s": 3124, "text": "All components are richly documented and well written." }, { "code": null, "e": 3234, "s": 3179, "text": "All components are richly documented and well written." }, { "code": null, "e": 3329, "s": 3234, "text": "All components are have multiple working demos to exihibits multiple types of functionalities." }, { "code": null, "e": 3424, "s": 3329, "text": "All components are have multiple working demos to exihibits multiple types of functionalities." }, { "code": null, "e": 3491, "s": 3424, "text": "ngx-bootstrap is open source project. It is backed by MIT License." }, { "code": null, "e": 3558, "s": 3491, "text": "ngx-bootstrap is open source project. It is backed by MIT License." }, { "code": null, "e": 3807, "s": 3558, "text": "In this chapter, you will learn in detail about setting up the working environment of ngx-bootstrap on your local computer. As ngx-bootstrap is primarily for angular projects, make sure you have Node.js and npm and angular installed on your system." }, { "code": null, "e": 3897, "s": 3807, "text": "First create a angular project to test ngx-bootstrap components using following commands." }, { "code": null, "e": 3918, "s": 3897, "text": "ng new ngxbootstrap\n" }, { "code": null, "e": 3972, "s": 3918, "text": "It will create an angular project named ngxbootstrap." }, { "code": null, "e": 4057, "s": 3972, "text": "You can use the following command to install ngx-bootstrap in newly created project−" }, { "code": null, "e": 4084, "s": 4057, "text": "npm install ngx-bootstrap\n" }, { "code": null, "e": 4168, "s": 4084, "text": "You can observe the following output once ngx-bootstrap is successfully installed −" }, { "code": null, "e": 4263, "s": 4168, "text": "+ [email protected]\nadded 1 package from 1 contributor and audited 1454 packages in 16.743s\n" }, { "code": null, "e": 4366, "s": 4263, "text": "Now, to test if bootstrap works fine with Node.js, create the test component using following command −" }, { "code": null, "e": 4633, "s": 4366, "text": "ng g component test\nCREATE src/app/test/test.component.html (19 bytes)\nCREATE src/app/test/test.component.spec.ts (614 bytes)\nCREATE src/app/test/test.component.ts (267 bytes)\nCREATE src/app/test/test.component.css (0 bytes)\nUPDATE src/app/app.module.ts (388 bytes)\n" }, { "code": null, "e": 4703, "s": 4633, "text": "Clear content of app.component.html and update it following contents." }, { "code": null, "e": 4722, "s": 4703, "text": "app.component.html" }, { "code": null, "e": 4745, "s": 4722, "text": "<app-test></app-test>\n" }, { "code": null, "e": 4897, "s": 4745, "text": "Update content of app.module.ts to include ngx-bootstrap accordion module. We'll add other module in subsequent chapters. Update it following contents." }, { "code": null, "e": 4911, "s": 4897, "text": "app.module.ts" }, { "code": null, "e": 5511, "s": 4911, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion'\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule.forRoot()\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 5596, "s": 5511, "text": "Update content of index.html to include bootstrap.css. Update it following contents." }, { "code": null, "e": 5607, "s": 5596, "text": "index.html" }, { "code": null, "e": 6048, "s": 5607, "text": "<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Ngxbootstrap</title>\n <base href=\"/\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"icon\" type=\"image/x-icon\" href=\"favicon.ico\">\n <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" rel=\"stylesheet\">\n </head>\n <body>\n <app-root></app-root>\n </body>\n</html>" }, { "code": null, "e": 6126, "s": 6048, "text": "In next chapter, we'll update test component to use ngx-bootstrap components." }, { "code": null, "e": 6235, "s": 6126, "text": "Accordion is a control to display collapsible panels and it is used to display information in limited space." }, { "code": null, "e": 6328, "s": 6235, "text": "Displays collapsible content panels for presenting information in a limited amount of space." }, { "code": null, "e": 6338, "s": 6328, "text": "accordion" }, { "code": null, "e": 6348, "s": 6338, "text": "accordion" }, { "code": null, "e": 6420, "s": 6348, "text": "closeOthers − boolean, if true expanding one item will close all others" }, { "code": null, "e": 6492, "s": 6420, "text": "closeOthers − boolean, if true expanding one item will close all others" }, { "code": null, "e": 6552, "s": 6492, "text": "isAnimated − boolean, turn on/off animation, default: false" }, { "code": null, "e": 6612, "s": 6552, "text": "isAnimated − boolean, turn on/off animation, default: false" }, { "code": null, "e": 6793, "s": 6612, "text": "Instead of using heading attribute on the accordion-group, you can use an accordion-heading attribute on any element inside of a group that will be used as group's header template." }, { "code": null, "e": 6826, "s": 6793, "text": "accordion-group, accordion-panel" }, { "code": null, "e": 6859, "s": 6826, "text": "accordion-group, accordion-panel" }, { "code": null, "e": 6920, "s": 6859, "text": "heading − string, Clickable text in accordion's group header" }, { "code": null, "e": 6981, "s": 6920, "text": "heading − string, Clickable text in accordion's group header" }, { "code": null, "e": 7036, "s": 6981, "text": "isDisabled − boolean, enables/disables accordion group" }, { "code": null, "e": 7091, "s": 7036, "text": "isDisabled − boolean, enables/disables accordion group" }, { "code": null, "e": 7183, "s": 7091, "text": "isOpen − boolean, Is accordion group open or closed. This property supports two-way binding" }, { "code": null, "e": 7275, "s": 7183, "text": "isOpen − boolean, Is accordion group open or closed. This property supports two-way binding" }, { "code": null, "e": 7412, "s": 7275, "text": "panelClass − string, Provides an ability to use Bootstrap's contextual panel classes (panel-primary, panel-success, panel-info, etc...)." }, { "code": null, "e": 7549, "s": 7412, "text": "panelClass − string, Provides an ability to use Bootstrap's contextual panel classes (panel-primary, panel-success, panel-info, etc...)." }, { "code": null, "e": 7600, "s": 7549, "text": "isOpenChange − Emits when the opened state changes" }, { "code": null, "e": 7651, "s": 7600, "text": "isOpenChange − Emits when the opened state changes" }, { "code": null, "e": 7726, "s": 7651, "text": "Configuration service, provides default values for the AccordionComponent." }, { "code": null, "e": 7830, "s": 7726, "text": "closeOthers − boolean, Whether the other panels should be closed when a panel is opened. Default: false" }, { "code": null, "e": 7934, "s": 7830, "text": "closeOthers − boolean, Whether the other panels should be closed when a panel is opened. Default: false" }, { "code": null, "e": 7978, "s": 7934, "text": "isAnimated − boolean, turn on/off animation" }, { "code": null, "e": 8022, "s": 7978, "text": "isAnimated − boolean, turn on/off animation" }, { "code": null, "e": 8153, "s": 8022, "text": "As we're going to use accordion, We've updated app.module.ts to use AccordionModule as in ngx-bootstrap Environment Setup chapter." }, { "code": null, "e": 8202, "s": 8153, "text": "Update test.component.html to use the accordion." }, { "code": null, "e": 8222, "s": 8202, "text": "test.component.html" }, { "code": null, "e": 8593, "s": 8222, "text": "<accordion>\n <accordion-group heading=\"Open By Default\" [isOpen]=\"open\">\n <p>Open By Default</p>\n </accordion-group>\n <accordion-group heading=\"Disabled\" [isDisabled]=\"disabled\">\n <p>Disabled</p>\n </accordion-group>\n <accordion-group heading=\"with isOpenChange\" (isOpenChange)=\"log($event)\">\n <p>Open Event</p>\n </accordion-group>\n</accordion>" }, { "code": null, "e": 8659, "s": 8593, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 8677, "s": 8659, "text": "test.component.ts" }, { "code": null, "e": 9061, "s": 8677, "text": "import { Component, OnInit } from '@angular/core';\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n open: boolean = true;\n disabled: boolean = true;\n constructor() { }\n ngOnInit(): void {\n }\n log(isOpened: boolean){\n console.log(isOpened);\n }\n}" }, { "code": null, "e": 9116, "s": 9061, "text": "Run the following command to start the angular server." }, { "code": null, "e": 9126, "s": 9116, "text": "ng serve\n" }, { "code": null, "e": 9217, "s": 9126, "text": "Once server is up and running. Open http://localhost:4200 and verify the following output." }, { "code": null, "e": 9339, "s": 9217, "text": "Alerts provides contextual messages for typical user actions like info, error with available and flexible alert messages." }, { "code": null, "e": 9432, "s": 9339, "text": "Displays collapsible content panels for presenting information in a limited amount of space." }, { "code": null, "e": 9447, "s": 9432, "text": "alert,bs-alert" }, { "code": null, "e": 9462, "s": 9447, "text": "alert,bs-alert" }, { "code": null, "e": 9543, "s": 9462, "text": "dismissible − boolean, If set, displays an inline \"Close\" button, default: false" }, { "code": null, "e": 9624, "s": 9543, "text": "dismissible − boolean, If set, displays an inline \"Close\" button, default: false" }, { "code": null, "e": 9717, "s": 9624, "text": "dismissOnTimeout − string | number, Number in milliseconds, after which alert will be closed" }, { "code": null, "e": 9810, "s": 9717, "text": "dismissOnTimeout − string | number, Number in milliseconds, after which alert will be closed" }, { "code": null, "e": 9860, "s": 9810, "text": "isOpen − boolean, Is alert visible, default: true" }, { "code": null, "e": 9910, "s": 9860, "text": "isOpen − boolean, Is alert visible, default: true" }, { "code": null, "e": 10050, "s": 9910, "text": "type − string, alert type. Provides one of four bootstrap supported contextual classes: success, info, warning and danger, default: warning" }, { "code": null, "e": 10190, "s": 10050, "text": "type − string, alert type. Provides one of four bootstrap supported contextual classes: success, info, warning and danger, default: warning" }, { "code": null, "e": 10310, "s": 10190, "text": "onClose − This event fires immediately after close instance method is called, $event is an instance of Alert component." }, { "code": null, "e": 10430, "s": 10310, "text": "onClose − This event fires immediately after close instance method is called, $event is an instance of Alert component." }, { "code": null, "e": 10518, "s": 10430, "text": "onClosed − This event fires when alert closed, $event is an instance of Alert component" }, { "code": null, "e": 10606, "s": 10518, "text": "onClosed − This event fires when alert closed, $event is an instance of Alert component" }, { "code": null, "e": 10682, "s": 10606, "text": "dismissible − boolean, is alerts are dismissible by default, default: false" }, { "code": null, "e": 10758, "s": 10682, "text": "dismissible − boolean, is alerts are dismissible by default, default: false" }, { "code": null, "e": 10844, "s": 10758, "text": "dismissOnTimeout − number, default time before alert will dismiss, default: undefined" }, { "code": null, "e": 10930, "s": 10844, "text": "dismissOnTimeout − number, default time before alert will dismiss, default: undefined" }, { "code": null, "e": 10982, "s": 10930, "text": "type − string, default alert type, default: warning" }, { "code": null, "e": 11034, "s": 10982, "text": "type − string, default alert type, default: warning" }, { "code": null, "e": 11170, "s": 11034, "text": "As we're going to use alerts, We've to update app.module.ts used in ngx-bootstrap Accordion chapter to use AlertModule and AlertConfig." }, { "code": null, "e": 11231, "s": 11170, "text": "Update app.module.ts to use the AlertModule and AlertConfig." }, { "code": null, "e": 11245, "s": 11231, "text": "app.module.ts" }, { "code": null, "e": 11930, "s": 11245, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule, AlertConfig } from 'ngx-bootstrap/alert';\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule\n ],\n providers: [AlertConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 11976, "s": 11930, "text": "Update test.component.html to use the alerts." }, { "code": null, "e": 11996, "s": 11976, "text": "test.component.html" }, { "code": null, "e": 12409, "s": 11996, "text": "<alert type=\"success\" \n [dismissible]=\"dismissible\"\n [isOpen]=\"open\"\n (onClosed)=\"log($event)\"\n [dismissOnTimeout]=\"timeout\">\n <h4 class=\"alert-heading\">Well done!</h4>\n <p>Success Message</p>\n</alert>\n<alert type=\"info\">\n <strong>Heads up!</strong> Info\n</alert>\n<alert type=\"warning\">\n <strong>Warning!</strong> Warning\n</alert>\n<alert type=\"danger\">\n <strong>Oh snap!</strong> Error\n</alert>" }, { "code": null, "e": 12475, "s": 12409, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 12493, "s": 12475, "text": "test.component.ts" }, { "code": null, "e": 12914, "s": 12493, "text": "import { Component, OnInit } from '@angular/core';\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n open: boolean = true;\n dismissible: boolean = true;\n timeout: number = 10000;\n constructor() { }\n \n ngOnInit(): void {\n }\n log(alert){\n console.log('alert message closed');\n }\n}" }, { "code": null, "e": 12969, "s": 12914, "text": "Run the following command to start the angular server." }, { "code": null, "e": 12979, "s": 12969, "text": "ng serve\n" }, { "code": null, "e": 13070, "s": 12979, "text": "Once server is up and running. Open http://localhost:4200 and verify the following output." }, { "code": null, "e": 13240, "s": 13070, "text": "ngx-bootstrap buttons have two specific directives which makes a group of buttons to behave as checkbox or radio buttons or hybrid where a radio button can be unchecked." }, { "code": null, "e": 13283, "s": 13240, "text": "Add checkbox functionality to any element." }, { "code": null, "e": 13297, "s": 13283, "text": "[btnCheckbox]" }, { "code": null, "e": 13311, "s": 13297, "text": "[btnCheckbox]" }, { "code": null, "e": 13391, "s": 13311, "text": "btnCheckboxFalse − boolean, Falsy value, will be set to ngModel, default: false" }, { "code": null, "e": 13471, "s": 13391, "text": "btnCheckboxFalse − boolean, Falsy value, will be set to ngModel, default: false" }, { "code": null, "e": 13550, "s": 13471, "text": "btnCheckboxTrue − boolean, Truthy value, will be set to ngModel, default: true" }, { "code": null, "e": 13629, "s": 13550, "text": "btnCheckboxTrue − boolean, Truthy value, will be set to ngModel, default: true" }, { "code": null, "e": 13747, "s": 13629, "text": "Create radio buttons or groups of buttons. A value of a selected button is bound to a variable specified via ngModel." }, { "code": null, "e": 13758, "s": 13747, "text": "[btnRadio]" }, { "code": null, "e": 13769, "s": 13758, "text": "[btnRadio]" }, { "code": null, "e": 13831, "s": 13769, "text": "btnRadio − string, Radio button value, will be set to ngModel" }, { "code": null, "e": 13893, "s": 13831, "text": "btnRadio − string, Radio button value, will be set to ngModel" }, { "code": null, "e": 13948, "s": 13893, "text": "disabled − boolean, If true - radio button is disabled" }, { "code": null, "e": 14003, "s": 13948, "text": "disabled − boolean, If true - radio button is disabled" }, { "code": null, "e": 14066, "s": 14003, "text": "uncheckable − boolean, If true - radio button can be unchecked" }, { "code": null, "e": 14129, "s": 14066, "text": "uncheckable − boolean, If true - radio button can be unchecked" }, { "code": null, "e": 14187, "s": 14129, "text": "value − string, Current value of radio component or group" }, { "code": null, "e": 14245, "s": 14187, "text": "value − string, Current value of radio component or group" }, { "code": null, "e": 14346, "s": 14245, "text": "A group of radio buttons. A value of a selected button is bound to a variable specified via ngModel." }, { "code": null, "e": 14362, "s": 14346, "text": "[btnRadioGroup]" }, { "code": null, "e": 14378, "s": 14362, "text": "[btnRadioGroup]" }, { "code": null, "e": 14561, "s": 14378, "text": "As we're going to use buttons, We've to update app.module.ts used in ngx-bootstrap Alerts chapter to use ButtonsModule. We're also adding support for input controls using FormModule." }, { "code": null, "e": 14622, "s": 14561, "text": "Update app.module.ts to use the AlertModule and AlertConfig." }, { "code": null, "e": 14636, "s": 14622, "text": "app.module.ts" }, { "code": null, "e": 15461, "s": 14636, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule\n ],\n providers: [AlertConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 15508, "s": 15461, "text": "Update test.component.html to use the buttons." }, { "code": null, "e": 15528, "s": 15508, "text": "test.component.html" }, { "code": null, "e": 16408, "s": 15528, "text": "<button type=\"button\" class=\"btn btn-primary\" (click)=\"clicked()\">\n Single Button\n</button>\n<pre class=\"card card-block card-header\">\n {{clickCounter}}\n</pre>\n<p>Button as Checkbox</p>\n<div class=\"btn-group\">\n <label class=\"btn btn-primary\" [(ngModel)]=\"checkModel.left\"\n btnCheckbox tabindex=\"0\" role=\"button\">Left</label>\n <label class=\"btn btn-primary\" [(ngModel)]=\"checkModel.right\"\n btnCheckbox tabindex=\"0\" role=\"button\">Right</label>\n</div>\n<pre class=\"card card-block card-header\">\n {{checkModel | json}}\n</pre>\n<p>Button as RadionButton</p>\n<div class=\"form-inline\">\n <div class=\"btn-group\" btnRadioGroup [(ngModel)]=\"radioModel\">\n <label class=\"btn btn-success\" btnRadio=\"Left\">Left</label>\n <label class=\"btn btn-success\" btnRadio=\"Right\">Right</label>\n </div>\n</div>\n<pre class=\"card card-block card-header\">\n {{radioModel}}\n</pre>" }, { "code": null, "e": 16474, "s": 16408, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 16492, "s": 16474, "text": "test.component.ts" }, { "code": null, "e": 16907, "s": 16492, "text": "import { Component, OnInit } from '@angular/core';\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n checkModel = { left: false, right: false };\n radioModel = 'Left';\n clickCounter = 0;\n constructor() { }\n\n ngOnInit(): void {\n }\n clicked(): void {\n this.clickCounter++;\n }\n}" }, { "code": null, "e": 16962, "s": 16907, "text": "Run the following command to start the angular server." }, { "code": null, "e": 16972, "s": 16962, "text": "ng serve\n" }, { "code": null, "e": 17063, "s": 16972, "text": "Once server is up and running. Open http://localhost:4200 and verify the following output." }, { "code": null, "e": 17133, "s": 17063, "text": "ngx-bootstrap Carousel is used to create slide show of images or text" }, { "code": null, "e": 17166, "s": 17133, "text": "Base element to create carousel." }, { "code": null, "e": 17175, "s": 17166, "text": "carousel" }, { "code": null, "e": 17184, "s": 17175, "text": "carousel" }, { "code": null, "e": 17256, "s": 17184, "text": "activeSlide − number, Index of currently displayed slide(started for 0)" }, { "code": null, "e": 17328, "s": 17256, "text": "activeSlide − number, Index of currently displayed slide(started for 0)" }, { "code": null, "e": 17372, "s": 17328, "text": "indicatorsByChunk − boolean, default: false" }, { "code": null, "e": 17416, "s": 17372, "text": "indicatorsByChunk − boolean, default: false" }, { "code": null, "e": 17520, "s": 17416, "text": "interval − number, Delay of item cycling in milliseconds. If false, carousel won't cycle automatically." }, { "code": null, "e": 17624, "s": 17520, "text": "interval − number, Delay of item cycling in milliseconds. If false, carousel won't cycle automatically." }, { "code": null, "e": 17731, "s": 17624, "text": "isAnimated − boolean, Turn on/off animation. Animation doesn't work for multilist carousel, default: false" }, { "code": null, "e": 17838, "s": 17731, "text": "isAnimated − boolean, Turn on/off animation. Animation doesn't work for multilist carousel, default: false" }, { "code": null, "e": 17873, "s": 17838, "text": "itemsPerSlide − number, default: 1" }, { "code": null, "e": 17908, "s": 17873, "text": "itemsPerSlide − number, default: 1" }, { "code": null, "e": 17926, "s": 17908, "text": "noPause − boolean" }, { "code": null, "e": 17944, "s": 17926, "text": "noPause − boolean" }, { "code": null, "e": 17961, "s": 17944, "text": "noWrap − boolean" }, { "code": null, "e": 17978, "s": 17961, "text": "noWrap − boolean" }, { "code": null, "e": 18001, "s": 17978, "text": "pauseOnFocus − boolean" }, { "code": null, "e": 18024, "s": 18001, "text": "pauseOnFocus − boolean" }, { "code": null, "e": 18049, "s": 18024, "text": "showIndicators − boolean" }, { "code": null, "e": 18074, "s": 18049, "text": "showIndicators − boolean" }, { "code": null, "e": 18102, "s": 18074, "text": "singleSlideOffset − boolean" }, { "code": null, "e": 18130, "s": 18102, "text": "singleSlideOffset − boolean" }, { "code": null, "e": 18166, "s": 18130, "text": "startFromIndex − number, default: 0" }, { "code": null, "e": 18202, "s": 18166, "text": "startFromIndex − number, default: 0" }, { "code": null, "e": 18324, "s": 18202, "text": "activeSlideChange − Will be emitted when active slide has been changed. Part of two-way-bindable [(activeSlide)] property" }, { "code": null, "e": 18446, "s": 18324, "text": "activeSlideChange − Will be emitted when active slide has been changed. Part of two-way-bindable [(activeSlide)] property" }, { "code": null, "e": 18535, "s": 18446, "text": "slideRangeChange − Will be emitted when active slides has been changed in multilist mode" }, { "code": null, "e": 18624, "s": 18535, "text": "slideRangeChange − Will be emitted when active slides has been changed in multilist mode" }, { "code": null, "e": 18630, "s": 18624, "text": "slide" }, { "code": null, "e": 18636, "s": 18630, "text": "slide" }, { "code": null, "e": 18678, "s": 18636, "text": "active − boolean, Is current slide active" }, { "code": null, "e": 18720, "s": 18678, "text": "active − boolean, Is current slide active" }, { "code": null, "e": 18843, "s": 18720, "text": "As we're going to use carousel, We've to update app.module.ts used in ngx-bootstrap Buttons chapter to use CarouselModule." }, { "code": null, "e": 18891, "s": 18843, "text": "Update app.module.ts to use the CarouselModule." }, { "code": null, "e": 18905, "s": 18891, "text": "app.module.ts" }, { "code": null, "e": 19810, "s": 18905, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule\n ],\n providers: [AlertConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 19858, "s": 19810, "text": "Update test.component.html to use the Carousel." }, { "code": null, "e": 19878, "s": 19858, "text": "test.component.html" }, { "code": null, "e": 20555, "s": 19878, "text": "<div style=\"width: 500px; height: 500px;\">\n <carousel [noWrap]=\"noWrapSlides\" [showIndicators]=\"showIndicator\">\n <slide *ngFor=\"let slide of slides; let index=index\">\n <img [src]=\"slide.image\" alt=\"image slide\" style=\"display: block; width: 100%;\">\n <div class=\"carousel-caption\">\n\t\t\t<h4>Slide {{index}}</h4>\n <p>{{slide.text}}</p>\n </div>\n </slide>\n </carousel>\n <br/>\n <div>\n <div class=\"checkbox\">\n <label><input type=\"checkbox\" [(ngModel)]=\"noWrapSlides\">Disable Slide Looping</label>\n <label><input type=\"checkbox\" [(ngModel)]=\"showIndicator\">Enable Indicator</label>\n </div>\n </div>\n</div>" }, { "code": null, "e": 20621, "s": 20555, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 20639, "s": 20621, "text": "test.component.ts" }, { "code": null, "e": 21339, "s": 20639, "text": "import { Component, OnInit } from '@angular/core';\nimport { CarouselConfig } from 'ngx-bootstrap/carousel';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n providers: [\n { provide: CarouselConfig, useValue: { interval: 1500, noPause: false, showIndicators: true } }\n ],\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n slides = [\n {image: 'assets/images/nature/1.jpg', text: 'First'},\n {image: 'assets/images/nature/2.jpg',text: 'Second'},\n {image: 'assets/images/nature/3.jpg',text: 'Third'}\n ];\n noWrapSlides = false;\n showIndicator = true;\n constructor() { }\n\n ngOnInit(): void {\n }\n}" }, { "code": null, "e": 21394, "s": 21339, "text": "Run the following command to start the angular server." }, { "code": null, "e": 21404, "s": 21394, "text": "ng serve\n" }, { "code": null, "e": 21495, "s": 21404, "text": "Once server is up and running. Open http://localhost:4200 and verify the following output." }, { "code": null, "e": 21568, "s": 21495, "text": "ngx-bootstrap Collapse directive helps to show/hide a container content." }, { "code": null, "e": 21579, "s": 21568, "text": "[collapse]" }, { "code": null, "e": 21590, "s": 21579, "text": "[collapse]" }, { "code": null, "e": 21668, "s": 21590, "text": "collapse − boolean, A flag indicating visibility of content (shown or hidden)" }, { "code": null, "e": 21746, "s": 21668, "text": "collapse − boolean, A flag indicating visibility of content (shown or hidden)" }, { "code": null, "e": 21763, "s": 21746, "text": "display − string" }, { "code": null, "e": 21780, "s": 21763, "text": "display − string" }, { "code": null, "e": 21840, "s": 21780, "text": "isAnimated − boolean, turn on/off animation. default: false" }, { "code": null, "e": 21900, "s": 21840, "text": "isAnimated − boolean, turn on/off animation. default: false" }, { "code": null, "e": 21958, "s": 21900, "text": "collapsed − This event fires as soon as content collapses" }, { "code": null, "e": 22016, "s": 21958, "text": "collapsed − This event fires as soon as content collapses" }, { "code": null, "e": 22072, "s": 22016, "text": "collapses − This event fires when collapsing is started" }, { "code": null, "e": 22128, "s": 22072, "text": "collapses − This event fires when collapsing is started" }, { "code": null, "e": 22191, "s": 22128, "text": "expanded − This event fires as soon as content becomes visible" }, { "code": null, "e": 22254, "s": 22191, "text": "expanded − This event fires as soon as content becomes visible" }, { "code": null, "e": 22307, "s": 22254, "text": "expands − This event fires when expansion is started" }, { "code": null, "e": 22360, "s": 22307, "text": "expands − This event fires when expansion is started" }, { "code": null, "e": 22416, "s": 22360, "text": "toggle() − allows to manually toggle content visibility" }, { "code": null, "e": 22472, "s": 22416, "text": "toggle() − allows to manually toggle content visibility" }, { "code": null, "e": 22511, "s": 22472, "text": "hide − allows to manually hide content" }, { "code": null, "e": 22550, "s": 22511, "text": "hide − allows to manually hide content" }, { "code": null, "e": 22599, "s": 22550, "text": "show − allows to manually show collapsed content" }, { "code": null, "e": 22648, "s": 22599, "text": "show − allows to manually show collapsed content" }, { "code": null, "e": 22772, "s": 22648, "text": "As we're going to use collapse, We've to update app.module.ts used in ngx-bootstrap Carousel chapter to use CollapseModule." }, { "code": null, "e": 22820, "s": 22772, "text": "Update app.module.ts to use the CollapseModule." }, { "code": null, "e": 22834, "s": 22820, "text": "app.module.ts" }, { "code": null, "e": 23818, "s": 22834, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule\n ],\n providers: [AlertConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 23866, "s": 23818, "text": "Update test.component.html to use the Collapse." }, { "code": null, "e": 23886, "s": 23866, "text": "test.component.html" }, { "code": null, "e": 24162, "s": 23886, "text": "<div>\n <div class=\"checkbox\">\n <label><input type=\"checkbox\" [(ngModel)]=\"isCollapsed\">Collapse</label>\n </div>\n</div>\n<div [collapse]=\"isCollapsed\" [isAnimated]=\"true\">\n <div class=\"well well-lg card card-block card-header\">Welcome to Tutorialspoint.</div>\n</div>" }, { "code": null, "e": 24228, "s": 24162, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 24246, "s": 24228, "text": "test.component.ts" }, { "code": null, "e": 24550, "s": 24246, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n isCollapsed: boolean = false;\n constructor() { }\n\n ngOnInit(): void {\n }\n}" }, { "code": null, "e": 24605, "s": 24550, "text": "Run the following command to start the angular server." }, { "code": null, "e": 24615, "s": 24605, "text": "ng serve\n" }, { "code": null, "e": 24706, "s": 24615, "text": "Once server is up and running. Open http://localhost:4200 and verify the following output." }, { "code": null, "e": 24771, "s": 24706, "text": "Check the collapse check box and then content will be collapsed." }, { "code": null, "e": 24921, "s": 24771, "text": "ngx-bootstrap DatePicker component is highly configurable and customizable as per our need. It provides various options to select date or date range." }, { "code": null, "e": 24936, "s": 24921, "text": "[bsDatepicker]" }, { "code": null, "e": 24951, "s": 24936, "text": "[bsDatepicker]" }, { "code": null, "e": 25020, "s": 24951, "text": "bsConfig − Partial<BsDatepickerConfig>, Config object for datepicker" }, { "code": null, "e": 25089, "s": 25020, "text": "bsConfig − Partial<BsDatepickerConfig>, Config object for datepicker" }, { "code": null, "e": 25133, "s": 25089, "text": "bsValue − Date, Initial value of datepicker" }, { "code": null, "e": 25177, "s": 25133, "text": "bsValue − Date, Initial value of datepicker" }, { "code": null, "e": 25283, "s": 25177, "text": "container − string, A selector specifying the element the datepicker should be appended to. default: body" }, { "code": null, "e": 25389, "s": 25283, "text": "container − string, A selector specifying the element the datepicker should be appended to. default: body" }, { "code": null, "e": 25460, "s": 25389, "text": "dateCustomClasses − DatepickerDateCustomClasses[], Date custom classes" }, { "code": null, "e": 25531, "s": 25460, "text": "dateCustomClasses − DatepickerDateCustomClasses[], Date custom classes" }, { "code": null, "e": 25578, "s": 25531, "text": "datesDisabled − Date[], Disable specific dates" }, { "code": null, "e": 25625, "s": 25578, "text": "datesDisabled − Date[], Disable specific dates" }, { "code": null, "e": 25670, "s": 25625, "text": "datesEnabled − Date[], Enable specific dates" }, { "code": null, "e": 25715, "s": 25670, "text": "datesEnabled − Date[], Enable specific dates" }, { "code": null, "e": 25781, "s": 25715, "text": "dateTooltipTexts − DatepickerDateTooltipText[], Date tooltip text" }, { "code": null, "e": 25847, "s": 25781, "text": "dateTooltipTexts − DatepickerDateTooltipText[], Date tooltip text" }, { "code": null, "e": 25905, "s": 25847, "text": "daysDisabled − number[], Disable Certain days in the week" }, { "code": null, "e": 25963, "s": 25905, "text": "daysDisabled − number[], Disable Certain days in the week" }, { "code": null, "e": 26042, "s": 25963, "text": "isDisabled − boolean, Indicates whether datepicker's content is enabled or not" }, { "code": null, "e": 26121, "s": 26042, "text": "isDisabled − boolean, Indicates whether datepicker's content is enabled or not" }, { "code": null, "e": 26202, "s": 26121, "text": "isOpen − boolean, Returns whether or not the datepicker is currently being shown" }, { "code": null, "e": 26283, "s": 26202, "text": "isOpen − boolean, Returns whether or not the datepicker is currently being shown" }, { "code": null, "e": 26348, "s": 26283, "text": "maxDate − boolean, Maximum date which is available for selection" }, { "code": null, "e": 26413, "s": 26348, "text": "maxDate − boolean, Maximum date which is available for selection" }, { "code": null, "e": 26478, "s": 26413, "text": "minDate − boolean, Minimum date which is available for selection" }, { "code": null, "e": 26543, "s": 26478, "text": "minDate − boolean, Minimum date which is available for selection" }, { "code": null, "e": 26615, "s": 26543, "text": "minMode − BsDatepickerViewMode, Minimum view mode : day, month, or year" }, { "code": null, "e": 26687, "s": 26615, "text": "minMode − BsDatepickerViewMode, Minimum view mode : day, month, or year" }, { "code": null, "e": 26760, "s": 26687, "text": "outsideClick − boolean, Close datepicker on outside click, default: true" }, { "code": null, "e": 26833, "s": 26760, "text": "outsideClick − boolean, Close datepicker on outside click, default: true" }, { "code": null, "e": 26903, "s": 26833, "text": "outsideEsc − boolean, Close datepicker on escape click, default: true" }, { "code": null, "e": 26973, "s": 26903, "text": "outsideEsc − boolean, Close datepicker on escape click, default: true" }, { "code": null, "e": 27108, "s": 26973, "text": "placement − \"top\" | \"bottom\" | \"left\" | \"right\", Placement of a datepicker. Accepts: \"top\", \"bottom\", \"left\", \"right\", default: bottom" }, { "code": null, "e": 27243, "s": 27108, "text": "placement − \"top\" | \"bottom\" | \"left\" | \"right\", Placement of a datepicker. Accepts: \"top\", \"bottom\", \"left\", \"right\", default: bottom" }, { "code": null, "e": 27364, "s": 27243, "text": "triggers − string, Specifies events that should trigger. Supports a space separated list of event names., default: click" }, { "code": null, "e": 27485, "s": 27364, "text": "triggers − string, Specifies events that should trigger. Supports a space separated list of event names., default: click" }, { "code": null, "e": 27546, "s": 27485, "text": "bsValueChange − Emits when datepicker value has been changed" }, { "code": null, "e": 27607, "s": 27546, "text": "bsValueChange − Emits when datepicker value has been changed" }, { "code": null, "e": 27663, "s": 27607, "text": "onHidden − Emits an event when the datepicker is hidden" }, { "code": null, "e": 27719, "s": 27663, "text": "onHidden − Emits an event when the datepicker is hidden" }, { "code": null, "e": 27773, "s": 27719, "text": "onShown − Emits an event when the datepicker is shown" }, { "code": null, "e": 27827, "s": 27773, "text": "onShown − Emits an event when the datepicker is shown" }, { "code": null, "e": 27927, "s": 27827, "text": "show() − Opens an element's datepicker. This is considered a 'manual' triggering of the datepicker." }, { "code": null, "e": 28027, "s": 27927, "text": "show() − Opens an element's datepicker. This is considered a 'manual' triggering of the datepicker." }, { "code": null, "e": 28128, "s": 28027, "text": "hide() − Closes an element's datepicker. This is considered a 'manual' triggering of the datepicker." }, { "code": null, "e": 28229, "s": 28128, "text": "hide() − Closes an element's datepicker. This is considered a 'manual' triggering of the datepicker." }, { "code": null, "e": 28333, "s": 28229, "text": "toggle() − Toggles an element's datepicker. This is considered a 'manual' triggering of the datepicker." }, { "code": null, "e": 28437, "s": 28333, "text": "toggle() − Toggles an element's datepicker. This is considered a 'manual' triggering of the datepicker." }, { "code": null, "e": 28477, "s": 28437, "text": "setConfig() − Set config for datepicker" }, { "code": null, "e": 28517, "s": 28477, "text": "setConfig() − Set config for datepicker" }, { "code": null, "e": 28537, "s": 28517, "text": "[bsDaterangepicker]" }, { "code": null, "e": 28557, "s": 28537, "text": "[bsDaterangepicker]" }, { "code": null, "e": 28636, "s": 28557, "text": "bsConfig − Partial<BsDaterangepickerConfig>, Config object for daterangepicker" }, { "code": null, "e": 28715, "s": 28636, "text": "bsConfig − Partial<BsDaterangepickerConfig>, Config object for daterangepicker" }, { "code": null, "e": 28764, "s": 28715, "text": "bsValue − Date, Initial value of daterangepicker" }, { "code": null, "e": 28813, "s": 28764, "text": "bsValue − Date, Initial value of daterangepicker" }, { "code": null, "e": 28924, "s": 28813, "text": "container − string, A selector specifying the element the daterangepicker should be appended to. default: body" }, { "code": null, "e": 29035, "s": 28924, "text": "container − string, A selector specifying the element the daterangepicker should be appended to. default: body" }, { "code": null, "e": 29106, "s": 29035, "text": "dateCustomClasses − DatepickerDateCustomClasses[], Date custom classes" }, { "code": null, "e": 29177, "s": 29106, "text": "dateCustomClasses − DatepickerDateCustomClasses[], Date custom classes" }, { "code": null, "e": 29224, "s": 29177, "text": "datesDisabled − Date[], Disable specific dates" }, { "code": null, "e": 29271, "s": 29224, "text": "datesDisabled − Date[], Disable specific dates" }, { "code": null, "e": 29316, "s": 29271, "text": "datesEnabled − Date[], Enable specific dates" }, { "code": null, "e": 29361, "s": 29316, "text": "datesEnabled − Date[], Enable specific dates" }, { "code": null, "e": 29427, "s": 29361, "text": "dateTooltipTexts − DatepickerDateTooltipText[], Date tooltip text" }, { "code": null, "e": 29493, "s": 29427, "text": "dateTooltipTexts − DatepickerDateTooltipText[], Date tooltip text" }, { "code": null, "e": 29551, "s": 29493, "text": "daysDisabled − number[], Disable Certain days in the week" }, { "code": null, "e": 29609, "s": 29551, "text": "daysDisabled − number[], Disable Certain days in the week" }, { "code": null, "e": 29693, "s": 29609, "text": "isDisabled − boolean, Indicates whether daterangepicker's content is enabled or not" }, { "code": null, "e": 29777, "s": 29693, "text": "isDisabled − boolean, Indicates whether daterangepicker's content is enabled or not" }, { "code": null, "e": 29863, "s": 29777, "text": "isOpen − boolean, Returns whether or not the daterangepicker is currently being shown" }, { "code": null, "e": 29949, "s": 29863, "text": "isOpen − boolean, Returns whether or not the daterangepicker is currently being shown" }, { "code": null, "e": 30014, "s": 29949, "text": "maxDate − boolean, Maximum date which is available for selection" }, { "code": null, "e": 30079, "s": 30014, "text": "maxDate − boolean, Maximum date which is available for selection" }, { "code": null, "e": 30144, "s": 30079, "text": "minDate − boolean, Minimum date which is available for selection" }, { "code": null, "e": 30209, "s": 30144, "text": "minDate − boolean, Minimum date which is available for selection" }, { "code": null, "e": 30281, "s": 30209, "text": "minMode − BsDatepickerViewMode, Minimum view mode : day, month, or year" }, { "code": null, "e": 30353, "s": 30281, "text": "minMode − BsDatepickerViewMode, Minimum view mode : day, month, or year" }, { "code": null, "e": 30431, "s": 30353, "text": "outsideClick − boolean, Close daterangepicker on outside click, default: true" }, { "code": null, "e": 30509, "s": 30431, "text": "outsideClick − boolean, Close daterangepicker on outside click, default: true" }, { "code": null, "e": 30584, "s": 30509, "text": "outsideEsc − boolean, Close daterangepicker on escape click, default: true" }, { "code": null, "e": 30659, "s": 30584, "text": "outsideEsc − boolean, Close daterangepicker on escape click, default: true" }, { "code": null, "e": 30799, "s": 30659, "text": "placement − \"top\" | \"bottom\" | \"left\" | \"right\", Placement of a daterangepicker. Accepts: \"top\", \"bottom\", \"left\", \"right\", default: bottom" }, { "code": null, "e": 30939, "s": 30799, "text": "placement − \"top\" | \"bottom\" | \"left\" | \"right\", Placement of a daterangepicker. Accepts: \"top\", \"bottom\", \"left\", \"right\", default: bottom" }, { "code": null, "e": 31060, "s": 30939, "text": "triggers − string, Specifies events that should trigger. Supports a space separated list of event names., default: click" }, { "code": null, "e": 31181, "s": 31060, "text": "triggers − string, Specifies events that should trigger. Supports a space separated list of event names., default: click" }, { "code": null, "e": 31247, "s": 31181, "text": "bsValueChange − Emits when daterangepicker value has been changed" }, { "code": null, "e": 31313, "s": 31247, "text": "bsValueChange − Emits when daterangepicker value has been changed" }, { "code": null, "e": 31374, "s": 31313, "text": "onHidden − Emits an event when the daterangepicker is hidden" }, { "code": null, "e": 31435, "s": 31374, "text": "onHidden − Emits an event when the daterangepicker is hidden" }, { "code": null, "e": 31494, "s": 31435, "text": "onShown − Emits an event when the daterangepicker is shown" }, { "code": null, "e": 31553, "s": 31494, "text": "onShown − Emits an event when the daterangepicker is shown" }, { "code": null, "e": 31653, "s": 31553, "text": "show() − Opens an element's datepicker. This is considered a 'manual' triggering of the datepicker." }, { "code": null, "e": 31753, "s": 31653, "text": "show() − Opens an element's datepicker. This is considered a 'manual' triggering of the datepicker." }, { "code": null, "e": 31854, "s": 31753, "text": "hide() − Closes an element's datepicker. This is considered a 'manual' triggering of the datepicker." }, { "code": null, "e": 31955, "s": 31854, "text": "hide() − Closes an element's datepicker. This is considered a 'manual' triggering of the datepicker." }, { "code": null, "e": 32059, "s": 31955, "text": "toggle() − Toggles an element's datepicker. This is considered a 'manual' triggering of the datepicker." }, { "code": null, "e": 32163, "s": 32059, "text": "toggle() − Toggles an element's datepicker. This is considered a 'manual' triggering of the datepicker." }, { "code": null, "e": 32203, "s": 32163, "text": "setConfig() − Set config for datepicker" }, { "code": null, "e": 32243, "s": 32203, "text": "setConfig() − Set config for datepicker" }, { "code": null, "e": 32416, "s": 32243, "text": "As we're going to use DatePicker and DateRangePicker, We've to update app.module.ts used in ngx-bootstrap Collapse chapter to use BsDatepickerModule and BsDatepickerConfig." }, { "code": null, "e": 32491, "s": 32416, "text": "Update app.module.ts to use the BsDatepickerModule and BsDatepickerConfig." }, { "code": null, "e": 32505, "s": 32491, "text": "app.module.ts" }, { "code": null, "e": 33628, "s": 32505, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot()\n ],\n providers: [AlertConfig, BsDatepickerConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 33676, "s": 33628, "text": "Update index.html to use the bs-datepicker.css." }, { "code": null, "e": 33690, "s": 33676, "text": "app.module.ts" }, { "code": null, "e": 34230, "s": 33690, "text": "<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Ngxbootstrap</title>\n <base href=\"/\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"icon\" type=\"image/x-icon\" href=\"favicon.ico\">\n <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" rel=\"stylesheet\">\n <link href=\"https://unpkg.com/ngx-bootstrap/datepicker/bs-datepicker.css\" rel=\"stylesheet\" >\n </head>\n <body>\n <app-root></app-root>\n </body>\n</html>" }, { "code": null, "e": 34281, "s": 34230, "text": "Update test.component.html to use the datepickers." }, { "code": null, "e": 34301, "s": 34281, "text": "test.component.html" }, { "code": null, "e": 35040, "s": 34301, "text": "<div class=\"row\">\n <div class=\"col-xs-12 col-12 col-md-4 form-group\">\n <input type=\"text\"\n placeholder=\"Datepicker\"\n class=\"form-control\"\n bsDatepicker\n [bsValue]=\"bsValue\"\n [minDate]=\"minDate\"\n [maxDate]=\"maxDate\"\n [daysDisabled]=\"[6,0]\"\n [datesDisabled]=\"disabledDates\"\n [bsConfig]=\"{ isAnimated: true, dateInputFormat: 'YYYY-MM-DD' }\">\n </div>\n <div class=\"col-xs-12 col-12 col-md-4 form-group\">\n <input type=\"text\"\n placeholder=\"Daterangepicker\"\n class=\"form-control\"\n bsDaterangepicker\n [(ngModel)]=\"bsRangeValue\"\n [datesEnabled]=\"enabledDates\"\n [bsConfig]=\"{ isAnimated: true }\">\n </div>\n</div>" }, { "code": null, "e": 35106, "s": 35040, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 35124, "s": 35106, "text": "test.component.ts" }, { "code": null, "e": 35668, "s": 35124, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n\n bsValue = new Date();\n bsRangeValue: Date[];\n maxDate = new Date();\n minDate = new Date();\n\n constructor() {\n this.minDate.setDate(this.minDate.getDate() - 1);\n this.maxDate.setDate(this.maxDate.getDate() + 7);\n this.bsRangeValue = [this.bsValue, this.maxDate];\n }\n\n ngOnInit(): void {\n }\n}" }, { "code": null, "e": 35723, "s": 35668, "text": "Run the following command to start the angular server." }, { "code": null, "e": 35733, "s": 35723, "text": "ng serve\n" }, { "code": null, "e": 35824, "s": 35733, "text": "Once server is up and running. Open http://localhost:4200 and verify the following output." }, { "code": null, "e": 35993, "s": 35824, "text": "ngx-bootstrap dropdown component is toggleable and provides contextual overlay to display list of links etc. With dropdown directives we can make dropdowns interactive." }, { "code": null, "e": 36017, "s": 35993, "text": "[bsDropdown],[dropdown]" }, { "code": null, "e": 36041, "s": 36017, "text": "[bsDropdown],[dropdown]" }, { "code": null, "e": 36151, "s": 36041, "text": "autoClose − boolean, Indicates that dropdown will be closed on item or document click, and after pressing ESC" }, { "code": null, "e": 36261, "s": 36151, "text": "autoClose − boolean, Indicates that dropdown will be closed on item or document click, and after pressing ESC" }, { "code": null, "e": 36350, "s": 36261, "text": "container − string, A selector specifying the element the popover should be appended to." }, { "code": null, "e": 36439, "s": 36350, "text": "container − string, A selector specifying the element the popover should be appended to." }, { "code": null, "e": 36526, "s": 36439, "text": "dropup − boolean, This attribute indicates that the dropdown should be opened upwards." }, { "code": null, "e": 36613, "s": 36526, "text": "dropup − boolean, This attribute indicates that the dropdown should be opened upwards." }, { "code": null, "e": 36742, "s": 36613, "text": "insideClick − boolean, This attribute indicates that the dropdown shouldn't close on inside click when autoClose is set to true." }, { "code": null, "e": 36871, "s": 36742, "text": "insideClick − boolean, This attribute indicates that the dropdown shouldn't close on inside click when autoClose is set to true." }, { "code": null, "e": 36934, "s": 36871, "text": "isAnimated − boolean, Indicates that dropdown will be animated" }, { "code": null, "e": 36997, "s": 36934, "text": "isAnimated − boolean, Indicates that dropdown will be animated" }, { "code": null, "e": 37078, "s": 36997, "text": "isDisabled − boolean, Disables dropdown toggle and hides dropdown menu if opened" }, { "code": null, "e": 37159, "s": 37078, "text": "isDisabled − boolean, Disables dropdown toggle and hides dropdown menu if opened" }, { "code": null, "e": 37237, "s": 37159, "text": "isOpen − boolean, Returns whether or not the popover is currently being shown" }, { "code": null, "e": 37315, "s": 37237, "text": "isOpen − boolean, Returns whether or not the popover is currently being shown" }, { "code": null, "e": 37401, "s": 37315, "text": "placement − string, Placement of a popover. Accepts: \"top\", \"bottom\", \"left\", \"right\"" }, { "code": null, "e": 37487, "s": 37401, "text": "placement − string, Placement of a popover. Accepts: \"top\", \"bottom\", \"left\", \"right\"" }, { "code": null, "e": 37592, "s": 37487, "text": "triggers − string, Specifies events that should trigger. Supports a space separated list of event names." }, { "code": null, "e": 37697, "s": 37592, "text": "triggers − string, Specifies events that should trigger. Supports a space separated list of event names." }, { "code": null, "e": 37746, "s": 37697, "text": "isOpenChange − Emits an event when isOpen change" }, { "code": null, "e": 37795, "s": 37746, "text": "isOpenChange − Emits an event when isOpen change" }, { "code": null, "e": 37848, "s": 37795, "text": "onHidden − Emits an event when the popover is hidden" }, { "code": null, "e": 37901, "s": 37848, "text": "onHidden − Emits an event when the popover is hidden" }, { "code": null, "e": 37952, "s": 37901, "text": "onShown − Emits an event when the popover is shown" }, { "code": null, "e": 38003, "s": 37952, "text": "onShown − Emits an event when the popover is shown" }, { "code": null, "e": 38097, "s": 38003, "text": "show() − Opens an element's popover. This is considered a 'manual' triggering of the popover." }, { "code": null, "e": 38191, "s": 38097, "text": "show() − Opens an element's popover. This is considered a 'manual' triggering of the popover." }, { "code": null, "e": 38286, "s": 38191, "text": "hide() − Closes an element's popover. This is considered a 'manual' triggering of the popover." }, { "code": null, "e": 38381, "s": 38286, "text": "hide() − Closes an element's popover. This is considered a 'manual' triggering of the popover." }, { "code": null, "e": 38479, "s": 38381, "text": "toggle() − Toggles an element's popover. This is considered a 'manual' triggering of the popover." }, { "code": null, "e": 38577, "s": 38479, "text": "toggle() − Toggles an element's popover. This is considered a 'manual' triggering of the popover." }, { "code": null, "e": 38614, "s": 38577, "text": "setConfig() − Set config for popover" }, { "code": null, "e": 38651, "s": 38614, "text": "setConfig() − Set config for popover" }, { "code": null, "e": 38801, "s": 38651, "text": "As we're going to use dropdowns, We've to update app.module.ts used in ngx-bootstrap DatePicker chapter to use BsDropdownModule and BsDropdownConfig." }, { "code": null, "e": 38872, "s": 38801, "text": "Update app.module.ts to use the BsDropdownModule and BsDropdownConfig." }, { "code": null, "e": 38886, "s": 38872, "text": "app.module.ts" }, { "code": null, "e": 40127, "s": 38886, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule\n ],\n providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 40176, "s": 40127, "text": "Update test.component.html to use the dropdowns." }, { "code": null, "e": 40196, "s": 40176, "text": "test.component.html" }, { "code": null, "e": 41069, "s": 40196, "text": "<div class=\"btn-group\" dropdown #dropdown=\"bs-dropdown\" [autoClose]=\"false\">\n <button id=\"button-basic\" dropdownToggle type=\"button\" \n class=\"btn btn-primary dropdown-toggle\"\n aria-controls=\"dropdown-basic\">\n Menu <span class=\"caret\"></span>\n </button>\n <ul id=\"dropdown-basic\" *dropdownMenu class=\"dropdown-menu\"\n role=\"menu\" aria-labelledby=\"button-basic\">\n <li role=\"menuitem\"><a class=\"dropdown-item\" href=\"#\">File</a></li>\n <li role=\"menuitem\"><a class=\"dropdown-item\" href=\"#\">Edit</a></li>\n <li role=\"menuitem\"><a class=\"dropdown-item\" href=\"#\">Search</a></li>\n <li class=\"divider dropdown-divider\"></li>\n <li role=\"menuitem\"><a class=\"dropdown-item\" href=\"#\">Recents</a>\n </li>\n </ul>\n</div>\n<button type=\"button\" class=\"btn btn-primary\" \n (click)=\"dropdown.isOpen = !dropdown.isOpen\">Show/Hide\n</button>" }, { "code": null, "e": 41135, "s": 41069, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 41153, "s": 41135, "text": "test.component.ts" }, { "code": null, "e": 41419, "s": 41153, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n constructor() {}\n\n ngOnInit(): void {}\n}" }, { "code": null, "e": 41474, "s": 41419, "text": "Run the following command to start the angular server." }, { "code": null, "e": 41484, "s": 41474, "text": "ng serve\n" }, { "code": null, "e": 41575, "s": 41484, "text": "Once server is up and running. Open http://localhost:4200 and verify the following output." }, { "code": null, "e": 41723, "s": 41575, "text": "ngx-bootstrap modal component is a flexible and highly configurable dialog prompt and provides multiple defaults and can be used with minimum code." }, { "code": null, "e": 41733, "s": 41723, "text": "[bsModal]" }, { "code": null, "e": 41743, "s": 41733, "text": "[bsModal]" }, { "code": null, "e": 41821, "s": 41743, "text": "config − ModalOptions, allows to set modal configuration via element property" }, { "code": null, "e": 41899, "s": 41821, "text": "config − ModalOptions, allows to set modal configuration via element property" }, { "code": null, "e": 42030, "s": 41899, "text": "onHidden − This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete)." }, { "code": null, "e": 42161, "s": 42030, "text": "onHidden − This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete)." }, { "code": null, "e": 42249, "s": 42161, "text": "onHide − This event is fired immediately when the hide instance method has been called." }, { "code": null, "e": 42337, "s": 42249, "text": "onHide − This event is fired immediately when the hide instance method has been called." }, { "code": null, "e": 42416, "s": 42337, "text": "onShow − This event fires immediately when the show instance method is called." }, { "code": null, "e": 42495, "s": 42416, "text": "onShow − This event fires immediately when the show instance method is called." }, { "code": null, "e": 42619, "s": 42495, "text": "onShown − This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete)." }, { "code": null, "e": 42743, "s": 42619, "text": "onShown − This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete)." }, { "code": null, "e": 42783, "s": 42743, "text": "show() − Allows to manually open modal." }, { "code": null, "e": 42823, "s": 42783, "text": "show() − Allows to manually open modal." }, { "code": null, "e": 42864, "s": 42823, "text": "hide() − Allows to manually close modal." }, { "code": null, "e": 42905, "s": 42864, "text": "hide() − Allows to manually close modal." }, { "code": null, "e": 42960, "s": 42905, "text": "toggle() − Allows to manually toggle modal visibility." }, { "code": null, "e": 43015, "s": 42960, "text": "toggle() − Allows to manually toggle modal visibility." }, { "code": null, "e": 43044, "s": 43015, "text": "showElement() − Show dialog." }, { "code": null, "e": 43073, "s": 43044, "text": "showElement() − Show dialog." }, { "code": null, "e": 43108, "s": 43073, "text": "focusOtherModal() − Events tricks." }, { "code": null, "e": 43143, "s": 43108, "text": "focusOtherModal() − Events tricks." }, { "code": null, "e": 43283, "s": 43143, "text": "As we're going to use a modal, We've to update app.module.ts used in ngx-bootstrap Dropdowns chapter to use ModalModule and BsModalService." }, { "code": null, "e": 43347, "s": 43283, "text": "Update app.module.ts to use the ModalModule and BsModalService." }, { "code": null, "e": 43361, "s": 43347, "text": "app.module.ts" }, { "code": null, "e": 44703, "s": 43361, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\nimport { ModalModule, BsModalService } from 'ngx-bootstrap/modal';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule,\n ModalModule\n ],\n providers: [AlertConfig, BsDatepickerConfig, BsDropdownConfig,BsModalService],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 44748, "s": 44703, "text": "Update test.component.html to use the modal." }, { "code": null, "e": 44768, "s": 44748, "text": "test.component.html" }, { "code": null, "e": 45365, "s": 44768, "text": "<button type=\"button\" class=\"btn btn-primary\" (click)=\"openModal(template)\">Open modal</button>\n\n<ng-template #template>\n <div class=\"modal-header\">\n <h4 class=\"modal-title pull-left\">Modal</h4>\n <button type=\"button\" class=\"close pull-right\" aria-label=\"Close\" (click)=\"modalRef.hide()\">\n <span aria-hidden=\"true\">×</span>\n </button>\n </div>\n <div class=\"modal-body\">\n This is a sample modal dialog box.\n </div>\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-default\" (click)=\"modalRef.hide()\">Close</button>\n </div>\n</ng-template>" }, { "code": null, "e": 45431, "s": 45365, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 45449, "s": 45431, "text": "test.component.ts" }, { "code": null, "e": 45965, "s": 45449, "text": "import { Component, OnInit, TemplateRef } from '@angular/core';\nimport { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n\n modalRef: BsModalRef;\n constructor(private modalService: BsModalService) {}\n\n openModal(template: TemplateRef<any>) {\n this.modalRef = this.modalService.show(template);\n }\n\n ngOnInit(): void {\n }\n}" }, { "code": null, "e": 46020, "s": 45965, "text": "Run the following command to start the angular server." }, { "code": null, "e": 46030, "s": 46020, "text": "ng serve\n" }, { "code": null, "e": 46149, "s": 46030, "text": "Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output." }, { "code": null, "e": 46258, "s": 46149, "text": "ngx-bootstrap pagination component provides pagination links or a pager component to your site or component." }, { "code": null, "e": 46269, "s": 46258, "text": "pagination" }, { "code": null, "e": 46280, "s": 46269, "text": "pagination" }, { "code": null, "e": 46344, "s": 46280, "text": "align − boolean, if true aligns each link to the sides of pager" }, { "code": null, "e": 46408, "s": 46344, "text": "align − boolean, if true aligns each link to the sides of pager" }, { "code": null, "e": 46480, "s": 46408, "text": "boundaryLinks − boolean, if false first and last buttons will be hidden" }, { "code": null, "e": 46552, "s": 46480, "text": "boundaryLinks − boolean, if false first and last buttons will be hidden" }, { "code": null, "e": 46641, "s": 46552, "text": "customFirstTemplate − TemplateRef<PaginationLinkContext>, custom template for first link" }, { "code": null, "e": 46730, "s": 46641, "text": "customFirstTemplate − TemplateRef<PaginationLinkContext>, custom template for first link" }, { "code": null, "e": 46817, "s": 46730, "text": "customLastTemplate − TemplateRef<PaginationLinkContext>, custom template for last link" }, { "code": null, "e": 46904, "s": 46817, "text": "customLastTemplate − TemplateRef<PaginationLinkContext>, custom template for last link" }, { "code": null, "e": 46991, "s": 46904, "text": "customNextTemplate − TemplateRef<PaginationLinkContext>, custom template for next link" }, { "code": null, "e": 47078, "s": 46991, "text": "customNextTemplate − TemplateRef<PaginationLinkContext>, custom template for next link" }, { "code": null, "e": 47165, "s": 47078, "text": "customPageTemplate − TemplateRef<PaginationLinkContext>, custom template for page link" }, { "code": null, "e": 47252, "s": 47165, "text": "customPageTemplate − TemplateRef<PaginationLinkContext>, custom template for page link" }, { "code": null, "e": 47347, "s": 47252, "text": "customPreviousTemplate − TemplateRef<PaginationLinkContext>, custom template for previous link" }, { "code": null, "e": 47442, "s": 47347, "text": "customPreviousTemplate − TemplateRef<PaginationLinkContext>, custom template for previous link" }, { "code": null, "e": 47518, "s": 47442, "text": "directionLinks − boolean, if false previous and next buttons will be hidden" }, { "code": null, "e": 47594, "s": 47518, "text": "directionLinks − boolean, if false previous and next buttons will be hidden" }, { "code": null, "e": 47660, "s": 47594, "text": "disabled − boolean, if true pagination component will be disabled" }, { "code": null, "e": 47726, "s": 47660, "text": "disabled − boolean, if true pagination component will be disabled" }, { "code": null, "e": 47765, "s": 47726, "text": "firstText − boolean, first button text" }, { "code": null, "e": 47804, "s": 47765, "text": "firstText − boolean, first button text" }, { "code": null, "e": 47917, "s": 47804, "text": "itemsPerPage − number, maximum number of items per page. If value less than 1 will display all items on one page" }, { "code": null, "e": 48030, "s": 47917, "text": "itemsPerPage − number, maximum number of items per page. If value less than 1 will display all items on one page" }, { "code": null, "e": 48066, "s": 48030, "text": "lastText − string, last button text" }, { "code": null, "e": 48102, "s": 48066, "text": "lastText − string, last button text" }, { "code": null, "e": 48157, "s": 48102, "text": "maxSize − number, limit number for page links in pager" }, { "code": null, "e": 48212, "s": 48157, "text": "maxSize − number, limit number for page links in pager" }, { "code": null, "e": 48248, "s": 48212, "text": "nextText − string, next button text" }, { "code": null, "e": 48284, "s": 48248, "text": "nextText − string, next button text" }, { "code": null, "e": 48325, "s": 48284, "text": "pageBtnClass − string, add class to <li>" }, { "code": null, "e": 48366, "s": 48325, "text": "pageBtnClass − string, add class to <li>" }, { "code": null, "e": 48410, "s": 48366, "text": "previousText − string, previous button text" }, { "code": null, "e": 48454, "s": 48410, "text": "previousText − string, previous button text" }, { "code": null, "e": 48526, "s": 48454, "text": "rotate − boolean, if true current page will in the middle of pages list" }, { "code": null, "e": 48598, "s": 48526, "text": "rotate − boolean, if true current page will in the middle of pages list" }, { "code": null, "e": 48654, "s": 48598, "text": "totalItems − number, total number of items in all pages" }, { "code": null, "e": 48710, "s": 48654, "text": "totalItems − number, total number of items in all pages" }, { "code": null, "e": 48802, "s": 48710, "text": "numPages − fired when total pages count changes, $event:number equals to total pages count." }, { "code": null, "e": 48894, "s": 48802, "text": "numPages − fired when total pages count changes, $event:number equals to total pages count." }, { "code": null, "e": 49036, "s": 48894, "text": "pageChanged − fired when page was changed, $event:{page, itemsPerPage} equals to object with current page index and number of items per page." }, { "code": null, "e": 49178, "s": 49036, "text": "pageChanged − fired when page was changed, $event:{page, itemsPerPage} equals to object with current page index and number of items per page." }, { "code": null, "e": 49327, "s": 49178, "text": "As we're going to use a pagination, We've to update app.module.ts used in ngx-bootstrap Modals chapter to use PaginationModule and PaginationConfig." }, { "code": null, "e": 49398, "s": 49327, "text": "Update app.module.ts to use the PaginationModule and PaginationConfig." }, { "code": null, "e": 49412, "s": 49398, "text": "app.module.ts" }, { "code": null, "e": 50834, "s": 49412, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\nimport { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule,\n ModalModule,\n PaginationModule\n ],\n providers: [AlertConfig, \n BsDatepickerConfig, \n BsDropdownConfig,\n BsModalService,\n PaginationConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 50879, "s": 50834, "text": "Update test.component.html to use the modal." }, { "code": null, "e": 50899, "s": 50879, "text": "test.component.html" }, { "code": null, "e": 51593, "s": 50899, "text": "<div class=\"row\">\n <div class=\"col-xs-12 col-12\">\n <div class=\"content-wrapper\">\n <p class=\"content-item\" *ngFor=\"let content of returnedArray\">{{content}}</p>\n </div>\n <pagination [boundaryLinks]=\"showBoundaryLinks\" \n [directionLinks]=\"showDirectionLinks\" \n [totalItems]=\"contentArray.length\"\n [itemsPerPage]=\"5\"\n (pageChanged)=\"pageChanged($event)\"></pagination>\n </div>\n</div>\n<div>\n <div class=\"checkbox\">\n <label><input type=\"checkbox\" [(ngModel)]=\"showBoundaryLinks\">Show Boundary Links</label>\n <br/>\n <label><input type=\"checkbox\" [(ngModel)]=\"showDirectionLinks\">Show Direction Links</label>\n </div>\n</div>" }, { "code": null, "e": 51659, "s": 51593, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 51677, "s": 51659, "text": "test.component.ts" }, { "code": null, "e": 52640, "s": 51677, "text": "import { Component, OnInit } from '@angular/core';\nimport { BsModalService } from 'ngx-bootstrap/modal';\nimport { PageChangedEvent } from 'ngx-bootstrap/pagination';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n contentArray: string[] = new Array(50).fill('');\n returnedArray: string[];\n showBoundaryLinks: boolean = true;\n showDirectionLinks: boolean = true;\n constructor() {}\n\n pageChanged(event: PageChangedEvent): void {\n const startItem = (event.page - 1) * event.itemsPerPage;\n const endItem = event.page * event.itemsPerPage;\n this.returnedArray = this.contentArray.slice(startItem, endItem);\n }\n ngOnInit(): void {\n this.contentArray = this.contentArray.map((v: string, i: number) => {\n return 'Line '+ (i + 1);\n });\n this.returnedArray = this.contentArray.slice(0, 5);\n }\n}" }, { "code": null, "e": 52695, "s": 52640, "text": "Run the following command to start the angular server." }, { "code": null, "e": 52705, "s": 52695, "text": "ng serve\n" }, { "code": null, "e": 52824, "s": 52705, "text": "Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output." }, { "code": null, "e": 52939, "s": 52824, "text": "ngx-bootstrap popover component provides a small overlay component to provide small information about a component." }, { "code": null, "e": 52947, "s": 52939, "text": "popover" }, { "code": null, "e": 52955, "s": 52947, "text": "popover" }, { "code": null, "e": 53015, "s": 52955, "text": "adaptivePosition − boolean, sets disable adaptive position." }, { "code": null, "e": 53075, "s": 53015, "text": "adaptivePosition − boolean, sets disable adaptive position." }, { "code": null, "e": 53164, "s": 53075, "text": "container − string, A selector specifying the element the popover should be appended to." }, { "code": null, "e": 53253, "s": 53164, "text": "container − string, A selector specifying the element the popover should be appended to." }, { "code": null, "e": 53310, "s": 53253, "text": "containerClass − string, Css class for popover container" }, { "code": null, "e": 53367, "s": 53310, "text": "containerClass − string, Css class for popover container" }, { "code": null, "e": 53416, "s": 53367, "text": "delay − number, Delay before showing the tooltip" }, { "code": null, "e": 53465, "s": 53416, "text": "delay − number, Delay before showing the tooltip" }, { "code": null, "e": 53543, "s": 53465, "text": "isOpen − boolean, Returns whether or not the popover is currently being shown" }, { "code": null, "e": 53621, "s": 53543, "text": "isOpen − boolean, Returns whether or not the popover is currently being shown" }, { "code": null, "e": 53692, "s": 53621, "text": "outsideClick − boolean, Close popover on outside click, default: false" }, { "code": null, "e": 53763, "s": 53692, "text": "outsideClick − boolean, Close popover on outside click, default: false" }, { "code": null, "e": 54008, "s": 53763, "text": "placement − \"top\" | \"bottom\" | \"left\" | \"right\" | \"auto\" | \"top left\" | \"top right\" | \"right top\" | \"right bottom\" | \"bottom right\" | \"bottom left\" | \"left bottom\" | \"left top\", Placement of a popover. Accepts: \"top\", \"bottom\", \"left\", \"right\"." }, { "code": null, "e": 54253, "s": 54008, "text": "placement − \"top\" | \"bottom\" | \"left\" | \"right\" | \"auto\" | \"top left\" | \"top right\" | \"right top\" | \"right bottom\" | \"bottom right\" | \"bottom left\" | \"left bottom\" | \"left top\", Placement of a popover. Accepts: \"top\", \"bottom\", \"left\", \"right\"." }, { "code": null, "e": 54326, "s": 54253, "text": "popover − string | TemplateRef<any>, Content to be displayed as popover." }, { "code": null, "e": 54399, "s": 54326, "text": "popover − string | TemplateRef<any>, Content to be displayed as popover." }, { "code": null, "e": 54466, "s": 54399, "text": "popoverContext − any, Context to be used if popover is a template." }, { "code": null, "e": 54533, "s": 54466, "text": "popoverContext − any, Context to be used if popover is a template." }, { "code": null, "e": 54576, "s": 54533, "text": "popoverTitle − string, Title of a popover." }, { "code": null, "e": 54619, "s": 54576, "text": "popoverTitle − string, Title of a popover." }, { "code": null, "e": 54724, "s": 54619, "text": "triggers − string, Specifies events that should trigger. Supports a space separated list of event names." }, { "code": null, "e": 54829, "s": 54724, "text": "triggers − string, Specifies events that should trigger. Supports a space separated list of event names." }, { "code": null, "e": 54883, "s": 54829, "text": "onHidden − Emits an event when the popover is hidden." }, { "code": null, "e": 54937, "s": 54883, "text": "onHidden − Emits an event when the popover is hidden." }, { "code": null, "e": 54989, "s": 54937, "text": "onShown − Emits an event when the popover is shown." }, { "code": null, "e": 55041, "s": 54989, "text": "onShown − Emits an event when the popover is shown." }, { "code": null, "e": 55145, "s": 55041, "text": "setAriaDescribedBy() − Set attribute aria-describedBy for element directive and set id for the popover." }, { "code": null, "e": 55249, "s": 55145, "text": "setAriaDescribedBy() − Set attribute aria-describedBy for element directive and set id for the popover." }, { "code": null, "e": 55343, "s": 55249, "text": "show() − Opens an element's popover. This is considered a \"manual\" triggering of the popover." }, { "code": null, "e": 55437, "s": 55343, "text": "show() − Opens an element's popover. This is considered a \"manual\" triggering of the popover." }, { "code": null, "e": 55532, "s": 55437, "text": "hide() − Closes an element's popover. This is considered a \"manual\" triggering of the popover." }, { "code": null, "e": 55627, "s": 55532, "text": "hide() − Closes an element's popover. This is considered a \"manual\" triggering of the popover." }, { "code": null, "e": 55725, "s": 55627, "text": "toggle() − Toggles an element's popover. This is considered a \"manual\" triggering of the popover." }, { "code": null, "e": 55823, "s": 55725, "text": "toggle() − Toggles an element's popover. This is considered a \"manual\" triggering of the popover." }, { "code": null, "e": 55967, "s": 55823, "text": "As we're going to use a popover, We've to update app.module.ts used in ngx-bootstrap Pagination chapter to use PopoverModule and PopoverConfig." }, { "code": null, "e": 56032, "s": 55967, "text": "Update app.module.ts to use the PopoverModule and PopoverConfig." }, { "code": null, "e": 56046, "s": 56032, "text": "app.module.ts" }, { "code": null, "e": 57559, "s": 56046, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\nimport { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination';\nimport { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule,\n ModalModule,\n PaginationModule,\n PopoverModule\n ],\n providers: [AlertConfig, \n BsDatepickerConfig, \n BsDropdownConfig,\n BsModalService,\n PaginationConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 57604, "s": 57559, "text": "Update test.component.html to use the modal." }, { "code": null, "e": 57624, "s": 57604, "text": "test.component.html" }, { "code": null, "e": 57988, "s": 57624, "text": "<button type=\"button\" class=\"btn btn-default btn-primary\"\n popover=\"Welcome to Tutorialspoint.\" [outsideClick]=\"true\">\n Default Popover\n</button>\n<button type=\"button\" class=\"btn btn-default btn-primary\"\n popover=\"Welcome to Tutorialspoint.\"\n popoverTitle=\"Tutorialspoint\" \n [outsideClick]=\"true\"\n placement=\"right\">\n Right Aligned popover\n</button>" }, { "code": null, "e": 58054, "s": 57988, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 58072, "s": 58054, "text": "test.component.ts" }, { "code": null, "e": 58456, "s": 58072, "text": "import { Component, OnInit } from '@angular/core';\nimport { BsModalService } from 'ngx-bootstrap/modal';\nimport { PageChangedEvent } from 'ngx-bootstrap/pagination';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n constructor() {}\n ngOnInit(): void {\n }\n}" }, { "code": null, "e": 58511, "s": 58456, "text": "Run the following command to start the angular server." }, { "code": null, "e": 58521, "s": 58511, "text": "ng serve\n" }, { "code": null, "e": 58640, "s": 58521, "text": "Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output." }, { "code": null, "e": 58758, "s": 58640, "text": "ngx-bootstrap progress bar component provides a progress component to show progress of a workflow with flexible bars." }, { "code": null, "e": 58770, "s": 58758, "text": "progressbar" }, { "code": null, "e": 58782, "s": 58770, "text": "progressbar" }, { "code": null, "e": 58858, "s": 58782, "text": "animate − boolean, if true changing value of progress bar will be animated." }, { "code": null, "e": 58934, "s": 58858, "text": "animate − boolean, if true changing value of progress bar will be animated." }, { "code": null, "e": 58989, "s": 58934, "text": "max − number, maximum total value of progress element." }, { "code": null, "e": 59044, "s": 58989, "text": "max − number, maximum total value of progress element." }, { "code": null, "e": 59101, "s": 59044, "text": "striped − boolean, If true, striped classes are applied." }, { "code": null, "e": 59158, "s": 59101, "text": "striped − boolean, If true, striped classes are applied." }, { "code": null, "e": 59268, "s": 59158, "text": "type − ProgressbarType, provide one of the four supported contextual classes: success, info, warning, danger." }, { "code": null, "e": 59378, "s": 59268, "text": "type − ProgressbarType, provide one of the four supported contextual classes: success, info, warning, danger." }, { "code": null, "e": 59519, "s": 59378, "text": "value − number | any[], current value of progress bar. Could be a number or array of objects like {\"value\":15,\"type\":\"info\",\"label\":\"15 %\"}." }, { "code": null, "e": 59660, "s": 59519, "text": "value − number | any[], current value of progress bar. Could be a number or array of objects like {\"value\":15,\"type\":\"info\",\"label\":\"15 %\"}." }, { "code": null, "e": 59813, "s": 59660, "text": "As we're going to use a progressbar, We've to update app.module.ts used in ngx-bootstrap Popover chapter to use ProgressbarModule and ProgressbarConfig." }, { "code": null, "e": 59886, "s": 59813, "text": "Update app.module.ts to use the ProgressbarModule and ProgressbarConfig." }, { "code": null, "e": 59900, "s": 59886, "text": "app.module.ts" }, { "code": null, "e": 61544, "s": 59900, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\nimport { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination';\nimport { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover';\nimport { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule,\n ModalModule,\n PaginationModule,\n PopoverModule,\n ProgressbarModule\n ],\n providers: [AlertConfig, \n BsDatepickerConfig, \n BsDropdownConfig,\n BsModalService,\n PaginationConfig,\n ProgressbarConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 61589, "s": 61544, "text": "Update test.component.html to use the modal." }, { "code": null, "e": 61609, "s": 61589, "text": "test.component.html" }, { "code": null, "e": 62170, "s": 61609, "text": "<div class=\"row\">\n <div class=\"col-sm-4\">\n <div class=\"mb-2\">\n <progressbar [value]=\"value\"></progressbar>\n </div>\n </div>\n <div class=\"col-sm-4\">\n <div class=\"mb-2\">\n <progressbar [value]=\"value\" type=\"warning\"\n [striped]=\"true\">{{value}}%</progressbar>\n </div>\n </div>\n <div class=\"col-sm-4\">\n <div class=\"mb-2\">\n <progressbar [value]=\"value\" type=\"danger\" \n [striped]=\"true\" [animate]=\"true\"\n ><i>{{value}} / {{max}}</i></progressbar>\n </div>\n </div>\n</div> " }, { "code": null, "e": 62236, "s": 62170, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 62254, "s": 62236, "text": "test.component.ts" }, { "code": null, "e": 62571, "s": 62254, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n\n max: number = 100;\n value: number = 25;\n constructor() {}\n\n ngOnInit(): void {\n } \n}" }, { "code": null, "e": 62626, "s": 62571, "text": "Run the following command to start the angular server." }, { "code": null, "e": 62636, "s": 62626, "text": "ng serve\n" }, { "code": null, "e": 62695, "s": 62636, "text": "Once server is up and running. Open http://localhost:4200." }, { "code": null, "e": 62791, "s": 62695, "text": "ngx-bootstrap rating component provides a configurable rating component, a star bar by default." }, { "code": null, "e": 62798, "s": 62791, "text": "rating" }, { "code": null, "e": 62805, "s": 62798, "text": "rating" }, { "code": null, "e": 62867, "s": 62805, "text": "customTemplate − TemplateRef<any>, custom template for icons." }, { "code": null, "e": 62929, "s": 62867, "text": "customTemplate − TemplateRef<any>, custom template for icons." }, { "code": null, "e": 62969, "s": 62929, "text": "max − number, no. of icons, default: 5." }, { "code": null, "e": 63009, "s": 62969, "text": "max − number, no. of icons, default: 5." }, { "code": null, "e": 63072, "s": 63009, "text": "readonly − boolean, if true will not react on any user events." }, { "code": null, "e": 63135, "s": 63072, "text": "readonly − boolean, if true will not react on any user events." }, { "code": null, "e": 63204, "s": 63135, "text": "titles − string[], array of icons titles, default: ([1, 2, 3, 4, 5])" }, { "code": null, "e": 63273, "s": 63204, "text": "titles − string[], array of icons titles, default: ([1, 2, 3, 4, 5])" }, { "code": null, "e": 63350, "s": 63273, "text": "onHover − fired when icon selected, $event:number equals to selected rating." }, { "code": null, "e": 63427, "s": 63350, "text": "onHover − fired when icon selected, $event:number equals to selected rating." }, { "code": null, "e": 63510, "s": 63427, "text": "onLeave − fired when icon selected, $event:number equals to previous rating value." }, { "code": null, "e": 63593, "s": 63510, "text": "onLeave − fired when icon selected, $event:number equals to previous rating value." }, { "code": null, "e": 63732, "s": 63593, "text": "As we're going to use a rating, We've to update app.module.ts used in ngx-bootstrap ProgressBar chapter to use RatingModule, RatingConfig." }, { "code": null, "e": 63795, "s": 63732, "text": "Update app.module.ts to use the RatingModule and RatingConfig." }, { "code": null, "e": 63809, "s": 63795, "text": "app.module.ts" }, { "code": null, "e": 65560, "s": 63809, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\nimport { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination';\nimport { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover';\nimport { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar';\nimport { RatingModule, RatingConfig } from 'ngx-bootstrap/rating';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule,\n ModalModule,\n PaginationModule,\n PopoverModule,\n ProgressbarModule,\n RatingModule\n ],\n providers: [AlertConfig, \n BsDatepickerConfig, \n BsDropdownConfig,\n BsModalService,\n PaginationConfig,\n ProgressbarConfig,\n RatingConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 65606, "s": 65560, "text": "Update test.component.html to use the rating." }, { "code": null, "e": 65626, "s": 65606, "text": "test.component.html" }, { "code": null, "e": 65747, "s": 65626, "text": "<rating [(ngModel)]=\"value\" \n [max]=\"max\" \n [readonly]=\"false\" \n [titles]=\"['one','two','three','four']\"></rating>" }, { "code": null, "e": 65813, "s": 65747, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 65831, "s": 65813, "text": "test.component.ts" }, { "code": null, "e": 66144, "s": 65831, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n max: number = 10;\n value: number = 5;\n constructor() {}\n ngOnInit(): void {\n } \n}" }, { "code": null, "e": 66199, "s": 66144, "text": "Run the following command to start the angular server." }, { "code": null, "e": 66209, "s": 66199, "text": "ng serve\n" }, { "code": null, "e": 66328, "s": 66209, "text": "Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output." }, { "code": null, "e": 66429, "s": 66328, "text": "ngx-bootstrap sortable component provides a configurable sortable component, with drag drop support." }, { "code": null, "e": 66441, "s": 66429, "text": "bs-sortable" }, { "code": null, "e": 66453, "s": 66441, "text": "bs-sortable" }, { "code": null, "e": 66520, "s": 66453, "text": "fieldName − string, field name if input array consists of objects." }, { "code": null, "e": 66587, "s": 66520, "text": "fieldName − string, field name if input array consists of objects." }, { "code": null, "e": 66641, "s": 66587, "text": "itemActiveClass − string, class name for active item." }, { "code": null, "e": 66695, "s": 66641, "text": "itemActiveClass − string, class name for active item." }, { "code": null, "e": 66771, "s": 66695, "text": "itemActiveStyle − { [key: string]: string; }, style object for active item." }, { "code": null, "e": 66847, "s": 66771, "text": "itemActiveStyle − { [key: string]: string; }, style object for active item." }, { "code": null, "e": 66887, "s": 66847, "text": "itemClass − string, class name for item" }, { "code": null, "e": 66927, "s": 66887, "text": "itemClass − string, class name for item" }, { "code": null, "e": 66967, "s": 66927, "text": "itemStyle − string, class name for item" }, { "code": null, "e": 67007, "s": 66967, "text": "itemStyle − string, class name for item" }, { "code": null, "e": 67116, "s": 67007, "text": "itemTemplate − TemplateRef<any>, used to specify a custom item template. Template variables: item and index;" }, { "code": null, "e": 67225, "s": 67116, "text": "itemTemplate − TemplateRef<any>, used to specify a custom item template. Template variables: item and index;" }, { "code": null, "e": 67279, "s": 67225, "text": "placeholderClass − string, class name for placeholder" }, { "code": null, "e": 67333, "s": 67279, "text": "placeholderClass − string, class name for placeholder" }, { "code": null, "e": 67419, "s": 67333, "text": "placeholderItem − string, placeholder item which will be shown if collection is empty" }, { "code": null, "e": 67505, "s": 67419, "text": "placeholderItem − string, placeholder item which will be shown if collection is empty" }, { "code": null, "e": 67561, "s": 67505, "text": "placeholderStyle − string, style object for placeholder" }, { "code": null, "e": 67617, "s": 67561, "text": "placeholderStyle − string, style object for placeholder" }, { "code": null, "e": 67669, "s": 67617, "text": "wrapperClass − string, class name for items wrapper" }, { "code": null, "e": 67721, "s": 67669, "text": "wrapperClass − string, class name for items wrapper" }, { "code": null, "e": 67795, "s": 67721, "text": "wrapperStyle − { [key: string]: string; }, style object for items wrapper" }, { "code": null, "e": 67869, "s": 67795, "text": "wrapperStyle − { [key: string]: string; }, style object for items wrapper" }, { "code": null, "e": 67998, "s": 67869, "text": "onChange − fired on array change (reordering, insert, remove), same as ngModelChange. Returns new items collection as a payload." }, { "code": null, "e": 68127, "s": 67998, "text": "onChange − fired on array change (reordering, insert, remove), same as ngModelChange. Returns new items collection as a payload." }, { "code": null, "e": 68276, "s": 68127, "text": "As we're going to use a sortable, We've to update app.module.ts used in ngx-bootstrap Rating chapter to use SortableModule and DraggableItemService." }, { "code": null, "e": 68349, "s": 68276, "text": "Update app.module.ts to use the SortableModule and DraggableItemService." }, { "code": null, "e": 68363, "s": 68349, "text": "app.module.ts" }, { "code": null, "e": 70243, "s": 68363, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\nimport { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination';\nimport { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover';\nimport { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar';\nimport { RatingModule, RatingConfig } from 'ngx-bootstrap/rating';\nimport { SortableModule, DraggableItemService } from 'ngx-bootstrap/sortable';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule,\n ModalModule,\n PaginationModule,\n PopoverModule,\n ProgressbarModule,\n RatingModule,\n SortableModule\n ],\n providers: [AlertConfig, \n BsDatepickerConfig, \n BsDropdownConfig,\n BsModalService,\n PaginationConfig,\n ProgressbarConfig,\n RatingConfig,\n DraggableItemService],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 70299, "s": 70243, "text": "Update styles.css to use styles for sortable component." }, { "code": null, "e": 70310, "s": 70299, "text": "Styles.css" }, { "code": null, "e": 70687, "s": 70310, "text": ".sortableItem {\n padding: 6px 12px;\n margin-bottom: 4px;\n font-size: 14px;\n line-height: 1.4em;\n text-align: center;\n cursor: grab;\n border: 1px solid transparent;\n border-radius: 4px;\n border-color: #adadad;\n}\n\n.sortableItemActive {\n background-color: #e6e6e6;\n box-shadow: inset 0 3px 5px rgba(0,0,0,.125);\n}\n\n.sortableWrapper {\n min-height: 150px;\n}" }, { "code": null, "e": 70745, "s": 70687, "text": "Update test.component.html to use the sortable component." }, { "code": null, "e": 70765, "s": 70745, "text": "test.component.html" }, { "code": null, "e": 70939, "s": 70765, "text": "<bs-sortable\n [(ngModel)]=\"items\"\n fieldName=\"name\"\n itemClass=\"sortableItem\"\n itemActiveClass=\"sortableItemActive\"\n wrapperClass=\"sortableWrapper\">\n</bs-sortable>" }, { "code": null, "e": 71005, "s": 70939, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 71023, "s": 71005, "text": "test.component.ts" }, { "code": null, "e": 71480, "s": 71023, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n items = [\n {\n id: 1,\n name: 'Apple'\n },\n {\n id: 2,\n name: 'Orange'\n },\n {\n id: 3,\n name: 'Mango'\n }\n ];\n constructor() {}\n ngOnInit(): void {\n } \n}" }, { "code": null, "e": 71535, "s": 71480, "text": "Run the following command to start the angular server." }, { "code": null, "e": 71545, "s": 71535, "text": "ng serve\n" }, { "code": null, "e": 71604, "s": 71545, "text": "Once server is up and running. Open http://localhost:4200." }, { "code": null, "e": 71695, "s": 71604, "text": "ngx-bootstrap tabs component provides a easy to use and highly configurable Tab component." }, { "code": null, "e": 71702, "s": 71695, "text": "tabset" }, { "code": null, "e": 71709, "s": 71702, "text": "tabset" }, { "code": null, "e": 71791, "s": 71709, "text": "justified − boolean, if true tabs fill the container and have a consistent width." }, { "code": null, "e": 71873, "s": 71791, "text": "justified − boolean, if true tabs fill the container and have a consistent width." }, { "code": null, "e": 71933, "s": 71873, "text": "type − string, navigation context class: 'tabs' or 'pills'." }, { "code": null, "e": 71993, "s": 71933, "text": "type − string, navigation context class: 'tabs' or 'pills'." }, { "code": null, "e": 72044, "s": 71993, "text": "vertical − if true tabs will be placed vertically." }, { "code": null, "e": 72095, "s": 72044, "text": "vertical − if true tabs will be placed vertically." }, { "code": null, "e": 72106, "s": 72095, "text": "tab, [tab]" }, { "code": null, "e": 72117, "s": 72106, "text": "tab, [tab]" }, { "code": null, "e": 72160, "s": 72117, "text": "active − boolean, tab active state toggle." }, { "code": null, "e": 72203, "s": 72160, "text": "active − boolean, tab active state toggle." }, { "code": null, "e": 72309, "s": 72203, "text": "customClass − string, if set, will be added to the tab's class attribute. Multiple classes are supported." }, { "code": null, "e": 72415, "s": 72309, "text": "customClass − string, if set, will be added to the tab's class attribute. Multiple classes are supported." }, { "code": null, "e": 72469, "s": 72415, "text": "disabled − boolean, if true tab can not be activated." }, { "code": null, "e": 72523, "s": 72469, "text": "disabled − boolean, if true tab can not be activated." }, { "code": null, "e": 72558, "s": 72523, "text": "heading − string, tab header text." }, { "code": null, "e": 72593, "s": 72558, "text": "heading − string, tab header text." }, { "code": null, "e": 72682, "s": 72593, "text": "id − string, tab id. The same id with suffix '-link' will be added to the corresponding " }, { "code": null, "e": 72771, "s": 72682, "text": "id − string, tab id. The same id with suffix '-link' will be added to the corresponding " }, { "code": null, "e": 72781, "s": 72771, "text": " element." }, { "code": null, "e": 72863, "s": 72781, "text": "removable − boolean, if true tab can be removable, additional button will appear." }, { "code": null, "e": 72945, "s": 72863, "text": "removable − boolean, if true tab can be removable, additional button will appear." }, { "code": null, "e": 73047, "s": 72945, "text": "deselect − fired when tab became inactive, $event:Tab equals to deselected instance of Tab component." }, { "code": null, "e": 73149, "s": 73047, "text": "deselect − fired when tab became inactive, $event:Tab equals to deselected instance of Tab component." }, { "code": null, "e": 73239, "s": 73149, "text": "removed − fired before tab will be removed, $event:Tab equals to instance of removed tab." }, { "code": null, "e": 73329, "s": 73239, "text": "removed − fired before tab will be removed, $event:Tab equals to instance of removed tab." }, { "code": null, "e": 73428, "s": 73329, "text": "selectTab − fired when tab became active, $event:Tab equals to selected instance of Tab component." }, { "code": null, "e": 73527, "s": 73428, "text": "selectTab − fired when tab became active, $event:Tab equals to selected instance of Tab component." }, { "code": null, "e": 73661, "s": 73527, "text": "As we're going to use a Tab, We've to update app.module.ts used in ngx-bootstrap Sortable chapter to use TabsModule and TabsetConfig." }, { "code": null, "e": 73722, "s": 73661, "text": "Update app.module.ts to use the TabsModule and TabsetConfig." }, { "code": null, "e": 73736, "s": 73722, "text": "app.module.ts" }, { "code": null, "e": 75717, "s": 73736, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\nimport { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination';\nimport { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover';\nimport { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar';\nimport { RatingModule, RatingConfig } from 'ngx-bootstrap/rating';\nimport { SortableModule, DraggableItemService } from 'ngx-bootstrap/sortable';\nimport { TabsModule, TabsetConfig } from 'ngx-bootstrap/tabs';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule,\n ModalModule,\n PaginationModule,\n PopoverModule,\n ProgressbarModule,\n RatingModule,\n SortableModule,\n TabsModule\n ],\n providers: [AlertConfig, \n BsDatepickerConfig, \n BsDropdownConfig,\n BsModalService,\n PaginationConfig,\n ProgressbarConfig,\n RatingConfig,\n DraggableItemService,\n TabsetConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 75771, "s": 75717, "text": "Update test.component.html to use the tabs component." }, { "code": null, "e": 75791, "s": 75771, "text": "test.component.html" }, { "code": null, "e": 76051, "s": 75791, "text": "<tabset>\n <tab heading=\"Home\">Home</tab>\n <tab *ngFor=\"let tabz of tabs\"\n [heading]=\"tabz.title\"\n [active]=\"tabz.active\"\n (selectTab)=\"tabz.active = true\" \n [disabled]=\"tabz.disabled\">\n {{tabz?.content}}\n </tab>\n</tabset>" }, { "code": null, "e": 76117, "s": 76051, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 76135, "s": 76117, "text": "test.component.ts" }, { "code": null, "e": 76695, "s": 76135, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n tabs = [\n { title: 'First', content: 'First Tab Content' },\n { title: 'Second', content: 'Second Tab Content', active: true },\n { title: 'Third', content: 'Third Tab Content', removable: true },\n { title: 'Four', content: 'Fourth Tab Content', disabled: true }\n ];\n constructor() {}\n ngOnInit(): void {\n } \n}" }, { "code": null, "e": 76750, "s": 76695, "text": "Run the following command to start the angular server." }, { "code": null, "e": 76760, "s": 76750, "text": "ng serve\n" }, { "code": null, "e": 76879, "s": 76760, "text": "Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output." }, { "code": null, "e": 76984, "s": 76879, "text": "ngx-bootstrap timepicker component provides a easy to use and highly configurable Time Picker component." }, { "code": null, "e": 76995, "s": 76984, "text": "timepicker" }, { "code": null, "e": 77006, "s": 76995, "text": "timepicker" }, { "code": null, "e": 77128, "s": 77006, "text": "arrowkeys − boolean, if true the values of hours and minutes can be changed using the up/down arrow keys on the keyboard." }, { "code": null, "e": 77250, "s": 77128, "text": "arrowkeys − boolean, if true the values of hours and minutes can be changed using the up/down arrow keys on the keyboard." }, { "code": null, "e": 77321, "s": 77250, "text": "disabled − boolean, if true hours and minutes fields will be disabled." }, { "code": null, "e": 77392, "s": 77321, "text": "disabled − boolean, if true hours and minutes fields will be disabled." }, { "code": null, "e": 77462, "s": 77392, "text": "hoursPlaceholder − string, placeholder for hours field in timepicker." }, { "code": null, "e": 77532, "s": 77462, "text": "hoursPlaceholder − string, placeholder for hours field in timepicker." }, { "code": null, "e": 77570, "s": 77532, "text": "hourStep − number, hours change step." }, { "code": null, "e": 77608, "s": 77570, "text": "hourStep − number, hours change step." }, { "code": null, "e": 77650, "s": 77608, "text": "max − Date, maximum time user can select." }, { "code": null, "e": 77692, "s": 77650, "text": "max − Date, maximum time user can select." }, { "code": null, "e": 77747, "s": 77692, "text": "meridians − string[], meridian labels based on locale." }, { "code": null, "e": 77802, "s": 77747, "text": "meridians − string[], meridian labels based on locale." }, { "code": null, "e": 77844, "s": 77802, "text": "min − Date, minimum time user can select." }, { "code": null, "e": 77886, "s": 77844, "text": "min − Date, minimum time user can select." }, { "code": null, "e": 77960, "s": 77886, "text": "minutesPlaceholder − string, placeholder for minutes field in timepicker." }, { "code": null, "e": 78034, "s": 77960, "text": "minutesPlaceholder − string, placeholder for minutes field in timepicker." }, { "code": null, "e": 78074, "s": 78034, "text": "minuteStep − number, hours change step." }, { "code": null, "e": 78114, "s": 78074, "text": "minuteStep − number, hours change step." }, { "code": null, "e": 78201, "s": 78114, "text": "mousewheel − boolean, if true scroll inside hours and minutes inputs will change time." }, { "code": null, "e": 78288, "s": 78201, "text": "mousewheel − boolean, if true scroll inside hours and minutes inputs will change time." }, { "code": null, "e": 78364, "s": 78288, "text": "readonlyInput − boolean, if true hours and minutes fields will be readonly." }, { "code": null, "e": 78440, "s": 78364, "text": "readonlyInput − boolean, if true hours and minutes fields will be readonly." }, { "code": null, "e": 78514, "s": 78440, "text": "secondsPlaceholder − string, placeholder for seconds field in timepicker." }, { "code": null, "e": 78588, "s": 78514, "text": "secondsPlaceholder − string, placeholder for seconds field in timepicker." }, { "code": null, "e": 78631, "s": 78588, "text": "secondsStep − number, seconds change step." }, { "code": null, "e": 78674, "s": 78631, "text": "secondsStep − number, seconds change step." }, { "code": null, "e": 78737, "s": 78674, "text": "showMeridian − boolean, if true meridian button will be shown." }, { "code": null, "e": 78800, "s": 78737, "text": "showMeridian − boolean, if true meridian button will be shown." }, { "code": null, "e": 78851, "s": 78800, "text": "showMinutes − boolean, show minutes in timepicker." }, { "code": null, "e": 78902, "s": 78851, "text": "showMinutes − boolean, show minutes in timepicker." }, { "code": null, "e": 78953, "s": 78902, "text": "showSeconds − boolean, show seconds in timepicker." }, { "code": null, "e": 79004, "s": 78953, "text": "showSeconds − boolean, show seconds in timepicker." }, { "code": null, "e": 79093, "s": 79004, "text": "showSpinners − boolean, if true spinner arrows above and below the inputs will be shown." }, { "code": null, "e": 79182, "s": 79093, "text": "showSpinners − boolean, if true spinner arrows above and below the inputs will be shown." }, { "code": null, "e": 79229, "s": 79182, "text": "isValid − emits true if value is a valid date." }, { "code": null, "e": 79276, "s": 79229, "text": "isValid − emits true if value is a valid date." }, { "code": null, "e": 79402, "s": 79276, "text": "As we're going to use a TimePicker, We've to update app.module.ts used in ngx-bootstrap Tabs chapter to use TimepickerModule." }, { "code": null, "e": 79452, "s": 79402, "text": "Update app.module.ts to use the TimepickerModule." }, { "code": null, "e": 79466, "s": 79452, "text": "app.module.ts" }, { "code": null, "e": 81542, "s": 79466, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\nimport { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination';\nimport { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover';\nimport { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar';\nimport { RatingModule, RatingConfig } from 'ngx-bootstrap/rating';\nimport { SortableModule, DraggableItemService } from 'ngx-bootstrap/sortable';\nimport { TabsModule, TabsetConfig } from 'ngx-bootstrap/tabs';\nimport { TimepickerModule } from 'ngx-bootstrap/timepicker';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule,\n ModalModule,\n PaginationModule,\n PopoverModule,\n ProgressbarModule,\n RatingModule,\n SortableModule,\n TabsModule,\n TimepickerModule.forRoot()\n ],\n providers: [AlertConfig, \n BsDatepickerConfig, \n BsDropdownConfig,\n BsModalService,\n PaginationConfig,\n ProgressbarConfig,\n RatingConfig,\n DraggableItemService,\n TabsetConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 81602, "s": 81542, "text": "Update test.component.html to use the timepicker component." }, { "code": null, "e": 81622, "s": 81602, "text": "test.component.html" }, { "code": null, "e": 81844, "s": 81622, "text": "<timepicker [(ngModel)]=\"time\"></timepicker>\n<pre class=\"alert alert-info\">Time is: {{time}}</pre>\n\n<timepicker [(ngModel)]=\"time\" [showMeridian]=\"false\"></timepicker>\n<pre class=\"alert alert-info\">Time is: {{time}}</pre>" }, { "code": null, "e": 81910, "s": 81844, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 81928, "s": 81910, "text": "test.component.ts" }, { "code": null, "e": 82226, "s": 81928, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n time: Date = new Date();\n constructor() {}\n ngOnInit(): void {\n } \n}" }, { "code": null, "e": 82281, "s": 82226, "text": "Run the following command to start the angular server." }, { "code": null, "e": 82291, "s": 82281, "text": "ng serve\n" }, { "code": null, "e": 82410, "s": 82291, "text": "Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output." }, { "code": null, "e": 82508, "s": 82410, "text": "ngx-bootstrap tooltip component provides a easy to use and highly configurable Tooltip component." }, { "code": null, "e": 82533, "s": 82508, "text": "[tooltip], [tooltipHtml]" }, { "code": null, "e": 82558, "s": 82533, "text": "[tooltip], [tooltipHtml]" }, { "code": null, "e": 82618, "s": 82558, "text": "adaptivePosition − boolean, sets disable adaptive position." }, { "code": null, "e": 82678, "s": 82618, "text": "adaptivePosition − boolean, sets disable adaptive position." }, { "code": null, "e": 82767, "s": 82678, "text": "container − string, A selector specifying the element the tooltip should be appended to." }, { "code": null, "e": 82856, "s": 82767, "text": "container − string, A selector specifying the element the tooltip should be appended to." }, { "code": null, "e": 82914, "s": 82856, "text": "containerClass − string, Css class for tooltip container." }, { "code": null, "e": 82972, "s": 82914, "text": "containerClass − string, Css class for tooltip container." }, { "code": null, "e": 83022, "s": 82972, "text": "delay − number, Delay before showing the tooltip." }, { "code": null, "e": 83072, "s": 83022, "text": "delay − number, Delay before showing the tooltip." }, { "code": null, "e": 83121, "s": 83072, "text": "isDisabled − boolean, Allows to disable tooltip." }, { "code": null, "e": 83170, "s": 83121, "text": "isDisabled − boolean, Allows to disable tooltip." }, { "code": null, "e": 83249, "s": 83170, "text": "isOpen − boolean, Returns whether or not the tooltip is currently being shown." }, { "code": null, "e": 83328, "s": 83249, "text": "isOpen − boolean, Returns whether or not the tooltip is currently being shown." }, { "code": null, "e": 83415, "s": 83328, "text": "placement − string, Placement of a tooltip. Accepts: \"top\", \"bottom\", \"left\", \"right\"." }, { "code": null, "e": 83502, "s": 83415, "text": "placement − string, Placement of a tooltip. Accepts: \"top\", \"bottom\", \"left\", \"right\"." }, { "code": null, "e": 83575, "s": 83502, "text": "tooltip − string | TemplateRef<any>, Content to be displayed as tooltip." }, { "code": null, "e": 83648, "s": 83575, "text": "tooltip − string | TemplateRef<any>, Content to be displayed as tooltip." }, { "code": null, "e": 83691, "s": 83648, "text": "tooltipAnimation − boolean, default: true." }, { "code": null, "e": 83734, "s": 83691, "text": "tooltipAnimation − boolean, default: true." }, { "code": null, "e": 83765, "s": 83734, "text": "tooltipAppendToBody − boolean." }, { "code": null, "e": 83796, "s": 83765, "text": "tooltipAppendToBody − boolean." }, { "code": null, "e": 83819, "s": 83796, "text": "tooltipClass − string." }, { "code": null, "e": 83842, "s": 83819, "text": "tooltipClass − string." }, { "code": null, "e": 83864, "s": 83842, "text": "tooltipContext − any." }, { "code": null, "e": 83886, "s": 83864, "text": "tooltipContext − any." }, { "code": null, "e": 83911, "s": 83886, "text": "tooltipEnable − boolean." }, { "code": null, "e": 83936, "s": 83911, "text": "tooltipEnable − boolean." }, { "code": null, "e": 83980, "s": 83936, "text": "tooltipFadeDuration − number, default: 150." }, { "code": null, "e": 84024, "s": 83980, "text": "tooltipFadeDuration − number, default: 150." }, { "code": null, "e": 84065, "s": 84024, "text": "tooltipHtml − string | TemplateRef<any>." }, { "code": null, "e": 84106, "s": 84065, "text": "tooltipHtml − string | TemplateRef<any>." }, { "code": null, "e": 84131, "s": 84106, "text": "tooltipIsOpen − boolean." }, { "code": null, "e": 84156, "s": 84131, "text": "tooltipIsOpen − boolean." }, { "code": null, "e": 84182, "s": 84156, "text": "tooltipPlacement − string" }, { "code": null, "e": 84208, "s": 84182, "text": "tooltipPlacement − string" }, { "code": null, "e": 84235, "s": 84208, "text": "tooltipPopupDelay − number" }, { "code": null, "e": 84262, "s": 84235, "text": "tooltipPopupDelay − number" }, { "code": null, "e": 84297, "s": 84262, "text": "tooltipTrigger − string | string[]" }, { "code": null, "e": 84332, "s": 84297, "text": "tooltipTrigger − string | string[]" }, { "code": null, "e": 84437, "s": 84332, "text": "triggers − string, Specifies events that should trigger. Supports a space separated list of event names." }, { "code": null, "e": 84542, "s": 84437, "text": "triggers − string, Specifies events that should trigger. Supports a space separated list of event names." }, { "code": null, "e": 84596, "s": 84542, "text": "onHidden − Emits an event when the tooltip is hidden." }, { "code": null, "e": 84650, "s": 84596, "text": "onHidden − Emits an event when the tooltip is hidden." }, { "code": null, "e": 84702, "s": 84650, "text": "onShown − Emits an event when the tooltip is shown." }, { "code": null, "e": 84754, "s": 84702, "text": "onShown − Emits an event when the tooltip is shown." }, { "code": null, "e": 84806, "s": 84754, "text": "tooltipChange − Fired when tooltip content changes." }, { "code": null, "e": 84858, "s": 84806, "text": "tooltipChange − Fired when tooltip content changes." }, { "code": null, "e": 84914, "s": 84858, "text": "tooltipStateChanged − Fired when tooltip state changes." }, { "code": null, "e": 84970, "s": 84914, "text": "tooltipStateChanged − Fired when tooltip state changes." }, { "code": null, "e": 85094, "s": 84970, "text": "As we're going to use Tooltip, We've to update app.module.ts used in ngx-bootstrap TimePicker chapter to use TooltipModule." }, { "code": null, "e": 85141, "s": 85094, "text": "Update app.module.ts to use the TooltipModule." }, { "code": null, "e": 85155, "s": 85141, "text": "app.module.ts" }, { "code": null, "e": 87318, "s": 85155, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\nimport { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination';\nimport { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover';\nimport { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar';\nimport { RatingModule, RatingConfig } from 'ngx-bootstrap/rating';\nimport { SortableModule, DraggableItemService } from 'ngx-bootstrap/sortable';\nimport { TabsModule, TabsetConfig } from 'ngx-bootstrap/tabs';\nimport { TimepickerModule } from 'ngx-bootstrap/timepicker';\nimport { TooltipModule } from 'ngx-bootstrap/tooltip';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule,\n ModalModule,\n PaginationModule,\n PopoverModule,\n ProgressbarModule,\n RatingModule,\n SortableModule,\n TabsModule,\n TimepickerModule.forRoot(),\n TooltipModule.forRoot()\n ],\n providers: [AlertConfig, \n BsDatepickerConfig, \n BsDropdownConfig,\n BsModalService,\n PaginationConfig,\n ProgressbarConfig,\n RatingConfig,\n DraggableItemService,\n TabsetConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 87378, "s": 87318, "text": "Update test.component.html to use the timepicker component." }, { "code": null, "e": 87398, "s": 87378, "text": "test.component.html" }, { "code": null, "e": 87620, "s": 87398, "text": "<timepicker [(ngModel)]=\"time\"></timepicker>\n<pre class=\"alert alert-info\">Time is: {{time}}</pre>\n\n<timepicker [(ngModel)]=\"time\" [showMeridian]=\"false\"></timepicker>\n<pre class=\"alert alert-info\">Time is: {{time}}</pre>" }, { "code": null, "e": 87686, "s": 87620, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 87704, "s": 87686, "text": "test.component.ts" }, { "code": null, "e": 88002, "s": 87704, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n time: Date = new Date();\n constructor() {}\n ngOnInit(): void {\n } \n}" }, { "code": null, "e": 88057, "s": 88002, "text": "Run the following command to start the angular server." }, { "code": null, "e": 88067, "s": 88057, "text": "ng serve\n" }, { "code": null, "e": 88186, "s": 88067, "text": "Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output." }, { "code": null, "e": 88301, "s": 88186, "text": "ngx-bootstrap Typeahead directive provides a easy to use and highly configurable, easy to use Typeahead component." }, { "code": null, "e": 88313, "s": 88301, "text": "[typeahead]" }, { "code": null, "e": 88325, "s": 88313, "text": "[typeahead]" }, { "code": null, "e": 88381, "s": 88325, "text": "adaptivePosition − boolean, sets use adaptive position." }, { "code": null, "e": 88437, "s": 88381, "text": "adaptivePosition − boolean, sets use adaptive position." }, { "code": null, "e": 88528, "s": 88437, "text": "container − string, A selector specifying the element the typeahead should be appended to." }, { "code": null, "e": 88619, "s": 88528, "text": "container − string, A selector specifying the element the typeahead should be appended to." }, { "code": null, "e": 88721, "s": 88619, "text": "dropup − boolean, This attribute indicates that the dropdown should be opened upwards, default:false." }, { "code": null, "e": 88823, "s": 88721, "text": "dropup − boolean, This attribute indicates that the dropdown should be opened upwards, default:false." }, { "code": null, "e": 88883, "s": 88823, "text": "isAnimated − boolean, turn on/off animation, default:false." }, { "code": null, "e": 88943, "s": 88883, "text": "isAnimated − boolean, turn on/off animation, default:false." }, { "code": null, "e": 89104, "s": 88943, "text": "optionsListTemplate − TemplateRef<TypeaheadOptionListContext>, used to specify a custom options list template. Template variables: matches, itemTemplate, query." }, { "code": null, "e": 89265, "s": 89104, "text": "optionsListTemplate − TemplateRef<TypeaheadOptionListContext>, used to specify a custom options list template. Template variables: matches, itemTemplate, query." }, { "code": null, "e": 89385, "s": 89265, "text": "typeahead − Typeahead, options source, can be Array of strings, objects or an Observable for external matching process." }, { "code": null, "e": 89505, "s": 89385, "text": "typeahead − Typeahead, options source, can be Array of strings, objects or an Observable for external matching process." }, { "code": null, "e": 89711, "s": 89505, "text": "typeaheadAsync − boolean, should be used only in case of typeahead attribute is Observable of array. If true - loading of options will be async, otherwise - sync. true make sense if options array is large." }, { "code": null, "e": 89917, "s": 89711, "text": "typeaheadAsync − boolean, should be used only in case of typeahead attribute is Observable of array. If true - loading of options will be async, otherwise - sync. true make sense if options array is large." }, { "code": null, "e": 90084, "s": 89917, "text": "typeaheadGroupField − string, when options source is an array of objects, the name of field that contains the group value, matches are grouped by this field when set." }, { "code": null, "e": 90251, "s": 90084, "text": "typeaheadGroupField − string, when options source is an array of objects, the name of field that contains the group value, matches are grouped by this field when set." }, { "code": null, "e": 90318, "s": 90251, "text": "typeaheadHideResultsOnBlur − boolean, used to hide result on blur." }, { "code": null, "e": 90385, "s": 90318, "text": "typeaheadHideResultsOnBlur − boolean, used to hide result on blur." }, { "code": null, "e": 90472, "s": 90385, "text": "typeaheadIsFirstItemActive − boolean, makes active first item in a list. Default:true." }, { "code": null, "e": 90559, "s": 90472, "text": "typeaheadIsFirstItemActive − boolean, makes active first item in a list. Default:true." }, { "code": null, "e": 90718, "s": 90559, "text": "typeaheadItemTemplate − TemplateRef<TypeaheadOptionItemContext>, used to specify a custom item template. Template variables exposed are called item and index." }, { "code": null, "e": 90877, "s": 90718, "text": "typeaheadItemTemplate − TemplateRef<TypeaheadOptionItemContext>, used to specify a custom item template. Template variables exposed are called item and index." }, { "code": null, "e": 90998, "s": 90877, "text": "typeaheadLatinize − boolean, match latin symbols. If true the word s�per would match super and vice versa.Default: true." }, { "code": null, "e": 91119, "s": 90998, "text": "typeaheadLatinize − boolean, match latin symbols. If true the word s�per would match super and vice versa.Default: true." }, { "code": null, "e": 91336, "s": 91119, "text": "typeaheadMinLength − number, minimal no of characters that needs to be entered before typeahead kicks-in. When set to 0, typeahead shows on focus with full list of options (limited as normal by typeaheadOptionsLimit)" }, { "code": null, "e": 91553, "s": 91336, "text": "typeaheadMinLength − number, minimal no of characters that needs to be entered before typeahead kicks-in. When set to 0, typeahead shows on focus with full list of options (limited as normal by typeaheadOptionsLimit)" }, { "code": null, "e": 92072, "s": 91553, "text": "typeaheadMultipleSearch − boolean, Can be used to conduct a search of multiple items and have suggestion not for the whole value of the input but for the value that comes after a delimiter provided via typeaheadMultipleSearchDelimiters attribute. This option can only be used together with typeaheadSingleWords option if typeaheadWordDelimiters and typeaheadPhraseDelimiters are different from typeaheadMultipleSearchDelimiters to avoid conflict in determining when to delimit multiple searches and when a single word." }, { "code": null, "e": 92591, "s": 92072, "text": "typeaheadMultipleSearch − boolean, Can be used to conduct a search of multiple items and have suggestion not for the whole value of the input but for the value that comes after a delimiter provided via typeaheadMultipleSearchDelimiters attribute. This option can only be used together with typeaheadSingleWords option if typeaheadWordDelimiters and typeaheadPhraseDelimiters are different from typeaheadMultipleSearchDelimiters to avoid conflict in determining when to delimit multiple searches and when a single word." }, { "code": null, "e": 93035, "s": 92591, "text": "typeaheadMultipleSearchDelimiters − string, should be used only in case typeaheadMultipleSearch attribute is true. Sets the multiple search delimiter to know when to start a new search. Defaults to comma. If space needs to be used, then explicitly set typeaheadWordDelimiters to something else than space because space is used by default OR set typeaheadSingleWords attribute to false if you don't need to use it together with multiple search." }, { "code": null, "e": 93479, "s": 93035, "text": "typeaheadMultipleSearchDelimiters − string, should be used only in case typeaheadMultipleSearch attribute is true. Sets the multiple search delimiter to know when to start a new search. Defaults to comma. If space needs to be used, then explicitly set typeaheadWordDelimiters to something else than space because space is used by default OR set typeaheadSingleWords attribute to false if you don't need to use it together with multiple search." }, { "code": null, "e": 93707, "s": 93479, "text": "typeaheadOptionField − string, when options source is an array of objects, the name of field that contains the options value, we use array item as option in case of this field is missing. Supports nested properties and methods." }, { "code": null, "e": 93935, "s": 93707, "text": "typeaheadOptionField − string, when options source is an array of objects, the name of field that contains the options value, we use array item as option in case of this field is missing. Supports nested properties and methods." }, { "code": null, "e": 94046, "s": 93935, "text": "typeaheadOptionsInScrollableView − number, Default value: 5,specifies number of options to show in scroll view" }, { "code": null, "e": 94157, "s": 94046, "text": "typeaheadOptionsInScrollableView − number, Default value: 5,specifies number of options to show in scroll view" }, { "code": null, "e": 94252, "s": 94157, "text": "typeaheadOptionsLimit − number, maximum length of options items list. The default value is 20." }, { "code": null, "e": 94347, "s": 94252, "text": "typeaheadOptionsLimit − number, maximum length of options items list. The default value is 20." }, { "code": null, "e": 94654, "s": 94347, "text": "typeaheadOrderBy − TypeaheadOrder, Used to specify a custom order of matches. When options source is an array of objects a field for sorting has to be set up. In case of options source is an array of string, a field for sorting is absent. The ordering direction could be changed to ascending or descending." }, { "code": null, "e": 94961, "s": 94654, "text": "typeaheadOrderBy − TypeaheadOrder, Used to specify a custom order of matches. When options source is an array of objects a field for sorting has to be set up. In case of options source is an array of string, a field for sorting is absent. The ordering direction could be changed to ascending or descending." }, { "code": null, "e": 95150, "s": 94961, "text": "typeaheadPhraseDelimiters − string, should be used only in case typeaheadSingleWords attribute is true. Sets the word delimiter to match exact phrase. Defaults to simple and double quotes." }, { "code": null, "e": 95339, "s": 95150, "text": "typeaheadPhraseDelimiters − string, should be used only in case typeaheadSingleWords attribute is true. Sets the word delimiter to match exact phrase. Defaults to simple and double quotes." }, { "code": null, "e": 95429, "s": 95339, "text": "typeaheadScrollable − boolean, Default value: false, specifies if typeahead is scrollable" }, { "code": null, "e": 95519, "s": 95429, "text": "typeaheadScrollable − boolean, Default value: false, specifies if typeahead is scrollable" }, { "code": null, "e": 95791, "s": 95519, "text": "typeaheadSelectFirstItem − boolean, Default value: true, fired when an options list was opened and the user clicked Tab If a value equal true, it will be chosen first or active item in the list If value equal false, it will be chosen an active item in the list or nothing" }, { "code": null, "e": 96063, "s": 95791, "text": "typeaheadSelectFirstItem − boolean, Default value: true, fired when an options list was opened and the user clicked Tab If a value equal true, it will be chosen first or active item in the list If value equal false, it will be chosen an active item in the list or nothing" }, { "code": null, "e": 96260, "s": 96063, "text": "typeaheadSingleWords − boolean, Default value: true, Can be use to search words by inserting a single white space between each characters for example 'C a l i f o r n i a' will match 'California'." }, { "code": null, "e": 96457, "s": 96260, "text": "typeaheadSingleWords − boolean, Default value: true, Can be use to search words by inserting a single white space between each characters for example 'C a l i f o r n i a' will match 'California'." }, { "code": null, "e": 96554, "s": 96457, "text": "typeaheadWaitMs − number, minimal wait time after last character typed before typeahead kicks-in" }, { "code": null, "e": 96651, "s": 96554, "text": "typeaheadWaitMs − number, minimal wait time after last character typed before typeahead kicks-in" }, { "code": null, "e": 96812, "s": 96651, "text": "typeaheadWordDelimiters − string, should be used only in case typeaheadSingleWords attribute is true. Sets the word delimiter to break words. Defaults to space." }, { "code": null, "e": 96973, "s": 96812, "text": "typeaheadWordDelimiters − string, should be used only in case typeaheadSingleWords attribute is true. Sets the word delimiter to break words. Defaults to space." }, { "code": null, "e": 97090, "s": 96973, "text": "typeaheadLoading − fired when 'busy' state of this component was changed, fired on async mode only, returns boolean." }, { "code": null, "e": 97207, "s": 97090, "text": "typeaheadLoading − fired when 'busy' state of this component was changed, fired on async mode only, returns boolean." }, { "code": null, "e": 97307, "s": 97207, "text": "typeaheadNoResults − fired on every key event and returns true in case of matches are not detected." }, { "code": null, "e": 97407, "s": 97307, "text": "typeaheadNoResults − fired on every key event and returns true in case of matches are not detected." }, { "code": null, "e": 97480, "s": 97407, "text": "typeaheadOnBlur − fired when blur event occurs. returns the active item." }, { "code": null, "e": 97553, "s": 97480, "text": "typeaheadOnBlur − fired when blur event occurs. returns the active item." }, { "code": null, "e": 97645, "s": 97553, "text": "typeaheadOnSelect − fired when option was selected, return object with data of this option." }, { "code": null, "e": 97737, "s": 97645, "text": "typeaheadOnSelect − fired when option was selected, return object with data of this option." }, { "code": null, "e": 97867, "s": 97737, "text": "As we're going to use a Typeahead, We've to update app.module.ts used in ngx-bootstrap Timepicker chapter to use TypeaheadModule." }, { "code": null, "e": 97916, "s": 97867, "text": "Update app.module.ts to use the TypeaheadModule." }, { "code": null, "e": 97930, "s": 97916, "text": "app.module.ts" }, { "code": null, "e": 100098, "s": 97930, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\nimport { TestComponent } from './test/test.component';\nimport { AccordionModule } from 'ngx-bootstrap/accordion';\nimport { AlertModule,AlertConfig } from 'ngx-bootstrap/alert';\nimport { ButtonsModule } from 'ngx-bootstrap/buttons';\nimport { FormsModule } from '@angular/forms';\nimport { CarouselModule } from 'ngx-bootstrap/carousel';\nimport { CollapseModule } from 'ngx-bootstrap/collapse';\nimport { BsDatepickerModule, BsDatepickerConfig } from 'ngx-bootstrap/datepicker';\nimport { BsDropdownModule,BsDropdownConfig } from 'ngx-bootstrap/dropdown';\nimport { PaginationModule,PaginationConfig } from 'ngx-bootstrap/pagination';\nimport { PopoverModule, PopoverConfig } from 'ngx-bootstrap/popover';\nimport { ProgressbarModule,ProgressbarConfig } from 'ngx-bootstrap/progressbar';\nimport { RatingModule, RatingConfig } from 'ngx-bootstrap/rating';\nimport { SortableModule, DraggableItemService } from 'ngx-bootstrap/sortable';\nimport { TabsModule, TabsetConfig } from 'ngx-bootstrap/tabs';\nimport { TimepickerModule } from 'ngx-bootstrap/timepicker';\nimport { TypeaheadModule } from 'ngx-bootstrap/typeahead';\n\n@NgModule({\n declarations: [\n AppComponent,\n TestComponent\n ],\n imports: [\n BrowserAnimationsModule,\n BrowserModule,\n AccordionModule,\n AlertModule,\n ButtonsModule,\n FormsModule,\n CarouselModule,\n CollapseModule,\n BsDatepickerModule.forRoot(),\n BsDropdownModule,\n ModalModule,\n PaginationModule,\n PopoverModule,\n ProgressbarModule,\n RatingModule,\n SortableModule,\n TabsModule,\n TimepickerModule.forRoot(),\n TypeaheadModule.forRoot()\n ],\n providers: [AlertConfig, \n BsDatepickerConfig, \n BsDropdownConfig,\n BsModalService,\n PaginationConfig,\n ProgressbarConfig,\n RatingConfig,\n DraggableItemService,\n TabsetConfig],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 100158, "s": 100098, "text": "Update test.component.html to use the timepicker component." }, { "code": null, "e": 100178, "s": 100158, "text": "test.component.html" }, { "code": null, "e": 100346, "s": 100178, "text": "<input [(ngModel)]=\"selectedState\"\n [typeahead]=\"states\"\n class=\"form-control\">\n<pre class=\"card card-block card-header mb-3\">Model: {{selectedState | json}}</pre>" }, { "code": null, "e": 100412, "s": 100346, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 100430, "s": 100412, "text": "test.component.ts" }, { "code": null, "e": 101355, "s": 100430, "text": "import { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n selectedState: string;\n states: string[] = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado',\n 'Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois',\n 'Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine',\n 'Maryland','Massachusetts','Michigan','Minnesota','Mississippi',\n 'Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey',\n 'New Mexico','New York','North Dakota','North Carolina','Ohio',\n 'Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina',\n 'South Dakota','Tennessee','Texas','Utah','Vermont',\n 'Virginia','Washington','West Virginia','Wisconsin','Wyoming'];\n constructor() {}\n ngOnInit(): void {\n } \n}" }, { "code": null, "e": 101410, "s": 101355, "text": "Run the following command to start the angular server." }, { "code": null, "e": 101420, "s": 101410, "text": "ng serve\n" }, { "code": null, "e": 101539, "s": 101420, "text": "Once server is up and running. Open http://localhost:4200. Click on Open modal button and verify the following output." }, { "code": null, "e": 101546, "s": 101539, "text": " Print" }, { "code": null, "e": 101557, "s": 101546, "text": " Add Notes" } ]
Trading Strategy: Technical Analysis with Python TA-Lib | by J Li | Towards Data Science
(This post is also available in my blog) In finance, a trading strategy is a fixed plan that is designed to achieve a profitable return by going long or short in markets. The main reasons that a properly researched trading strategy helps are its verifiability, quantifiability, consistency, and objectivity. For every trading strategy one needs to define assets to trade, entry/exit points and money management rules. Bad money management can make a potentially profitable strategy unprofitable. — From Wikipedia Strategies are categorized as fundamental analysis based and technical analysis based. While fundamental analysis focus on company’s assets, earnings, market, dividend etc, technical analysis solely focus on its stock price and volume. Technical analysis widely use technical indicators which are computed with price and volume to provide insights of trading action. Technical indicators further categorized in volatility, momentum, trend, volume etc. Selectively combining indicators for a stock may yield great profitable strategy. Once a strategy is built, one should backtest the strategy with simulator to measure performance (return and risk) before live trading. I have another post covering backtest with backtrader. As technical indicators play important roles in building a strategy, I will demonstrate how to use TA-Lib to compute technical indicators and build a simple strategy. (Please do not directly use the strategy for live trading as backtest is required). If you want to calculate the indicator by yourself, refer to my previous post on how to do it in Pandas. In this post, I will build a strategy with RSI (a momentum indicator) and Bollinger Bands %b (a volatility indicator). High RSI (usually above 70) may indicate a stock is overbought, therefore it is a sell signal. Low RSI (usually below 30) indicates stock is oversold, which means a buy signal. Bollinger Bands tell us most of price action between the two bands. Therefore, if %b is above 1, price will likely go down back within the bands. Hence, it is a sell signal. While if it is lower than 0, it is considered a buy signal. The strategy is a simple voting mechanism. When two indicators think it is time to buy, then it issues buy order to enter. When both indicators think it is time to sell, then it issues sell order to exit. python3 -m venv tutorial-envsource ~/tutorial-env/bin/activatepip install pandapip install pandas_datareaderpip install matplotlibpip install scipypip install cythonbrew install ta-libpip install TA-lib import pandas_datareader.data as webimport pandas as pdimport numpy as npfrom talib import RSI, BBANDSimport matplotlib.pyplot as pltstart = '2015-04-22'end = '2017-04-22'symbol = 'MCD'max_holding = 100price = web.DataReader(name=symbol, data_source='quandl', start=start, end=end)price = price.iloc[::-1]price = price.dropna()close = price['AdjClose'].valuesup, mid, low = BBANDS(close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)rsi = RSI(close, timeperiod=14)print("RSI (first 10 elements)\n", rsi[14:24]) Output RSI (first 10 elements) [50.45417011 47.89845022 49.54971141 51.0802541 50.97931103 61.79355957 58.80010324 54.64867736 53.23445848 50.65447261] Convert Bollinger Bands to %b def bbp(price): up, mid, low = BBANDS(close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0) bbp = (price['AdjClose'] - low) / (up - low) return bbp Compute the holdings based on the indicators holdings = pd.DataFrame(index=price.index, data={'Holdings': np.array([np.nan] * index.shape[0])})holdings.loc[((price['RSI'] < 30) & (price['BBP'] < 0)), 'Holdings'] = max_holdingholdings.loc[((price['RSI'] > 70) & (price['BBP'] > 1)), 'Holdings'] = 0holdings.ffill(inplace=True)holdings.fillna(0, inplace=True) Further, we should get the trading action based on the holdings holdings['Order'] = holdings.diff()holdings.dropna(inplace=True) Let’s visualize our action and indicators fig, (ax0, ax1, ax2) = plt.subplots(3, 1, sharex=True, figsize=(12, 8))ax0.plot(index, price['AdjClose'], label='AdjClose')ax0.set_xlabel('Date')ax0.set_ylabel('AdjClose')ax0.grid()for day, holding in holdings.iterrows(): order = holding['Order'] if order > 0: ax0.scatter(x=day, y=price.loc[day, 'AdjClose'], color='green') elif order < 0: ax0.scatter(x=day, y=price.loc[day, 'AdjClose'], color='red')ax1.plot(index, price['RSI'], label='RSI')ax1.fill_between(index, y1=30, y2=70, color='#adccff', alpha='0.3')ax1.set_xlabel('Date')ax1.set_ylabel('RSI')ax1.grid()ax2.plot(index, price['BB_up'], label='BB_up')ax2.plot(index, price['AdjClose'], label='AdjClose')ax2.plot(index, price['BB_low'], label='BB_low')ax2.fill_between(index, y1=price['BB_low'], y2=price['BB_up'], color='#adccff', alpha='0.3')ax2.set_xlabel('Date')ax2.set_ylabel('Bollinger Bands')ax2.grid()fig.tight_layout()plt.show() The below, I plot the action with green points (entry points) and red points (exit points) with the Adjusted Close Price of the McDonald (2015 April to 2017 April). Alongside, the RSI indicators and Bollinger Bands are plotted to show how two indicators contribute to a trading action. From the graph, it shows the strategy is good. It captures a couple relative some low prices and high price during the period. One should backtest to get how well the strategy does compared to benchmark. That’s it for this post. If you would like to learn more about Machine Learning there is a helpful series of courses in educative.io. These courses cover topics like basic ML, NLP, Image Recognition etc. Happy investment and coding! Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. Recommended reading: Hands-On Machine Learning Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython What Hedge Funds Really Do My posts: My posts about FAANG interview My YouTube Channel My posts about Finance and Tech From CRUD web app dev to SDE in voice assistant — My ongoing Journey to Machine Learning Full Stack Development Tutorial: Integrate AWS Lambda Serverless Service into Angular SPA Full Stack Development Tutorial: Serving Trading Data with Serverless REST API running on AWS Lambda Full Stack Development Tutorial: Visualize Trading Data on Angular SPA (1) Reinforcement Learning: Introduction to Q Learning
[ { "code": null, "e": 213, "s": 172, "text": "(This post is also available in my blog)" }, { "code": null, "e": 480, "s": 213, "text": "In finance, a trading strategy is a fixed plan that is designed to achieve a profitable return by going long or short in markets. The main reasons that a properly researched trading strategy helps are its verifiability, quantifiability, consistency, and objectivity." }, { "code": null, "e": 668, "s": 480, "text": "For every trading strategy one needs to define assets to trade, entry/exit points and money management rules. Bad money management can make a potentially profitable strategy unprofitable." }, { "code": null, "e": 685, "s": 668, "text": "— From Wikipedia" }, { "code": null, "e": 1410, "s": 685, "text": "Strategies are categorized as fundamental analysis based and technical analysis based. While fundamental analysis focus on company’s assets, earnings, market, dividend etc, technical analysis solely focus on its stock price and volume. Technical analysis widely use technical indicators which are computed with price and volume to provide insights of trading action. Technical indicators further categorized in volatility, momentum, trend, volume etc. Selectively combining indicators for a stock may yield great profitable strategy. Once a strategy is built, one should backtest the strategy with simulator to measure performance (return and risk) before live trading. I have another post covering backtest with backtrader." }, { "code": null, "e": 1766, "s": 1410, "text": "As technical indicators play important roles in building a strategy, I will demonstrate how to use TA-Lib to compute technical indicators and build a simple strategy. (Please do not directly use the strategy for live trading as backtest is required). If you want to calculate the indicator by yourself, refer to my previous post on how to do it in Pandas." }, { "code": null, "e": 2501, "s": 1766, "text": "In this post, I will build a strategy with RSI (a momentum indicator) and Bollinger Bands %b (a volatility indicator). High RSI (usually above 70) may indicate a stock is overbought, therefore it is a sell signal. Low RSI (usually below 30) indicates stock is oversold, which means a buy signal. Bollinger Bands tell us most of price action between the two bands. Therefore, if %b is above 1, price will likely go down back within the bands. Hence, it is a sell signal. While if it is lower than 0, it is considered a buy signal. The strategy is a simple voting mechanism. When two indicators think it is time to buy, then it issues buy order to enter. When both indicators think it is time to sell, then it issues sell order to exit." }, { "code": null, "e": 2704, "s": 2501, "text": "python3 -m venv tutorial-envsource ~/tutorial-env/bin/activatepip install pandapip install pandas_datareaderpip install matplotlibpip install scipypip install cythonbrew install ta-libpip install TA-lib" }, { "code": null, "e": 3216, "s": 2704, "text": "import pandas_datareader.data as webimport pandas as pdimport numpy as npfrom talib import RSI, BBANDSimport matplotlib.pyplot as pltstart = '2015-04-22'end = '2017-04-22'symbol = 'MCD'max_holding = 100price = web.DataReader(name=symbol, data_source='quandl', start=start, end=end)price = price.iloc[::-1]price = price.dropna()close = price['AdjClose'].valuesup, mid, low = BBANDS(close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)rsi = RSI(close, timeperiod=14)print(\"RSI (first 10 elements)\\n\", rsi[14:24])" }, { "code": null, "e": 3223, "s": 3216, "text": "Output" }, { "code": null, "e": 3369, "s": 3223, "text": "RSI (first 10 elements) [50.45417011 47.89845022 49.54971141 51.0802541 50.97931103 61.79355957 58.80010324 54.64867736 53.23445848 50.65447261]" }, { "code": null, "e": 3399, "s": 3369, "text": "Convert Bollinger Bands to %b" }, { "code": null, "e": 3556, "s": 3399, "text": "def bbp(price): up, mid, low = BBANDS(close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0) bbp = (price['AdjClose'] - low) / (up - low) return bbp" }, { "code": null, "e": 3601, "s": 3556, "text": "Compute the holdings based on the indicators" }, { "code": null, "e": 3914, "s": 3601, "text": "holdings = pd.DataFrame(index=price.index, data={'Holdings': np.array([np.nan] * index.shape[0])})holdings.loc[((price['RSI'] < 30) & (price['BBP'] < 0)), 'Holdings'] = max_holdingholdings.loc[((price['RSI'] > 70) & (price['BBP'] > 1)), 'Holdings'] = 0holdings.ffill(inplace=True)holdings.fillna(0, inplace=True)" }, { "code": null, "e": 3978, "s": 3914, "text": "Further, we should get the trading action based on the holdings" }, { "code": null, "e": 4043, "s": 3978, "text": "holdings['Order'] = holdings.diff()holdings.dropna(inplace=True)" }, { "code": null, "e": 4085, "s": 4043, "text": "Let’s visualize our action and indicators" }, { "code": null, "e": 5004, "s": 4085, "text": "fig, (ax0, ax1, ax2) = plt.subplots(3, 1, sharex=True, figsize=(12, 8))ax0.plot(index, price['AdjClose'], label='AdjClose')ax0.set_xlabel('Date')ax0.set_ylabel('AdjClose')ax0.grid()for day, holding in holdings.iterrows(): order = holding['Order'] if order > 0: ax0.scatter(x=day, y=price.loc[day, 'AdjClose'], color='green') elif order < 0: ax0.scatter(x=day, y=price.loc[day, 'AdjClose'], color='red')ax1.plot(index, price['RSI'], label='RSI')ax1.fill_between(index, y1=30, y2=70, color='#adccff', alpha='0.3')ax1.set_xlabel('Date')ax1.set_ylabel('RSI')ax1.grid()ax2.plot(index, price['BB_up'], label='BB_up')ax2.plot(index, price['AdjClose'], label='AdjClose')ax2.plot(index, price['BB_low'], label='BB_low')ax2.fill_between(index, y1=price['BB_low'], y2=price['BB_up'], color='#adccff', alpha='0.3')ax2.set_xlabel('Date')ax2.set_ylabel('Bollinger Bands')ax2.grid()fig.tight_layout()plt.show()" }, { "code": null, "e": 5494, "s": 5004, "text": "The below, I plot the action with green points (entry points) and red points (exit points) with the Adjusted Close Price of the McDonald (2015 April to 2017 April). Alongside, the RSI indicators and Bollinger Bands are plotted to show how two indicators contribute to a trading action. From the graph, it shows the strategy is good. It captures a couple relative some low prices and high price during the period. One should backtest to get how well the strategy does compared to benchmark." }, { "code": null, "e": 5727, "s": 5494, "text": "That’s it for this post. If you would like to learn more about Machine Learning there is a helpful series of courses in educative.io. These courses cover topics like basic ML, NLP, Image Recognition etc. Happy investment and coding!" }, { "code": null, "e": 6027, "s": 5727, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 6048, "s": 6027, "text": "Recommended reading:" }, { "code": null, "e": 6074, "s": 6048, "text": "Hands-On Machine Learning" }, { "code": null, "e": 6147, "s": 6074, "text": "Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython" }, { "code": null, "e": 6174, "s": 6147, "text": "What Hedge Funds Really Do" }, { "code": null, "e": 6184, "s": 6174, "text": "My posts:" }, { "code": null, "e": 6215, "s": 6184, "text": "My posts about FAANG interview" }, { "code": null, "e": 6234, "s": 6215, "text": "My YouTube Channel" }, { "code": null, "e": 6266, "s": 6234, "text": "My posts about Finance and Tech" }, { "code": null, "e": 6355, "s": 6266, "text": "From CRUD web app dev to SDE in voice assistant — My ongoing Journey to Machine Learning" }, { "code": null, "e": 6445, "s": 6355, "text": "Full Stack Development Tutorial: Integrate AWS Lambda Serverless Service into Angular SPA" }, { "code": null, "e": 6546, "s": 6445, "text": "Full Stack Development Tutorial: Serving Trading Data with Serverless REST API running on AWS Lambda" }, { "code": null, "e": 6621, "s": 6546, "text": "Full Stack Development Tutorial: Visualize Trading Data on Angular SPA (1)" } ]
Getting an enumerator that iterates through LinkedList in C#
To get an enumerator that iterates through LinkedList, the code is as follows − Live Demo using System; using System.Collections.Generic; public class Demo { public static void Main(){ LinkedList<string> list = new LinkedList<string>(); list.AddLast("A"); list.AddLast("B"); list.AddLast("C"); list.AddLast("D"); list.AddLast("E"); list.AddLast("F"); list.AddLast("G"); list.AddLast("H"); list.AddLast("I"); list.AddLast("J"); Console.WriteLine("Count of nodes = " + list.Count); Console.WriteLine("Elements in LinkedList... (Enumerator iterating through LinkedList)"); LinkedList<string>.Enumerator demoEnum = list.GetEnumerator(); while (demoEnum.MoveNext()) { string res = demoEnum.Current; Console.WriteLine(res); } } } This will produce the following output − Count of nodes = 10 Elements in LinkedList... (Enumerator iterating through LinkedList) A B C D E F G H I J Let us see another example − Live Demo using System; using System.Collections.Generic; public class Demo { public static void Main(String[] args){ LinkedList<string> list1 = new LinkedList<string>(); list1.AddLast("One"); list1.AddLast("Two"); list1.AddLast("Three"); list1.AddLast("Four"); list1.AddLast("Five"); Console.WriteLine("Elements in LinkedList1..."); foreach (string res in list1){ Console.WriteLine(res); } LinkedList<string> list2 = new LinkedList<string>(); list2.AddLast("India"); list2.AddLast("US"); list2.AddLast("UK"); list2.AddLast("Canada"); list2.AddLast("Poland"); list2.AddLast("Netherlands"); Console.WriteLine("Elements in LinkedList2... (Enumerator iterating through LinkedList2)"); LinkedList<string>.Enumerator demoEnum = list2.GetEnumerator(); while (demoEnum.MoveNext()) { string res = demoEnum.Current; Console.WriteLine(res); } LinkedList<string> list3 = new LinkedList<string>(); list3 = list2; Console.WriteLine("Is LinkedList3 equal to LinkedList2? = "+list3.Equals(list2)); } } This will produce the following output − Elements in LinkedList1... One Two Three Four Five Elements in LinkedList2... (Enumerator iterating through LinkedList2) India US UK Canada Poland Netherlands Is LinkedList3 equal to LinkedList2? = True
[ { "code": null, "e": 1142, "s": 1062, "text": "To get an enumerator that iterates through LinkedList, the code is as follows −" }, { "code": null, "e": 1153, "s": 1142, "text": " Live Demo" }, { "code": null, "e": 1907, "s": 1153, "text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(){\n LinkedList<string> list = new LinkedList<string>();\n list.AddLast(\"A\");\n list.AddLast(\"B\");\n list.AddLast(\"C\");\n list.AddLast(\"D\");\n list.AddLast(\"E\");\n list.AddLast(\"F\");\n list.AddLast(\"G\");\n list.AddLast(\"H\");\n list.AddLast(\"I\");\n list.AddLast(\"J\");\n Console.WriteLine(\"Count of nodes = \" + list.Count);\n Console.WriteLine(\"Elements in LinkedList... (Enumerator iterating through LinkedList)\");\n LinkedList<string>.Enumerator demoEnum = list.GetEnumerator();\n while (demoEnum.MoveNext()) {\n string res = demoEnum.Current;\n Console.WriteLine(res);\n }\n }\n}" }, { "code": null, "e": 1948, "s": 1907, "text": "This will produce the following output −" }, { "code": null, "e": 2056, "s": 1948, "text": "Count of nodes = 10\nElements in LinkedList... (Enumerator iterating through LinkedList)\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ" }, { "code": null, "e": 2085, "s": 2056, "text": "Let us see another example −" }, { "code": null, "e": 2096, "s": 2085, "text": " Live Demo" }, { "code": null, "e": 3244, "s": 2096, "text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(String[] args){\n LinkedList<string> list1 = new LinkedList<string>();\n list1.AddLast(\"One\");\n list1.AddLast(\"Two\");\n list1.AddLast(\"Three\");\n list1.AddLast(\"Four\");\n list1.AddLast(\"Five\");\n Console.WriteLine(\"Elements in LinkedList1...\");\n foreach (string res in list1){\n Console.WriteLine(res);\n }\n LinkedList<string> list2 = new LinkedList<string>();\n list2.AddLast(\"India\");\n list2.AddLast(\"US\");\n list2.AddLast(\"UK\");\n list2.AddLast(\"Canada\");\n list2.AddLast(\"Poland\");\n list2.AddLast(\"Netherlands\");\n Console.WriteLine(\"Elements in LinkedList2... (Enumerator iterating through LinkedList2)\");\n LinkedList<string>.Enumerator demoEnum = list2.GetEnumerator();\n while (demoEnum.MoveNext()) {\n string res = demoEnum.Current;\n Console.WriteLine(res);\n }\n LinkedList<string> list3 = new LinkedList<string>();\n list3 = list2;\n Console.WriteLine(\"Is LinkedList3 equal to LinkedList2? = \"+list3.Equals(list2));\n }\n}" }, { "code": null, "e": 3285, "s": 3244, "text": "This will produce the following output −" }, { "code": null, "e": 3488, "s": 3285, "text": "Elements in LinkedList1...\nOne\nTwo\nThree\nFour\nFive\nElements in LinkedList2... (Enumerator iterating through LinkedList2)\nIndia\nUS\nUK\nCanada\nPoland\nNetherlands\nIs LinkedList3 equal to LinkedList2? = True" } ]
How to round the decimal number to the nearest tenth in JavaScript?
To round the decimal number to the nearest tenth, use toFixed(1) in JavaScript. The syntax is as follows − var anyVaribleName=yourVariableName.toFixed(1) Let’s say the following is our decimal number − var decimalValue =200.432144444555; console.log("Actual value="+decimalValue) Let’s now round the decimal number. Following is the code − var decimalValue =200.432144444555; console.log("Actual value="+decimalValue) var modifiedValue=decimalValue.toFixed(1) console.log("Modified value="+ modifiedValue); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo38.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo38.js Actual value=200.432144444555 Modified value=200.4
[ { "code": null, "e": 1169, "s": 1062, "text": "To round the decimal number to the nearest tenth, use toFixed(1) in JavaScript. The syntax is\nas follows −" }, { "code": null, "e": 1216, "s": 1169, "text": "var anyVaribleName=yourVariableName.toFixed(1)" }, { "code": null, "e": 1264, "s": 1216, "text": "Let’s say the following is our decimal number −" }, { "code": null, "e": 1342, "s": 1264, "text": "var decimalValue =200.432144444555;\nconsole.log(\"Actual value=\"+decimalValue)" }, { "code": null, "e": 1402, "s": 1342, "text": "Let’s now round the decimal number. Following is the code −" }, { "code": null, "e": 1569, "s": 1402, "text": "var decimalValue =200.432144444555;\nconsole.log(\"Actual value=\"+decimalValue)\nvar modifiedValue=decimalValue.toFixed(1)\nconsole.log(\"Modified value=\"+ modifiedValue);" }, { "code": null, "e": 1635, "s": 1569, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1653, "s": 1635, "text": "node fileName.js." }, { "code": null, "e": 1686, "s": 1653, "text": "Here, my file name is demo38.js." }, { "code": null, "e": 1727, "s": 1686, "text": "This will produce the following output −" }, { "code": null, "e": 1827, "s": 1727, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo38.js\nActual value=200.432144444555\nModified value=200.4" } ]
Calculate the mean across dimension in a 2D NumPy array - GeeksforGeeks
29 Aug, 2020 We can find out the mean of each row and column of 2d array using numpy with the function np.mean(). Here we have to provide the axis for finding mean. Syntax: numpy.mean(arr, axis = None) For Row mean: axis=1 For Column mean: axis=0 Example: Python3 # Importing Libraryimport numpy as np # creating 2d arrayarr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Calculating mean across Rowsrow_mean = np.mean(arr, axis=1) row1_mean = row_mean[0]print("Mean of Row 1 is", row1_mean) row2_mean = row_mean[1]print("Mean of Row 2 is", row2_mean) row3_mean = row_mean[2]print("Mean of Row 3 is", row3_mean) # Calculating mean across Columnscolumn_mean = np.mean(arr, axis=0) column1_mean = column_mean[0]print("Mean of column 1 is", column1_mean) column2_mean = column_mean[1]print("Mean of column 2 is", column2_mean) column3_mean = column_mean[2]print("Mean of column 3 is", column3_mean) Output: Mean of Row 1 is 2.0 Mean of Row 2 is 5.0 Mean of Row 3 is 8.0 Mean of column 1 is 4.0 Mean of column 2 is 5.0 Mean of column 3 is 6.0 Python numpy-program Python numpy-Statistics Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24230, "s": 24202, "text": "\n29 Aug, 2020" }, { "code": null, "e": 24382, "s": 24230, "text": "We can find out the mean of each row and column of 2d array using numpy with the function np.mean(). Here we have to provide the axis for finding mean." }, { "code": null, "e": 24419, "s": 24382, "text": "Syntax: numpy.mean(arr, axis = None)" }, { "code": null, "e": 24440, "s": 24419, "text": "For Row mean: axis=1" }, { "code": null, "e": 24464, "s": 24440, "text": "For Column mean: axis=0" }, { "code": null, "e": 24473, "s": 24464, "text": "Example:" }, { "code": null, "e": 24481, "s": 24473, "text": "Python3" }, { "code": "# Importing Libraryimport numpy as np # creating 2d arrayarr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Calculating mean across Rowsrow_mean = np.mean(arr, axis=1) row1_mean = row_mean[0]print(\"Mean of Row 1 is\", row1_mean) row2_mean = row_mean[1]print(\"Mean of Row 2 is\", row2_mean) row3_mean = row_mean[2]print(\"Mean of Row 3 is\", row3_mean) # Calculating mean across Columnscolumn_mean = np.mean(arr, axis=0) column1_mean = column_mean[0]print(\"Mean of column 1 is\", column1_mean) column2_mean = column_mean[1]print(\"Mean of column 2 is\", column2_mean) column3_mean = column_mean[2]print(\"Mean of column 3 is\", column3_mean)", "e": 25125, "s": 24481, "text": null }, { "code": null, "e": 25133, "s": 25125, "text": "Output:" }, { "code": null, "e": 25269, "s": 25133, "text": "Mean of Row 1 is 2.0\nMean of Row 2 is 5.0\nMean of Row 3 is 8.0\nMean of column 1 is 4.0\nMean of column 2 is 5.0\nMean of column 3 is 6.0\n" }, { "code": null, "e": 25290, "s": 25269, "text": "Python numpy-program" }, { "code": null, "e": 25324, "s": 25290, "text": "Python numpy-Statistics Functions" }, { "code": null, "e": 25337, "s": 25324, "text": "Python-numpy" }, { "code": null, "e": 25344, "s": 25337, "text": "Python" }, { "code": null, "e": 25442, "s": 25344, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25460, "s": 25442, "text": "Python Dictionary" }, { "code": null, "e": 25495, "s": 25460, "text": "Read a file line by line in Python" }, { "code": null, "e": 25517, "s": 25495, "text": "Enumerate() in Python" }, { "code": null, "e": 25549, "s": 25517, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25579, "s": 25549, "text": "Iterate over a list in Python" }, { "code": null, "e": 25621, "s": 25579, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25647, "s": 25621, "text": "Python String | replace()" }, { "code": null, "e": 25684, "s": 25647, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 25727, "s": 25684, "text": "Python program to convert a list to string" } ]
Smallest String With Swaps in C++
Suppose we have given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. We can swap the characters at any pair of indices in the given pairs any number of times as we want. We have to find the lexicographically smallest string that s can be changed to after using the swaps. So if the input is like s = “dcab” and pairs = [[0,3], [1,2]], then the output will be “bacd”. Exchange s[0] and s[3], s = "bcad", then exchange s[1] and s[2], s = "bacd". To solve this, we will follow these steps − n := size of array, parent := make an array of size n, and fill this with -1 n := size of array, parent := make an array of size n, and fill this with -1 make a string called ret of size n and fill this with * make a string called ret of size n and fill this with * for i in range 0 to size of pairsu := pairs[i, 0] and v := pairs[i, 1]if parent of u is same as parent of v, then skip to next iterationparent[parent of u] := parent of v for i in range 0 to size of pairs u := pairs[i, 0] and v := pairs[i, 1] u := pairs[i, 0] and v := pairs[i, 1] if parent of u is same as parent of v, then skip to next iteration if parent of u is same as parent of v, then skip to next iteration parent[parent of u] := parent of v parent[parent of u] := parent of v define an array arr1 of size n define an array arr1 of size n for i in range 0 to n – 1: insert s[i] into arr[parent of i] for i in range 0 to n – 1: insert s[i] into arr[parent of i] for i in range 0 to n – 1: sort arr[i] by reading the value from right for i in range 0 to n – 1: sort arr[i] by reading the value from right for i in range 0 to n – 1 −ret[i] := last entry of arr1[parent of i]delete the last node from arr1[parent of i] for i in range 0 to n – 1 − ret[i] := last entry of arr1[parent of i] ret[i] := last entry of arr1[parent of i] delete the last node from arr1[parent of i] delete the last node from arr1[parent of i] Let us see the following implementation to get a better understanding − class Solution { public: vector <int> parent; int getParent(int x){ if(parent[x] == -1) return x; return parent[x] = getParent(parent[x]); } string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) { int n = s.size(); parent = vector <int>(n, -1); string ret(n, '*'); for(int i = 0; i < pairs.size(); i++){ int u = pairs[i][0]; int v = pairs[i][1]; if(getParent(u) == getParent(v)) continue; parent[getParent(u)] = getParent(v); } vector < char > arr1[n]; for(int i = 0; i < n; i++){ arr1[getParent(i)].push_back(s[i]); } for(int i = 0; i < n; i++){ sort(arr1[i].rbegin(), arr1[i].rend()); } for(int i = 0; i < n; i++){ ret[i] = arr1[getParent(i)].back(); arr1[getParent(i)].pop_back(); } return ret; } }; "dcab" [[0,3],[1,2]] "bacd"
[ { "code": null, "e": 1594, "s": 1062, "text": "Suppose we have given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. We can swap the characters at any pair of indices in the given pairs any number of times as we want. We have to find the lexicographically smallest string that s can be changed to after using the swaps. So if the input is like s = “dcab” and pairs = [[0,3], [1,2]], then the output will be “bacd”. Exchange s[0] and s[3], s = \"bcad\", then exchange s[1] and s[2], s = \"bacd\"." }, { "code": null, "e": 1638, "s": 1594, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1715, "s": 1638, "text": "n := size of array, parent := make an array of size n, and fill this with -1" }, { "code": null, "e": 1792, "s": 1715, "text": "n := size of array, parent := make an array of size n, and fill this with -1" }, { "code": null, "e": 1848, "s": 1792, "text": "make a string called ret of size n and fill this with *" }, { "code": null, "e": 1904, "s": 1848, "text": "make a string called ret of size n and fill this with *" }, { "code": null, "e": 2075, "s": 1904, "text": "for i in range 0 to size of pairsu := pairs[i, 0] and v := pairs[i, 1]if parent of u is same as parent of v, then skip to next iterationparent[parent of u] := parent of v" }, { "code": null, "e": 2109, "s": 2075, "text": "for i in range 0 to size of pairs" }, { "code": null, "e": 2147, "s": 2109, "text": "u := pairs[i, 0] and v := pairs[i, 1]" }, { "code": null, "e": 2185, "s": 2147, "text": "u := pairs[i, 0] and v := pairs[i, 1]" }, { "code": null, "e": 2252, "s": 2185, "text": "if parent of u is same as parent of v, then skip to next iteration" }, { "code": null, "e": 2319, "s": 2252, "text": "if parent of u is same as parent of v, then skip to next iteration" }, { "code": null, "e": 2354, "s": 2319, "text": "parent[parent of u] := parent of v" }, { "code": null, "e": 2389, "s": 2354, "text": "parent[parent of u] := parent of v" }, { "code": null, "e": 2420, "s": 2389, "text": "define an array arr1 of size n" }, { "code": null, "e": 2451, "s": 2420, "text": "define an array arr1 of size n" }, { "code": null, "e": 2512, "s": 2451, "text": "for i in range 0 to n – 1: insert s[i] into arr[parent of i]" }, { "code": null, "e": 2573, "s": 2512, "text": "for i in range 0 to n – 1: insert s[i] into arr[parent of i]" }, { "code": null, "e": 2644, "s": 2573, "text": "for i in range 0 to n – 1: sort arr[i] by reading the value from right" }, { "code": null, "e": 2715, "s": 2644, "text": "for i in range 0 to n – 1: sort arr[i] by reading the value from right" }, { "code": null, "e": 2827, "s": 2715, "text": "for i in range 0 to n – 1 −ret[i] := last entry of arr1[parent of i]delete the last node from arr1[parent of i]" }, { "code": null, "e": 2855, "s": 2827, "text": "for i in range 0 to n – 1 −" }, { "code": null, "e": 2897, "s": 2855, "text": "ret[i] := last entry of arr1[parent of i]" }, { "code": null, "e": 2939, "s": 2897, "text": "ret[i] := last entry of arr1[parent of i]" }, { "code": null, "e": 2983, "s": 2939, "text": "delete the last node from arr1[parent of i]" }, { "code": null, "e": 3027, "s": 2983, "text": "delete the last node from arr1[parent of i]" }, { "code": null, "e": 3099, "s": 3027, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 3994, "s": 3099, "text": "class Solution {\npublic:\n vector <int> parent;\n int getParent(int x){\n if(parent[x] == -1) return x;\n return parent[x] = getParent(parent[x]);\n }\n string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {\n int n = s.size();\n parent = vector <int>(n, -1);\n string ret(n, '*');\n for(int i = 0; i < pairs.size(); i++){\n int u = pairs[i][0];\n int v = pairs[i][1];\n if(getParent(u) == getParent(v)) continue;\n parent[getParent(u)] = getParent(v);\n }\n vector < char > arr1[n];\n for(int i = 0; i < n; i++){\n arr1[getParent(i)].push_back(s[i]);\n }\n for(int i = 0; i < n; i++){\n sort(arr1[i].rbegin(), arr1[i].rend());\n }\n for(int i = 0; i < n; i++){\n ret[i] = arr1[getParent(i)].back();\n arr1[getParent(i)].pop_back();\n }\n return ret;\n }\n};" }, { "code": null, "e": 4015, "s": 3994, "text": "\"dcab\"\n[[0,3],[1,2]]" }, { "code": null, "e": 4022, "s": 4015, "text": "\"bacd\"" } ]
Deploying Streamlit Apps to GCP. Streamlit is a minimal, modern data... | by Mark Douthwaite | Towards Data Science
If you’re familiar with the Data Science software ecosystem in Python, you’ll likely have come across a handful of widely used dashboarding and data visualization tools designed for programmatic usage (e.g. to be embedded in notebooks or to be served as standalone web-apps). For the last few years, the likes of Dash, Bokeh and Voila have been some of the biggest open-source players in this space. Within the world of R, there’s also the long-standing champion of dashboarding tools: Shiny. With this relatively mature ecosystem in place, you may question the need for a yet another framework to join the pack. But that’s exactly what the team over at Streamlit are doing: introducing a brand new framework for building data applications. What’s more, they’ve created quite a bit of buzz around their project too, so much so that they recently closed a $21M Series A funding round to allow them to continue developing their framework. medium.com So what has got folks so excited about Streamlit? Well firstly, it is quite literally one of the most straightforward tools you’re likely to come across. There’s no boilerplate, and pretty much no framework-specific concepts you need to keep in mind. It feels very well designed. Altogether this simplicity makes it remarkably quick and easy to get an app built in (pretty much) seconds. This minimalism lends itself to a second key point: event management is a breeze. This might sound dull, but it’s kind of a big deal in this case. There’s no framework-specific design patterns/callbacks needed to manage events in Streamlit. For example, say you want to run some code on the click of a button, you’d capture this in Streamlit with: import streamlit as stif st.button("Click Me"): print("Clicked") Whenever the Click Me button is pressed, the block beneath it will be executed. The same concept is applied pretty much the same way to all of their interactive components. It does some clever tricks under the hood to make this work, but the end effect is the same: you can quickly and simply write apps with complex behaviour with very little change to your underlying code. In the same way that Fire makes it incredibly easy to create CLIs for your existing code, Streamlit makes it ludicrously easy to create interactive apps from existing code. As they put it: it's designed to be 'sprinkled' onto your code. Finally, Streamlit is also pretty much painless to integrate with existing data visualization tools, and is super easy to deploy to boot — it plays nicely with modern deployment tools and technologies. You can embed your matplotlib charts alongside your dash plots to your heart's content, and then containerize it all ready for deployment in moments. All in all, these features conspire to make Streamlit one of the most productive, modern data visualization tools out there at the moment. While the docs for Streamlit are pretty good for getting started, there’s not a huge amount out there on deploying your apps. This post aims to highlight how simple it is to deploy a Streamlit app as a live, public-facing website. It’s going to be using one of the ‘standard’ demo apps provided by Streamlit: a visualization of Uber Pickups in New York City by time of day. However, feel free to create your own app and deploy that instead (the template you’ll be using won’t need to be changed!). To get started, you’ll need to make sure you have few things set up. You’ll be deploying your app with Google App Engine, so this means you’ll need to both register for a Google Cloud account (there’s $300 of credit available on signup too!) and then install their gcloud command line tool. You can sign up for an account here (it's not an affiliate link, don't worry!): cloud.google.com Google Cloud also provides a great ‘Getting Started’ guide to installing gcloud. cloud.google.com When this is done, make sure you have Docker installed and running. You won’t need to interact with Docker to follow along with this post, but you will need it running! You’ll also need to have a valid version of Python 3.6 or greater, too. It’s a good idea to set up and activate a Python virtual environment for the project too. So, first thing’s first. You’re going to need to clone the deployment-ready Streamlit project template from GitHub. In your terminal, run: git clone https://github.com/markdouthwaite/streamlit-project Navigate into your new streamlit-project directory and run: pip install -r requirements.txt As you might expect, this’ll install packages you’ll need to run this app. With this setup, time to test your app! You can do that with: make run-container To build your app into a Docker image and launch a new container running your app at http://0.0.0.0:8080. It'll automatically open a new browser tab and load your app. You should see a lovely visualization like this: Feel free to edit the app however you want. It’s worth getting to grips with how powerful Streamlit can be. When you’re done, just make sure that make run still successfully launches your app on http://0.0.0.0:8080, and then you can head to deployment. You’ll be using Google App Engine to deploy the app. This is a managed service provided by Google Cloud that helps you deploy and scale your apps super easily. Google will manage scaling, server settings and other bits and pieces for you. All you need is a properly configured Docker image and you’re pretty much there. Go to your Google Cloud Console, head to App Engine in the left hand navigation menu and check that your App Engine API is live. You should now be able to run: make gcloud-deploy This’ll build your image, store it in Google Container Registry (GCR), and then configure and launch your app. It’ll tell you when it’s done. You should see something like (where {{YOUR-URL}} will be the URL for your deployed app): Deployed service [default] to [{{YOUR-URL}}] Navigate to the URL provided and look at your app in all its glory! With that done, your app is now publicly visible and can be shared with anyone you wish. You can also now edit and redeploy your app freely using make gcloud-deploy. You could even look at building a Continuous Integration and Continuous Delivery (CI/CD) pipeline with GitHub Actions to automatically re-deploy your app every time you push a change to GitHub. That's up to you though! If you run into any issues with the above steps, the docs for App Engine are pretty good and well worth a look: If you’re still struggling, feel free to reach out to me on Twitter. So that’s pretty much it. Deploying a new Streamlit app in a scalable, secure way. Simple, eh? As you dig in to Streamlit, you’ll notice that it’s still a bit restrictive in a few ways: layouts and styling are highly restricted by default, for example. However, their recent funding rounds have given them a lot of runway to develop some cool new features, and these things are on their feature roadmap, so it should just be a matter of time until they arrive. If you’re interested in data visualization, Streamlit is definitely one to watch.
[ { "code": null, "e": 665, "s": 172, "text": "If you’re familiar with the Data Science software ecosystem in Python, you’ll likely have come across a handful of widely used dashboarding and data visualization tools designed for programmatic usage (e.g. to be embedded in notebooks or to be served as standalone web-apps). For the last few years, the likes of Dash, Bokeh and Voila have been some of the biggest open-source players in this space. Within the world of R, there’s also the long-standing champion of dashboarding tools: Shiny." }, { "code": null, "e": 1109, "s": 665, "text": "With this relatively mature ecosystem in place, you may question the need for a yet another framework to join the pack. But that’s exactly what the team over at Streamlit are doing: introducing a brand new framework for building data applications. What’s more, they’ve created quite a bit of buzz around their project too, so much so that they recently closed a $21M Series A funding round to allow them to continue developing their framework." }, { "code": null, "e": 1120, "s": 1109, "text": "medium.com" }, { "code": null, "e": 1170, "s": 1120, "text": "So what has got folks so excited about Streamlit?" }, { "code": null, "e": 1508, "s": 1170, "text": "Well firstly, it is quite literally one of the most straightforward tools you’re likely to come across. There’s no boilerplate, and pretty much no framework-specific concepts you need to keep in mind. It feels very well designed. Altogether this simplicity makes it remarkably quick and easy to get an app built in (pretty much) seconds." }, { "code": null, "e": 1856, "s": 1508, "text": "This minimalism lends itself to a second key point: event management is a breeze. This might sound dull, but it’s kind of a big deal in this case. There’s no framework-specific design patterns/callbacks needed to manage events in Streamlit. For example, say you want to run some code on the click of a button, you’d capture this in Streamlit with:" }, { "code": null, "e": 1921, "s": 1856, "text": "import streamlit as stif st.button(\"Click Me\"): print(\"Clicked\")" }, { "code": null, "e": 2534, "s": 1921, "text": "Whenever the Click Me button is pressed, the block beneath it will be executed. The same concept is applied pretty much the same way to all of their interactive components. It does some clever tricks under the hood to make this work, but the end effect is the same: you can quickly and simply write apps with complex behaviour with very little change to your underlying code. In the same way that Fire makes it incredibly easy to create CLIs for your existing code, Streamlit makes it ludicrously easy to create interactive apps from existing code. As they put it: it's designed to be 'sprinkled' onto your code." }, { "code": null, "e": 3025, "s": 2534, "text": "Finally, Streamlit is also pretty much painless to integrate with existing data visualization tools, and is super easy to deploy to boot — it plays nicely with modern deployment tools and technologies. You can embed your matplotlib charts alongside your dash plots to your heart's content, and then containerize it all ready for deployment in moments. All in all, these features conspire to make Streamlit one of the most productive, modern data visualization tools out there at the moment." }, { "code": null, "e": 3523, "s": 3025, "text": "While the docs for Streamlit are pretty good for getting started, there’s not a huge amount out there on deploying your apps. This post aims to highlight how simple it is to deploy a Streamlit app as a live, public-facing website. It’s going to be using one of the ‘standard’ demo apps provided by Streamlit: a visualization of Uber Pickups in New York City by time of day. However, feel free to create your own app and deploy that instead (the template you’ll be using won’t need to be changed!)." }, { "code": null, "e": 3894, "s": 3523, "text": "To get started, you’ll need to make sure you have few things set up. You’ll be deploying your app with Google App Engine, so this means you’ll need to both register for a Google Cloud account (there’s $300 of credit available on signup too!) and then install their gcloud command line tool. You can sign up for an account here (it's not an affiliate link, don't worry!):" }, { "code": null, "e": 3911, "s": 3894, "text": "cloud.google.com" }, { "code": null, "e": 3992, "s": 3911, "text": "Google Cloud also provides a great ‘Getting Started’ guide to installing gcloud." }, { "code": null, "e": 4009, "s": 3992, "text": "cloud.google.com" }, { "code": null, "e": 4340, "s": 4009, "text": "When this is done, make sure you have Docker installed and running. You won’t need to interact with Docker to follow along with this post, but you will need it running! You’ll also need to have a valid version of Python 3.6 or greater, too. It’s a good idea to set up and activate a Python virtual environment for the project too." }, { "code": null, "e": 4479, "s": 4340, "text": "So, first thing’s first. You’re going to need to clone the deployment-ready Streamlit project template from GitHub. In your terminal, run:" }, { "code": null, "e": 4541, "s": 4479, "text": "git clone https://github.com/markdouthwaite/streamlit-project" }, { "code": null, "e": 4601, "s": 4541, "text": "Navigate into your new streamlit-project directory and run:" }, { "code": null, "e": 4633, "s": 4601, "text": "pip install -r requirements.txt" }, { "code": null, "e": 4770, "s": 4633, "text": "As you might expect, this’ll install packages you’ll need to run this app. With this setup, time to test your app! You can do that with:" }, { "code": null, "e": 4789, "s": 4770, "text": "make run-container" }, { "code": null, "e": 5006, "s": 4789, "text": "To build your app into a Docker image and launch a new container running your app at http://0.0.0.0:8080. It'll automatically open a new browser tab and load your app. You should see a lovely visualization like this:" }, { "code": null, "e": 5259, "s": 5006, "text": "Feel free to edit the app however you want. It’s worth getting to grips with how powerful Streamlit can be. When you’re done, just make sure that make run still successfully launches your app on http://0.0.0.0:8080, and then you can head to deployment." }, { "code": null, "e": 5739, "s": 5259, "text": "You’ll be using Google App Engine to deploy the app. This is a managed service provided by Google Cloud that helps you deploy and scale your apps super easily. Google will manage scaling, server settings and other bits and pieces for you. All you need is a properly configured Docker image and you’re pretty much there. Go to your Google Cloud Console, head to App Engine in the left hand navigation menu and check that your App Engine API is live. You should now be able to run:" }, { "code": null, "e": 5758, "s": 5739, "text": "make gcloud-deploy" }, { "code": null, "e": 5990, "s": 5758, "text": "This’ll build your image, store it in Google Container Registry (GCR), and then configure and launch your app. It’ll tell you when it’s done. You should see something like (where {{YOUR-URL}} will be the URL for your deployed app):" }, { "code": null, "e": 6035, "s": 5990, "text": "Deployed service [default] to [{{YOUR-URL}}]" }, { "code": null, "e": 6103, "s": 6035, "text": "Navigate to the URL provided and look at your app in all its glory!" }, { "code": null, "e": 6488, "s": 6103, "text": "With that done, your app is now publicly visible and can be shared with anyone you wish. You can also now edit and redeploy your app freely using make gcloud-deploy. You could even look at building a Continuous Integration and Continuous Delivery (CI/CD) pipeline with GitHub Actions to automatically re-deploy your app every time you push a change to GitHub. That's up to you though!" }, { "code": null, "e": 6600, "s": 6488, "text": "If you run into any issues with the above steps, the docs for App Engine are pretty good and well worth a look:" }, { "code": null, "e": 6669, "s": 6600, "text": "If you’re still struggling, feel free to reach out to me on Twitter." } ]
Kubeflow: An MLOps Perspective. ML Pipelines and ML Components | by Alex Punnen | Towards Data Science
When designing new technologies, almost always choices are made that would sacrifice some characteristic for some others. And it is important to understand those choices and how they may or may not affect your use case. Usually, such a study is never done when technology or framework is chosen over others; or sometimes there is no choice. For example, we have well-designed platforms like Kubernetes, that can’t be faulted by either the most technical; or the least. Though of course it is still evolving and there could be better solutions for things like hard multi-tenancy, these do not concern a general user very much now. It has become the de-facto execution engine for any cloud-native application. This has induced a lot of changes in traditional software development. Instead of compiling the source code for one or more Operating Systems and creating an installer or packager for it; developers need to containerize their code and create the related artefacts — like Services, Config-maps, Secrets; Ingress and similar in a Kubernetes specific markup language (YAML). This has become common practice and routine now. For a developer; wrapping your micro-service in a container and deploying it in a pod; guarantees that it will perform the same; on any Kubernetes cluster with enough resources. One need not worry about the internal intricacy of pod networking or scheduling or Linux internals related to Control Groups or Namespaces or the like. Of course, that is a simplification; as if you are mounting a host volume and making an assumption of the underlying Linux OS and such, then such could break; but again these are outliers and not the way the technology has to be used. And that’s a good thing. You wish similar abstraction was there for other technologies; for example, databases; That without having an understanding of the internals of data storage; one can efficiently store and efficiently retrieve data. For example, a DB stored for fast access may not be good at fast updates; and it would be surprising to know that many developers will not be aware; till the feature requirements come mid-way exposing the hidden characteristic of the systems. Basically, the system starts behaving in an unexpected way, when it is used for a use-case it was designed for. How does all this factor in what we want to discuss? What we are looking for in Kubeflow, is how non-leaky the abstraction is — to borrow a term from Joel Spolsky. What we are looking for in Kubeflow is how ‘Cloud Native’ it is — to borrow a widely used or misused cliche. Basically, execution is scheduled in Kubernetes cluster Edge Cluster or Data Center. This box is ticked as Kubeflow is designed for Kubernetes. Unlike say MLFlow — https://mlflow.org/. Other contenders TFX , ZenML as of now Before we go into Kubeflow, let's check the environment where it fits. MLOps process should help in ensuring production quality is present and maintained for ML projects. Is it enough to make a container out of your ML project and deploy in on Kubernetes? Or are there other things that need to be taken care of ? How is CI done? How are tests executed? and test evaluated? From a heavily over-quoted paper; it seems the ML code has the least significance when deployed in production. Example from this excellent blog → https://cloud.google.com/architecture/mlops-continuous-delivery-and-automation-pipelines-in-machine-learning The authors may have exaggerated to get our attention to the rest of the system that we tend to miss; or maybe not. And the authors may be taking more about structured data and classical ML methodology that depends on Features; than unstructured data like say for Audio or Video or Image Analytics and Deep Neural Networks MLOps - like DevOps, seems to be again a term that is used to mean a lot of different things to a lot of different people in a lot of different ways. We need to define what we mean when we say MLOps. DevOps generally have settled to represent the CI/CD part more -https://aws.amazon.com/devops/what-is-devops/; than the original concept of developers doing end to end development, deployment and operations of their components — the principle of more feedback between developers and their deployments. This could be like proactively checking the error logs from customer deployments for possible problems even before bugs are raised. It is surely more than just CI/CD; though it is also tied more to development and management culture than a technical process. It is not strange that you have a ‘DevOps’ team now in many companies that does this role, providing the tools and services for CI/CD, and tools and infrastructure for better feedback from deployments — monitoring, logging etc. MLOps — is similar to DevOps for micro-services. But this has more ML related aspects to it, over just the algorithm, like data and model management, model versioning, model drift etc. At least that’s the promise, and we have so many tools and services in this space, commercial and open-source that it is really easy to get confused and bogged down unless we have some selection criteria. Some idea you would get by browsing here or here; some authors referring to the proliferation as Cambrian explosion of MLOps projects. However, we could simplify this a bit to a few main stages and a lot of similar actors. Some actors like the Hadoop ecosystem are quite old and ready to step off the stage and we can safely ignore it. Also, similarly simpler technologies like S3 trumps over more complex ones like Ceph. What Characteristics are we looking for in MLOps specific tools? Cloud-Native — The system should be designed for container and pod-based execution; and not retrofitted into working with Kubernetes. Example XCom of Airflow may not be the best for pipeline components (containers) to pass data -https://medium.com/the-prefect-blog/why-not-airflow-4cfa423299c4. Similar MLFlow could be containerized but may not be the best fit for Kubernetes based system. Open Source — We don’t want to be locked to a particular vendor if that can be helped. This takes out a lot of tools — Data management tools like Pachyderm Easy for ML Engineers to incorporate — There is a lot of work after creating a prototype Jupyter notebook for an ML problem to production. Still, we do not want our ML Engineers to know more about Kubernetes, Docker files and the like, than their business domain — Data Engineering, Model development and tuning. Scalable — This is a characteristic of Cloud-Native and Kubernetes based design. Things like distributed training and state-full load-balancing are very complex and we leave such things out for now. Before we go further it would be good to glance over the main phases of MLOps. The tools change with time and it is more subjective https://valohai.com/blog/the-mlops-stack/. There needs to be a good Data analysis tool or OLAP database. Something like Apache Presto; that can ingest data from multiple data stores or traditional databases. Something similar to Google BigQuery but in Opensource space. The data scientist or ML engineer can use a simple SQL type query to analyze vast amounts of data; this will be important for algorithm selection and further ML work. This is a whole infrastructure in itself, but actually can be kept out of MLOps as it comes more in the preview of (Big)Data Infrastructure. We can put this in the Data Engineering side and revisit this later in a future post. Sometimes the ML project could start with fewer data; but as data is collected and analyzed, and used for better training of the models, a scale-able data analytic system should be chosen. A snapshot of the eco-system here https://raw.githubusercontent.com/alexcpn/learnEvolve/master/mlflow.png Then there is Model Development Environment and related — Languages and Frameworks. For example python libraries like Pandas, Scikit Learn, and Programming languages -Python, R. ML frameworks like TensorFlow or PyTorch and data formats like the simple CSV or more efficient ones like Apache Parquet. This part ties itself to the development environment which is usually Jupyter Notebook. Whereas most data analytics are based on Python and its libraries, for things like Video analytics, it could be C++, Go and related libraries — GStreamer, OpenCV etc. This much would be clear to every practitioner. Now comes a part that does not seem so obvious at the beginning. Modular components tied through data flow graphs or Pipelines. This is where projects like Kubeflow fit in. Why is this needed? From Kubeflow site https://www.kubeflow.org/docs/about/kubeflow/#the-kubeflow-mission Our goal is to make scaling machine learning (ML) models and deploying them to production as simple as possible, by letting Kubernetes do what it’s great at: Easy, repeatable, portable deployments on a diverse infrastructure (for example, experimenting on a laptop, then moving to an on-premises cluster or to the cloud) Deploying and managing loosely-coupled microservices Scaling based on demand The first sentence says it all — Easy, repeatable and portable. So instead of creating a monolithic python code or notebook, we are splitting it into discreet components; and each task does one part, and these steps are portable -reusable in other projects. We are creating ML microservices and using a workflow scheduler to orchestrate the microservices together. This is one important part of the MLOps picture. Via Pipelines you are ensuring that a monolith is not formed. Here is a similar opinion from one of the maintainers of a similar stack https://towardsdatascience.com/why-ml-should-be-written-as-pipelines-from-the-get-go-b2d95003f998 Whether Kubeflow makes it Easy and Efficient to create such modular ML components we will see later. But yes it makes it Easy; though - Efficiency not so much, as all data between components are serialized and de-serialized via Python pickle mechanism to disk. So if you are writing out plain CSV instead of Apache Parquet format; or not using TFData or similar efficient data representation in your code; you could take a hit. It will not be too difficult to pass this through an interface mechanism like GRPC or REST, but Kubelow has to persist the In/Out data between components as artefacts. So it needs data to be stored as well. What else we need as essential for MLOps. Model Training — And tacking the training parameters. The real training is done by Model frameworks like Tensorflow, Pytorch etc; and there are more complex frameworks here like Horvod that does distributed training https://github.com/horovod/horovod using parallel programming frameworks like MPI or distributed Tensorflow based training using https://developer.nvidia.com/nccl. Note that for very Deep Neural Networks like the one used for Image or Video analytics; training will need an NVIDIA GPU with CUDA cores, while for data analytics CPU may be enough. Experiment Tracking — This could be useful to check historically the accuracy, precision, confusion matrix or similar metrics with the data and model and connected to Model Validation phase with the test set. Maybe more useful in the CI-CD pipeline for ML than in development. Model Serving — TFServing, Seldon, KFServing or the like. The main thing is to make sure that the model is separated from the application and it can be versioned and independently updated via CI/CD. Another thing to note is that usually lot of data needs to be passed to the model in case of use-cases such as media analytics. So the model and the business microservice should be colocated in the same Kubernetes node and scaled via a load balancing layer. Model Monitoring — In traditional DevOps, the feedback to Ops or Developers was via matrices collected from the deployment via Prometheus or a similar tool and displayed in Grafana dashboards. Similar could be used for Model monitoring also. However, to check if the model is accurate in prediction, there should be some manual checks or operator involvement or customer feedback incorporated in the predict — analyze loop. Or more advanced A/B test with other models and compare results using complex algorithms like Multi-Arm Bandit. Also validating the Model with newer data that is available is needed to detect Model Drift. Model monitoring is surely a higher level of MLOps proficiency, that would need very strong infrastructure to implement. Model, Data and Experimentation Sharing — You need to have a central, access-controlled sharing between different teams; For this, some model or data registry is needed. There are other parts which I have missed. Model Tuning could be one, where we have popular software like Optuna or Katib. There could be other important ones too, which I am not aware of now. Please indicate in the comments. Kubeflow is an umbrella project; There are multiple projects that are integrated with it, some for Visualization like Tensor Board, others for Optimization like Katib and then ML operators for training and serving etc. But what is primarily meant is the Kubeflow Pipeline. This is the core of the Kubeflow project and the Pipeline tasks integrate into various other Projects. Note that everything in Kubeflow is running on Kubernetes Cluster. Kubernetes is the resource supplier and execution engine. Kubeflow is based on Kubernetes. This is its strength. However, this means that everything internally has to run as Containers. However, exposing a ML Scientist or ML Engineer to the intricacies of creating a container image via Docker file and K8s deployment files are not optimal. Companies would have teams of engineers to do this. But is there a way that ML scientists or ML Engineer can be nudged to develop their ML program as discreet components without them having to understand too much Kubernetes or Container technology? As we described before, this is one main raison d’etre of Kubeflow. So, what we are going to do is to take a regular Jupyter Notebook based ML development and try to convert the same to a Kubeflow system but in a modular way. Here is the Colab project that we use for reference [1]https://colab.research.google.com/gist/alexcpn/fa8b3207fbc72f471bdb72433102344c/heartattack-prediction-tfdata.ipynb We will make this Jupyter Notebook, Kubeflow compliant. Installing Kubeflow Kubeflow uses the service mesh Istio. This means that it is a bit of a challenge to set this up. And this will be surely done by the ‘MLOps Team’. If you have a Linux based modern laptop; you can set this up using Kind cluster. Please follow this; if you already do not have a Kubeflow cluster ready https://gist.github.com/alexcpn/f7068ba5b7205e75b955404f2fc24427. Note that if you are using a GKE cluster do make sure your nodes have sufficient CPU and memory as there are resource requests set in the deployments. Also if you are planning to use GKE AutoPilot mode, at least for now it does not work as Istio is not supported. Note that we are using the manifest method of installing Kubeflow from the Kubeflow Manifests Repo -https://github.com/kubeflow/manifests Create a Jupyter Notebook If you have successfully installed Kubeflow, you will get a Jupyter Notebook in the Kubeflow dashboard -where most of the default ‘components’ can be viewed Let’s create a Jupyter Notebook instance; The following is used to connect to the Kubeflow Pipeline Server. We will use the `create_component_from_func_v2` SDK helper method to create a deployment out of our Python component Listing the python component here; Let’s see this component a bit more in detail. Creating a Component from Python function and Publishing it What we are doing above is pretty simple; Take in a URL and read some data using the Pandas library. If you see the original Colab Jupyter Notebook [1] you can see that we are splitting the reading part into a different function. This function has an Input that is a URL of type string. Since this is an in-built data structure in Python it can be provided as-is. We are going to output a Pandas Data-frame as output. Once we make this a component, it becomes a container Image and runs as a container in Docker. So all function input-output need to be via some interface. Kubeflow uses file interface -K8s persistent volume. Kubeflow (v1) has this InputPath and OuputPath components helper functions that take in the data and uses the Python pickle function to serialize to disk. Note that you can attach a PVC to the component and write to that. But this is against the Kubeflow usage principle; because of the moment you add a PVC the component no longer becomes non-re-usable. You may need to use such for external visualizations like Tensor-board visualization. Full code here https://colab.research.google.com/drive/1PyfLflTftWFSHkhWo5quFLonHcKeXc_c#scrollTo=d19ebe08-eb0d-4917-b3d1-8a7ddf448280 Snippet below: Let’s see how this component is created. As you can see the base image and the packages to install are given in the create_component_from_func method Rest is Kubeflow magic to create a Pod deployment out of it. You can see how the Input and Output are represented in this Kubeflow dashboard snapshot Note that I can also write this to a component and say put this in a component store and load from the component from the store I have just uploaded this to gist, and you can see that in the second snippet I am reading from the URL. Anyone who has access can re-use the same component for their flow, by changing the input data to their own. A similar flow is followed for other components. Wiring Components Together Now let’s see how the components are wired together. In the second snippet, you can see that read_data output is piped to the input of process_data Let’s see the magic that’s happening in the process_data function #Lets use output or target as preiction labeldef process_data( pandas_parquet: InputPath("PandasDataFrame"), out_train_path: OutputPath("TF_DataSet"), out_test_path: OutputPath("TF_DataSet"), out_validate_path:OutputPath("TF_DataSet") ): import pandas as pd import sklearn as sk import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.layers.experimental import preprocessing from sklearn.model_selection import train_test_split df = pd.read_parquet(pandas_parquet) We are reading in the Parquet file as input and converting to Pandas DataFrame. So yes — no magic; Similar you can see where we out a h5 Keras model in one component and read that in another. This is the trade-off that you make in having to split into different components. Maybe future versions of Kubeflow will give GRPC interfaces for some of these, which could speed things a bit. But then also this example is a toy example and you don’t have to slice everything into components. Visualization of the Data Flow Kubeflow provides an interactive drill-down visualization of the Data flow. If the Pods are still in Kubernetes you could see the Pod logs. T The Input/Output artefacts are persisted in the S3. Kubeflow by default runs a Minio based S3 bucket. You can access the Minio directly by port forwarding kubectl port-forward svc/minio-service -n kubeflow 9000:9000 default — minio/minio123 Sort of like a poor man's Artifact store. Note that you can also use this to output Tensor-board matrices; though I have not been able to connect the Tensorboard Pod running in the namespace to reach the S3 URL properly from the Dashboard UI. Visualization of Experiments The output of the Component in Kubeflow V1 Pipeline can be visualized from the Dashboard. However, it is not a very strong GUI as of now. In V2 version there seems to be better support of this; however, the version I have tested seems buggy (Kubeflow V2 is in Beta) And the output You can also compare between runs; on the matrices that you exposed Optimization There is an integration of Katib within Kubeflow; But one needs to specify the full YAML file -https://www.kubeflow.org/docs/components/katib/experiment/ with docker container and such. Unlike Optuna I guess Katib is Kubernetes first and hence the complexity.
[ { "code": null, "e": 512, "s": 171, "text": "When designing new technologies, almost always choices are made that would sacrifice some characteristic for some others. And it is important to understand those choices and how they may or may not affect your use case. Usually, such a study is never done when technology or framework is chosen over others; or sometimes there is no choice." }, { "code": null, "e": 879, "s": 512, "text": "For example, we have well-designed platforms like Kubernetes, that can’t be faulted by either the most technical; or the least. Though of course it is still evolving and there could be better solutions for things like hard multi-tenancy, these do not concern a general user very much now. It has become the de-facto execution engine for any cloud-native application." }, { "code": null, "e": 1300, "s": 879, "text": "This has induced a lot of changes in traditional software development. Instead of compiling the source code for one or more Operating Systems and creating an installer or packager for it; developers need to containerize their code and create the related artefacts — like Services, Config-maps, Secrets; Ingress and similar in a Kubernetes specific markup language (YAML). This has become common practice and routine now." }, { "code": null, "e": 1865, "s": 1300, "text": "For a developer; wrapping your micro-service in a container and deploying it in a pod; guarantees that it will perform the same; on any Kubernetes cluster with enough resources. One need not worry about the internal intricacy of pod networking or scheduling or Linux internals related to Control Groups or Namespaces or the like. Of course, that is a simplification; as if you are mounting a host volume and making an assumption of the underlying Linux OS and such, then such could break; but again these are outliers and not the way the technology has to be used." }, { "code": null, "e": 2460, "s": 1865, "text": "And that’s a good thing. You wish similar abstraction was there for other technologies; for example, databases; That without having an understanding of the internals of data storage; one can efficiently store and efficiently retrieve data. For example, a DB stored for fast access may not be good at fast updates; and it would be surprising to know that many developers will not be aware; till the feature requirements come mid-way exposing the hidden characteristic of the systems. Basically, the system starts behaving in an unexpected way, when it is used for a use-case it was designed for." }, { "code": null, "e": 2513, "s": 2460, "text": "How does all this factor in what we want to discuss?" }, { "code": null, "e": 2624, "s": 2513, "text": "What we are looking for in Kubeflow, is how non-leaky the abstraction is — to borrow a term from Joel Spolsky." }, { "code": null, "e": 2957, "s": 2624, "text": "What we are looking for in Kubeflow is how ‘Cloud Native’ it is — to borrow a widely used or misused cliche. Basically, execution is scheduled in Kubernetes cluster Edge Cluster or Data Center. This box is ticked as Kubeflow is designed for Kubernetes. Unlike say MLFlow — https://mlflow.org/. Other contenders TFX , ZenML as of now" }, { "code": null, "e": 3028, "s": 2957, "text": "Before we go into Kubeflow, let's check the environment where it fits." }, { "code": null, "e": 3128, "s": 3028, "text": "MLOps process should help in ensuring production quality is present and maintained for ML projects." }, { "code": null, "e": 3331, "s": 3128, "text": "Is it enough to make a container out of your ML project and deploy in on Kubernetes? Or are there other things that need to be taken care of ? How is CI done? How are tests executed? and test evaluated?" }, { "code": null, "e": 3442, "s": 3331, "text": "From a heavily over-quoted paper; it seems the ML code has the least significance when deployed in production." }, { "code": null, "e": 3586, "s": 3442, "text": "Example from this excellent blog → https://cloud.google.com/architecture/mlops-continuous-delivery-and-automation-pipelines-in-machine-learning" }, { "code": null, "e": 3702, "s": 3586, "text": "The authors may have exaggerated to get our attention to the rest of the system that we tend to miss; or maybe not." }, { "code": null, "e": 3909, "s": 3702, "text": "And the authors may be taking more about structured data and classical ML methodology that depends on Features; than unstructured data like say for Audio or Video or Image Analytics and Deep Neural Networks" }, { "code": null, "e": 4109, "s": 3909, "text": "MLOps - like DevOps, seems to be again a term that is used to mean a lot of different things to a lot of different people in a lot of different ways. We need to define what we mean when we say MLOps." }, { "code": null, "e": 4670, "s": 4109, "text": "DevOps generally have settled to represent the CI/CD part more -https://aws.amazon.com/devops/what-is-devops/; than the original concept of developers doing end to end development, deployment and operations of their components — the principle of more feedback between developers and their deployments. This could be like proactively checking the error logs from customer deployments for possible problems even before bugs are raised. It is surely more than just CI/CD; though it is also tied more to development and management culture than a technical process." }, { "code": null, "e": 4898, "s": 4670, "text": "It is not strange that you have a ‘DevOps’ team now in many companies that does this role, providing the tools and services for CI/CD, and tools and infrastructure for better feedback from deployments — monitoring, logging etc." }, { "code": null, "e": 5288, "s": 4898, "text": "MLOps — is similar to DevOps for micro-services. But this has more ML related aspects to it, over just the algorithm, like data and model management, model versioning, model drift etc. At least that’s the promise, and we have so many tools and services in this space, commercial and open-source that it is really easy to get confused and bogged down unless we have some selection criteria." }, { "code": null, "e": 5710, "s": 5288, "text": "Some idea you would get by browsing here or here; some authors referring to the proliferation as Cambrian explosion of MLOps projects. However, we could simplify this a bit to a few main stages and a lot of similar actors. Some actors like the Hadoop ecosystem are quite old and ready to step off the stage and we can safely ignore it. Also, similarly simpler technologies like S3 trumps over more complex ones like Ceph." }, { "code": null, "e": 5775, "s": 5710, "text": "What Characteristics are we looking for in MLOps specific tools?" }, { "code": null, "e": 6165, "s": 5775, "text": "Cloud-Native — The system should be designed for container and pod-based execution; and not retrofitted into working with Kubernetes. Example XCom of Airflow may not be the best for pipeline components (containers) to pass data -https://medium.com/the-prefect-blog/why-not-airflow-4cfa423299c4. Similar MLFlow could be containerized but may not be the best fit for Kubernetes based system." }, { "code": null, "e": 6321, "s": 6165, "text": "Open Source — We don’t want to be locked to a particular vendor if that can be helped. This takes out a lot of tools — Data management tools like Pachyderm" }, { "code": null, "e": 6634, "s": 6321, "text": "Easy for ML Engineers to incorporate — There is a lot of work after creating a prototype Jupyter notebook for an ML problem to production. Still, we do not want our ML Engineers to know more about Kubernetes, Docker files and the like, than their business domain — Data Engineering, Model development and tuning." }, { "code": null, "e": 6833, "s": 6634, "text": "Scalable — This is a characteristic of Cloud-Native and Kubernetes based design. Things like distributed training and state-full load-balancing are very complex and we leave such things out for now." }, { "code": null, "e": 7008, "s": 6833, "text": "Before we go further it would be good to glance over the main phases of MLOps. The tools change with time and it is more subjective https://valohai.com/blog/the-mlops-stack/." }, { "code": null, "e": 7402, "s": 7008, "text": "There needs to be a good Data analysis tool or OLAP database. Something like Apache Presto; that can ingest data from multiple data stores or traditional databases. Something similar to Google BigQuery but in Opensource space. The data scientist or ML engineer can use a simple SQL type query to analyze vast amounts of data; this will be important for algorithm selection and further ML work." }, { "code": null, "e": 7924, "s": 7402, "text": "This is a whole infrastructure in itself, but actually can be kept out of MLOps as it comes more in the preview of (Big)Data Infrastructure. We can put this in the Data Engineering side and revisit this later in a future post. Sometimes the ML project could start with fewer data; but as data is collected and analyzed, and used for better training of the models, a scale-able data analytic system should be chosen. A snapshot of the eco-system here https://raw.githubusercontent.com/alexcpn/learnEvolve/master/mlflow.png" }, { "code": null, "e": 8479, "s": 7924, "text": "Then there is Model Development Environment and related — Languages and Frameworks. For example python libraries like Pandas, Scikit Learn, and Programming languages -Python, R. ML frameworks like TensorFlow or PyTorch and data formats like the simple CSV or more efficient ones like Apache Parquet. This part ties itself to the development environment which is usually Jupyter Notebook. Whereas most data analytics are based on Python and its libraries, for things like Video analytics, it could be C++, Go and related libraries — GStreamer, OpenCV etc." }, { "code": null, "e": 8739, "s": 8479, "text": "This much would be clear to every practitioner. Now comes a part that does not seem so obvious at the beginning. Modular components tied through data flow graphs or Pipelines. This is where projects like Kubeflow fit in. Why is this needed? From Kubeflow site" }, { "code": null, "e": 8806, "s": 8739, "text": "https://www.kubeflow.org/docs/about/kubeflow/#the-kubeflow-mission" }, { "code": null, "e": 8964, "s": 8806, "text": "Our goal is to make scaling machine learning (ML) models and deploying them to production as simple as possible, by letting Kubernetes do what it’s great at:" }, { "code": null, "e": 9127, "s": 8964, "text": "Easy, repeatable, portable deployments on a diverse infrastructure (for example, experimenting on a laptop, then moving to an on-premises cluster or to the cloud)" }, { "code": null, "e": 9180, "s": 9127, "text": "Deploying and managing loosely-coupled microservices" }, { "code": null, "e": 9204, "s": 9180, "text": "Scaling based on demand" }, { "code": null, "e": 9569, "s": 9204, "text": "The first sentence says it all — Easy, repeatable and portable. So instead of creating a monolithic python code or notebook, we are splitting it into discreet components; and each task does one part, and these steps are portable -reusable in other projects. We are creating ML microservices and using a workflow scheduler to orchestrate the microservices together." }, { "code": null, "e": 9851, "s": 9569, "text": "This is one important part of the MLOps picture. Via Pipelines you are ensuring that a monolith is not formed. Here is a similar opinion from one of the maintainers of a similar stack https://towardsdatascience.com/why-ml-should-be-written-as-pipelines-from-the-get-go-b2d95003f998" }, { "code": null, "e": 10486, "s": 9851, "text": "Whether Kubeflow makes it Easy and Efficient to create such modular ML components we will see later. But yes it makes it Easy; though - Efficiency not so much, as all data between components are serialized and de-serialized via Python pickle mechanism to disk. So if you are writing out plain CSV instead of Apache Parquet format; or not using TFData or similar efficient data representation in your code; you could take a hit. It will not be too difficult to pass this through an interface mechanism like GRPC or REST, but Kubelow has to persist the In/Out data between components as artefacts. So it needs data to be stored as well." }, { "code": null, "e": 10528, "s": 10486, "text": "What else we need as essential for MLOps." }, { "code": null, "e": 11090, "s": 10528, "text": "Model Training — And tacking the training parameters. The real training is done by Model frameworks like Tensorflow, Pytorch etc; and there are more complex frameworks here like Horvod that does distributed training https://github.com/horovod/horovod using parallel programming frameworks like MPI or distributed Tensorflow based training using https://developer.nvidia.com/nccl. Note that for very Deep Neural Networks like the one used for Image or Video analytics; training will need an NVIDIA GPU with CUDA cores, while for data analytics CPU may be enough." }, { "code": null, "e": 11367, "s": 11090, "text": "Experiment Tracking — This could be useful to check historically the accuracy, precision, confusion matrix or similar metrics with the data and model and connected to Model Validation phase with the test set. Maybe more useful in the CI-CD pipeline for ML than in development." }, { "code": null, "e": 11824, "s": 11367, "text": "Model Serving — TFServing, Seldon, KFServing or the like. The main thing is to make sure that the model is separated from the application and it can be versioned and independently updated via CI/CD. Another thing to note is that usually lot of data needs to be passed to the model in case of use-cases such as media analytics. So the model and the business microservice should be colocated in the same Kubernetes node and scaled via a load balancing layer." }, { "code": null, "e": 12574, "s": 11824, "text": "Model Monitoring — In traditional DevOps, the feedback to Ops or Developers was via matrices collected from the deployment via Prometheus or a similar tool and displayed in Grafana dashboards. Similar could be used for Model monitoring also. However, to check if the model is accurate in prediction, there should be some manual checks or operator involvement or customer feedback incorporated in the predict — analyze loop. Or more advanced A/B test with other models and compare results using complex algorithms like Multi-Arm Bandit. Also validating the Model with newer data that is available is needed to detect Model Drift. Model monitoring is surely a higher level of MLOps proficiency, that would need very strong infrastructure to implement." }, { "code": null, "e": 12744, "s": 12574, "text": "Model, Data and Experimentation Sharing — You need to have a central, access-controlled sharing between different teams; For this, some model or data registry is needed." }, { "code": null, "e": 12970, "s": 12744, "text": "There are other parts which I have missed. Model Tuning could be one, where we have popular software like Optuna or Katib. There could be other important ones too, which I am not aware of now. Please indicate in the comments." }, { "code": null, "e": 13471, "s": 12970, "text": "Kubeflow is an umbrella project; There are multiple projects that are integrated with it, some for Visualization like Tensor Board, others for Optimization like Katib and then ML operators for training and serving etc. But what is primarily meant is the Kubeflow Pipeline. This is the core of the Kubeflow project and the Pipeline tasks integrate into various other Projects. Note that everything in Kubeflow is running on Kubernetes Cluster. Kubernetes is the resource supplier and execution engine." }, { "code": null, "e": 13599, "s": 13471, "text": "Kubeflow is based on Kubernetes. This is its strength. However, this means that everything internally has to run as Containers." }, { "code": null, "e": 14071, "s": 13599, "text": "However, exposing a ML Scientist or ML Engineer to the intricacies of creating a container image via Docker file and K8s deployment files are not optimal. Companies would have teams of engineers to do this. But is there a way that ML scientists or ML Engineer can be nudged to develop their ML program as discreet components without them having to understand too much Kubernetes or Container technology? As we described before, this is one main raison d’etre of Kubeflow." }, { "code": null, "e": 14229, "s": 14071, "text": "So, what we are going to do is to take a regular Jupyter Notebook based ML development and try to convert the same to a Kubeflow system but in a modular way." }, { "code": null, "e": 14400, "s": 14229, "text": "Here is the Colab project that we use for reference [1]https://colab.research.google.com/gist/alexcpn/fa8b3207fbc72f471bdb72433102344c/heartattack-prediction-tfdata.ipynb" }, { "code": null, "e": 14456, "s": 14400, "text": "We will make this Jupyter Notebook, Kubeflow compliant." }, { "code": null, "e": 14476, "s": 14456, "text": "Installing Kubeflow" }, { "code": null, "e": 14704, "s": 14476, "text": "Kubeflow uses the service mesh Istio. This means that it is a bit of a challenge to set this up. And this will be surely done by the ‘MLOps Team’. If you have a Linux based modern laptop; you can set this up using Kind cluster." }, { "code": null, "e": 14842, "s": 14704, "text": "Please follow this; if you already do not have a Kubeflow cluster ready https://gist.github.com/alexcpn/f7068ba5b7205e75b955404f2fc24427." }, { "code": null, "e": 15106, "s": 14842, "text": "Note that if you are using a GKE cluster do make sure your nodes have sufficient CPU and memory as there are resource requests set in the deployments. Also if you are planning to use GKE AutoPilot mode, at least for now it does not work as Istio is not supported." }, { "code": null, "e": 15244, "s": 15106, "text": "Note that we are using the manifest method of installing Kubeflow from the Kubeflow Manifests Repo -https://github.com/kubeflow/manifests" }, { "code": null, "e": 15270, "s": 15244, "text": "Create a Jupyter Notebook" }, { "code": null, "e": 15427, "s": 15270, "text": "If you have successfully installed Kubeflow, you will get a Jupyter Notebook in the Kubeflow dashboard -where most of the default ‘components’ can be viewed" }, { "code": null, "e": 15535, "s": 15427, "text": "Let’s create a Jupyter Notebook instance; The following is used to connect to the Kubeflow Pipeline Server." }, { "code": null, "e": 15652, "s": 15535, "text": "We will use the `create_component_from_func_v2` SDK helper method to create a deployment out of our Python component" }, { "code": null, "e": 15687, "s": 15652, "text": "Listing the python component here;" }, { "code": null, "e": 15734, "s": 15687, "text": "Let’s see this component a bit more in detail." }, { "code": null, "e": 15794, "s": 15734, "text": "Creating a Component from Python function and Publishing it" }, { "code": null, "e": 16024, "s": 15794, "text": "What we are doing above is pretty simple; Take in a URL and read some data using the Pandas library. If you see the original Colab Jupyter Notebook [1] you can see that we are splitting the reading part into a different function." }, { "code": null, "e": 16212, "s": 16024, "text": "This function has an Input that is a URL of type string. Since this is an in-built data structure in Python it can be provided as-is. We are going to output a Pandas Data-frame as output." }, { "code": null, "e": 16575, "s": 16212, "text": "Once we make this a component, it becomes a container Image and runs as a container in Docker. So all function input-output need to be via some interface. Kubeflow uses file interface -K8s persistent volume. Kubeflow (v1) has this InputPath and OuputPath components helper functions that take in the data and uses the Python pickle function to serialize to disk." }, { "code": null, "e": 16861, "s": 16575, "text": "Note that you can attach a PVC to the component and write to that. But this is against the Kubeflow usage principle; because of the moment you add a PVC the component no longer becomes non-re-usable. You may need to use such for external visualizations like Tensor-board visualization." }, { "code": null, "e": 16996, "s": 16861, "text": "Full code here https://colab.research.google.com/drive/1PyfLflTftWFSHkhWo5quFLonHcKeXc_c#scrollTo=d19ebe08-eb0d-4917-b3d1-8a7ddf448280" }, { "code": null, "e": 17011, "s": 16996, "text": "Snippet below:" }, { "code": null, "e": 17222, "s": 17011, "text": "Let’s see how this component is created. As you can see the base image and the packages to install are given in the create_component_from_func method Rest is Kubeflow magic to create a Pod deployment out of it." }, { "code": null, "e": 17311, "s": 17222, "text": "You can see how the Input and Output are represented in this Kubeflow dashboard snapshot" }, { "code": null, "e": 17439, "s": 17311, "text": "Note that I can also write this to a component and say put this in a component store and load from the component from the store" }, { "code": null, "e": 17653, "s": 17439, "text": "I have just uploaded this to gist, and you can see that in the second snippet I am reading from the URL. Anyone who has access can re-use the same component for their flow, by changing the input data to their own." }, { "code": null, "e": 17702, "s": 17653, "text": "A similar flow is followed for other components." }, { "code": null, "e": 17729, "s": 17702, "text": "Wiring Components Together" }, { "code": null, "e": 17782, "s": 17729, "text": "Now let’s see how the components are wired together." }, { "code": null, "e": 17877, "s": 17782, "text": "In the second snippet, you can see that read_data output is piped to the input of process_data" }, { "code": null, "e": 17943, "s": 17877, "text": "Let’s see the magic that’s happening in the process_data function" }, { "code": null, "e": 18580, "s": 17943, "text": "#Lets use output or target as preiction labeldef process_data( pandas_parquet: InputPath(\"PandasDataFrame\"), out_train_path: OutputPath(\"TF_DataSet\"), out_test_path: OutputPath(\"TF_DataSet\"), out_validate_path:OutputPath(\"TF_DataSet\") ): import pandas as pd import sklearn as sk import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.layers.experimental import preprocessing from sklearn.model_selection import train_test_split df = pd.read_parquet(pandas_parquet)" }, { "code": null, "e": 18772, "s": 18580, "text": "We are reading in the Parquet file as input and converting to Pandas DataFrame. So yes — no magic; Similar you can see where we out a h5 Keras model in one component and read that in another." }, { "code": null, "e": 19065, "s": 18772, "text": "This is the trade-off that you make in having to split into different components. Maybe future versions of Kubeflow will give GRPC interfaces for some of these, which could speed things a bit. But then also this example is a toy example and you don’t have to slice everything into components." }, { "code": null, "e": 19096, "s": 19065, "text": "Visualization of the Data Flow" }, { "code": null, "e": 19238, "s": 19096, "text": "Kubeflow provides an interactive drill-down visualization of the Data flow. If the Pods are still in Kubernetes you could see the Pod logs. T" }, { "code": null, "e": 19340, "s": 19238, "text": "The Input/Output artefacts are persisted in the S3. Kubeflow by default runs a Minio based S3 bucket." }, { "code": null, "e": 19393, "s": 19340, "text": "You can access the Minio directly by port forwarding" }, { "code": null, "e": 19455, "s": 19393, "text": "kubectl port-forward svc/minio-service -n kubeflow 9000:9000" }, { "code": null, "e": 19480, "s": 19455, "text": "default — minio/minio123" }, { "code": null, "e": 19723, "s": 19480, "text": "Sort of like a poor man's Artifact store. Note that you can also use this to output Tensor-board matrices; though I have not been able to connect the Tensorboard Pod running in the namespace to reach the S3 URL properly from the Dashboard UI." }, { "code": null, "e": 19752, "s": 19723, "text": "Visualization of Experiments" }, { "code": null, "e": 20018, "s": 19752, "text": "The output of the Component in Kubeflow V1 Pipeline can be visualized from the Dashboard. However, it is not a very strong GUI as of now. In V2 version there seems to be better support of this; however, the version I have tested seems buggy (Kubeflow V2 is in Beta)" }, { "code": null, "e": 20033, "s": 20018, "text": "And the output" }, { "code": null, "e": 20101, "s": 20033, "text": "You can also compare between runs; on the matrices that you exposed" }, { "code": null, "e": 20114, "s": 20101, "text": "Optimization" } ]
C++ Program to Perform Addition Operation Using Bitwise Operators
Bitwise operators are used to perform bitwise operations. That implies the manipulation of bits. Some of the bitwise operators are bitwise AND, bitwise OR, bitwise XOR etc. A program to perform addition operation using bitwise operators is given below − Live Demo #include<iostream> using namespace std; int main() { int num1, num2, carry; cout << "Enter first number:"<<endl; cin >> num1; cout << "Enter second number:"<<endl; cin >> num2; while (num2 != 0) { carry = num1 & num2; num1 = num1 ^ num2; num2 = carry << 1; } cout << "The Sum is: " << num1; return 0; } The output of the above program is as follows − Enter first number:11 Enter second number: 5 The Sum is: 16 In the above program, the two numbers are obtained from the user. This is given below − cout << "Enter first number:"<<endl; cin >> num1; cout << "Enter second number:"<<endl; cin >> num2; After that, addition is carried out using a while loop. It involves using the bitwise AND, bitwise XOR and left shift operators. The code snippet is given below − while (num2 != 0) { carry = num1 & num2; num1 = num1 ^ num2; num2 = carry << 1; } Finally, the sum is displayed. This is given below − cout << "The Sum is: " << num1;
[ { "code": null, "e": 1235, "s": 1062, "text": "Bitwise operators are used to perform bitwise operations. That implies the manipulation of bits. Some of the bitwise operators are bitwise AND, bitwise OR, bitwise XOR etc." }, { "code": null, "e": 1316, "s": 1235, "text": "A program to perform addition operation using bitwise operators is given below −" }, { "code": null, "e": 1327, "s": 1316, "text": " Live Demo" }, { "code": null, "e": 1676, "s": 1327, "text": "#include<iostream>\nusing namespace std;\nint main() {\n int num1, num2, carry;\n cout << \"Enter first number:\"<<endl;\n cin >> num1;\n cout << \"Enter second number:\"<<endl;\n cin >> num2;\n\n while (num2 != 0) {\n carry = num1 & num2;\n num1 = num1 ^ num2;\n num2 = carry << 1;\n }\n cout << \"The Sum is: \" << num1;\n return 0;\n}" }, { "code": null, "e": 1724, "s": 1676, "text": "The output of the above program is as follows −" }, { "code": null, "e": 1784, "s": 1724, "text": "Enter first number:11\nEnter second number: 5\nThe Sum is: 16" }, { "code": null, "e": 1872, "s": 1784, "text": "In the above program, the two numbers are obtained from the user. This is given below −" }, { "code": null, "e": 1974, "s": 1872, "text": "cout << \"Enter first number:\"<<endl;\ncin >> num1;\n\ncout << \"Enter second number:\"<<endl;\ncin >> num2;" }, { "code": null, "e": 2137, "s": 1974, "text": "After that, addition is carried out using a while loop. It involves using the bitwise AND, bitwise XOR and left shift operators. The code snippet is given below −" }, { "code": null, "e": 2228, "s": 2137, "text": "while (num2 != 0) {\n carry = num1 & num2;\n num1 = num1 ^ num2;\n num2 = carry << 1;\n}" }, { "code": null, "e": 2281, "s": 2228, "text": "Finally, the sum is displayed. This is given below −" }, { "code": null, "e": 2313, "s": 2281, "text": "cout << \"The Sum is: \" << num1;" } ]
Docker for Python Development?. Experimenting, Developing and Deploying... | by Chinmay Shah | Towards Data Science
Part 1 covered what is docker. In this article, we’ll be talking about how to start using Docker for python development. A standard python installation involves setting up environment variables and if you’re dealing with different versions of python, there are tons of environment variables to be dealt with be it Windows or Linux. And if you’re dealing with production where you’re very particular about the python version, you need to make sure your program is tested on this version and there are no additional as well as missing dependencies which you might a have taken granted on your local system. Dealing with Python 2 and 3 simultaneously is still manageable, but think if you have to deal with python 3.6 installed and need to try out python 3.7. Changing the python version is as simple as FROM python:3.6.7 to FROM python:3.7. Docker not only allows to do quick experimentation but also helps restrict to particular package version that is required to maintain stability. Think of it as a virtual environment in Anaconda. But, when you have Anaconda configured, most of the packages are already pre-installed on the system and when you’ll try to deploy it, you might just take them for granted. Additionally, Anaconda for python 3.7 takes up more than 3GB on disk space. On the other hand, docker image hardly takes a gigabyte. Decide the python version you need and if you’re just looking for the latest version, just write python:latest . The way images are usually named image_name:tag which needs to be provided when you build an image using docker build -t image_name:tag . . If you don’t provide any tag during the build, docker automatically assigns it latest. On docker hub, Python offers different images to choose from an Alpine version which is a very minimal image to a full version. # Python 3.6.7FROM python:3.6.7-alpine3.6# author of fileLABEL maintainer=”Chinmay Shah <[email protected]>” RUN — This instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile , usually in shell form, unless specified otherwise. # Packages that we need COPY requirement.txt /app/WORKDIR /app# instruction to be run during image buildRUN pip install -r requirement.txt# Copy all the files from current source duirectory(from your system) to# Docker container in /app directory COPY . /app You might notice that in we’re copying the requirement.txt twice. It’s for build optimization. Each line in Dockerfile is executed as a separate step and creates a new container. This is highly inefficient because you don’t always want to start rebuilding everything from scratch during every build command. To deal with that, Docker uses something known as Layer caching, which is a fancy way of saying, rather than re-creating a container each time, it re-uses a container previously created in the previous build and stores it. So unless you make a change in a previous step, the build process can re-use the old container. The idea is that requirement will hardly change, but the code will often, thus using cache is a better way, rather than downloading requirement packages each time image is built. Note that each line in dockerfile is a separate step but also, each step has a unique alphanumeric name attached to it. ENTRYPOINT — specifies a command that will always be executed when the container starts. CMD — Specifies arguments that will be fed to the ENTRYPOINT. It is used when you want to run a container as an executable. Without entrypoint, the default argument is a command that is executed. With entrypoint, CMD is passed to entrypoint as the argument. More about it here. # Specifies a command that will always be executed when the # container starts.# In this case we want to start the python interpreterENTRYPOINT [“python”]# We want to start app.py file. (change it with your file name) # Argument to python commandCMD [“app.py”] Building the file: docker build -t python:test . Starting the container using a cmd or bash: docker run — rm -it -v /c/Users/chinm/Desktop/python_run:/teste pythontest:alpine -v or --volume is used to attach a volume. What is volume? Volumes are the preferred mechanism for persisting data generated by and used by Docker containers. They are completely managed by Docker. To connect a directory to a Docker container: -v source_on_local_machine:destination_on_docker_container If you want to create a volume so that it can be accessed across different docker containers, creating a docker volume would be a way to go. More about it here. If you’re trying to use Python for DataScience, you’ll probably use volume so that you can share the raw data with the container, do some operations on it, and write the cleaned data back to the host machine. Note: If you’re using docker using Docker Toolbox, the -v will map your container to VM, which has your local machine’s C directory mapped, thus making it difficult to use your other logical drives as volumes on docker. I hope you’re equipped with the basic knowledge to get started with Python on docker. Happy Hacking! Feel free to reach out on Twitter, Linkedin or E-Mail.
[ { "code": null, "e": 203, "s": 172, "text": "Part 1 covered what is docker." }, { "code": null, "e": 293, "s": 203, "text": "In this article, we’ll be talking about how to start using Docker for python development." }, { "code": null, "e": 504, "s": 293, "text": "A standard python installation involves setting up environment variables and if you’re dealing with different versions of python, there are tons of environment variables to be dealt with be it Windows or Linux." }, { "code": null, "e": 777, "s": 504, "text": "And if you’re dealing with production where you’re very particular about the python version, you need to make sure your program is tested on this version and there are no additional as well as missing dependencies which you might a have taken granted on your local system." }, { "code": null, "e": 929, "s": 777, "text": "Dealing with Python 2 and 3 simultaneously is still manageable, but think if you have to deal with python 3.6 installed and need to try out python 3.7." }, { "code": null, "e": 1011, "s": 929, "text": "Changing the python version is as simple as FROM python:3.6.7 to FROM python:3.7." }, { "code": null, "e": 1156, "s": 1011, "text": "Docker not only allows to do quick experimentation but also helps restrict to particular package version that is required to maintain stability." }, { "code": null, "e": 1206, "s": 1156, "text": "Think of it as a virtual environment in Anaconda." }, { "code": null, "e": 1379, "s": 1206, "text": "But, when you have Anaconda configured, most of the packages are already pre-installed on the system and when you’ll try to deploy it, you might just take them for granted." }, { "code": null, "e": 1455, "s": 1379, "text": "Additionally, Anaconda for python 3.7 takes up more than 3GB on disk space." }, { "code": null, "e": 1512, "s": 1455, "text": "On the other hand, docker image hardly takes a gigabyte." }, { "code": null, "e": 1625, "s": 1512, "text": "Decide the python version you need and if you’re just looking for the latest version, just write python:latest ." }, { "code": null, "e": 1852, "s": 1625, "text": "The way images are usually named image_name:tag which needs to be provided when you build an image using docker build -t image_name:tag . . If you don’t provide any tag during the build, docker automatically assigns it latest." }, { "code": null, "e": 1980, "s": 1852, "text": "On docker hub, Python offers different images to choose from an Alpine version which is a very minimal image to a full version." }, { "code": null, "e": 2097, "s": 1980, "text": "# Python 3.6.7FROM python:3.6.7-alpine3.6# author of fileLABEL maintainer=”Chinmay Shah <[email protected]>”" }, { "code": null, "e": 2345, "s": 2097, "text": "RUN — This instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile , usually in shell form, unless specified otherwise." }, { "code": null, "e": 2604, "s": 2345, "text": "# Packages that we need COPY requirement.txt /app/WORKDIR /app# instruction to be run during image buildRUN pip install -r requirement.txt# Copy all the files from current source duirectory(from your system) to# Docker container in /app directory COPY . /app" }, { "code": null, "e": 2699, "s": 2604, "text": "You might notice that in we’re copying the requirement.txt twice. It’s for build optimization." }, { "code": null, "e": 2783, "s": 2699, "text": "Each line in Dockerfile is executed as a separate step and creates a new container." }, { "code": null, "e": 2912, "s": 2783, "text": "This is highly inefficient because you don’t always want to start rebuilding everything from scratch during every build command." }, { "code": null, "e": 3231, "s": 2912, "text": "To deal with that, Docker uses something known as Layer caching, which is a fancy way of saying, rather than re-creating a container each time, it re-uses a container previously created in the previous build and stores it. So unless you make a change in a previous step, the build process can re-use the old container." }, { "code": null, "e": 3410, "s": 3231, "text": "The idea is that requirement will hardly change, but the code will often, thus using cache is a better way, rather than downloading requirement packages each time image is built." }, { "code": null, "e": 3530, "s": 3410, "text": "Note that each line in dockerfile is a separate step but also, each step has a unique alphanumeric name attached to it." }, { "code": null, "e": 3619, "s": 3530, "text": "ENTRYPOINT — specifies a command that will always be executed when the container starts." }, { "code": null, "e": 3743, "s": 3619, "text": "CMD — Specifies arguments that will be fed to the ENTRYPOINT. It is used when you want to run a container as an executable." }, { "code": null, "e": 3815, "s": 3743, "text": "Without entrypoint, the default argument is a command that is executed." }, { "code": null, "e": 3877, "s": 3815, "text": "With entrypoint, CMD is passed to entrypoint as the argument." }, { "code": null, "e": 3897, "s": 3877, "text": "More about it here." }, { "code": null, "e": 4159, "s": 3897, "text": "# Specifies a command that will always be executed when the # container starts.# In this case we want to start the python interpreterENTRYPOINT [“python”]# We want to start app.py file. (change it with your file name) # Argument to python commandCMD [“app.py”]" }, { "code": null, "e": 4178, "s": 4159, "text": "Building the file:" }, { "code": null, "e": 4208, "s": 4178, "text": "docker build -t python:test ." }, { "code": null, "e": 4252, "s": 4208, "text": "Starting the container using a cmd or bash:" }, { "code": null, "e": 4334, "s": 4252, "text": "docker run — rm -it -v /c/Users/chinm/Desktop/python_run:/teste pythontest:alpine" }, { "code": null, "e": 4377, "s": 4334, "text": "-v or --volume is used to attach a volume." }, { "code": null, "e": 4393, "s": 4377, "text": "What is volume?" }, { "code": null, "e": 4532, "s": 4393, "text": "Volumes are the preferred mechanism for persisting data generated by and used by Docker containers. They are completely managed by Docker." }, { "code": null, "e": 4578, "s": 4532, "text": "To connect a directory to a Docker container:" }, { "code": null, "e": 4637, "s": 4578, "text": "-v source_on_local_machine:destination_on_docker_container" }, { "code": null, "e": 4798, "s": 4637, "text": "If you want to create a volume so that it can be accessed across different docker containers, creating a docker volume would be a way to go. More about it here." }, { "code": null, "e": 5007, "s": 4798, "text": "If you’re trying to use Python for DataScience, you’ll probably use volume so that you can share the raw data with the container, do some operations on it, and write the cleaned data back to the host machine." }, { "code": null, "e": 5227, "s": 5007, "text": "Note: If you’re using docker using Docker Toolbox, the -v will map your container to VM, which has your local machine’s C directory mapped, thus making it difficult to use your other logical drives as volumes on docker." }, { "code": null, "e": 5328, "s": 5227, "text": "I hope you’re equipped with the basic knowledge to get started with Python on docker. Happy Hacking!" } ]
Kth Largest Element in a Stream in Python
Suppose we want to design a class to find the kth largest element in a stream. It is the kth largest element in the sorted order, not the kth distinct element. The KthLargest class will have a constructor which accepts an integer k and an array nums, that will contain initial elements from the stream. For each call to the method KthLargest.add, will return the element representing the kth largest element in the stream. So, if the input is like k = 3, initial elements = [4,5,8,2], then call add(3), add(5), add(10), add(9), add(4). , then the output will be 4,5,5,8,8 respectively. To solve this, we will follow these steps − Define the initializer, This will take k, numsarray := nums array := nums Define a function add() . This will take valinsert val at the end of arraysort the arrayreturn array[size of array -k] insert val at the end of array sort the array return array[size of array -k] Let us see the following implementation to get better understanding − Live Demo class KthLargest: def __init__(self, k, nums): self.array = nums self.k = k def add(self, val): self.array.append(val) self.array.sort() return self.array[len(self.array)-self.k] ob = KthLargest(3, [4,5,8,2]) print(ob.add(3)) print(ob.add(5)) print(ob.add(10)) print(ob.add(9)) print(ob.add(4)) ob.add(3) ob.add(5) ob.add(10) ob.add(9) ob.add(4) 4 5 5 8 8
[ { "code": null, "e": 1222, "s": 1062, "text": "Suppose we want to design a class to find the kth largest element in a stream. It is the kth largest element in the sorted order, not the kth distinct element." }, { "code": null, "e": 1485, "s": 1222, "text": "The KthLargest class will have a constructor which accepts an integer k and an array nums, that will contain initial elements from the stream. For each call to the method KthLargest.add, will return the element representing the kth largest element in the stream." }, { "code": null, "e": 1648, "s": 1485, "text": "So, if the input is like k = 3, initial elements = [4,5,8,2], then call add(3), add(5), add(10), add(9), add(4). , then the output will be 4,5,5,8,8 respectively." }, { "code": null, "e": 1692, "s": 1648, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1752, "s": 1692, "text": "Define the initializer, This will take k, numsarray := nums" }, { "code": null, "e": 1766, "s": 1752, "text": "array := nums" }, { "code": null, "e": 1885, "s": 1766, "text": "Define a function add() . This will take valinsert val at the end of arraysort the arrayreturn array[size of array -k]" }, { "code": null, "e": 1916, "s": 1885, "text": "insert val at the end of array" }, { "code": null, "e": 1931, "s": 1916, "text": "sort the array" }, { "code": null, "e": 1962, "s": 1931, "text": "return array[size of array -k]" }, { "code": null, "e": 2032, "s": 1962, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2043, "s": 2032, "text": " Live Demo" }, { "code": null, "e": 2374, "s": 2043, "text": "class KthLargest:\n def __init__(self, k, nums):\n self.array = nums\n self.k = k\n def add(self, val):\n self.array.append(val)\n self.array.sort()\n return self.array[len(self.array)-self.k]\nob = KthLargest(3, [4,5,8,2])\nprint(ob.add(3))\nprint(ob.add(5))\nprint(ob.add(10))\nprint(ob.add(9))\nprint(ob.add(4))" }, { "code": null, "e": 2425, "s": 2374, "text": "ob.add(3)\nob.add(5)\nob.add(10)\nob.add(9)\nob.add(4)" }, { "code": null, "e": 2435, "s": 2425, "text": "4\n5\n5\n8\n8" } ]
C++ Queue Library - front() Function
The C++ function std::queue::front() returns a reference to the first element of the queue. This element will be removed after performing pop operation on queue. This member function effectively calls the front member function of underlying container. Following is the declaration for std::queue::front() function form std::queue header. value_type& front(); const value_type& front() const; reference& front(); const_reference& front() const; None Returns reference to the first element of the queue. Constant i.e. O(1) The following example shows the usage of std::queue::front() function. #include <iostream> #include <queue> using namespace std; int main(void) { queue<int> q; for (int i = 0; i < 5; ++i) q.emplace(i + 1); cout << "First element of queue = " << q.front() << endl; return 0; } Let us compile and run the above program, this will produce the following result − First element of queue = 1 Print Add Notes Bookmark this page
[ { "code": null, "e": 2766, "s": 2603, "text": "The C++ function std::queue::front() returns a reference to the first element of the queue. This element will be removed after performing pop operation on queue." }, { "code": null, "e": 2856, "s": 2766, "text": "This member function effectively calls the front member function of underlying container." }, { "code": null, "e": 2942, "s": 2856, "text": "Following is the declaration for std::queue::front() function form std::queue header." }, { "code": null, "e": 2997, "s": 2942, "text": "value_type& front();\nconst value_type& front() const;\n" }, { "code": null, "e": 3050, "s": 2997, "text": "reference& front();\nconst_reference& front() const;\n" }, { "code": null, "e": 3055, "s": 3050, "text": "None" }, { "code": null, "e": 3108, "s": 3055, "text": "Returns reference to the first element of the queue." }, { "code": null, "e": 3127, "s": 3108, "text": "Constant i.e. O(1)" }, { "code": null, "e": 3198, "s": 3127, "text": "The following example shows the usage of std::queue::front() function." }, { "code": null, "e": 3426, "s": 3198, "text": "#include <iostream>\n#include <queue>\n\nusing namespace std;\n\nint main(void) {\n queue<int> q;\n\n for (int i = 0; i < 5; ++i)\n q.emplace(i + 1);\n\n cout << \"First element of queue = \" << q.front() << endl;\n\n return 0;\n}" }, { "code": null, "e": 3509, "s": 3426, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3537, "s": 3509, "text": "First element of queue = 1\n" }, { "code": null, "e": 3544, "s": 3537, "text": " Print" }, { "code": null, "e": 3555, "s": 3544, "text": " Add Notes" } ]
How to write a jQuery selector to find links with # in href attribute?
You can try to run the following code to write a jQuery selector to find links with # in href. Here,^ is used to find links starting with # in href. Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $('a[href^="#"]').click(function(){ alert('Success! Selected link starting with # in href.'); }); }); </script> </head> <body> <a href="#demo" title="new" >Demo</a><br> <a href="/cplusplus/" title="C++ Tutorial" >C++</a> </body> </html>
[ { "code": null, "e": 1211, "s": 1062, "text": "You can try to run the following code to write a jQuery selector to find links with # in href. Here,^ is used to find links starting with # in href." }, { "code": null, "e": 1221, "s": 1211, "text": "Live Demo" }, { "code": null, "e": 1632, "s": 1221, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n\n $('a[href^=\"#\"]').click(function(){\n alert('Success! Selected link starting with # in href.');\n });\n\n});\n</script>\n</head>\n<body>\n\n<a href=\"#demo\" title=\"new\" >Demo</a><br>\n<a href=\"/cplusplus/\" title=\"C++ Tutorial\" >C++</a>\n\n</body>\n</html>" } ]
Entity Framework - Lifecycle
The lifetime of a context begins when the instance is created and ends when the instance is either disposed or garbage-collected. Context lifetime is a very crucial decision to make when we use ORMs. Context lifetime is a very crucial decision to make when we use ORMs. The context is performing like an entity cache, so it means it holds references to all the loaded entities which may grow very fast in memory consumption and it can also cause memory leaks. The context is performing like an entity cache, so it means it holds references to all the loaded entities which may grow very fast in memory consumption and it can also cause memory leaks. In the below diagram, you can see the upper level of data workflow from application to database via Context and vice versa. In the below diagram, you can see the upper level of data workflow from application to database via Context and vice versa. The Entity Lifecycle describes the process in which an Entity is created, added, modified, deleted, etc. Entities have many states during its lifetime. Before looking at how to retrieve entity state, let’s take a look at what is entity state. The state is an enum of type System.Data.EntityState that declares the following values − Added: The entity is marked as added. Added: The entity is marked as added. Deleted: The entity is marked as deleted. Deleted: The entity is marked as deleted. Modified: The entity has been modified. Modified: The entity has been modified. Unchanged: The entity hasn’t been modified. Unchanged: The entity hasn’t been modified. Detached: The entity isn’t tracked. Detached: The entity isn’t tracked. Sometimes state of entities are set automatically by the context, but it can also be modified manually by the developer. Even though all the combinations of switches from one state to another are possible, but some of them are meaningless. For example, Added entity to the Deleted state, or vice versa. Let’s discuss about different states. When an entity is Unchanged, it’s bound to the context but it hasn’t been modified. When an entity is Unchanged, it’s bound to the context but it hasn’t been modified. By default, an entity retrieved from the database is in this state. By default, an entity retrieved from the database is in this state. When an entity is attached to the context (with the Attach method), it similarly is in the Unchanged state. When an entity is attached to the context (with the Attach method), it similarly is in the Unchanged state. The context can’t track changes to objects that it doesn’t reference, so when they’re attached it assumes they’re Unchanged. The context can’t track changes to objects that it doesn’t reference, so when they’re attached it assumes they’re Unchanged. Detached is the default state of a newly created entity because the context can’t track the creation of any object in your code. Detached is the default state of a newly created entity because the context can’t track the creation of any object in your code. This is true even if you instantiate the entity inside a using block of the context. This is true even if you instantiate the entity inside a using block of the context. Detached is even the state of entities retrieved from the database when tracking is disabled. Detached is even the state of entities retrieved from the database when tracking is disabled. When an entity is detached, it isn’t bound to the context, so its state isn’t tracked. When an entity is detached, it isn’t bound to the context, so its state isn’t tracked. It can be disposed of, modified, used in combination with other classes, or used in any other way you might need. It can be disposed of, modified, used in combination with other classes, or used in any other way you might need. Because there is no context tracking it, it has no meaning to Entity Framework. Because there is no context tracking it, it has no meaning to Entity Framework. When an entity is in the Added state, you have few options. In fact, you can only detach it from the context. When an entity is in the Added state, you have few options. In fact, you can only detach it from the context. Naturally, even if you modify some property, the state remains Added, because moving it to Modified, Unchanged, or Deleted makes no sense. Naturally, even if you modify some property, the state remains Added, because moving it to Modified, Unchanged, or Deleted makes no sense. It’s a new entity and has no correspondence with a row in the database. It’s a new entity and has no correspondence with a row in the database. This is a fundamental prerequisite for being in one of those states (but this rule isn’t enforced by the context). This is a fundamental prerequisite for being in one of those states (but this rule isn’t enforced by the context). When an entity is modified, that means it was in Unchanged state and then some property was changed. When an entity is modified, that means it was in Unchanged state and then some property was changed. After an entity enters the Modified state, it can move to the Detached or Deleted state, but it can’t roll back to the Unchanged state even if you manually restore the original values. After an entity enters the Modified state, it can move to the Detached or Deleted state, but it can’t roll back to the Unchanged state even if you manually restore the original values. It can’t even be changed to Added, unless you detach and add the entity to the context, because a row with this ID already exists in the database, and you would get a runtime exception when persisting it. It can’t even be changed to Added, unless you detach and add the entity to the context, because a row with this ID already exists in the database, and you would get a runtime exception when persisting it. An entity enters the Deleted state because it was Unchanged or Modified and then the DeleteObject method was used. An entity enters the Deleted state because it was Unchanged or Modified and then the DeleteObject method was used. This is the most restrictive state, because it’s pointless changing from this state to any other value but Detached. This is the most restrictive state, because it’s pointless changing from this state to any other value but Detached. The using statement if you want all the resources that the context controls to be disposed at the end of the block. When you use the using statement, then compiler automatically creates a try/finally block and calls dispose in the finally block. using (var context = new UniContext()) { var student = new Student { LastName = "Khan", FirstMidName = "Ali", EnrollmentDate = DateTime.Parse("2005-09-01") }; context.Students.Add(student); context.SaveChanges(); } When working with long-running context consider the following − As you load more objects and their references into memory, the memory consumption of the context may increase rapidly. This may cause performance issues. As you load more objects and their references into memory, the memory consumption of the context may increase rapidly. This may cause performance issues. Remember to dispose of the context when it is no longer required. Remember to dispose of the context when it is no longer required. If an exception causes the context to be in an unrecoverable state, the whole application may terminate. If an exception causes the context to be in an unrecoverable state, the whole application may terminate. The chances of running into concurrency-related issues increases as the gap between the time when the data is queried and updated grows. The chances of running into concurrency-related issues increases as the gap between the time when the data is queried and updated grows. When working with Web applications, use a context instance per request. When working with Web applications, use a context instance per request. When working with Windows Presentation Foundation (WPF) or Windows Forms, use a context instance per form. This lets you use change-tracking functionality that context provides. When working with Windows Presentation Foundation (WPF) or Windows Forms, use a context instance per form. This lets you use change-tracking functionality that context provides. Web Applications It is now a common and best practice that for web applications, context is used per request. It is now a common and best practice that for web applications, context is used per request. In web applications, we deal with requests that are very short but holds all the server transaction they are therefore the proper duration for the context to live in. In web applications, we deal with requests that are very short but holds all the server transaction they are therefore the proper duration for the context to live in. Desktop Applications For desktop application, like Win Forms/WPF, etc. the context is used per form/dialog/page. For desktop application, like Win Forms/WPF, etc. the context is used per form/dialog/page. Since we don’t want to have the context as a singleton for our application we will dispose it when we move from one form to another. Since we don’t want to have the context as a singleton for our application we will dispose it when we move from one form to another. In this way, we will gain a lot of the context’s abilities and won’t suffer from the implications of long running contexts. In this way, we will gain a lot of the context’s abilities and won’t suffer from the implications of long running contexts. 19 Lectures 5 hours Trevoir Williams 33 Lectures 3.5 hours Nilay Mehta 21 Lectures 2.5 hours TELCOMA Global 89 Lectures 7.5 hours Mustafa Radaideh Print Add Notes Bookmark this page
[ { "code": null, "e": 3162, "s": 3032, "text": "The lifetime of a context begins when the instance is created and ends when the instance is either disposed or garbage-collected." }, { "code": null, "e": 3232, "s": 3162, "text": "Context lifetime is a very crucial decision to make when we use ORMs." }, { "code": null, "e": 3302, "s": 3232, "text": "Context lifetime is a very crucial decision to make when we use ORMs." }, { "code": null, "e": 3492, "s": 3302, "text": "The context is performing like an entity cache, so it means it holds references to all the loaded entities which may grow very fast in memory consumption and it can also cause memory leaks." }, { "code": null, "e": 3682, "s": 3492, "text": "The context is performing like an entity cache, so it means it holds references to all the loaded entities which may grow very fast in memory consumption and it can also cause memory leaks." }, { "code": null, "e": 3806, "s": 3682, "text": "In the below diagram, you can see the upper level of data workflow from application to database via Context and vice versa." }, { "code": null, "e": 3930, "s": 3806, "text": "In the below diagram, you can see the upper level of data workflow from application to database via Context and vice versa." }, { "code": null, "e": 4263, "s": 3930, "text": "The Entity Lifecycle describes the process in which an Entity is created, added, modified, deleted, etc. Entities have many states during its lifetime. Before looking at how to retrieve entity state, let’s take a look at what is entity state. The state is an enum of type System.Data.EntityState that declares the following values −" }, { "code": null, "e": 4301, "s": 4263, "text": "Added: The entity is marked as added." }, { "code": null, "e": 4339, "s": 4301, "text": "Added: The entity is marked as added." }, { "code": null, "e": 4381, "s": 4339, "text": "Deleted: The entity is marked as deleted." }, { "code": null, "e": 4423, "s": 4381, "text": "Deleted: The entity is marked as deleted." }, { "code": null, "e": 4463, "s": 4423, "text": "Modified: The entity has been modified." }, { "code": null, "e": 4503, "s": 4463, "text": "Modified: The entity has been modified." }, { "code": null, "e": 4547, "s": 4503, "text": "Unchanged: The entity hasn’t been modified." }, { "code": null, "e": 4591, "s": 4547, "text": "Unchanged: The entity hasn’t been modified." }, { "code": null, "e": 4627, "s": 4591, "text": "Detached: The entity isn’t tracked." }, { "code": null, "e": 4663, "s": 4627, "text": "Detached: The entity isn’t tracked." }, { "code": null, "e": 4966, "s": 4663, "text": "Sometimes state of entities are set automatically by the context, but it can also be modified manually by the developer. Even though all the combinations of switches from one state to another are possible, but some of them are meaningless. For example, Added entity to the Deleted state, or vice versa." }, { "code": null, "e": 5004, "s": 4966, "text": "Let’s discuss about different states." }, { "code": null, "e": 5088, "s": 5004, "text": "When an entity is Unchanged, it’s bound to the context but it hasn’t been modified." }, { "code": null, "e": 5172, "s": 5088, "text": "When an entity is Unchanged, it’s bound to the context but it hasn’t been modified." }, { "code": null, "e": 5240, "s": 5172, "text": "By default, an entity retrieved from the database is in this state." }, { "code": null, "e": 5308, "s": 5240, "text": "By default, an entity retrieved from the database is in this state." }, { "code": null, "e": 5416, "s": 5308, "text": "When an entity is attached to the context (with the Attach method), it similarly is in the Unchanged state." }, { "code": null, "e": 5524, "s": 5416, "text": "When an entity is attached to the context (with the Attach method), it similarly is in the Unchanged state." }, { "code": null, "e": 5649, "s": 5524, "text": "The context can’t track changes to objects that it doesn’t reference, so when they’re attached it assumes they’re Unchanged." }, { "code": null, "e": 5774, "s": 5649, "text": "The context can’t track changes to objects that it doesn’t reference, so when they’re attached it assumes they’re Unchanged." }, { "code": null, "e": 5903, "s": 5774, "text": "Detached is the default state of a newly created entity because the context can’t track the creation of any object in your code." }, { "code": null, "e": 6032, "s": 5903, "text": "Detached is the default state of a newly created entity because the context can’t track the creation of any object in your code." }, { "code": null, "e": 6117, "s": 6032, "text": "This is true even if you instantiate the entity inside a using block of the context." }, { "code": null, "e": 6202, "s": 6117, "text": "This is true even if you instantiate the entity inside a using block of the context." }, { "code": null, "e": 6296, "s": 6202, "text": "Detached is even the state of entities retrieved from the database when tracking is disabled." }, { "code": null, "e": 6390, "s": 6296, "text": "Detached is even the state of entities retrieved from the database when tracking is disabled." }, { "code": null, "e": 6477, "s": 6390, "text": "When an entity is detached, it isn’t bound to the context, so its state isn’t tracked." }, { "code": null, "e": 6564, "s": 6477, "text": "When an entity is detached, it isn’t bound to the context, so its state isn’t tracked." }, { "code": null, "e": 6678, "s": 6564, "text": "It can be disposed of, modified, used in combination with other classes, or used in any other way you might need." }, { "code": null, "e": 6792, "s": 6678, "text": "It can be disposed of, modified, used in combination with other classes, or used in any other way you might need." }, { "code": null, "e": 6872, "s": 6792, "text": "Because there is no context tracking it, it has no meaning to Entity Framework." }, { "code": null, "e": 6952, "s": 6872, "text": "Because there is no context tracking it, it has no meaning to Entity Framework." }, { "code": null, "e": 7062, "s": 6952, "text": "When an entity is in the Added state, you have few options. In fact, you can only detach it from the context." }, { "code": null, "e": 7172, "s": 7062, "text": "When an entity is in the Added state, you have few options. In fact, you can only detach it from the context." }, { "code": null, "e": 7311, "s": 7172, "text": "Naturally, even if you modify some property, the state remains Added, because moving it to Modified, Unchanged, or Deleted makes no sense." }, { "code": null, "e": 7450, "s": 7311, "text": "Naturally, even if you modify some property, the state remains Added, because moving it to Modified, Unchanged, or Deleted makes no sense." }, { "code": null, "e": 7522, "s": 7450, "text": "It’s a new entity and has no correspondence with a row in the database." }, { "code": null, "e": 7594, "s": 7522, "text": "It’s a new entity and has no correspondence with a row in the database." }, { "code": null, "e": 7709, "s": 7594, "text": "This is a fundamental prerequisite for being in one of those states (but this rule isn’t enforced by the context)." }, { "code": null, "e": 7824, "s": 7709, "text": "This is a fundamental prerequisite for being in one of those states (but this rule isn’t enforced by the context)." }, { "code": null, "e": 7925, "s": 7824, "text": "When an entity is modified, that means it was in Unchanged state and then some property was changed." }, { "code": null, "e": 8026, "s": 7925, "text": "When an entity is modified, that means it was in Unchanged state and then some property was changed." }, { "code": null, "e": 8211, "s": 8026, "text": "After an entity enters the Modified state, it can move to the Detached or Deleted state, but it can’t roll back to the Unchanged state even if you manually restore the original values." }, { "code": null, "e": 8396, "s": 8211, "text": "After an entity enters the Modified state, it can move to the Detached or Deleted state, but it can’t roll back to the Unchanged state even if you manually restore the original values." }, { "code": null, "e": 8601, "s": 8396, "text": "It can’t even be changed to Added, unless you detach and add the entity to the context, because a row with this ID already exists in the database, and you would get a runtime exception when persisting it." }, { "code": null, "e": 8806, "s": 8601, "text": "It can’t even be changed to Added, unless you detach and add the entity to the context, because a row with this ID already exists in the database, and you would get a runtime exception when persisting it." }, { "code": null, "e": 8921, "s": 8806, "text": "An entity enters the Deleted state because it was Unchanged or Modified and then the DeleteObject method was used." }, { "code": null, "e": 9036, "s": 8921, "text": "An entity enters the Deleted state because it was Unchanged or Modified and then the DeleteObject method was used." }, { "code": null, "e": 9153, "s": 9036, "text": "This is the most restrictive state, because it’s pointless changing from this state to any other value but Detached." }, { "code": null, "e": 9270, "s": 9153, "text": "This is the most restrictive state, because it’s pointless changing from this state to any other value but Detached." }, { "code": null, "e": 9516, "s": 9270, "text": "The using statement if you want all the resources that the context controls to be disposed at the end of the block. When you use the using statement, then compiler automatically creates a try/finally block and calls dispose in the finally block." }, { "code": null, "e": 9765, "s": 9516, "text": "using (var context = new UniContext()) {\n\n var student = new Student {\n LastName = \"Khan\", \n FirstMidName = \"Ali\", \n EnrollmentDate = DateTime.Parse(\"2005-09-01\")\n };\n\n context.Students.Add(student);\n context.SaveChanges();\n}" }, { "code": null, "e": 9829, "s": 9765, "text": "When working with long-running context consider the following −" }, { "code": null, "e": 9983, "s": 9829, "text": "As you load more objects and their references into memory, the memory consumption of the context may increase rapidly. This may cause performance issues." }, { "code": null, "e": 10137, "s": 9983, "text": "As you load more objects and their references into memory, the memory consumption of the context may increase rapidly. This may cause performance issues." }, { "code": null, "e": 10203, "s": 10137, "text": "Remember to dispose of the context when it is no longer required." }, { "code": null, "e": 10269, "s": 10203, "text": "Remember to dispose of the context when it is no longer required." }, { "code": null, "e": 10374, "s": 10269, "text": "If an exception causes the context to be in an unrecoverable state, the whole application may terminate." }, { "code": null, "e": 10479, "s": 10374, "text": "If an exception causes the context to be in an unrecoverable state, the whole application may terminate." }, { "code": null, "e": 10616, "s": 10479, "text": "The chances of running into concurrency-related issues increases as the gap between the time when the data is queried and updated grows." }, { "code": null, "e": 10753, "s": 10616, "text": "The chances of running into concurrency-related issues increases as the gap between the time when the data is queried and updated grows." }, { "code": null, "e": 10825, "s": 10753, "text": "When working with Web applications, use a context instance per request." }, { "code": null, "e": 10897, "s": 10825, "text": "When working with Web applications, use a context instance per request." }, { "code": null, "e": 11075, "s": 10897, "text": "When working with Windows Presentation Foundation (WPF) or Windows Forms, use a context instance per form. This lets you use change-tracking functionality that context provides." }, { "code": null, "e": 11253, "s": 11075, "text": "When working with Windows Presentation Foundation (WPF) or Windows Forms, use a context instance per form. This lets you use change-tracking functionality that context provides." }, { "code": null, "e": 11270, "s": 11253, "text": "Web Applications" }, { "code": null, "e": 11363, "s": 11270, "text": "It is now a common and best practice that for web applications, context is used per request." }, { "code": null, "e": 11456, "s": 11363, "text": "It is now a common and best practice that for web applications, context is used per request." }, { "code": null, "e": 11623, "s": 11456, "text": "In web applications, we deal with requests that are very short but holds all the server transaction they are therefore the proper duration for the context to live in." }, { "code": null, "e": 11790, "s": 11623, "text": "In web applications, we deal with requests that are very short but holds all the server transaction they are therefore the proper duration for the context to live in." }, { "code": null, "e": 11811, "s": 11790, "text": "Desktop Applications" }, { "code": null, "e": 11903, "s": 11811, "text": "For desktop application, like Win Forms/WPF, etc. the context is used per form/dialog/page." }, { "code": null, "e": 11995, "s": 11903, "text": "For desktop application, like Win Forms/WPF, etc. the context is used per form/dialog/page." }, { "code": null, "e": 12128, "s": 11995, "text": "Since we don’t want to have the context as a singleton for our application we will dispose it when we move from one form to another." }, { "code": null, "e": 12261, "s": 12128, "text": "Since we don’t want to have the context as a singleton for our application we will dispose it when we move from one form to another." }, { "code": null, "e": 12385, "s": 12261, "text": "In this way, we will gain a lot of the context’s abilities and won’t suffer from the implications of long running contexts." }, { "code": null, "e": 12509, "s": 12385, "text": "In this way, we will gain a lot of the context’s abilities and won’t suffer from the implications of long running contexts." }, { "code": null, "e": 12542, "s": 12509, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 12560, "s": 12542, "text": " Trevoir Williams" }, { "code": null, "e": 12595, "s": 12560, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12608, "s": 12595, "text": " Nilay Mehta" }, { "code": null, "e": 12643, "s": 12608, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12659, "s": 12643, "text": " TELCOMA Global" }, { "code": null, "e": 12694, "s": 12659, "text": "\n 89 Lectures \n 7.5 hours \n" }, { "code": null, "e": 12712, "s": 12694, "text": " Mustafa Radaideh" }, { "code": null, "e": 12719, "s": 12712, "text": " Print" }, { "code": null, "e": 12730, "s": 12719, "text": " Add Notes" } ]
C# String Concat with examples
To concat strings in C#, use the String.Concat() method. public static string Concat (string str1, string str2); Above, the parameters str1 and str2 are the strings to be concatenated. Live Demo using System; public class Demo { public static void Main(String[] args) { string str1 = "Jack"; string str2 = "Sparrow"; Console.WriteLine("String 1 = "+str1); Console.WriteLine("HashCode of String 1 = "+str1.GetHashCode()); Console.WriteLine("Does String1 begins with E? = "+str1.StartsWith("E")); Console.WriteLine("\nString 2 = "+str2); Console.WriteLine("HashCode of String 2 = "+str2.GetHashCode()); Console.WriteLine("Does String2 begins with E? = "+str2.StartsWith("E")); Console.WriteLine("\nString 1 is equal to String 2? = {0}", str1.Equals(str2)); Console.WriteLine("Concatenation Result = "+String.Concat(str1,str2)); } } String 1 = Jack HashCode of String 1 = 1167841345 Does String1 begins with E? = False String 2 = Sparrow HashCode of String 2 = -359606417 Does String2 begins with E? = False String 1 is equal to String 2? = False Concatenation Result = JackSparrow Let us now see another example wherein we will use the concat() method with only a single parameter. public static string Concat (params string[] arr); Above, arr is the string array. Live Demo using System; public class Demo { public static void Main(string[] args) { string[] strArr = {"This", "is", "it", "!" }; Console.WriteLine("String Array..."); foreach(string s in strArr) { Console.WriteLine(s); } Console.WriteLine("Concatenation = {0}",string.Concat(strArr)); string str = string.Join("/", strArr); Console.WriteLine("Result (after joining) = " + str); } } String Array... This is it ! Concatenation = Thisisit! Result (after joining) = This/is/it/!
[ { "code": null, "e": 1119, "s": 1062, "text": "To concat strings in C#, use the String.Concat() method." }, { "code": null, "e": 1175, "s": 1119, "text": "public static string Concat (string str1, string str2);" }, { "code": null, "e": 1247, "s": 1175, "text": "Above, the parameters str1 and str2 are the strings to be concatenated." }, { "code": null, "e": 1258, "s": 1247, "text": " Live Demo" }, { "code": null, "e": 1959, "s": 1258, "text": "using System;\npublic class Demo {\n public static void Main(String[] args) {\n string str1 = \"Jack\";\n string str2 = \"Sparrow\";\n Console.WriteLine(\"String 1 = \"+str1);\n Console.WriteLine(\"HashCode of String 1 = \"+str1.GetHashCode());\n Console.WriteLine(\"Does String1 begins with E? = \"+str1.StartsWith(\"E\"));\n Console.WriteLine(\"\\nString 2 = \"+str2);\n Console.WriteLine(\"HashCode of String 2 = \"+str2.GetHashCode());\n Console.WriteLine(\"Does String2 begins with E? = \"+str2.StartsWith(\"E\"));\n Console.WriteLine(\"\\nString 1 is equal to String 2? = {0}\", str1.Equals(str2));\n Console.WriteLine(\"Concatenation Result = \"+String.Concat(str1,str2));\n }\n}" }, { "code": null, "e": 2208, "s": 1959, "text": "String 1 = Jack\nHashCode of String 1 = 1167841345\nDoes String1 begins with E? = False\nString 2 = Sparrow\nHashCode of String 2 = -359606417\nDoes String2 begins with E? = False\nString 1 is equal to String 2? = False\nConcatenation Result = JackSparrow" }, { "code": null, "e": 2309, "s": 2208, "text": "Let us now see another example wherein we will use the concat() method with only a single parameter." }, { "code": null, "e": 2360, "s": 2309, "text": "public static string Concat (params string[] arr);" }, { "code": null, "e": 2392, "s": 2360, "text": "Above, arr is the string array." }, { "code": null, "e": 2403, "s": 2392, "text": " Live Demo" }, { "code": null, "e": 2840, "s": 2403, "text": "using System;\npublic class Demo {\n public static void Main(string[] args) {\n string[] strArr = {\"This\", \"is\", \"it\", \"!\" };\n Console.WriteLine(\"String Array...\");\n foreach(string s in strArr) {\n Console.WriteLine(s);\n } \n Console.WriteLine(\"Concatenation = {0}\",string.Concat(strArr));\n string str = string.Join(\"/\", strArr);\n Console.WriteLine(\"Result (after joining) = \" + str);\n }\n}" }, { "code": null, "e": 2933, "s": 2840, "text": "String Array...\nThis\nis\nit\n!\nConcatenation = Thisisit!\nResult (after joining) = This/is/it/!" } ]
Perl - References
A Perl reference is a scalar data type that holds the location of another value which could be scalar, arrays, or hashes. Because of its scalar nature, a reference can be used anywhere, a scalar can be used. You can construct lists containing references to other lists, which can contain references to hashes, and so on. This is how the nested data structures are built in Perl. It is easy to create a reference for any variable, subroutine or value by prefixing it with a backslash as follows − $scalarref = \$foo; $arrayref = \@ARGV; $hashref = \%ENV; $coderef = \&handler; $globref = \*foo; You cannot create a reference on an I/O handle (filehandle or dirhandle) using the backslash operator but a reference to an anonymous array can be created using the square brackets as follows − $arrayref = [1, 2, ['a', 'b', 'c']]; Similar way you can create a reference to an anonymous hash using the curly brackets as follows − $hashref = { 'Adam' => 'Eve', 'Clyde' => 'Bonnie', }; A reference to an anonymous subroutine can be created by using sub without a subname as follows − $coderef = sub { print "Boink!\n" }; Dereferencing returns the value from a reference point to the location. To dereference a reference simply use $, @ or % as prefix of the reference variable depending on whether the reference is pointing to a scalar, array, or hash. Following is the example to explain the concept − #!/usr/bin/perl $var = 10; # Now $r has reference to $var scalar. $r = \$var; # Print value available at the location stored in $r. print "Value of $var is : ", $$r, "\n"; @var = (1, 2, 3); # Now $r has reference to @var array. $r = \@var; # Print values available at the location stored in $r. print "Value of @var is : ", @$r, "\n"; %var = ('key1' => 10, 'key2' => 20); # Now $r has reference to %var hash. $r = \%var; # Print values available at the location stored in $r. print "Value of %var is : ", %$r, "\n"; When above program is executed, it produces the following result − Value of 10 is : 10 Value of 1 2 3 is : 123 Value of %var is : key220key110 If you are not sure about a variable type, then its easy to know its type using ref, which returns one of the following strings if its argument is a reference. Otherwise, it returns false − SCALAR ARRAY HASH CODE GLOB REF Let's try the following example − #!/usr/bin/perl $var = 10; $r = \$var; print "Reference type in r : ", ref($r), "\n"; @var = (1, 2, 3); $r = \@var; print "Reference type in r : ", ref($r), "\n"; %var = ('key1' => 10, 'key2' => 20); $r = \%var; print "Reference type in r : ", ref($r), "\n"; When above program is executed, it produces the following result − Reference type in r : SCALAR Reference type in r : ARRAY Reference type in r : HASH A circular reference occurs when two references contain a reference to each other. You have to be careful while creating references otherwise a circular reference can lead to memory leaks. Following is an example − #!/usr/bin/perl my $foo = 100; $foo = \$foo; print "Value of foo is : ", $$foo, "\n"; When above program is executed, it produces the following result − Value of foo is : REF(0x9aae38) This might happen if you need to create a signal handler so you can produce a reference to a function by preceding that function name with \& and to dereference that reference you simply need to prefix reference variable using ampersand &. Following is an example − #!/usr/bin/perl # Function definition sub PrintHash { my (%hash) = @_; foreach $item (%hash) { print "Item : $item\n"; } } %hash = ('name' => 'Tom', 'age' => 19); # Create a reference to above function. $cref = \&PrintHash; # Function call using reference. &$cref(%hash); When above program is executed, it produces the following result − Item : name Item : Tom Item : age Item : 19 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2428, "s": 2220, "text": "A Perl reference is a scalar data type that holds the location of another value which could be scalar, arrays, or hashes. Because of its scalar nature, a reference can be used anywhere, a scalar can be used." }, { "code": null, "e": 2599, "s": 2428, "text": "You can construct lists containing references to other lists, which can contain references to hashes, and so on. This is how the nested data structures are built in Perl." }, { "code": null, "e": 2716, "s": 2599, "text": "It is easy to create a reference for any variable, subroutine or value by prefixing it with a backslash as follows −" }, { "code": null, "e": 2822, "s": 2716, "text": "$scalarref = \\$foo;\n$arrayref = \\@ARGV;\n$hashref = \\%ENV;\n$coderef = \\&handler;\n$globref = \\*foo;\n" }, { "code": null, "e": 3016, "s": 2822, "text": "You cannot create a reference on an I/O handle (filehandle or dirhandle) using the backslash operator but a reference to an anonymous array can be created using the square brackets as follows −" }, { "code": null, "e": 3054, "s": 3016, "text": " $arrayref = [1, 2, ['a', 'b', 'c']];" }, { "code": null, "e": 3152, "s": 3054, "text": "Similar way you can create a reference to an anonymous hash using the curly brackets as follows −" }, { "code": null, "e": 3213, "s": 3152, "text": "$hashref = {\n 'Adam' => 'Eve',\n 'Clyde' => 'Bonnie',\n};" }, { "code": null, "e": 3311, "s": 3213, "text": "A reference to an anonymous subroutine can be created by using sub without a subname as follows −" }, { "code": null, "e": 3348, "s": 3311, "text": "$coderef = sub { print \"Boink!\\n\" };" }, { "code": null, "e": 3630, "s": 3348, "text": "Dereferencing returns the value from a reference point to the location. To dereference a reference simply use $, @ or % as prefix of the reference variable depending on whether the reference is pointing to a scalar, array, or hash. Following is the example to explain the concept −" }, { "code": null, "e": 4152, "s": 3630, "text": "#!/usr/bin/perl\n\n$var = 10;\n\n# Now $r has reference to $var scalar.\n$r = \\$var;\n\n# Print value available at the location stored in $r.\nprint \"Value of $var is : \", $$r, \"\\n\";\n\n@var = (1, 2, 3);\n# Now $r has reference to @var array.\n$r = \\@var;\n# Print values available at the location stored in $r.\nprint \"Value of @var is : \", @$r, \"\\n\";\n\n%var = ('key1' => 10, 'key2' => 20);\n# Now $r has reference to %var hash.\n$r = \\%var;\n# Print values available at the location stored in $r.\nprint \"Value of %var is : \", %$r, \"\\n\";" }, { "code": null, "e": 4219, "s": 4152, "text": "When above program is executed, it produces the following result −" }, { "code": null, "e": 4296, "s": 4219, "text": "Value of 10 is : 10\nValue of 1 2 3 is : 123\nValue of %var is : key220key110\n" }, { "code": null, "e": 4486, "s": 4296, "text": "If you are not sure about a variable type, then its easy to know its type using ref, which returns one of the following strings if its argument is a reference. Otherwise, it returns false −" }, { "code": null, "e": 4519, "s": 4486, "text": "SCALAR\nARRAY\nHASH\nCODE\nGLOB\nREF\n" }, { "code": null, "e": 4553, "s": 4519, "text": "Let's try the following example −" }, { "code": null, "e": 4815, "s": 4553, "text": "#!/usr/bin/perl\n\n$var = 10;\n$r = \\$var;\nprint \"Reference type in r : \", ref($r), \"\\n\";\n\n@var = (1, 2, 3);\n$r = \\@var;\nprint \"Reference type in r : \", ref($r), \"\\n\";\n\n%var = ('key1' => 10, 'key2' => 20);\n$r = \\%var;\nprint \"Reference type in r : \", ref($r), \"\\n\";" }, { "code": null, "e": 4882, "s": 4815, "text": "When above program is executed, it produces the following result −" }, { "code": null, "e": 4967, "s": 4882, "text": "Reference type in r : SCALAR\nReference type in r : ARRAY\nReference type in r : HASH\n" }, { "code": null, "e": 5182, "s": 4967, "text": "A circular reference occurs when two references contain a reference to each other. You have to be careful while creating references otherwise a circular reference can lead to memory leaks. Following is an example −" }, { "code": null, "e": 5274, "s": 5182, "text": "#!/usr/bin/perl\n\n my $foo = 100;\n $foo = \\$foo;\n \n print \"Value of foo is : \", $$foo, \"\\n\";" }, { "code": null, "e": 5341, "s": 5274, "text": "When above program is executed, it produces the following result −" }, { "code": null, "e": 5374, "s": 5341, "text": "Value of foo is : REF(0x9aae38)\n" }, { "code": null, "e": 5640, "s": 5374, "text": "This might happen if you need to create a signal handler so you can produce a reference to a function by preceding that function name with \\& and to dereference that reference you simply need to prefix reference variable using ampersand &. Following is an example −" }, { "code": null, "e": 5934, "s": 5640, "text": "#!/usr/bin/perl\n\n# Function definition\nsub PrintHash {\n my (%hash) = @_;\n \n foreach $item (%hash) {\n print \"Item : $item\\n\";\n }\n}\n%hash = ('name' => 'Tom', 'age' => 19);\n\n# Create a reference to above function.\n$cref = \\&PrintHash;\n\n# Function call using reference.\n&$cref(%hash);" }, { "code": null, "e": 6001, "s": 5934, "text": "When above program is executed, it produces the following result −" }, { "code": null, "e": 6046, "s": 6001, "text": "Item : name\nItem : Tom\nItem : age\nItem : 19\n" }, { "code": null, "e": 6081, "s": 6046, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6095, "s": 6081, "text": " Devi Killada" }, { "code": null, "e": 6130, "s": 6095, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6150, "s": 6130, "text": " Harshit Srivastava" }, { "code": null, "e": 6183, "s": 6150, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 6199, "s": 6183, "text": " TELCOMA Global" }, { "code": null, "e": 6232, "s": 6199, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 6249, "s": 6232, "text": " Mohammad Nauman" }, { "code": null, "e": 6282, "s": 6249, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 6305, "s": 6282, "text": " Stone River ELearning" }, { "code": null, "e": 6340, "s": 6305, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 6363, "s": 6340, "text": " Stone River ELearning" }, { "code": null, "e": 6370, "s": 6363, "text": " Print" }, { "code": null, "e": 6381, "s": 6370, "text": " Add Notes" } ]
Setting Up Data Pipelines Using Apache Airflow on Kubernetes | by Joshua Yeung | Towards Data Science
Apache Airflow is an open-source workflow orchestration tool for scheduling and monitoring data pipelines. It can be also used for machine learning workflows and other purposes. Kubernetes is a de facto orchestration tool for scheduling containerized applications. Airflow can utilize the ability provided by Kubernetes to scale up/down the worker depending on the workload. Last year, I have deployed Apache Airflow on Kubernetes. Bitnami provides an Apache Airflow Helm chart which makes me easy to deploy and scale. It mainly consists of three parts: webserver, scheduler, and worker. Web server: You can browse your DAGs, start/stop a process with GUIScheduler: manages and schedules the tasks in the backgroundWorkers: The actual instances that execute the tasks Web server: You can browse your DAGs, start/stop a process with GUI Scheduler: manages and schedules the tasks in the background Workers: The actual instances that execute the tasks Besides these three important parts, Airflow also has Redis and PostgreSQL for storing your connection settings, variables, and logs. You may check the details of the Bitnami chart in the below GitHub repository. github.com In Airflow, users create a Directed Acyclic Graph (DAG) file to define the processes and tasks that must be performed, how often they are executed, the order in which tasks within a process will be performed, and the relationships and dependencies between them. When Airflow is deployed on a normal server, we just need to load DAG files into a specific directory on the server. But when your Airflow is deployed on Kubernetes, you will need other ways to let Airflow load your DAG files. The way I used to load DAG files is from the Git repository. On my on-prem Kubernetes cluster, there is a private Git repository GitLab. I had to enable the Git section in the Helm chart and specify the repositories Airflow will use. You can download the values.yaml of the Bitnami Airflow chart from their repository: https://github.com/bitnami/charts/tree/master/bitnami/airflow In the Git section of the values.yaml, there is a field to define the repositories that Airflow will sync and load all the DAG files. git: dags: ## Enable in order to download DAG files from git repositories. enabled: true repositories: - repository: http://<User>:<Personal-Access-Tokens>@gitlab-webservice.gitlab.svc.cluster.local:8181/airflow/airflow.git branch: master name: gitlab path: After that, you can put all your DAG files in the folder called dags inside that Git repository. Since I am using a private repository, I clone the DAG files using a Personal Access Token as shown above. In order to let your users and yourself access the web UI of Airflow, you need to expose the service of the webserver. If there is an Ingress controller in your Kubernetes cluster, you may configure the ingress resource and allow yourself to access the Airflow webserver through Ingress. You just need to enable ingress and modify host to your hostname in the values.yaml of the Helm chart. ingress:## Set to true to enable ingress record generation enabled: true hosts: name: airflow.yourdomain.com path: / Before we deploy the Airflow, we need to consider more values of the Helm chart. Because we will need to upgrade our release in the future, passwords of the database PostgreSQL and Redis must be provided. You can set them in the PostgreSQL and Redis chart configuration. Also, we need to provide a password of the user and fernetKey for authentication. username and password to access the web UI can be modified in the auth section in the values.yaml. Remember to set forcePassword to true as well, this is required for the future upgrade to work properly. To generate a new fernet key, you can use the following code snippet provided by the Airflow official documentation. Some random text (for example2r3EPAQ-Fzc-rAexn5ltRsnaUP9QjoVi7Z36I3AcyZ4=) will be printed. Just copy it to the fernetKey field in the auth section. from cryptography.fernet import Fernetfernet_key= Fernet.generate_key()print(fernet_key.decode()) # your fernet_key, keep it in secured place! Once we have finished modifying the Helm chart, you can use just three commands to deploy Airflow on Kubernetes! First, you create a namespace called airflow: kubectl create ns airflow Second, you add the Bitnami charts repository to Helm: helm repo add bitnami https://charts.bitnami.com/bitnami Finally, you install Airflow with Helm. Easy! Of course, you can change “my-release” to any name you like for this Airflow release. helm install –n airflow my-release bitnami/airflow -f values.yaml Airflow is deployed! You should see something like that: NAME: my-releaseLAST DEPLOYED: Thu Mar 11 01:27:30 2021NAMESPACE: airflowSTATUS: deployedREVISION: 1TEST SUITE: NoneNOTES:1. Get the Airflow URL by running:echo URL : http://127.0.0.1:80802. Get your Airflow login credentials by running: export AIRFLOW_PASSWORD=$(kubectl get secret — namespace airflow my-release-airflow -o jsonpath=”{.data.airflow-password}” | base64 — decode) echo User: user echo Password: $AIRFLOW_PASSWORD You can get your Airflow login credentials by following the instruction above. You can also get access to your web UI by the URL you stated in the values.yaml (In this example it is airflow.yourdomain.com) After a while, you should see all your pods are running in the namespace airflow by the command kubectl get pod -n airflow. # kubectl get pod -n airflowNAME READY STATUS RESTARTS AGEairflow-postgresql-0 1/1 Running 0 3m53sairflow-redis-master-0 1/1 Running 0 3m53sairflow-redis-slave-0 1/1 Running 0 3m53sairflow-redis-slave-1 1/1 Running 0 3m53sairflow-scheduler-5f8cc4fd5f-jf4s9 2/2 Running 0 3m53sairflow-web-859dd77944-sfgw4 2/2 Running 0 3m53sairflow-worker-0 2/2 Running 0 3m53sairflow-worker-1 2/2 Running 0 3m53sairflow-worker-2 2/2 Running 0 3m53s Sometimes you may need extra Python packages which the original image doesn’t contain. Bitnami’s chart allows you to mount your own requirements.txt to install the required packages. You need to mount your volume to /bitnami/python/requirements.txt. When the container starts, it will execute pip install -r /bitnami/python/requirements.txt. In the worker component, you need to modify extraVolumeMounts by providing the name of volume and mountPath of the container instance. You also need to add your extraVolumes. I used ConfigMap to add the requirements.txt to the container as it is easier for me to add more extra python packages. extraVolumeMounts: - name: requirements mountPath: /bitnami/python/## Add extra volumesextraVolumes: - name: requirements configMap:# Provide the name of the ConfigMap containing the files you want# to add to the container name: requirements To create the ConfigMap we need, first, we prepare our requirements.txt file. And then we create the ConfigMap by the following command: kubectl create -n airflow configmap requirements --from-file=requirements.txt After we create the ConfigMap and our values.yaml is modified, we need to upgrade our Airflow. Just by a simple command: helm upgrade –n airflow my-release bitnami/airflow -f values.yaml In this article, I showed you the basics of how to deploy Airflow on Kubernetes. Bitnami provides a well-organized Helm chart for us to deploy Airflow on Kubernetes easily. Based on Bitnami’s Helm chart, there are still some minor parameters like database username and password, auth fernet key, extra python package, etc we need to tune. Although Bitnami has already saved us a lot of hard work, I have still gone through many trial and error processes before establishing the “right” setting. Hopefully, this guide will save you some time! If you have any ideas about the architecture of Airflow on Kubernetes, please let me know. I would like to hear from you about a better, more scalable Airflow on Kubernetes. If you want to know more about the use cases of Airflow, you can read my previous article. In that article, I showed how I built an automated reporting system for mobile network performance monitoring using Airflow. towardsdatascience.com If you want to learn how to build an on-premise Kubernetes using Kubespray, please visit this article: towardsdatascience.com If you want to learn more about Apache Airflow, there is a good course on Udemy teaching the basics of Airflow and also hands-on data pipeline building. Please refer to the following affiliated links if you are interested:
[ { "code": null, "e": 547, "s": 172, "text": "Apache Airflow is an open-source workflow orchestration tool for scheduling and monitoring data pipelines. It can be also used for machine learning workflows and other purposes. Kubernetes is a de facto orchestration tool for scheduling containerized applications. Airflow can utilize the ability provided by Kubernetes to scale up/down the worker depending on the workload." }, { "code": null, "e": 760, "s": 547, "text": "Last year, I have deployed Apache Airflow on Kubernetes. Bitnami provides an Apache Airflow Helm chart which makes me easy to deploy and scale. It mainly consists of three parts: webserver, scheduler, and worker." }, { "code": null, "e": 940, "s": 760, "text": "Web server: You can browse your DAGs, start/stop a process with GUIScheduler: manages and schedules the tasks in the backgroundWorkers: The actual instances that execute the tasks" }, { "code": null, "e": 1008, "s": 940, "text": "Web server: You can browse your DAGs, start/stop a process with GUI" }, { "code": null, "e": 1069, "s": 1008, "text": "Scheduler: manages and schedules the tasks in the background" }, { "code": null, "e": 1122, "s": 1069, "text": "Workers: The actual instances that execute the tasks" }, { "code": null, "e": 1256, "s": 1122, "text": "Besides these three important parts, Airflow also has Redis and PostgreSQL for storing your connection settings, variables, and logs." }, { "code": null, "e": 1335, "s": 1256, "text": "You may check the details of the Bitnami chart in the below GitHub repository." }, { "code": null, "e": 1346, "s": 1335, "text": "github.com" }, { "code": null, "e": 1608, "s": 1346, "text": "In Airflow, users create a Directed Acyclic Graph (DAG) file to define the processes and tasks that must be performed, how often they are executed, the order in which tasks within a process will be performed, and the relationships and dependencies between them." }, { "code": null, "e": 1835, "s": 1608, "text": "When Airflow is deployed on a normal server, we just need to load DAG files into a specific directory on the server. But when your Airflow is deployed on Kubernetes, you will need other ways to let Airflow load your DAG files." }, { "code": null, "e": 2069, "s": 1835, "text": "The way I used to load DAG files is from the Git repository. On my on-prem Kubernetes cluster, there is a private Git repository GitLab. I had to enable the Git section in the Helm chart and specify the repositories Airflow will use." }, { "code": null, "e": 2216, "s": 2069, "text": "You can download the values.yaml of the Bitnami Airflow chart from their repository: https://github.com/bitnami/charts/tree/master/bitnami/airflow" }, { "code": null, "e": 2350, "s": 2216, "text": "In the Git section of the values.yaml, there is a field to define the repositories that Airflow will sync and load all the DAG files." }, { "code": null, "e": 2642, "s": 2350, "text": "git: dags: ## Enable in order to download DAG files from git repositories. enabled: true repositories: - repository: http://<User>:<Personal-Access-Tokens>@gitlab-webservice.gitlab.svc.cluster.local:8181/airflow/airflow.git branch: master name: gitlab path:" }, { "code": null, "e": 2846, "s": 2642, "text": "After that, you can put all your DAG files in the folder called dags inside that Git repository. Since I am using a private repository, I clone the DAG files using a Personal Access Token as shown above." }, { "code": null, "e": 3237, "s": 2846, "text": "In order to let your users and yourself access the web UI of Airflow, you need to expose the service of the webserver. If there is an Ingress controller in your Kubernetes cluster, you may configure the ingress resource and allow yourself to access the Airflow webserver through Ingress. You just need to enable ingress and modify host to your hostname in the values.yaml of the Helm chart." }, { "code": null, "e": 3362, "s": 3237, "text": "ingress:## Set to true to enable ingress record generation enabled: true hosts: name: airflow.yourdomain.com path: /" }, { "code": null, "e": 3633, "s": 3362, "text": "Before we deploy the Airflow, we need to consider more values of the Helm chart. Because we will need to upgrade our release in the future, passwords of the database PostgreSQL and Redis must be provided. You can set them in the PostgreSQL and Redis chart configuration." }, { "code": null, "e": 3919, "s": 3633, "text": "Also, we need to provide a password of the user and fernetKey for authentication. username and password to access the web UI can be modified in the auth section in the values.yaml. Remember to set forcePassword to true as well, this is required for the future upgrade to work properly." }, { "code": null, "e": 4185, "s": 3919, "text": "To generate a new fernet key, you can use the following code snippet provided by the Airflow official documentation. Some random text (for example2r3EPAQ-Fzc-rAexn5ltRsnaUP9QjoVi7Z36I3AcyZ4=) will be printed. Just copy it to the fernetKey field in the auth section." }, { "code": null, "e": 4328, "s": 4185, "text": "from cryptography.fernet import Fernetfernet_key= Fernet.generate_key()print(fernet_key.decode()) # your fernet_key, keep it in secured place!" }, { "code": null, "e": 4441, "s": 4328, "text": "Once we have finished modifying the Helm chart, you can use just three commands to deploy Airflow on Kubernetes!" }, { "code": null, "e": 4487, "s": 4441, "text": "First, you create a namespace called airflow:" }, { "code": null, "e": 4513, "s": 4487, "text": "kubectl create ns airflow" }, { "code": null, "e": 4568, "s": 4513, "text": "Second, you add the Bitnami charts repository to Helm:" }, { "code": null, "e": 4625, "s": 4568, "text": "helm repo add bitnami https://charts.bitnami.com/bitnami" }, { "code": null, "e": 4757, "s": 4625, "text": "Finally, you install Airflow with Helm. Easy! Of course, you can change “my-release” to any name you like for this Airflow release." }, { "code": null, "e": 4823, "s": 4757, "text": "helm install –n airflow my-release bitnami/airflow -f values.yaml" }, { "code": null, "e": 4880, "s": 4823, "text": "Airflow is deployed! You should see something like that:" }, { "code": null, "e": 5309, "s": 4880, "text": "NAME: my-releaseLAST DEPLOYED: Thu Mar 11 01:27:30 2021NAMESPACE: airflowSTATUS: deployedREVISION: 1TEST SUITE: NoneNOTES:1. Get the Airflow URL by running:echo URL : http://127.0.0.1:80802. Get your Airflow login credentials by running: export AIRFLOW_PASSWORD=$(kubectl get secret — namespace airflow my-release-airflow -o jsonpath=”{.data.airflow-password}” | base64 — decode) echo User: user echo Password: $AIRFLOW_PASSWORD" }, { "code": null, "e": 5515, "s": 5309, "text": "You can get your Airflow login credentials by following the instruction above. You can also get access to your web UI by the URL you stated in the values.yaml (In this example it is airflow.yourdomain.com)" }, { "code": null, "e": 5639, "s": 5515, "text": "After a while, you should see all your pods are running in the namespace airflow by the command kubectl get pod -n airflow." }, { "code": null, "e": 6072, "s": 5639, "text": "# kubectl get pod -n airflowNAME READY STATUS RESTARTS AGEairflow-postgresql-0 1/1 Running 0 3m53sairflow-redis-master-0 1/1 Running 0 3m53sairflow-redis-slave-0 1/1 Running 0 3m53sairflow-redis-slave-1 1/1 Running 0 3m53sairflow-scheduler-5f8cc4fd5f-jf4s9 2/2 Running 0 3m53sairflow-web-859dd77944-sfgw4 2/2 Running 0 3m53sairflow-worker-0 2/2 Running 0 3m53sairflow-worker-1 2/2 Running 0 3m53sairflow-worker-2 2/2 Running 0 3m53s" }, { "code": null, "e": 6414, "s": 6072, "text": "Sometimes you may need extra Python packages which the original image doesn’t contain. Bitnami’s chart allows you to mount your own requirements.txt to install the required packages. You need to mount your volume to /bitnami/python/requirements.txt. When the container starts, it will execute pip install -r /bitnami/python/requirements.txt." }, { "code": null, "e": 6709, "s": 6414, "text": "In the worker component, you need to modify extraVolumeMounts by providing the name of volume and mountPath of the container instance. You also need to add your extraVolumes. I used ConfigMap to add the requirements.txt to the container as it is easier for me to add more extra python packages." }, { "code": null, "e": 6964, "s": 6709, "text": "extraVolumeMounts: - name: requirements mountPath: /bitnami/python/## Add extra volumesextraVolumes: - name: requirements configMap:# Provide the name of the ConfigMap containing the files you want# to add to the container name: requirements" }, { "code": null, "e": 7101, "s": 6964, "text": "To create the ConfigMap we need, first, we prepare our requirements.txt file. And then we create the ConfigMap by the following command:" }, { "code": null, "e": 7179, "s": 7101, "text": "kubectl create -n airflow configmap requirements --from-file=requirements.txt" }, { "code": null, "e": 7300, "s": 7179, "text": "After we create the ConfigMap and our values.yaml is modified, we need to upgrade our Airflow. Just by a simple command:" }, { "code": null, "e": 7366, "s": 7300, "text": "helm upgrade –n airflow my-release bitnami/airflow -f values.yaml" }, { "code": null, "e": 8082, "s": 7366, "text": "In this article, I showed you the basics of how to deploy Airflow on Kubernetes. Bitnami provides a well-organized Helm chart for us to deploy Airflow on Kubernetes easily. Based on Bitnami’s Helm chart, there are still some minor parameters like database username and password, auth fernet key, extra python package, etc we need to tune. Although Bitnami has already saved us a lot of hard work, I have still gone through many trial and error processes before establishing the “right” setting. Hopefully, this guide will save you some time! If you have any ideas about the architecture of Airflow on Kubernetes, please let me know. I would like to hear from you about a better, more scalable Airflow on Kubernetes." }, { "code": null, "e": 8298, "s": 8082, "text": "If you want to know more about the use cases of Airflow, you can read my previous article. In that article, I showed how I built an automated reporting system for mobile network performance monitoring using Airflow." }, { "code": null, "e": 8321, "s": 8298, "text": "towardsdatascience.com" }, { "code": null, "e": 8424, "s": 8321, "text": "If you want to learn how to build an on-premise Kubernetes using Kubespray, please visit this article:" }, { "code": null, "e": 8447, "s": 8424, "text": "towardsdatascience.com" } ]
How to create a JSON using Jackson Tree Model in Java?
In the Jackson library, we can use the Tree Model to represent the JSON structure and perform the CRUD operations via JsonNode. This Jackson Tree Model is useful, especially in cases where a JSON structure does not map to Java classes. We can create a JSON in the Jackson library using the JsonNodeFactory, it can specify the methods for getting access to Node instances as well as the basic implementation of the methods. We can use the set() and put() methods of ObjectNode class to populate the data. public class JsonNodeFactory extends Object implements Serializable import java.io.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.node.*; public class JacksonTreeModelTest { public static void main(String args[]) throws IOException { JsonNodeFactory factory = new JsonNodeFactory(false); ObjectMapper mapper = new ObjectMapper(); ObjectNode employee = factory.objectNode(); employee.put("empId", 125); employee.put("firstName", "Raja"); employee.put("lastName", "Ramesh"); ArrayNode technologies = factory.arrayNode(); technologies.add("Python").add("Java").add("SAP"); employee.set("technologies", technologies); System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee)); } } { "empId" : 125, "firstName" : "Raja", "lastName" : "Ramesh", "technologies" : [ "Python", "Java", "SAP" ] }
[ { "code": null, "e": 1566, "s": 1062, "text": "In the Jackson library, we can use the Tree Model to represent the JSON structure and perform the CRUD operations via JsonNode. This Jackson Tree Model is useful, especially in cases where a JSON structure does not map to Java classes. We can create a JSON in the Jackson library using the JsonNodeFactory, it can specify the methods for getting access to Node instances as well as the basic implementation of the methods. We can use the set() and put() methods of ObjectNode class to populate the data." }, { "code": null, "e": 1634, "s": 1566, "text": "public class JsonNodeFactory extends Object implements Serializable" }, { "code": null, "e": 2375, "s": 1634, "text": "import java.io.*;\nimport com.fasterxml.jackson.databind.*;\nimport com.fasterxml.jackson.databind.node.*;\npublic class JacksonTreeModelTest {\n public static void main(String args[]) throws IOException {\n JsonNodeFactory factory = new JsonNodeFactory(false);\n ObjectMapper mapper = new ObjectMapper();\n ObjectNode employee = factory.objectNode();\n employee.put(\"empId\", 125);\n employee.put(\"firstName\", \"Raja\");\n employee.put(\"lastName\", \"Ramesh\");\n ArrayNode technologies = factory.arrayNode();\n technologies.add(\"Python\").add(\"Java\").add(\"SAP\");\n employee.set(\"technologies\", technologies);\n System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee));\n }\n}" }, { "code": null, "e": 2496, "s": 2375, "text": "{\n \"empId\" : 125,\n \"firstName\" : \"Raja\",\n \"lastName\" : \"Ramesh\",\n \"technologies\" : [ \"Python\", \"Java\", \"SAP\" ]\n}" } ]
Renaming column name in a MongoDB collection?
To rename column name in a collection, you can use $rename operator. Following is the syntax db.yourCollectionName.update({}, {$rename: {'yourOldColumName': 'yourNewColumnName'}}, false, true); Let us first create a collection with documents: > db.renamingColumnNameDemo.insertOne({"StudentName":"Larry","Age":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ee2c6d628fa4220163b9a") } > db.renamingColumnNameDemo.insertOne({"StudentName":"Sam","Age":26}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ee2d0d628fa4220163b9b") } > db.renamingColumnNameDemo.insertOne({"StudentName":"Robert","Age":27}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ee2dbd628fa4220163b9c") } Following is the query to display all documents from a collection with the help of find() method > db.renamingColumnNameDemo.find().pretty(); This will produce the following output { "_id" : ObjectId("5c9ee2c6d628fa4220163b9a"), "StudentName" : "Larry", "Age" : 23 } { "_id" : ObjectId("5c9ee2d0d628fa4220163b9b"), "StudentName" : "Sam", "Age" : 26 } { "_id" : ObjectId("5c9ee2dbd628fa4220163b9c"), "StudentName" : "Robert", "Age" : 27 } Following is the query to rename column name in a MongoDB collection > db.renamingColumnNameDemo.update({}, {$rename: {'Age': 'StudentAge'}}, false, true); WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 }) Now check the column Age has been renamed with “StudentAge” > db.renamingColumnNameDemo.find().pretty(); This will produce the following output { "_id" : ObjectId("5c9ee2c6d628fa4220163b9a"), "StudentName" : "Larry", "StudentAge" : 23 } { "_id" : ObjectId("5c9ee2d0d628fa4220163b9b"), "StudentName" : "Sam", "StudentAge" : 26 } { "_id" : ObjectId("5c9ee2dbd628fa4220163b9c"), "StudentName" : "Robert", "StudentAge" : 27 }
[ { "code": null, "e": 1155, "s": 1062, "text": "To rename column name in a collection, you can use $rename operator. Following is the syntax" }, { "code": null, "e": 1256, "s": 1155, "text": "db.yourCollectionName.update({}, {$rename: {'yourOldColumName': 'yourNewColumnName'}}, false, true);" }, { "code": null, "e": 1305, "s": 1256, "text": "Let us first create a collection with documents:" }, { "code": null, "e": 1778, "s": 1305, "text": "> db.renamingColumnNameDemo.insertOne({\"StudentName\":\"Larry\",\"Age\":23});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9ee2c6d628fa4220163b9a\")\n}\n> db.renamingColumnNameDemo.insertOne({\"StudentName\":\"Sam\",\"Age\":26});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9ee2d0d628fa4220163b9b\")\n}\n> db.renamingColumnNameDemo.insertOne({\"StudentName\":\"Robert\",\"Age\":27});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9ee2dbd628fa4220163b9c\")\n}" }, { "code": null, "e": 1875, "s": 1778, "text": "Following is the query to display all documents from a collection with the help of find() method" }, { "code": null, "e": 1920, "s": 1875, "text": "> db.renamingColumnNameDemo.find().pretty();" }, { "code": null, "e": 1959, "s": 1920, "text": "This will produce the following output" }, { "code": null, "e": 2243, "s": 1959, "text": "{\n \"_id\" : ObjectId(\"5c9ee2c6d628fa4220163b9a\"),\n \"StudentName\" : \"Larry\",\n \"Age\" : 23\n}\n{\n \"_id\" : ObjectId(\"5c9ee2d0d628fa4220163b9b\"),\n \"StudentName\" : \"Sam\",\n \"Age\" : 26\n}\n{\n \"_id\" : ObjectId(\"5c9ee2dbd628fa4220163b9c\"),\n \"StudentName\" : \"Robert\",\n \"Age\" : 27\n}" }, { "code": null, "e": 2312, "s": 2243, "text": "Following is the query to rename column name in a MongoDB collection" }, { "code": null, "e": 2465, "s": 2312, "text": "> db.renamingColumnNameDemo.update({}, {$rename: {'Age': 'StudentAge'}}, false, true);\nWriteResult({ \"nMatched\" : 3, \"nUpserted\" : 0, \"nModified\" : 3 })" }, { "code": null, "e": 2525, "s": 2465, "text": "Now check the column Age has been renamed with “StudentAge”" }, { "code": null, "e": 2570, "s": 2525, "text": "> db.renamingColumnNameDemo.find().pretty();" }, { "code": null, "e": 2609, "s": 2570, "text": "This will produce the following output" }, { "code": null, "e": 2914, "s": 2609, "text": "{\n \"_id\" : ObjectId(\"5c9ee2c6d628fa4220163b9a\"),\n \"StudentName\" : \"Larry\",\n \"StudentAge\" : 23\n}\n{\n \"_id\" : ObjectId(\"5c9ee2d0d628fa4220163b9b\"),\n \"StudentName\" : \"Sam\",\n \"StudentAge\" : 26\n}\n{\n \"_id\" : ObjectId(\"5c9ee2dbd628fa4220163b9c\"),\n \"StudentName\" : \"Robert\",\n \"StudentAge\" : 27\n}" } ]
Angular CLI - ng new Command
This chapter explains the syntax, argument and options of ng new command along with an example. The syntax for ng new command is as follows − ng new <name> [options] ng n <name> [options] ng new command creates a workspace of given name with a default Angular Application. It provides interactive prompts to set optional configurations. All prompts have default values to choose. The argument for ng new command is as follows − Options are optional parameters. A collection of schematics to use in generating the initial app. Aliases: -c. Initial git repository commit information. Default: true. When true (the default), creates a new initial app project in the src folder of the new workspace. When false, creates an empty workspace with no initial app. You can then use to generate application command so that all apps are created in the projects folder. Default: true. When true, runs through and reports activity without writing out results. Default: false. Aliases: -d. When true, forces overwriting of existing files. Default: false. Aliases: -f. Shows a help message for this command in the console. Default: false. When true, includes styles inline in the component TS file. By default, an external styles file is created and referenced in the component TS file. Default: false. When true, includes styles inline in the componentTS file. By default, an external styles file is created and referenced in the component TS file. Default: false. Aliases: -t. When true, creates a project without any testing frameworks. (Use for learning purposes only.) Default: false. The path where new projects will be created, relative to the new workspace root. Default: projects. The prefix to apply to generated selectors for the initial project. Default: app. Aliases: -p. The prefix to apply to generated selectors for the initial project. Default: app. Aliases: -p. When true, does not initialize a git repository. Default: false. Aliases: -g. When true, does not install dependency packages. Default: false. When true, does not generate "spec.ts" test files for the new project. Default: false. Aliases: -S. Creates a workspace with stricter TypeScript compiler options. Default: false. When true, adds more details to output logging. Default: false. Aliases: -v. An example for ng new command is given below − \>Node ng new TutorialsPoint ? Would you like to add Angular routing? Yes ? Which stylesheet format would you like to use? CSS CREATE TutorialsPoint/angular.json (3630 bytes) CREATE TutorialsPoint/package.json (1291 bytes) CREATE TutorialsPoint/README.md (1031 bytes) CREATE TutorialsPoint/tsconfig.json (489 bytes) CREATE TutorialsPoint/tslint.json (3125 bytes) CREATE TutorialsPoint/.editorconfig (274 bytes) CREATE TutorialsPoint/.gitignore (631 bytes) CREATE TutorialsPoint/browserslist (429 bytes) CREATE TutorialsPoint/karma.conf.js (1026 bytes) CREATE TutorialsPoint/tsconfig.app.json (210 bytes) CREATE TutorialsPoint/tsconfig.spec.json (270 bytes) CREATE TutorialsPoint/src/favicon.ico (948 bytes) CREATE TutorialsPoint/src/index.html (300 bytes) CREATE TutorialsPoint/src/main.ts (372 bytes) CREATE TutorialsPoint/src/polyfills.ts (2835 bytes) CREATE TutorialsPoint/src/styles.css (80 bytes) CREATE TutorialsPoint/src/test.ts (753 bytes) CREATE TutorialsPoint/src/assets/.gitkeep (0 bytes) CREATE TutorialsPoint/src/environments/environment.prod.ts (51 bytes) CREATE TutorialsPoint/src/environments/environment.ts (662 bytes) CREATE TutorialsPoint/src/app/app-routing.module.ts (246 bytes) CREATE TutorialsPoint/src/app/app.module.ts (393 bytes) CREATE TutorialsPoint/src/app/app.component.html (25755 bytes) CREATE TutorialsPoint/src/app/app.component.spec.ts (1083 bytes) CREATE TutorialsPoint/src/app/app.component.ts (218 bytes) CREATE TutorialsPoint/src/app/app.component.css (0 bytes) CREATE TutorialsPoint/e2e/protractor.conf.js (808 bytes) CREATE TutorialsPoint/e2e/tsconfig.json (214 bytes) CREATE TutorialsPoint/e2e/src/app.e2e-spec.ts (647 bytes) CREATE TutorialsPoint/e2e/src/app.po.ts (301 bytes) Packages installed successfully. Here, ng new command has created an angular workspace and a project with name TutorialsPoint in our Node directory. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2171, "s": 2075, "text": "This chapter explains the syntax, argument and options of ng new command along with an example." }, { "code": null, "e": 2217, "s": 2171, "text": "The syntax for ng new command is as follows −" }, { "code": null, "e": 2264, "s": 2217, "text": "ng new <name> [options]\nng n <name> [options]\n" }, { "code": null, "e": 2349, "s": 2264, "text": "ng new command creates a workspace of given name with a default Angular Application." }, { "code": null, "e": 2456, "s": 2349, "text": "It provides interactive prompts to set optional configurations. All prompts have default values to choose." }, { "code": null, "e": 2504, "s": 2456, "text": "The argument for ng new command is as follows −" }, { "code": null, "e": 2537, "s": 2504, "text": "Options are optional parameters." }, { "code": null, "e": 2602, "s": 2537, "text": "A collection of schematics\nto use in generating the\ninitial app." }, { "code": null, "e": 2615, "s": 2602, "text": "Aliases: -c." }, { "code": null, "e": 2658, "s": 2615, "text": "Initial git repository commit information." }, { "code": null, "e": 2673, "s": 2658, "text": "Default: true." }, { "code": null, "e": 2934, "s": 2673, "text": "When true (the default), creates a new initial app project in the src folder of the new workspace. When false, creates an empty workspace with no initial app. You can then use to generate application command so that all apps are created in the projects folder." }, { "code": null, "e": 2949, "s": 2934, "text": "Default: true." }, { "code": null, "e": 3023, "s": 2949, "text": "When true, runs through\nand reports activity\nwithout writing out\nresults." }, { "code": null, "e": 3039, "s": 3023, "text": "Default: false." }, { "code": null, "e": 3052, "s": 3039, "text": "Aliases: -d." }, { "code": null, "e": 3101, "s": 3052, "text": "When true, forces\noverwriting of existing\nfiles." }, { "code": null, "e": 3117, "s": 3101, "text": "Default: false." }, { "code": null, "e": 3130, "s": 3117, "text": "Aliases: -f." }, { "code": null, "e": 3184, "s": 3130, "text": "Shows a help message for this command in the console." }, { "code": null, "e": 3200, "s": 3184, "text": "Default: false." }, { "code": null, "e": 3348, "s": 3200, "text": "When true, includes styles inline in the component TS file. By default, an external styles file is created and referenced in the component TS file." }, { "code": null, "e": 3364, "s": 3348, "text": "Default: false." }, { "code": null, "e": 3511, "s": 3364, "text": "When true, includes styles inline in the componentTS file. By default, an external styles file is created and referenced in the component TS file." }, { "code": null, "e": 3527, "s": 3511, "text": "Default: false." }, { "code": null, "e": 3540, "s": 3527, "text": "Aliases: -t." }, { "code": null, "e": 3635, "s": 3540, "text": "When true, creates a project without any testing frameworks. (Use for learning purposes only.)" }, { "code": null, "e": 3651, "s": 3635, "text": "Default: false." }, { "code": null, "e": 3732, "s": 3651, "text": "The path where new projects will be created, relative to the new workspace root." }, { "code": null, "e": 3751, "s": 3732, "text": "Default: projects." }, { "code": null, "e": 3819, "s": 3751, "text": "The prefix to apply to generated selectors for the initial project." }, { "code": null, "e": 3833, "s": 3819, "text": "Default: app." }, { "code": null, "e": 3846, "s": 3833, "text": "Aliases: -p." }, { "code": null, "e": 3914, "s": 3846, "text": "The prefix to apply to generated selectors for the initial project." }, { "code": null, "e": 3928, "s": 3914, "text": "Default: app." }, { "code": null, "e": 3941, "s": 3928, "text": "Aliases: -p." }, { "code": null, "e": 3990, "s": 3941, "text": "When true, does not\ninitialize a git repository." }, { "code": null, "e": 4006, "s": 3990, "text": "Default: false." }, { "code": null, "e": 4019, "s": 4006, "text": "Aliases: -g." }, { "code": null, "e": 4068, "s": 4019, "text": "When true, does not install dependency packages." }, { "code": null, "e": 4084, "s": 4068, "text": "Default: false." }, { "code": null, "e": 4155, "s": 4084, "text": "When true, does not generate \"spec.ts\" test files for the new project." }, { "code": null, "e": 4171, "s": 4155, "text": "Default: false." }, { "code": null, "e": 4184, "s": 4171, "text": "Aliases: -S." }, { "code": null, "e": 4247, "s": 4184, "text": "Creates a workspace with stricter TypeScript compiler options." }, { "code": null, "e": 4263, "s": 4247, "text": "Default: false." }, { "code": null, "e": 4311, "s": 4263, "text": "When true, adds more details to output logging." }, { "code": null, "e": 4327, "s": 4311, "text": "Default: false." }, { "code": null, "e": 4340, "s": 4327, "text": "Aliases: -v." }, { "code": null, "e": 4387, "s": 4340, "text": "An example for ng new command is given below −" }, { "code": null, "e": 6141, "s": 4387, "text": "\\>Node ng new TutorialsPoint\n? Would you like to add Angular routing? Yes\n? Which stylesheet format would you like to use? CSS\nCREATE TutorialsPoint/angular.json (3630 bytes)\nCREATE TutorialsPoint/package.json (1291 bytes)\nCREATE TutorialsPoint/README.md (1031 bytes)\nCREATE TutorialsPoint/tsconfig.json (489 bytes)\nCREATE TutorialsPoint/tslint.json (3125 bytes)\nCREATE TutorialsPoint/.editorconfig (274 bytes)\nCREATE TutorialsPoint/.gitignore (631 bytes)\nCREATE TutorialsPoint/browserslist (429 bytes)\nCREATE TutorialsPoint/karma.conf.js (1026 bytes)\nCREATE TutorialsPoint/tsconfig.app.json (210 bytes)\nCREATE TutorialsPoint/tsconfig.spec.json (270 bytes)\nCREATE TutorialsPoint/src/favicon.ico (948 bytes)\nCREATE TutorialsPoint/src/index.html (300 bytes)\nCREATE TutorialsPoint/src/main.ts (372 bytes)\nCREATE TutorialsPoint/src/polyfills.ts (2835 bytes)\nCREATE TutorialsPoint/src/styles.css (80 bytes)\nCREATE TutorialsPoint/src/test.ts (753 bytes)\nCREATE TutorialsPoint/src/assets/.gitkeep (0 bytes)\nCREATE TutorialsPoint/src/environments/environment.prod.ts (51 bytes)\nCREATE TutorialsPoint/src/environments/environment.ts (662 bytes)\nCREATE TutorialsPoint/src/app/app-routing.module.ts (246 bytes)\nCREATE TutorialsPoint/src/app/app.module.ts (393 bytes)\nCREATE TutorialsPoint/src/app/app.component.html (25755 bytes)\nCREATE TutorialsPoint/src/app/app.component.spec.ts (1083 bytes)\nCREATE TutorialsPoint/src/app/app.component.ts (218 bytes)\nCREATE TutorialsPoint/src/app/app.component.css (0 bytes)\nCREATE TutorialsPoint/e2e/protractor.conf.js (808 bytes)\nCREATE TutorialsPoint/e2e/tsconfig.json (214 bytes)\nCREATE TutorialsPoint/e2e/src/app.e2e-spec.ts (647 bytes)\nCREATE TutorialsPoint/e2e/src/app.po.ts (301 bytes)\nPackages installed successfully.\n" }, { "code": null, "e": 6257, "s": 6141, "text": "Here, ng new command has created an angular workspace and a project with name TutorialsPoint in our Node directory." }, { "code": null, "e": 6292, "s": 6257, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6306, "s": 6292, "text": " Anadi Sharma" }, { "code": null, "e": 6341, "s": 6306, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6355, "s": 6341, "text": " Anadi Sharma" }, { "code": null, "e": 6390, "s": 6355, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6410, "s": 6390, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 6445, "s": 6410, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6462, "s": 6445, "text": " Frahaan Hussain" }, { "code": null, "e": 6495, "s": 6462, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 6507, "s": 6495, "text": " Senol Atac" }, { "code": null, "e": 6542, "s": 6507, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6554, "s": 6542, "text": " Senol Atac" }, { "code": null, "e": 6561, "s": 6554, "text": " Print" }, { "code": null, "e": 6572, "s": 6561, "text": " Add Notes" } ]
60 Questions to Test Your Knowledge of Python Lists | by GreekDataGuy | Towards Data Science
I’ve been doing a lot of algorithm questions lately and discovered I don’t understand lists as well as I should This is my compilation of 60 list questions I’ve written to evaluate my own knowledge. I hope you’ll find it as useful as writing it has been for me. The in operator will return True if a specific element is in a list. li = [1,2,3,'a','b','c']'a' in li #=> True You can zip() lists and then iterate over the zip object. A zip object is an iterator of tuples. Below we iterate over 3 lists simultaneously and interpolate the values into a string. name = ['Snowball', 'Chewy', 'Bubbles', 'Gruff']animal = ['Cat', 'Dog', 'Fish', 'Goat']age = [1, 2, 2, 6]z = zip(name, animal, age)z #=> <zip at 0x111081e48>for name,animal,age in z: print("%s the %s is %s" % (name, animal, age)) #=> Snowball the Cat is 1#=> Chewy the Dog is 2#=> Bubbles the Fish is 2#=> Gruff the Goat is 6 Lists and dictionary generally have slightly different use cases but there is some overlap. The general rule of algorithm questions I’ve come to is that if you can use both, use a dictionary because lookups are faster. Use a list if you need to store the order of something. Ie: id’s of database records in the order they’ll be displayed. ids = [23,1,7,9] While both lists and dictionaries are ordered as of python 3.7, a list allows duplicate values while a dictionary doesn’t allow duplicate keys. Use a dictionary if you want to count occurrences of something. Like the number of pets in a home. pets = {'dogs':2,'cats':1,'fish':5} Each key can only exist once in a dictionary. Note that keys can also be other immutable data structures like tuples. Ie: {('a',1):1, ('b',2):1}. Yes. Notice in the code below how the value associated with the same identifier in memory has not changed. x = [1]print(id(x),':',x) #=> 4501046920 : [1]x.append(5)x.extend([6,7])print(id(x),':',x) #=> 4501046920 : [1, 5, 6, 7] No. Different types of object can be mixed together in a list. a = [1,'a',1.0,[]]a #=> [1, 'a', 1.0, []] .append() adds an object to the end of a list. a = [1,2,3]a.append(4)a #=> [1, 2, 3, 4] This also means appending a list adds that whole list as a single element, rather than appending each of its values. a.append([5,6])a #=> [1, 2, 3, 4, [5, 6]] .extend() adds each value from a 2nd list as its own element. So extending a list with another list combines their values. b = [1,2,3]b.extend([5,6])b #=> [1, 2, 3, 5, 6] Python lists don’t store values themselves. They store pointers to values stored elsewhere in memory. This allows lists to be mutable. Here we initialize values 1 and 2, then create a list including the values 1 and 2. print( id(1) ) #=> 4438537632print( id(2) ) #=> 4438537664a = [1,2,3]print( id(a) ) #=> 4579953480print( id(a[0]) ) #=> 4438537632print( id(a[1]) ) #=> 4438537664 Notice how the list has its own memory address. But 1 and 2 in the list point to the same place in memory as the 1 and 2 we previously defined. del removes an item from a list given its index. Here we’ll remove the value at index 1. a = ['w', 'x', 'y', 'z']a #=> ['w', 'x', 'y', 'z']del a[1]a #=> ['w', 'y', 'z'] Notice how del does not return the removed element. .remove() removes the first instance of a matching object. Below we remove the first b. a = ['a', 'a', 'b', 'b', 'c', 'c']a.remove('b')a #=> ['a', 'a', 'b', 'c', 'c'] .pop() removes an object by its index. The difference between pop and del is that pop returns the popped element. This allows using a list like a stack. a = ['a', 'a', 'b', 'b', 'c', 'c']a.pop(4) #=> 'c'a #=> ['a', 'a', 'b', 'b', 'c'] By default, pop removes the last element from a list if an index isn’t specified. If you’re not concerned about maintaining the order of a list, then converting to a set and back to a list will achieve this. li = [3, 2, 2, 1, 1, 1]list(set(li)) #=> [1, 2, 3] For example, you want to find the first “apple” in a list of fruit. Use the .index() method. fruit = ['pear', 'orange', 'apple', 'grapefruit', 'apple', 'pear']fruit.index('apple') #=> 2fruit.index('pear') #=> 0 Rather than creating a new empty list, we can clear the elements from an existing list with .clear(). fruit = ['pear', 'orange', 'apple']print( fruit ) #=> ['pear', 'orange', 'apple']print( id(fruit) ) #=> 4581174216fruit.clear()print( fruit ) #=> []print( id(fruit) ) #=> 4581174216 Or with del. fruit = ['pear', 'orange', 'apple']print( fruit ) #=> ['pear', 'orange', 'apple']print( id(fruit) ) #=> 4581166792del fruit[:]print( fruit ) #=> []print( id(fruit) ) #=> 4581166792 enumerate() adds a counter to the list passed as an argument. Below we iterate over the list and pass both value and index into string interpolation. grocery_list = ['flour','cheese','carrots']for idx,val in enumerate(grocery_list): print("%s: %s" % (idx, val)) #=> 0: flour#=> 1: cheese#=> 2: carrots The + operator will concatenate 2 lists. one = ['a', 'b', 'c']two = [1, 2, 3]one + two #=> ['a', 'b', 'c', 1, 2, 3] Below we return a new list with 1 added to every element. li = [0,25,50,100][i+1 for i in li] #=> [1, 26, 51, 101] The count() method returns the number of occurrences of a specific object. Below we return the number of times the string, “fish” exists in a list called pets. pets = ['dog','cat','fish','fish','cat']pets.count('fish')#=> 2 .copy() can be used to shallow copy a list. Below we create a shallow copy of round1, assign it to a new name, round2, and then remove the string sonny chiba. round1 = ['chuck norris', 'bruce lee', 'sonny chiba']round2 = round1.copy()round2.remove('sonny chiba')print(round1) #=> ['chuck norris', 'bruce lee', 'sonny chiba']print(round2) #=> ['chuck norris', 'bruce lee'] Building off the previous example, modifying round2 will modify round1 if we don’t create a shallow copy. round1 = ['chuck norris', 'bruce lee', 'sonny chiba']round2 = round1round2.remove('sonny chiba')print(round1) #=> ['chuck norris', 'bruce lee']print(round2) #=> ['chuck norris', 'bruce lee'] Without a shallow copy, round1 and round2 are just names pointing to the same list in memory. That’s why it appears that changing the value of one changes the value of the other. For this we need to import the copy module, then call copy.deepcopy(). Below we create a deep copy of a list, round1 called round2, update a value in round2, then print both. In this case, round1 isn’t affected. round1 = [ ['Arnold', 'Sylvester', 'Jean Claude'], ['Buttercup', 'Bubbles', 'Blossom']]import copyround2 = copy.deepcopy(round1)round2[0][0] = 'Jet Lee'print(round1)#=> [['Arnold', 'Sylvester', 'Jean Claude'], ['Buttercup', 'Bubbles', 'Blossom']]print(round2)#=> [['Jet Lee', 'Sylvester', 'Jean Claude'], ['Buttercup', 'Bubbles', 'Blossom']] Above we can see that changing the nested array in round2 did not update round1. Building off the previous example, creating a shallow copy and then modifying it would have affected the original list.. round1 = [ ['Arnold', 'Sylvester', 'Jean Claude'], ['Buttercup', 'Bubbles', 'Blossom']]import copyround2 = round1.copy()round2[0][0] = 'Jet Lee'print(round1)#=> [['Jet Lee', 'Sylvester', 'Jean Claude'], ['Buttercup', 'Bubbles', 'Blossom']]print(round2)#=> [['Jet Lee', 'Sylvester', 'Jean Claude'], ['Buttercup', 'Bubbles', 'Blossom']] Why does this happen? Creating a shallow copy does create a new object in memory, but it’s filled with the same references to existing objects that the previous list has. Creating a deep copy creates copies of the original objects and points to these new versions. So the new list is completely unaffected by changes to the old list and vice versa. Tuples cannot be updated after creation. Adding/removing/updating an existing tuple requires creating a new tuple. Lists can be modified after creation. Tuples often represent an object like a record loaded from a database where elements are of different datatypes. Lists are generally used to store an ordered sequence of a specific type of object (but not always). Both are sequences and allow duplicate values. len() can returns the length of a list. li = ['a', 'b', 'c', 'd', 'e']len(li)#=> 5 But note it counts top level objects, so a nested list of several integers will only be counted as a single object. Below, li has a length of 2, not 5. li = [[1,2],[3,4,5]]len(li)#=> 2 While a list is ordered, a set is not. That’s why using set to find unique values in a list, like list( set([3, 3, 2, 1]) ) loses the order. While lists are often used to track order, sets are often used to track existence. Lists allow duplicates, but all values in a set are unique by definition. For this we use the in operator, but prefix it with not. li = [1,2,3,4]5 not in li #=> True4 not in li #=> False .map() allows iterating over a sequence and updating each value with another function. map() returns a map object but I’ve wrapped it with a list comprehension so we can see the updated values. def multiply_5(val): return val * 5a = [10,20,30,40,50][val for val in map(multiply_5, a)] #=> [50, 100, 150, 200, 250] zip() combines multiple sequences into an iterator of tuples, where values at the same sequence index are combined in the same tuple. alphabet = ['a', 'b', 'c']integers = [1, 2, 3]list(zip(alphabet, integers)) The insert() method takes an object to insert and the index to insert it at. li = ['a','b','c','d','e']li.insert(2, 'HERE')li #=> ['a', 'b', 'HERE', 'c', 'd', 'e'] Note that the element previously at the specified index is shifted to the right, not overwritten. reduce() needs to be imported from functools. Given a function, reduce iterates over a sequence and calls the function on every element. The output from the previous element is passed as an argument when calling the function on the next element. from functools import reducedef subtract(a,b): return a - bnumbers = [100,10,5,1,2,7,5]reduce(subtract, numbers) #=> 70 Above we subtracted 10, 5, 1, 2, 7 and 5 from 100. Given a function, filter() will remove any elements from a sequence on which the function doesn’t return True. Below we remove elements less than zero. def remove_negatives(x): return True if x >= 0 else False a = [-10, 27, 1000, -1, 0, -30][x for x in filter(remove_negatives, a)] #=> [27, 1000, 0] For this we can use a dictionary comprehension. li = ['The', 'quick', 'brown', 'fox', 'was', 'quick']d = {k:1 for k in li}d #=> {'The': 1, 'quick': 1, 'brown': 1, 'fox': 1, 'was': 1} Let’s take the previous map function we wrote and turn it into a one-liner with a lambda. a = [10,20,30,40,50]list(map(lambda val:val*5, a))#=> [50, 100, 150, 200, 250] I could have left it as a map object until I needed to iterate over it but I converted to a list to show the elements inside. Using the slice syntax, we can return a new list with only the elements up to a specific index. li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]li[:10]#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] The slice syntax can also return a new list with the values after a specified index. li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]li[15:]#=> [16, 17, 18, 19, 10] Or between two indices. li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]li[12:17]#=> [13, 14, 15, 16, 17] Or before/after/between indices at a specific interval. Here we return every 2nd value between the indices 10 and 16 using the slice syntax. li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]li[10:16:2]#=> [11, 13, 15] The sort() method mutates a list into ascending order. li = [10,1,9,2,8,3,7,4,6,5]li.sort()li #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] It’s also possible to sort in descending order with sort() by adding the argument reverse=True. li = [10,1,9,2,8,3,7,4,6,5]li.sort(reverse=True)li #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] You can add conditional logic inside a list comprehension to filter out values following a given pattern. Here we filter out values divisible by 2. li = [1,2,3,4,5,6,7,8,9,10][i for i in li if i % 2 != 0]#=> [1, 3, 5, 7, 9] One option is to iterate over a list and add counts to a dictionary. But the easiest option is to import the Counter class from collections and pass the list to it. from collections import Counterli = ['blue', 'pink', 'green', 'green', 'yellow', 'pink', 'orange']Counter(li)#=> Counter({'blue': 1, 'pink': 2, 'green': 2, 'yellow': 1, 'orange': 1}) A list comprehension is well suited for iterating over a list of other objects and grabbing an element from each nested object. li = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]][i[0] for i in li]#=> [1, 4, 7, 10, 13] Insert is O(n). If an element is inserted at the beginning, all other elements must be shifted right. Find by index is O(1). But find by value is O(n) because elements need to be iterated over until the value is found. Delete is O(n). If an element is deleted at the beginning, all other elements must to be shifted left. This can be done with the join() function. li = ['The','quick','brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']' '.join(li)#=> 'The quick brown fox jumped over the lazy dog' Multiplying a list by an integer is called multiple concatenation and has the same affect as concatenating a list to itself n-times. Below we multiple a list by 5. ['a','b'] * 5#=> ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'] This is the same as. ['a','b'] + ['a','b'] + ['a','b'] + ['a','b'] + ['a','b']#=> ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'] We can combine any() with a list comprehension to return True if any values in the returned list evaluate to True. Below the 1st list comprehension returns True because the list has a 2 in it, which is divisible by 2. li1 = [1,2,3]li2 = [1,3]any(i % 2 == 0 for i in li1) #=> Trueany(i % 2 == 0 for i in li2) #=> False Similar to the any() function, all() can also be used with a list comprehension to return True only if all values in the returned list are True. li1 = [2,3,4]li2 = [2,4]all(i % 2 == 0 for i in li1) #=> Falseall(i % 2 == 0 for i in li2) #=> True You cannot sort a list with None in it because comparison operators (used by sort()) can’t compare an integer with None. li = [10,1,9,2,8,3,7,4,6,None]li.sort()li #=> TypeError: '<' not supported between instances of 'NoneType' and 'int' The list constructor creates a shallow copy of a passed in list. That said, this is less pythonic than using .copy(). li1 = ['a','b']li2 = list(li1)li2.append('c')print(li1) #=> ['a', 'b']print(li2) #=> ['a', 'b', 'c'] A list can be mutated into reverse order with the reverse() method. li = [1,2,3,4,5,6,7,8,9,10]li.reverse()li #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] Note that this mutates the object instead of returning a new object. reverse() reverses the list in place. reversed() returns an iterable of the list in reverse order. li = [1,2,3,4,5,6,7,8,9,10]list(reversed(li))#=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] sort() modifies the list in place. sorted() returns a new list in reverse order. li = [10,1,9,2,8,3,7,4,6,5]li.sort()li #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]li = [10,1,9,2,8,3,7,4,6,5]sorted(li) #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] The min() function returns the minimum value in a list. li = [10,1,9,2,8,3,7,4,6,5]min(li)#=> 1 The max() function returns the maximum value in a list. li = [10,1,9,2,8,3,7,4,6,5]max(li)#=> 10 The sum() function returns the sum of all values in a list. li = [10,1,9,2,8,3,7,4,6,5]sum(li)#=> 55 You can use append() and pop() to treat a list like a stack. Stacks function per LIFO (last in first out). stack = []stack.append('Jess')stack.append('Todd')stack.append('Yuan')print(stack) #=> ['Jess', 'Todd', 'Yuan']print(stack.pop()) #=> Yuanprint(stack) #=> ['Jess', 'Todd'] One benefit of a stack is that elements can be added and removed in O(1) time because the list does not need to be iterated over. We can do this by utilizing set() with an ampersand. li1 = [1,2,3]li2 = [2,3,4]set(li1) & set(li2)#=> {2, 3} We can’t subtract lists, but we can subtract sets. li1 = [1,2,3]li2 = [2,3,4]set(li1) - set(li2)#=> {1}set(li2) - set(li1)#=> {4} Unlike Ruby, Python3 doesn’t have an explicit flatten function. But we can use list comprehension to flatten a list of lists. li = [[1,2,3],[4,5,6]][i for x in li for i in x]#=> [1, 2, 3, 4, 5, 6] We can create a range between 2 values and then convert that to a list. list(range(5,10))#=> [5, 6, 7, 8, 9] Using zip() and the list() constructor we can combine 2 lists into a dictionary where one list becomes the keys and the other list becomes the values. name = ['Snowball', 'Chewy', 'Bubbles', 'Gruff']animal = ['Cat', 'Dog', 'Fish', 'Goat']dict(zip(name, animal))#=> {'Snowball': 'Cat', 'Chewy': 'Dog', 'Bubbles': 'Fish', 'Gruff': 'Goat'} While we can reverse a list with reverse() and reversed(), it can also be done with the slice syntax. This returns a new list by iterating back over the list from end to beginning. li = ['a','b',3,4]li[::-1]#=> [4, 3, 'b', 'a'] After working through this I feel more prepared to tackle algorithm questions without second guessing specific list method. Removing constant googling can free up energy for higher order thinking, like getting a function to do what it’s supposed to, and reducing function complexity. Again, I hope you found this useful as well. You may be interested in my previous post on strings questions, or the weekly series on algorithm questions I’ve started to publish.
[ { "code": null, "e": 284, "s": 172, "text": "I’ve been doing a lot of algorithm questions lately and discovered I don’t understand lists as well as I should" }, { "code": null, "e": 371, "s": 284, "text": "This is my compilation of 60 list questions I’ve written to evaluate my own knowledge." }, { "code": null, "e": 434, "s": 371, "text": "I hope you’ll find it as useful as writing it has been for me." }, { "code": null, "e": 503, "s": 434, "text": "The in operator will return True if a specific element is in a list." }, { "code": null, "e": 546, "s": 503, "text": "li = [1,2,3,'a','b','c']'a' in li #=> True" }, { "code": null, "e": 643, "s": 546, "text": "You can zip() lists and then iterate over the zip object. A zip object is an iterator of tuples." }, { "code": null, "e": 730, "s": 643, "text": "Below we iterate over 3 lists simultaneously and interpolate the values into a string." }, { "code": null, "e": 1062, "s": 730, "text": "name = ['Snowball', 'Chewy', 'Bubbles', 'Gruff']animal = ['Cat', 'Dog', 'Fish', 'Goat']age = [1, 2, 2, 6]z = zip(name, animal, age)z #=> <zip at 0x111081e48>for name,animal,age in z: print(\"%s the %s is %s\" % (name, animal, age)) #=> Snowball the Cat is 1#=> Chewy the Dog is 2#=> Bubbles the Fish is 2#=> Gruff the Goat is 6" }, { "code": null, "e": 1154, "s": 1062, "text": "Lists and dictionary generally have slightly different use cases but there is some overlap." }, { "code": null, "e": 1281, "s": 1154, "text": "The general rule of algorithm questions I’ve come to is that if you can use both, use a dictionary because lookups are faster." }, { "code": null, "e": 1337, "s": 1281, "text": "Use a list if you need to store the order of something." }, { "code": null, "e": 1401, "s": 1337, "text": "Ie: id’s of database records in the order they’ll be displayed." }, { "code": null, "e": 1418, "s": 1401, "text": "ids = [23,1,7,9]" }, { "code": null, "e": 1562, "s": 1418, "text": "While both lists and dictionaries are ordered as of python 3.7, a list allows duplicate values while a dictionary doesn’t allow duplicate keys." }, { "code": null, "e": 1661, "s": 1562, "text": "Use a dictionary if you want to count occurrences of something. Like the number of pets in a home." }, { "code": null, "e": 1697, "s": 1661, "text": "pets = {'dogs':2,'cats':1,'fish':5}" }, { "code": null, "e": 1843, "s": 1697, "text": "Each key can only exist once in a dictionary. Note that keys can also be other immutable data structures like tuples. Ie: {('a',1):1, ('b',2):1}." }, { "code": null, "e": 1950, "s": 1843, "text": "Yes. Notice in the code below how the value associated with the same identifier in memory has not changed." }, { "code": null, "e": 2071, "s": 1950, "text": "x = [1]print(id(x),':',x) #=> 4501046920 : [1]x.append(5)x.extend([6,7])print(id(x),':',x) #=> 4501046920 : [1, 5, 6, 7]" }, { "code": null, "e": 2134, "s": 2071, "text": "No. Different types of object can be mixed together in a list." }, { "code": null, "e": 2176, "s": 2134, "text": "a = [1,'a',1.0,[]]a #=> [1, 'a', 1.0, []]" }, { "code": null, "e": 2223, "s": 2176, "text": ".append() adds an object to the end of a list." }, { "code": null, "e": 2264, "s": 2223, "text": "a = [1,2,3]a.append(4)a #=> [1, 2, 3, 4]" }, { "code": null, "e": 2381, "s": 2264, "text": "This also means appending a list adds that whole list as a single element, rather than appending each of its values." }, { "code": null, "e": 2423, "s": 2381, "text": "a.append([5,6])a #=> [1, 2, 3, 4, [5, 6]]" }, { "code": null, "e": 2546, "s": 2423, "text": ".extend() adds each value from a 2nd list as its own element. So extending a list with another list combines their values." }, { "code": null, "e": 2594, "s": 2546, "text": "b = [1,2,3]b.extend([5,6])b #=> [1, 2, 3, 5, 6]" }, { "code": null, "e": 2729, "s": 2594, "text": "Python lists don’t store values themselves. They store pointers to values stored elsewhere in memory. This allows lists to be mutable." }, { "code": null, "e": 2813, "s": 2729, "text": "Here we initialize values 1 and 2, then create a list including the values 1 and 2." }, { "code": null, "e": 2976, "s": 2813, "text": "print( id(1) ) #=> 4438537632print( id(2) ) #=> 4438537664a = [1,2,3]print( id(a) ) #=> 4579953480print( id(a[0]) ) #=> 4438537632print( id(a[1]) ) #=> 4438537664" }, { "code": null, "e": 3120, "s": 2976, "text": "Notice how the list has its own memory address. But 1 and 2 in the list point to the same place in memory as the 1 and 2 we previously defined." }, { "code": null, "e": 3169, "s": 3120, "text": "del removes an item from a list given its index." }, { "code": null, "e": 3209, "s": 3169, "text": "Here we’ll remove the value at index 1." }, { "code": null, "e": 3289, "s": 3209, "text": "a = ['w', 'x', 'y', 'z']a #=> ['w', 'x', 'y', 'z']del a[1]a #=> ['w', 'y', 'z']" }, { "code": null, "e": 3341, "s": 3289, "text": "Notice how del does not return the removed element." }, { "code": null, "e": 3429, "s": 3341, "text": ".remove() removes the first instance of a matching object. Below we remove the first b." }, { "code": null, "e": 3508, "s": 3429, "text": "a = ['a', 'a', 'b', 'b', 'c', 'c']a.remove('b')a #=> ['a', 'a', 'b', 'c', 'c']" }, { "code": null, "e": 3547, "s": 3508, "text": ".pop() removes an object by its index." }, { "code": null, "e": 3661, "s": 3547, "text": "The difference between pop and del is that pop returns the popped element. This allows using a list like a stack." }, { "code": null, "e": 3743, "s": 3661, "text": "a = ['a', 'a', 'b', 'b', 'c', 'c']a.pop(4) #=> 'c'a #=> ['a', 'a', 'b', 'b', 'c']" }, { "code": null, "e": 3825, "s": 3743, "text": "By default, pop removes the last element from a list if an index isn’t specified." }, { "code": null, "e": 3951, "s": 3825, "text": "If you’re not concerned about maintaining the order of a list, then converting to a set and back to a list will achieve this." }, { "code": null, "e": 4002, "s": 3951, "text": "li = [3, 2, 2, 1, 1, 1]list(set(li)) #=> [1, 2, 3]" }, { "code": null, "e": 4095, "s": 4002, "text": "For example, you want to find the first “apple” in a list of fruit. Use the .index() method." }, { "code": null, "e": 4213, "s": 4095, "text": "fruit = ['pear', 'orange', 'apple', 'grapefruit', 'apple', 'pear']fruit.index('apple') #=> 2fruit.index('pear') #=> 0" }, { "code": null, "e": 4315, "s": 4213, "text": "Rather than creating a new empty list, we can clear the elements from an existing list with .clear()." }, { "code": null, "e": 4505, "s": 4315, "text": "fruit = ['pear', 'orange', 'apple']print( fruit ) #=> ['pear', 'orange', 'apple']print( id(fruit) ) #=> 4581174216fruit.clear()print( fruit ) #=> []print( id(fruit) ) #=> 4581174216" }, { "code": null, "e": 4518, "s": 4505, "text": "Or with del." }, { "code": null, "e": 4707, "s": 4518, "text": "fruit = ['pear', 'orange', 'apple']print( fruit ) #=> ['pear', 'orange', 'apple']print( id(fruit) ) #=> 4581166792del fruit[:]print( fruit ) #=> []print( id(fruit) ) #=> 4581166792" }, { "code": null, "e": 4769, "s": 4707, "text": "enumerate() adds a counter to the list passed as an argument." }, { "code": null, "e": 4857, "s": 4769, "text": "Below we iterate over the list and pass both value and index into string interpolation." }, { "code": null, "e": 5015, "s": 4857, "text": "grocery_list = ['flour','cheese','carrots']for idx,val in enumerate(grocery_list): print(\"%s: %s\" % (idx, val)) #=> 0: flour#=> 1: cheese#=> 2: carrots" }, { "code": null, "e": 5056, "s": 5015, "text": "The + operator will concatenate 2 lists." }, { "code": null, "e": 5131, "s": 5056, "text": "one = ['a', 'b', 'c']two = [1, 2, 3]one + two #=> ['a', 'b', 'c', 1, 2, 3]" }, { "code": null, "e": 5189, "s": 5131, "text": "Below we return a new list with 1 added to every element." }, { "code": null, "e": 5246, "s": 5189, "text": "li = [0,25,50,100][i+1 for i in li] #=> [1, 26, 51, 101]" }, { "code": null, "e": 5406, "s": 5246, "text": "The count() method returns the number of occurrences of a specific object. Below we return the number of times the string, “fish” exists in a list called pets." }, { "code": null, "e": 5470, "s": 5406, "text": "pets = ['dog','cat','fish','fish','cat']pets.count('fish')#=> 2" }, { "code": null, "e": 5514, "s": 5470, "text": ".copy() can be used to shallow copy a list." }, { "code": null, "e": 5629, "s": 5514, "text": "Below we create a shallow copy of round1, assign it to a new name, round2, and then remove the string sonny chiba." }, { "code": null, "e": 5842, "s": 5629, "text": "round1 = ['chuck norris', 'bruce lee', 'sonny chiba']round2 = round1.copy()round2.remove('sonny chiba')print(round1) #=> ['chuck norris', 'bruce lee', 'sonny chiba']print(round2) #=> ['chuck norris', 'bruce lee']" }, { "code": null, "e": 5948, "s": 5842, "text": "Building off the previous example, modifying round2 will modify round1 if we don’t create a shallow copy." }, { "code": null, "e": 6139, "s": 5948, "text": "round1 = ['chuck norris', 'bruce lee', 'sonny chiba']round2 = round1round2.remove('sonny chiba')print(round1) #=> ['chuck norris', 'bruce lee']print(round2) #=> ['chuck norris', 'bruce lee']" }, { "code": null, "e": 6318, "s": 6139, "text": "Without a shallow copy, round1 and round2 are just names pointing to the same list in memory. That’s why it appears that changing the value of one changes the value of the other." }, { "code": null, "e": 6389, "s": 6318, "text": "For this we need to import the copy module, then call copy.deepcopy()." }, { "code": null, "e": 6530, "s": 6389, "text": "Below we create a deep copy of a list, round1 called round2, update a value in round2, then print both. In this case, round1 isn’t affected." }, { "code": null, "e": 6878, "s": 6530, "text": "round1 = [ ['Arnold', 'Sylvester', 'Jean Claude'], ['Buttercup', 'Bubbles', 'Blossom']]import copyround2 = copy.deepcopy(round1)round2[0][0] = 'Jet Lee'print(round1)#=> [['Arnold', 'Sylvester', 'Jean Claude'], ['Buttercup', 'Bubbles', 'Blossom']]print(round2)#=> [['Jet Lee', 'Sylvester', 'Jean Claude'], ['Buttercup', 'Bubbles', 'Blossom']]" }, { "code": null, "e": 6959, "s": 6878, "text": "Above we can see that changing the nested array in round2 did not update round1." }, { "code": null, "e": 7080, "s": 6959, "text": "Building off the previous example, creating a shallow copy and then modifying it would have affected the original list.." }, { "code": null, "e": 7421, "s": 7080, "text": "round1 = [ ['Arnold', 'Sylvester', 'Jean Claude'], ['Buttercup', 'Bubbles', 'Blossom']]import copyround2 = round1.copy()round2[0][0] = 'Jet Lee'print(round1)#=> [['Jet Lee', 'Sylvester', 'Jean Claude'], ['Buttercup', 'Bubbles', 'Blossom']]print(round2)#=> [['Jet Lee', 'Sylvester', 'Jean Claude'], ['Buttercup', 'Bubbles', 'Blossom']]" }, { "code": null, "e": 7443, "s": 7421, "text": "Why does this happen?" }, { "code": null, "e": 7592, "s": 7443, "text": "Creating a shallow copy does create a new object in memory, but it’s filled with the same references to existing objects that the previous list has." }, { "code": null, "e": 7770, "s": 7592, "text": "Creating a deep copy creates copies of the original objects and points to these new versions. So the new list is completely unaffected by changes to the old list and vice versa." }, { "code": null, "e": 7885, "s": 7770, "text": "Tuples cannot be updated after creation. Adding/removing/updating an existing tuple requires creating a new tuple." }, { "code": null, "e": 7923, "s": 7885, "text": "Lists can be modified after creation." }, { "code": null, "e": 8036, "s": 7923, "text": "Tuples often represent an object like a record loaded from a database where elements are of different datatypes." }, { "code": null, "e": 8137, "s": 8036, "text": "Lists are generally used to store an ordered sequence of a specific type of object (but not always)." }, { "code": null, "e": 8184, "s": 8137, "text": "Both are sequences and allow duplicate values." }, { "code": null, "e": 8224, "s": 8184, "text": "len() can returns the length of a list." }, { "code": null, "e": 8267, "s": 8224, "text": "li = ['a', 'b', 'c', 'd', 'e']len(li)#=> 5" }, { "code": null, "e": 8419, "s": 8267, "text": "But note it counts top level objects, so a nested list of several integers will only be counted as a single object. Below, li has a length of 2, not 5." }, { "code": null, "e": 8452, "s": 8419, "text": "li = [[1,2],[3,4,5]]len(li)#=> 2" }, { "code": null, "e": 8593, "s": 8452, "text": "While a list is ordered, a set is not. That’s why using set to find unique values in a list, like list( set([3, 3, 2, 1]) ) loses the order." }, { "code": null, "e": 8676, "s": 8593, "text": "While lists are often used to track order, sets are often used to track existence." }, { "code": null, "e": 8750, "s": 8676, "text": "Lists allow duplicates, but all values in a set are unique by definition." }, { "code": null, "e": 8807, "s": 8750, "text": "For this we use the in operator, but prefix it with not." }, { "code": null, "e": 8863, "s": 8807, "text": "li = [1,2,3,4]5 not in li #=> True4 not in li #=> False" }, { "code": null, "e": 8950, "s": 8863, "text": ".map() allows iterating over a sequence and updating each value with another function." }, { "code": null, "e": 9057, "s": 8950, "text": "map() returns a map object but I’ve wrapped it with a list comprehension so we can see the updated values." }, { "code": null, "e": 9180, "s": 9057, "text": "def multiply_5(val): return val * 5a = [10,20,30,40,50][val for val in map(multiply_5, a)] #=> [50, 100, 150, 200, 250]" }, { "code": null, "e": 9314, "s": 9180, "text": "zip() combines multiple sequences into an iterator of tuples, where values at the same sequence index are combined in the same tuple." }, { "code": null, "e": 9390, "s": 9314, "text": "alphabet = ['a', 'b', 'c']integers = [1, 2, 3]list(zip(alphabet, integers))" }, { "code": null, "e": 9467, "s": 9390, "text": "The insert() method takes an object to insert and the index to insert it at." }, { "code": null, "e": 9554, "s": 9467, "text": "li = ['a','b','c','d','e']li.insert(2, 'HERE')li #=> ['a', 'b', 'HERE', 'c', 'd', 'e']" }, { "code": null, "e": 9652, "s": 9554, "text": "Note that the element previously at the specified index is shifted to the right, not overwritten." }, { "code": null, "e": 9698, "s": 9652, "text": "reduce() needs to be imported from functools." }, { "code": null, "e": 9898, "s": 9698, "text": "Given a function, reduce iterates over a sequence and calls the function on every element. The output from the previous element is passed as an argument when calling the function on the next element." }, { "code": null, "e": 10021, "s": 9898, "text": "from functools import reducedef subtract(a,b): return a - bnumbers = [100,10,5,1,2,7,5]reduce(subtract, numbers) #=> 70" }, { "code": null, "e": 10072, "s": 10021, "text": "Above we subtracted 10, 5, 1, 2, 7 and 5 from 100." }, { "code": null, "e": 10183, "s": 10072, "text": "Given a function, filter() will remove any elements from a sequence on which the function doesn’t return True." }, { "code": null, "e": 10224, "s": 10183, "text": "Below we remove elements less than zero." }, { "code": null, "e": 10378, "s": 10224, "text": "def remove_negatives(x): return True if x >= 0 else False a = [-10, 27, 1000, -1, 0, -30][x for x in filter(remove_negatives, a)] #=> [27, 1000, 0]" }, { "code": null, "e": 10426, "s": 10378, "text": "For this we can use a dictionary comprehension." }, { "code": null, "e": 10561, "s": 10426, "text": "li = ['The', 'quick', 'brown', 'fox', 'was', 'quick']d = {k:1 for k in li}d #=> {'The': 1, 'quick': 1, 'brown': 1, 'fox': 1, 'was': 1}" }, { "code": null, "e": 10651, "s": 10561, "text": "Let’s take the previous map function we wrote and turn it into a one-liner with a lambda." }, { "code": null, "e": 10730, "s": 10651, "text": "a = [10,20,30,40,50]list(map(lambda val:val*5, a))#=> [50, 100, 150, 200, 250]" }, { "code": null, "e": 10856, "s": 10730, "text": "I could have left it as a map object until I needed to iterate over it but I converted to a list to show the elements inside." }, { "code": null, "e": 10952, "s": 10856, "text": "Using the slice syntax, we can return a new list with only the elements up to a specific index." }, { "code": null, "e": 11052, "s": 10952, "text": "li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]li[:10]#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" }, { "code": null, "e": 11137, "s": 11052, "text": "The slice syntax can also return a new list with the values after a specified index." }, { "code": null, "e": 11226, "s": 11137, "text": "li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]li[15:]#=> [16, 17, 18, 19, 10]" }, { "code": null, "e": 11250, "s": 11226, "text": "Or between two indices." }, { "code": null, "e": 11341, "s": 11250, "text": "li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]li[12:17]#=> [13, 14, 15, 16, 17]" }, { "code": null, "e": 11397, "s": 11341, "text": "Or before/after/between indices at a specific interval." }, { "code": null, "e": 11482, "s": 11397, "text": "Here we return every 2nd value between the indices 10 and 16 using the slice syntax." }, { "code": null, "e": 11567, "s": 11482, "text": "li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]li[10:16:2]#=> [11, 13, 15]" }, { "code": null, "e": 11622, "s": 11567, "text": "The sort() method mutates a list into ascending order." }, { "code": null, "e": 11697, "s": 11622, "text": "li = [10,1,9,2,8,3,7,4,6,5]li.sort()li #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" }, { "code": null, "e": 11793, "s": 11697, "text": "It’s also possible to sort in descending order with sort() by adding the argument reverse=True." }, { "code": null, "e": 11880, "s": 11793, "text": "li = [10,1,9,2,8,3,7,4,6,5]li.sort(reverse=True)li #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]" }, { "code": null, "e": 11986, "s": 11880, "text": "You can add conditional logic inside a list comprehension to filter out values following a given pattern." }, { "code": null, "e": 12028, "s": 11986, "text": "Here we filter out values divisible by 2." }, { "code": null, "e": 12104, "s": 12028, "text": "li = [1,2,3,4,5,6,7,8,9,10][i for i in li if i % 2 != 0]#=> [1, 3, 5, 7, 9]" }, { "code": null, "e": 12269, "s": 12104, "text": "One option is to iterate over a list and add counts to a dictionary. But the easiest option is to import the Counter class from collections and pass the list to it." }, { "code": null, "e": 12452, "s": 12269, "text": "from collections import Counterli = ['blue', 'pink', 'green', 'green', 'yellow', 'pink', 'orange']Counter(li)#=> Counter({'blue': 1, 'pink': 2, 'green': 2, 'yellow': 1, 'orange': 1})" }, { "code": null, "e": 12580, "s": 12452, "text": "A list comprehension is well suited for iterating over a list of other objects and grabbing an element from each nested object." }, { "code": null, "e": 12672, "s": 12580, "text": "li = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]][i[0] for i in li]#=> [1, 4, 7, 10, 13]" }, { "code": null, "e": 12774, "s": 12672, "text": "Insert is O(n). If an element is inserted at the beginning, all other elements must be shifted right." }, { "code": null, "e": 12891, "s": 12774, "text": "Find by index is O(1). But find by value is O(n) because elements need to be iterated over until the value is found." }, { "code": null, "e": 12994, "s": 12891, "text": "Delete is O(n). If an element is deleted at the beginning, all other elements must to be shifted left." }, { "code": null, "e": 13037, "s": 12994, "text": "This can be done with the join() function." }, { "code": null, "e": 13175, "s": 13037, "text": "li = ['The','quick','brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']' '.join(li)#=> 'The quick brown fox jumped over the lazy dog'" }, { "code": null, "e": 13308, "s": 13175, "text": "Multiplying a list by an integer is called multiple concatenation and has the same affect as concatenating a list to itself n-times." }, { "code": null, "e": 13339, "s": 13308, "text": "Below we multiple a list by 5." }, { "code": null, "e": 13407, "s": 13339, "text": "['a','b'] * 5#=> ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']" }, { "code": null, "e": 13428, "s": 13407, "text": "This is the same as." }, { "code": null, "e": 13540, "s": 13428, "text": "['a','b'] + ['a','b'] + ['a','b'] + ['a','b'] + ['a','b']#=> ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']" }, { "code": null, "e": 13655, "s": 13540, "text": "We can combine any() with a list comprehension to return True if any values in the returned list evaluate to True." }, { "code": null, "e": 13758, "s": 13655, "text": "Below the 1st list comprehension returns True because the list has a 2 in it, which is divisible by 2." }, { "code": null, "e": 13858, "s": 13758, "text": "li1 = [1,2,3]li2 = [1,3]any(i % 2 == 0 for i in li1) #=> Trueany(i % 2 == 0 for i in li2) #=> False" }, { "code": null, "e": 14003, "s": 13858, "text": "Similar to the any() function, all() can also be used with a list comprehension to return True only if all values in the returned list are True." }, { "code": null, "e": 14103, "s": 14003, "text": "li1 = [2,3,4]li2 = [2,4]all(i % 2 == 0 for i in li1) #=> Falseall(i % 2 == 0 for i in li2) #=> True" }, { "code": null, "e": 14224, "s": 14103, "text": "You cannot sort a list with None in it because comparison operators (used by sort()) can’t compare an integer with None." }, { "code": null, "e": 14341, "s": 14224, "text": "li = [10,1,9,2,8,3,7,4,6,None]li.sort()li #=> TypeError: '<' not supported between instances of 'NoneType' and 'int'" }, { "code": null, "e": 14459, "s": 14341, "text": "The list constructor creates a shallow copy of a passed in list. That said, this is less pythonic than using .copy()." }, { "code": null, "e": 14560, "s": 14459, "text": "li1 = ['a','b']li2 = list(li1)li2.append('c')print(li1) #=> ['a', 'b']print(li2) #=> ['a', 'b', 'c']" }, { "code": null, "e": 14628, "s": 14560, "text": "A list can be mutated into reverse order with the reverse() method." }, { "code": null, "e": 14706, "s": 14628, "text": "li = [1,2,3,4,5,6,7,8,9,10]li.reverse()li #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]" }, { "code": null, "e": 14775, "s": 14706, "text": "Note that this mutates the object instead of returning a new object." }, { "code": null, "e": 14874, "s": 14775, "text": "reverse() reverses the list in place. reversed() returns an iterable of the list in reverse order." }, { "code": null, "e": 14955, "s": 14874, "text": "li = [1,2,3,4,5,6,7,8,9,10]list(reversed(li))#=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]" }, { "code": null, "e": 15036, "s": 14955, "text": "sort() modifies the list in place. sorted() returns a new list in reverse order." }, { "code": null, "e": 15184, "s": 15036, "text": "li = [10,1,9,2,8,3,7,4,6,5]li.sort()li #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]li = [10,1,9,2,8,3,7,4,6,5]sorted(li) #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" }, { "code": null, "e": 15240, "s": 15184, "text": "The min() function returns the minimum value in a list." }, { "code": null, "e": 15280, "s": 15240, "text": "li = [10,1,9,2,8,3,7,4,6,5]min(li)#=> 1" }, { "code": null, "e": 15336, "s": 15280, "text": "The max() function returns the maximum value in a list." }, { "code": null, "e": 15377, "s": 15336, "text": "li = [10,1,9,2,8,3,7,4,6,5]max(li)#=> 10" }, { "code": null, "e": 15437, "s": 15377, "text": "The sum() function returns the sum of all values in a list." }, { "code": null, "e": 15478, "s": 15437, "text": "li = [10,1,9,2,8,3,7,4,6,5]sum(li)#=> 55" }, { "code": null, "e": 15585, "s": 15478, "text": "You can use append() and pop() to treat a list like a stack. Stacks function per LIFO (last in first out)." }, { "code": null, "e": 15757, "s": 15585, "text": "stack = []stack.append('Jess')stack.append('Todd')stack.append('Yuan')print(stack) #=> ['Jess', 'Todd', 'Yuan']print(stack.pop()) #=> Yuanprint(stack) #=> ['Jess', 'Todd']" }, { "code": null, "e": 15887, "s": 15757, "text": "One benefit of a stack is that elements can be added and removed in O(1) time because the list does not need to be iterated over." }, { "code": null, "e": 15940, "s": 15887, "text": "We can do this by utilizing set() with an ampersand." }, { "code": null, "e": 15996, "s": 15940, "text": "li1 = [1,2,3]li2 = [2,3,4]set(li1) & set(li2)#=> {2, 3}" }, { "code": null, "e": 16047, "s": 15996, "text": "We can’t subtract lists, but we can subtract sets." }, { "code": null, "e": 16126, "s": 16047, "text": "li1 = [1,2,3]li2 = [2,3,4]set(li1) - set(li2)#=> {1}set(li2) - set(li1)#=> {4}" }, { "code": null, "e": 16252, "s": 16126, "text": "Unlike Ruby, Python3 doesn’t have an explicit flatten function. But we can use list comprehension to flatten a list of lists." }, { "code": null, "e": 16323, "s": 16252, "text": "li = [[1,2,3],[4,5,6]][i for x in li for i in x]#=> [1, 2, 3, 4, 5, 6]" }, { "code": null, "e": 16395, "s": 16323, "text": "We can create a range between 2 values and then convert that to a list." }, { "code": null, "e": 16432, "s": 16395, "text": "list(range(5,10))#=> [5, 6, 7, 8, 9]" }, { "code": null, "e": 16583, "s": 16432, "text": "Using zip() and the list() constructor we can combine 2 lists into a dictionary where one list becomes the keys and the other list becomes the values." }, { "code": null, "e": 16769, "s": 16583, "text": "name = ['Snowball', 'Chewy', 'Bubbles', 'Gruff']animal = ['Cat', 'Dog', 'Fish', 'Goat']dict(zip(name, animal))#=> {'Snowball': 'Cat', 'Chewy': 'Dog', 'Bubbles': 'Fish', 'Gruff': 'Goat'}" }, { "code": null, "e": 16871, "s": 16769, "text": "While we can reverse a list with reverse() and reversed(), it can also be done with the slice syntax." }, { "code": null, "e": 16950, "s": 16871, "text": "This returns a new list by iterating back over the list from end to beginning." }, { "code": null, "e": 16997, "s": 16950, "text": "li = ['a','b',3,4]li[::-1]#=> [4, 3, 'b', 'a']" }, { "code": null, "e": 17121, "s": 16997, "text": "After working through this I feel more prepared to tackle algorithm questions without second guessing specific list method." }, { "code": null, "e": 17281, "s": 17121, "text": "Removing constant googling can free up energy for higher order thinking, like getting a function to do what it’s supposed to, and reducing function complexity." }, { "code": null, "e": 17326, "s": 17281, "text": "Again, I hope you found this useful as well." } ]
Get MongoDB Databases in a JavaScript Array?
To get MongoDB databases in a JavaScript array, you can use runCommand(). Following is the query to get MongoDB databases in a JavaScript array > use admin; switched to db admin > allDatabasesDetails = db.runCommand({listDatabases: 1}); This will produce the following output { "databases" : [ { "name" : "admin", "sizeOnDisk" : 847872, "empty" : false }, { "name" : "config", "sizeOnDisk" : 98304, "empty" : false }, { "name" : "local", "sizeOnDisk" : 73728, "empty" : false }, { "name" : "sample", "sizeOnDisk" : 1273856, "empty" : false }, { "name" : "sampleDemo", "sizeOnDisk" : 352256, "empty" : false }, { "name" : "studentSearch", "sizeOnDisk" : 262144, "empty" : false }, { "name" : "test", "sizeOnDisk" : 9527296, "empty" : false } ], "totalSize" : 12435456, "ok" : 1 } Following is the query to get total databases: > allDatabaseName = [] [ ] > for (var j in allDatabasesDetails.databases) { allDatabaseName.push(dbs.databases[j].name) } This will produce the following output 7
[ { "code": null, "e": 1206, "s": 1062, "text": "To get MongoDB databases in a JavaScript array, you can use runCommand(). Following is the query to get MongoDB databases in a JavaScript array" }, { "code": null, "e": 1299, "s": 1206, "text": "> use admin;\nswitched to db admin\n> allDatabasesDetails = db.runCommand({listDatabases: 1});" }, { "code": null, "e": 1338, "s": 1299, "text": "This will produce the following output" }, { "code": null, "e": 2126, "s": 1338, "text": "{\n \"databases\" : [\n {\n \"name\" : \"admin\",\n \"sizeOnDisk\" : 847872,\n \"empty\" : false\n },\n {\n \"name\" : \"config\",\n \"sizeOnDisk\" : 98304,\n \"empty\" : false\n },\n {\n \"name\" : \"local\",\n \"sizeOnDisk\" : 73728,\n \"empty\" : false\n },\n {\n \"name\" : \"sample\",\n \"sizeOnDisk\" : 1273856,\n \"empty\" : false\n },\n {\n \"name\" : \"sampleDemo\",\n \"sizeOnDisk\" : 352256,\n \"empty\" : false\n },\n {\n \"name\" : \"studentSearch\",\n \"sizeOnDisk\" : 262144,\n \"empty\" : false\n },\n {\n \"name\" : \"test\",\n \"sizeOnDisk\" : 9527296,\n \"empty\" : false\n }\n ],\n \"totalSize\" : 12435456,\n \"ok\" : 1\n}" }, { "code": null, "e": 2173, "s": 2126, "text": "Following is the query to get total databases:" }, { "code": null, "e": 2295, "s": 2173, "text": "> allDatabaseName = []\n[ ]\n> for (var j in allDatabasesDetails.databases) { allDatabaseName.push(dbs.databases[j].name) }" }, { "code": null, "e": 2334, "s": 2295, "text": "This will produce the following output" }, { "code": null, "e": 2336, "s": 2334, "text": "7" } ]
PyQt5 QSpinBox - How to get the font of spin box - GeeksforGeeks
19 May, 2020 In this article we will see how we can get the font of all the text present in the spin box, in order to set the font use setFont method which takes QFont object as argument, using it with the spin box object will change the font of all the text. In order to get the font we use font method Syntax : spin_box.font() Argument : It takes no argument Return : It returns QFont object Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting range to the spin box self.spin.setRange(0, 999999) # setting prefix to spin self.spin.setPrefix("Prefix ") # setting suffix to spin self.spin.setSuffix(" Suffix") # setting font to the spin box self.spin.setFont(QFont('Arial', 12)) # creating a label label = QLabel(self) # making it multi line label.setWordWrap(True) # setting its geometry label.setGeometry(100, 200, 200, 60) # getting font of spin box font = self.spin.font() # setting text to the label label.setText(str(font)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-SpinBox Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n19 May, 2020" }, { "code": null, "e": 24148, "s": 23901, "text": "In this article we will see how we can get the font of all the text present in the spin box, in order to set the font use setFont method which takes QFont object as argument, using it with the spin box object will change the font of all the text." }, { "code": null, "e": 24192, "s": 24148, "text": "In order to get the font we use font method" }, { "code": null, "e": 24217, "s": 24192, "text": "Syntax : spin_box.font()" }, { "code": null, "e": 24249, "s": 24217, "text": "Argument : It takes no argument" }, { "code": null, "e": 24282, "s": 24249, "text": "Return : It returns QFont object" }, { "code": null, "e": 24310, "s": 24282, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting range to the spin box self.spin.setRange(0, 999999) # setting prefix to spin self.spin.setPrefix(\"Prefix \") # setting suffix to spin self.spin.setSuffix(\" Suffix\") # setting font to the spin box self.spin.setFont(QFont('Arial', 12)) # creating a label label = QLabel(self) # making it multi line label.setWordWrap(True) # setting its geometry label.setGeometry(100, 200, 200, 60) # getting font of spin box font = self.spin.font() # setting text to the label label.setText(str(font)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 25766, "s": 24310, "text": null }, { "code": null, "e": 25775, "s": 25766, "text": "Output :" }, { "code": null, "e": 25795, "s": 25775, "text": "Python PyQt-SpinBox" }, { "code": null, "e": 25806, "s": 25795, "text": "Python-gui" }, { "code": null, "e": 25818, "s": 25806, "text": "Python-PyQt" }, { "code": null, "e": 25825, "s": 25818, "text": "Python" }, { "code": null, "e": 25923, "s": 25825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25932, "s": 25923, "text": "Comments" }, { "code": null, "e": 25945, "s": 25932, "text": "Old Comments" }, { "code": null, "e": 25977, "s": 25945, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26033, "s": 25977, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26075, "s": 26033, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26117, "s": 26075, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26153, "s": 26117, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26175, "s": 26153, "text": "Defaultdict in Python" }, { "code": null, "e": 26214, "s": 26175, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26241, "s": 26214, "text": "Python Classes and Objects" }, { "code": null, "e": 26272, "s": 26241, "text": "Python | os.path.join() method" } ]
Shell Program to Find the Position of Substring in Given String - GeeksforGeeks
29 Dec, 2021 A string is made of many substrings or can say that if we delete one or more characters from the beginning or end then the remaining string is called substring. This article is about to write a shell program that will tell the position (index) of the substring in a given string. Let’s take an example of this. Example: Given ( String ): "geeks for geeks is the best platform for computer science geek" Input ( Substring ): "computer" Output ( Position ): 42 ( string index starting from 1 ) ( first index, from where substring start ) We will discuss here mainly two approaches in which the first one will be brute force approach and second will be using bash commands. Approach 1: To write the script code follow the below steps Step 1: make two choices input the main string or continue with default. Step 2: according to user choice of user get string and substring using the read command. Step 3: Now, run a loop to get the all character of the given string and compare those to the first character of the substring. Step 4: Run again a loop to check from matching character to match all other characters to find substring. Shell Script Code: # script to get the substring position in given string # let give a string str="geeks for geeks is the best platform for computer science geeks" # now ask user to give the new string or use the given default string echo "Hello there, do you wanna give new string or use default" echo echo "Enter 1 for new string" echo "Enter 0 for continue" # now read the choice form user read choice echo # make the condition to check the choice and perform action according to that if [[ choice == 1 ]] then # now ask reader to give the main string echo "Please, Enter the main string" # now read the string read str echo fi # print a message echo "Let's continue to get the index of the substring....." echo # make a loop to get the substring values from the user while [[ 1 ]] do # print the statement echo "Enter a substring to get the position of that string OR Enter -1 to get exit" # now read the substr read substr # make a condition to check the value of substr if [[ $substr != -1 ]] then # # 1st approach code to get the substring position from given string ( 1st approach ) # # This approach is comparison on char by char # ************************************************************************ # length of the given string lenGS=${#str} #length of the substr lenSS=${#substr} # check the condition where string length is less than substring length if [[ $lenGS -lt $lenSS ]] then echo "Sorry, Your substring exceed main string, Please Enter another" continue fi # variable to store position pos=-1 # variable to check found=0 # run three native loop ( brute force approach ) for (( i=0;i<lenGS;++i )) do if [[ ${str:i:1} == ${substr:0:1} ]] then # now loop to check that here substring or not kstr=$i ksubstr=$i while (( kstr<lenGS && ksubstr<lenSS )) do if [[ ${str:kstr:1} != ${substr:ksubstr:1} ]] then break fi kstr=`expr $kstr + 1` ksubstr=`expr $ksubstr + 1` done # check if substring found if [[ ${ksubstr} == ${lenSS} ]] then echo "Your substring $substr is found at the index ${i+1}" found=1 break fi fi done # check the substring found or not if [[ $found == 0 ]] then echo "Sorry, Your substring $substr is not found in main string" fi echo #********************************************************************** else echo "okay! Closed" break fi done # Geeks for Geeks Execution of the Script: Command: bash script.sh Hello there, do you wanna give new string or use default Enter 1 for new string Enter 0 for continue 0 Let's continue to get the index of the substring..... Enter a substring to get the position of that string OR Enter -1 to get exit geeks Your substring geeks is found at the index 1 Enter a substring to get the position of that string OR Enter -1 to get exit best Your substring best is found at the index 1 Enter a substring to get the position of that string OR Enter -1 to get exit web Sorry, Your substring web is not found in main string Enter a substring to get the position of that string OR Enter -1 to get exit -1 okay! Closed Output Screenshot: Approach 2: To write the script code follow the below steps Step 1: make two choices input the main string or continue with default. Step 2: according to user choice of user get string using the read command. Step 3: get the substring from the user using the read command. Step 4: Now run a loop and get all substring of the main string of the length of the given substring using the substring function in scripting. Step 5: check all substring one by one and stop when you find a substring equal to the given substring. Shell Script Code: # script to get the substring position in given string # let give a string str="geeks for geeks is the best platform for computer science geeks" # now ask user to give the new string or use the given default string echo "Hello there, do you wanna give new string or use default" echo echo "Enter 1 for new string" echo "Enter 0 for continue" # now read the choice form user read choice echo # make the condition to check the choice and perform action according to that if [[ choice == 1 ]] then # now ask reader to give the main string echo "Please, Enter the main string" # now read the string read str echo fi # print a message echo "Let's continue to get the index of the substring....." echo # make a loop to get the substring values from the user while [[ 1 ]] do # print the statement echo "Enter a substring to get the position of that string OR Enter -1 to get exit" # now read the substr read substr # make a condition to check the value of substr if [[ $substr != -1 ]] then # # 2nd approach code to get the substring position from given string ( 2nd approach ) # # This approach is comparison on string by string using bash string function # ************************************************************************ pos=-1 # length of the given string lenGS=${#str} #length of the substr lenSS=${#substr} # check the condition where string length is less than substring length if [[ $lenGS -lt $lenSS ]] then echo "Sorry, Your substring exceed main string, Please Enter another" continue fi # get the limit of the loop limit=`expr $lenGS - $lenSS + 1` # variable to check found=0 # run a loop to check the all substring for (( i=0; i<limit; i++ )) do # create substring from main string of the same length substr1=${str:$i:$lenSS} # now check if these two string equal or not if [[ $substr == $substr1 ]] then echo "So $substr substring position in main string is : `expr $i + 1`" found=1 break; fi done # check the substring found or not if [[ $found == 0 ]] then echo "Sorry, Your substring $substr is not found in main string" fi echo #********************************************************************** else echo "okay! Closed" break fi done Execution of the Script: Command: bash script.sh Hello there, do you wanna give new string or use default Enter 1 for new string Enter 0 for continue 0 Let's continue to get the index of the substring..... Enter a substring to get the position of that string OR Enter -1 to get exit computer So computer substring position in main string is : 42 Enter a substring to get the position of that string OR Enter -1 to get exit best So best substring position in main string is : 24 Enter a substring to get the position of that string OR Enter -1 to get exit geeksgeeks Sorry, Your substring geeksgeeks is not found in main string Enter a substring to get the position of that string OR Enter -1 to get exit -1 okay! Closed Output Screenshot: kapoorsagar226 subhra_jy sagartomar9927 anikakapoor Picked Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Thread functions in C/C++ nohup Command in Linux with Examples mv command in Linux with examples scp command in Linux with Examples Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24089, "s": 24058, "text": " \n29 Dec, 2021\n" }, { "code": null, "e": 24400, "s": 24089, "text": "A string is made of many substrings or can say that if we delete one or more characters from the beginning or end then the remaining string is called substring. This article is about to write a shell program that will tell the position (index) of the substring in a given string. Let’s take an example of this." }, { "code": null, "e": 24410, "s": 24400, "text": "Example: " }, { "code": null, "e": 24626, "s": 24410, "text": "Given ( String ): \"geeks for geeks is the best platform for computer science geek\"\nInput ( Substring ): \"computer\"\nOutput ( Position ): 42 ( string index starting from 1 ) ( first index, from where substring start )" }, { "code": null, "e": 24761, "s": 24626, "text": "We will discuss here mainly two approaches in which the first one will be brute force approach and second will be using bash commands." }, { "code": null, "e": 24773, "s": 24761, "text": "Approach 1:" }, { "code": null, "e": 24821, "s": 24773, "text": "To write the script code follow the below steps" }, { "code": null, "e": 24894, "s": 24821, "text": "Step 1: make two choices input the main string or continue with default." }, { "code": null, "e": 24984, "s": 24894, "text": "Step 2: according to user choice of user get string and substring using the read command." }, { "code": null, "e": 25113, "s": 24984, "text": "Step 3: Now, run a loop to get the all character of the given string and compare those to the first character of the substring. " }, { "code": null, "e": 25220, "s": 25113, "text": "Step 4: Run again a loop to check from matching character to match all other characters to find substring." }, { "code": null, "e": 25239, "s": 25220, "text": "Shell Script Code:" }, { "code": null, "e": 28355, "s": 25239, "text": "# script to get the substring position in given string\n\n# let give a string \nstr=\"geeks for geeks is the best platform for computer science geeks\"\n\n# now ask user to give the new string or use the given default string\necho \"Hello there, do you wanna give new string or use default\"\necho \necho \"Enter 1 for new string\"\necho \"Enter 0 for continue\"\n\n# now read the choice form user\nread choice\necho\n\n# make the condition to check the choice and perform action according to that\nif [[ choice == 1 ]]\nthen \n # now ask reader to give the main string\n echo \"Please, Enter the main string\"\n \n # now read the string \n read str\n echo\nfi\n\n# print a message\necho \"Let's continue to get the index of the substring.....\"\necho\n\n# make a loop to get the substring values from the user \nwhile [[ 1 ]]\ndo \n # print the statement\n echo \"Enter a substring to get the position of that string OR Enter -1 to get exit\"\n \n # now read the substr\n read substr\n \n # make a condition to check the value of substr\n if [[ $substr != -1 ]]\n then \n # # 1st approach code to get the substring position from given string ( 1st approach )\n # # This approach is comparison on char by char \n # ************************************************************************\n \n # length of the given string\n lenGS=${#str}\n #length of the substr\n lenSS=${#substr}\n \n # check the condition where string length is less than substring length\n if [[ $lenGS -lt $lenSS ]] \n then \n echo \"Sorry, Your substring exceed main string, Please Enter another\"\n continue\n fi\n \n # variable to store position \n pos=-1\n # variable to check\n found=0\n \n # run three native loop ( brute force approach ) \n for (( i=0;i<lenGS;++i ))\n do\n \n if [[ ${str:i:1} == ${substr:0:1} ]]\n then \n \n # now loop to check that here substring or not\n kstr=$i\n ksubstr=$i\n\n while (( kstr<lenGS && ksubstr<lenSS ))\n do \n if [[ ${str:kstr:1} != ${substr:ksubstr:1} ]]\n then\n break\n fi\n kstr=`expr $kstr + 1`\n ksubstr=`expr $ksubstr + 1`\n done\n \n # check if substring found\n if [[ ${ksubstr} == ${lenSS} ]]\n then\n echo \"Your substring $substr is found at the index ${i+1}\"\n found=1\n break\n fi\n fi\n done\n \n # check the substring found or not\n if [[ $found == 0 ]]\n then \n echo \"Sorry, Your substring $substr is not found in main string\"\n fi\n echo\n #**********************************************************************\n \n else\n echo \"okay! Closed\"\n break\n fi\ndone\n\n# Geeks for Geeks\n \n \n " }, { "code": null, "e": 28381, "s": 28355, "text": "Execution of the Script: " }, { "code": null, "e": 29051, "s": 28381, "text": "Command: bash script.sh\nHello there, do you wanna give new string or use default\n\nEnter 1 for new string\nEnter 0 for continue\n0\n\nLet's continue to get the index of the substring.....\n\nEnter a substring to get the position of that string OR Enter -1 to get exit\ngeeks\nYour substring geeks is found at the index 1\n\nEnter a substring to get the position of that string OR Enter -1 to get exit\nbest\nYour substring best is found at the index 1\n\nEnter a substring to get the position of that string OR Enter -1 to get exit\nweb \nSorry, Your substring web is not found in main string\n\nEnter a substring to get the position of that string OR Enter -1 to get exit\n-1\nokay! Closed" }, { "code": null, "e": 29071, "s": 29051, "text": "Output Screenshot: " }, { "code": null, "e": 29083, "s": 29071, "text": "Approach 2:" }, { "code": null, "e": 29131, "s": 29083, "text": "To write the script code follow the below steps" }, { "code": null, "e": 29204, "s": 29131, "text": "Step 1: make two choices input the main string or continue with default." }, { "code": null, "e": 29280, "s": 29204, "text": "Step 2: according to user choice of user get string using the read command." }, { "code": null, "e": 29345, "s": 29280, "text": "Step 3: get the substring from the user using the read command." }, { "code": null, "e": 29489, "s": 29345, "text": "Step 4: Now run a loop and get all substring of the main string of the length of the given substring using the substring function in scripting." }, { "code": null, "e": 29593, "s": 29489, "text": "Step 5: check all substring one by one and stop when you find a substring equal to the given substring." }, { "code": null, "e": 29612, "s": 29593, "text": "Shell Script Code:" }, { "code": null, "e": 32327, "s": 29612, "text": "# script to get the substring position in given string\n\n# let give a string \nstr=\"geeks for geeks is the best platform for computer science geeks\"\n\n# now ask user to give the new string or use the given default string\necho \"Hello there, do you wanna give new string or use default\"\necho \necho \"Enter 1 for new string\"\necho \"Enter 0 for continue\"\n\n# now read the choice form user\nread choice\necho\n\n# make the condition to check the choice and perform action according to that\nif [[ choice == 1 ]]\nthen \n # now ask reader to give the main string\n echo \"Please, Enter the main string\"\n \n # now read the string \n read str\n echo\nfi\n\n# print a message\necho \"Let's continue to get the index of the substring.....\"\necho\n\n# make a loop to get the substring values from the user \nwhile [[ 1 ]]\ndo \n # print the statement\n echo \"Enter a substring to get the position of that string OR Enter -1 to get exit\"\n \n # now read the substr\n read substr\n \n # make a condition to check the value of substr\n if [[ $substr != -1 ]]\n then \n # # 2nd approach code to get the substring position from given string ( 2nd approach )\n # # This approach is comparison on string by string using bash string function \n # ************************************************************************\n \n pos=-1\n \n # length of the given string\n lenGS=${#str}\n #length of the substr\n lenSS=${#substr}\n \n # check the condition where string length is less than substring length\n if [[ $lenGS -lt $lenSS ]] \n then \n echo \"Sorry, Your substring exceed main string, Please Enter another\"\n continue\n fi\n \n # get the limit of the loop\n limit=`expr $lenGS - $lenSS + 1`\n \n # variable to check\n found=0\n \n # run a loop to check the all substring \n for (( i=0; i<limit; i++ ))\n do\n # create substring from main string of the same length\n substr1=${str:$i:$lenSS}\n \n # now check if these two string equal or not \n if [[ $substr == $substr1 ]]\n then \n echo \"So $substr substring position in main string is : `expr $i + 1`\"\n found=1\n break;\n fi\n done\n \n # check the substring found or not\n if [[ $found == 0 ]]\n then \n echo \"Sorry, Your substring $substr is not found in main string\"\n fi\n echo\n #**********************************************************************\n \n else\n echo \"okay! Closed\"\n break\n fi\ndone" }, { "code": null, "e": 32352, "s": 32327, "text": "Execution of the Script:" }, { "code": null, "e": 33053, "s": 32352, "text": "Command: bash script.sh\nHello there, do you wanna give new string or use default\n\nEnter 1 for new string\nEnter 0 for continue\n0\n\nLet's continue to get the index of the substring.....\n\nEnter a substring to get the position of that string OR Enter -1 to get exit\ncomputer\nSo computer substring position in main string is : 42\n\nEnter a substring to get the position of that string OR Enter -1 to get exit\nbest\nSo best substring position in main string is : 24\n\nEnter a substring to get the position of that string OR Enter -1 to get exit\ngeeksgeeks\nSorry, Your substring geeksgeeks is not found in main string\n\nEnter a substring to get the position of that string OR Enter -1 to get exit\n-1\nokay! Closed" }, { "code": null, "e": 33073, "s": 33053, "text": "Output Screenshot: " }, { "code": null, "e": 33088, "s": 33073, "text": "kapoorsagar226" }, { "code": null, "e": 33098, "s": 33088, "text": "subhra_jy" }, { "code": null, "e": 33113, "s": 33098, "text": "sagartomar9927" }, { "code": null, "e": 33125, "s": 33113, "text": "anikakapoor" }, { "code": null, "e": 33134, "s": 33125, "text": "\nPicked\n" }, { "code": null, "e": 33149, "s": 33134, "text": "\nShell Script\n" }, { "code": null, "e": 33162, "s": 33149, "text": "\nLinux-Unix\n" }, { "code": null, "e": 33367, "s": 33162, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 33393, "s": 33367, "text": "Thread functions in C/C++" }, { "code": null, "e": 33430, "s": 33393, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 33464, "s": 33430, "text": "mv command in Linux with examples" }, { "code": null, "e": 33499, "s": 33464, "text": "scp command in Linux with Examples" }, { "code": null, "e": 33525, "s": 33499, "text": "Docker - COPY Instruction" }, { "code": null, "e": 33562, "s": 33525, "text": "chown command in Linux with Examples" }, { "code": null, "e": 33602, "s": 33562, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 33631, "s": 33602, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 33673, "s": 33631, "text": "Named Pipe or FIFO with example C program" } ]
Java.io.ByteArrayInputStream class in Java - GeeksforGeeks
12 Oct, 2021 java.io.ByteArrayInputStream class contains all the buffers, containing bytes to be read from the Input Stream. There is no IO exception in case of ByteArrayInputStream class methods. Methods of this class can be called even after closing the Stream, there is no effect of it on the class methods. Declaration : public class ByteArrayInputStream extends InputStream Fields protected byte[] buf: An array of bytes that was provided by the creator of the stream. protected int count: The index one greater than the last valid character in the input stream buffer. protected int mark: The currently marked position in the stream. protected int pos: This is the index of the next character to read from the input stream buffer. Constructors : ByteArrayInputStream(byte[] buffer) :creates ByteArrayInputStream to use buffer array – “buffer”. ByteArrayInputStream(byte[] buf, int offset, int length) :creates ByteArrayInputStream that uses some part of “buffer” i.e. buffer array Methods: mark(int arg) : Java.io.ByteArrayInputStream.mark(int arg) marks the current position of the input stream. It sets readlimit i.e. maximum number of bytes that can be read before mark position becomes invalid. Syntax : public void mark(int arg) Parameters : arg : integer specifying the read limit of the input Stream Return : void read() : java.io.ByteArrayInputStream.read() reads next byte of data from the Input Stream. The value byte is returned in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. Method doesn’t block Syntax : public int read() Parameters : ------ Return : Reads next data else, -1 i.e. when end of file is reached. Exception : -> IOException : If I/O error occurs. close() : java.io.ByteArrayInputStream.close() closes the input stream and releases system resources associated with this stream to Garbage Collector. Syntax : public void close() Parameters : ------ Return : void Exception : -> IOException : If I/O error occurs. read(byte[] buffer, int offset, int maxlen) : Java.io.ByteArrayInputStream.read(byte[] buffer, int offset, int maxlen) reads “buffer” byte array of Input Stream starting from position “offset” to maxlen. Syntax : public int read(byte[] buffer, int offset, int maxlen) Parameters : arg : array whose number of bytes to be read offset : starting position in buffer from where to read maxlen : maximum no. of bytes to be read Return : reads number of bytes and return to the buffer else, -1 i.e. when end of file is reached. Exception : -> IOException : If I/O error occurs. -> NullPointerException : if arg is null. reset() : Java.io.ByteArrayInputStream.reset() is invoked by mark() method. It repositions the input stream to the marked position. Syntax : public void reset() Parameters : ---- Return : void Exception : -> IOException : If I/O error occurs. markSupported() : Java.io.ByteArrayInputStream.markSupported() method tests if this input stream supports the mark and reset methods. The markSupported method of ByteArrayInputStreamInputStream returns true always Syntax : public boolean markSupported() Parameters : ------- Return : true if input stream supports the mark() and reset() method else,false skip(long arg) : Java.io.ByteArrayInputStream.skip(long arg) skips arg bytes in the input stream. Syntax : public long skip(long arg) Parameters : arg : no. of bytes to be skipped Return : skip bytes. Exception : -> IOException : If I/O error occurs. available() : Java.io.ByteArrayInputStream.available() tells total no. of bytes from the Input Stream to be read Syntax : public int available() Parameters : ----------- Return : total no. of bytes to be read Exception : ----------- Java Program explaining ByteArrayInputStream Class methods : Java // Java program illustrating the working of ByteArrayInputStream method// mark(), read(), skip(), available()// markSupported(), close(), reset() import java.io.*; public class NewClass{ public static void main(String[] args) throws Exception { byte[] buffer = {71, 69, 69, 75, 83}; ByteArrayInputStream geek = null; try { geek = new ByteArrayInputStream(buffer); // Use of available() method : telling the no. of bytes to be read int number = geek.available(); System.out.println("Use of available() method : " + number); // Use of read() method : reading and printing Characters one by one System.out.println("\nChar : "+(char)geek.read()); System.out.println("Char : "+(char)geek.read()); System.out.println("Char : "+(char)geek.read()); // Use of mark() : geek.mark(0); // Use of skip() : it results in skipping 'k' from "GEEKS" geek.skip(1); System.out.println("skip() method comes to play"); System.out.println("mark() method comes to play"); System.out.println("Char : "+(char)geek.read()); // Use of markSupported boolean check = geek.markSupported(); System.out.println("\nmarkSupported() : " + check); if(geek.markSupported()) { // Use of reset() method : repositioning the stream to marked positions. geek.reset(); System.out.println("\nreset() invoked"); System.out.println("Char : "+(char)geek.read()); System.out.println("Char : "+(char)geek.read()); } else { System.out.println("reset() method not supported."); } System.out.println("geek.markSupported() supported reset() : "+check); } catch(Exception except) { // in case of I/O error except.printStackTrace(); } finally { // releasing the resources back to the GarbageCollector when closes if(geek!=null) { // Use of close() : closing the file and releasing resources geek.close(); } } }} Output : Use of available() method : 5 Char : G Char : E Char : E skip() method comes to play mark() method comes to play Char : S markSupported() : true reset() invoked Char : K Char : S geek.markSupported() supported reset() : true Next Article: io.ByteArrayOutputStream() Class in Java This article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sooda367 simranarora5sos kalrap615 Java-I/O Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Object Oriented Programming (OOPs) Concept in Java Interfaces in Java Initialize an ArrayList in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Overriding in Java Collections in Java Singleton Class in Java
[ { "code": null, "e": 24500, "s": 24472, "text": "\n12 Oct, 2021" }, { "code": null, "e": 24798, "s": 24500, "text": "java.io.ByteArrayInputStream class contains all the buffers, containing bytes to be read from the Input Stream. There is no IO exception in case of ByteArrayInputStream class methods. Methods of this class can be called even after closing the Stream, there is no effect of it on the class methods." }, { "code": null, "e": 24813, "s": 24798, "text": "Declaration : " }, { "code": null, "e": 24870, "s": 24813, "text": "public class ByteArrayInputStream\n extends InputStream" }, { "code": null, "e": 24879, "s": 24870, "text": "Fields " }, { "code": null, "e": 24967, "s": 24879, "text": "protected byte[] buf: An array of bytes that was provided by the creator of the stream." }, { "code": null, "e": 25068, "s": 24967, "text": "protected int count: The index one greater than the last valid character in the input stream buffer." }, { "code": null, "e": 25133, "s": 25068, "text": "protected int mark: The currently marked position in the stream." }, { "code": null, "e": 25230, "s": 25133, "text": "protected int pos: This is the index of the next character to read from the input stream buffer." }, { "code": null, "e": 25247, "s": 25230, "text": "Constructors : " }, { "code": null, "e": 25345, "s": 25247, "text": "ByteArrayInputStream(byte[] buffer) :creates ByteArrayInputStream to use buffer array – “buffer”." }, { "code": null, "e": 25482, "s": 25345, "text": "ByteArrayInputStream(byte[] buf, int offset, int length) :creates ByteArrayInputStream that uses some part of “buffer” i.e. buffer array" }, { "code": null, "e": 25493, "s": 25482, "text": "Methods: " }, { "code": null, "e": 25711, "s": 25493, "text": "mark(int arg) : Java.io.ByteArrayInputStream.mark(int arg) marks the current position of the input stream. It sets readlimit i.e. maximum number of bytes that can be read before mark position becomes invalid. Syntax :" }, { "code": null, "e": 25825, "s": 25711, "text": "public void mark(int arg)\nParameters :\narg : integer specifying the read limit of the input Stream\nReturn : \nvoid" }, { "code": null, "e": 26095, "s": 25825, "text": "read() : java.io.ByteArrayInputStream.read() reads next byte of data from the Input Stream. The value byte is returned in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. Method doesn’t block Syntax :" }, { "code": null, "e": 26253, "s": 26095, "text": "public int read()\nParameters :\n------\nReturn : \nReads next data else, -1 i.e. when end of file is reached.\nException :\n-> IOException : If I/O error occurs." }, { "code": null, "e": 26413, "s": 26253, "text": "close() : java.io.ByteArrayInputStream.close() closes the input stream and releases system resources associated with this stream to Garbage Collector. Syntax :" }, { "code": null, "e": 26519, "s": 26413, "text": "public void close()\nParameters :\n------\nReturn : \nvoid\nException :\n-> IOException : If I/O error occurs." }, { "code": null, "e": 26732, "s": 26519, "text": "read(byte[] buffer, int offset, int maxlen) : Java.io.ByteArrayInputStream.read(byte[] buffer, int offset, int maxlen) reads “buffer” byte array of Input Stream starting from position “offset” to maxlen. Syntax :" }, { "code": null, "e": 27138, "s": 26732, "text": "public int read(byte[] buffer, int offset, int maxlen)\nParameters :\narg : array whose number of bytes to be read\noffset : starting position in buffer from where to read\nmaxlen : maximum no. of bytes to be read\nReturn : \n reads number of bytes and return to the buffer else, -1 i.e. when end of file is reached.\nException :\n-> IOException : If I/O error occurs.\n-> NullPointerException : if arg is null." }, { "code": null, "e": 27279, "s": 27138, "text": "reset() : Java.io.ByteArrayInputStream.reset() is invoked by mark() method. It repositions the input stream to the marked position. Syntax :" }, { "code": null, "e": 27383, "s": 27279, "text": "public void reset()\nParameters :\n----\nReturn : \nvoid\nException :\n-> IOException : If I/O error occurs." }, { "code": null, "e": 27606, "s": 27383, "text": "markSupported() : Java.io.ByteArrayInputStream.markSupported() method tests if this input stream supports the mark and reset methods. The markSupported method of ByteArrayInputStreamInputStream returns true always Syntax :" }, { "code": null, "e": 27740, "s": 27606, "text": "public boolean markSupported()\nParameters :\n-------\nReturn : \ntrue if input stream supports the mark() and reset() method else,false" }, { "code": null, "e": 27847, "s": 27740, "text": "skip(long arg) : Java.io.ByteArrayInputStream.skip(long arg) skips arg bytes in the input stream. Syntax :" }, { "code": null, "e": 27993, "s": 27847, "text": "public long skip(long arg)\nParameters :\narg : no. of bytes to be skipped\nReturn : \nskip bytes.\nException :\n-> IOException : If I/O error occurs." }, { "code": null, "e": 28115, "s": 27993, "text": "available() : Java.io.ByteArrayInputStream.available() tells total no. of bytes from the Input Stream to be read Syntax :" }, { "code": null, "e": 28227, "s": 28115, "text": "public int available()\nParameters :\n-----------\nReturn : \ntotal no. of bytes to be read\nException :\n-----------" }, { "code": null, "e": 28289, "s": 28227, "text": "Java Program explaining ByteArrayInputStream Class methods : " }, { "code": null, "e": 28294, "s": 28289, "text": "Java" }, { "code": "// Java program illustrating the working of ByteArrayInputStream method// mark(), read(), skip(), available()// markSupported(), close(), reset() import java.io.*; public class NewClass{ public static void main(String[] args) throws Exception { byte[] buffer = {71, 69, 69, 75, 83}; ByteArrayInputStream geek = null; try { geek = new ByteArrayInputStream(buffer); // Use of available() method : telling the no. of bytes to be read int number = geek.available(); System.out.println(\"Use of available() method : \" + number); // Use of read() method : reading and printing Characters one by one System.out.println(\"\\nChar : \"+(char)geek.read()); System.out.println(\"Char : \"+(char)geek.read()); System.out.println(\"Char : \"+(char)geek.read()); // Use of mark() : geek.mark(0); // Use of skip() : it results in skipping 'k' from \"GEEKS\" geek.skip(1); System.out.println(\"skip() method comes to play\"); System.out.println(\"mark() method comes to play\"); System.out.println(\"Char : \"+(char)geek.read()); // Use of markSupported boolean check = geek.markSupported(); System.out.println(\"\\nmarkSupported() : \" + check); if(geek.markSupported()) { // Use of reset() method : repositioning the stream to marked positions. geek.reset(); System.out.println(\"\\nreset() invoked\"); System.out.println(\"Char : \"+(char)geek.read()); System.out.println(\"Char : \"+(char)geek.read()); } else { System.out.println(\"reset() method not supported.\"); } System.out.println(\"geek.markSupported() supported reset() : \"+check); } catch(Exception except) { // in case of I/O error except.printStackTrace(); } finally { // releasing the resources back to the GarbageCollector when closes if(geek!=null) { // Use of close() : closing the file and releasing resources geek.close(); } } }}", "e": 30655, "s": 28294, "text": null }, { "code": null, "e": 30665, "s": 30655, "text": "Output : " }, { "code": null, "e": 30893, "s": 30665, "text": "Use of available() method : 5\n\nChar : G\nChar : E\nChar : E\nskip() method comes to play\nmark() method comes to play\nChar : S\n\nmarkSupported() : true\n\nreset() invoked\nChar : K\nChar : S\ngeek.markSupported() supported reset() : true" }, { "code": null, "e": 30948, "s": 30893, "text": "Next Article: io.ByteArrayOutputStream() Class in Java" }, { "code": null, "e": 31369, "s": 30948, "text": "This article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31378, "s": 31369, "text": "sooda367" }, { "code": null, "e": 31394, "s": 31378, "text": "simranarora5sos" }, { "code": null, "e": 31404, "s": 31394, "text": "kalrap615" }, { "code": null, "e": 31413, "s": 31404, "text": "Java-I/O" }, { "code": null, "e": 31418, "s": 31413, "text": "Java" }, { "code": null, "e": 31423, "s": 31418, "text": "Java" }, { "code": null, "e": 31521, "s": 31423, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31530, "s": 31521, "text": "Comments" }, { "code": null, "e": 31543, "s": 31530, "text": "Old Comments" }, { "code": null, "e": 31573, "s": 31543, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31624, "s": 31573, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 31643, "s": 31624, "text": "Interfaces in Java" }, { "code": null, "e": 31675, "s": 31643, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 31693, "s": 31675, "text": "ArrayList in Java" }, { "code": null, "e": 31724, "s": 31693, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31756, "s": 31724, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31775, "s": 31756, "text": "Overriding in Java" }, { "code": null, "e": 31795, "s": 31775, "text": "Collections in Java" } ]
CSS - Rotate Out Effect
It provides to move or cause to move in a circle round an axis or center. @keyframes rotateOut { 0% { transform-origin: center center; transform: rotate(0); opacity: 1; } 100% { transform-origin: center center; transform: rotate(200deg); opacity: 0; } } Transform − Transform applies to 2d and 3d transformation to an element. Transform − Transform applies to 2d and 3d transformation to an element. Opacity − Opacity applies to an element to make translucence. Opacity − Opacity applies to an element to make translucence. <html> <head> <style> .animated { background-image: url(/css/images/logo.png); background-repeat: no-repeat; background-position: left top; padding-top:95px; margin-bottom:60px; -webkit-animation-duration: 10s; animation-duration: 10s; -webkit-animation-fill-mode: both; animation-fill-mode: both; } @-webkit-keyframes rotateOut { 0% { -webkit-transform-origin: center center; -webkit-transform: rotate(0); opacity: 1; } 100% { -webkit-transform-origin: center center; -webkit-transform: rotate(200deg); opacity: 0; } } @keyframes rotateOut { 0% { transform-origin: center center; transform: rotate(0); opacity: 1; } 100% { transform-origin: center center; transform: rotate(200deg); opacity: 0; } } .rotateOut { -webkit-animation-name: rotateOut; animation-name: rotateOut; } </style> </head> <body> <div id = "animated-example" class = "animated rotateOut"></div> <button onclick = "myFunction()">Reload page</button> <script> function myFunction() { location.reload(); } </script> </body> </html> It will produce the following result − Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Selected Reading UPSC IAS Exams Notes Developer's Best Practices Questions and Answers Effective Resume Writing HR Interview Questions Computer Glossary Who is Who Print Add Notes Bookmark this page
[ { "code": null, "e": 2700, "s": 2626, "text": "It provides to move or cause to move in a circle round an axis or center." }, { "code": null, "e": 2929, "s": 2700, "text": "@keyframes rotateOut {\n 0% {\n transform-origin: center center;\n transform: rotate(0);\n opacity: 1;\n }\n 100% {\n transform-origin: center center;\n transform: rotate(200deg);\n opacity: 0;\n }\n} " }, { "code": null, "e": 3002, "s": 2929, "text": "Transform − Transform applies to 2d and 3d transformation to an element." }, { "code": null, "e": 3075, "s": 3002, "text": "Transform − Transform applies to 2d and 3d transformation to an element." }, { "code": null, "e": 3137, "s": 3075, "text": "Opacity − Opacity applies to an element to make translucence." }, { "code": null, "e": 3199, "s": 3137, "text": "Opacity − Opacity applies to an element to make translucence." }, { "code": null, "e": 4806, "s": 3199, "text": "<html>\n <head>\n <style>\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;\n animation-duration: 10s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n \n @-webkit-keyframes rotateOut {\n 0% {\n -webkit-transform-origin: center center;\n -webkit-transform: rotate(0);\n opacity: 1;\n }\n 100% {\n -webkit-transform-origin: center center;\n -webkit-transform: rotate(200deg);\n opacity: 0;\n }\n }\n \n @keyframes rotateOut {\n 0% {\n transform-origin: center center;\n transform: rotate(0);\n opacity: 1;\n }\n 100% {\n transform-origin: center center;\n transform: rotate(200deg);\n opacity: 0;\n }\n }\n \n .rotateOut {\n -webkit-animation-name: rotateOut;\n animation-name: rotateOut;\n }\n </style>\n </head>\n\n <body>\n \n <div id = \"animated-example\" class = \"animated rotateOut\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n \n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 4845, "s": 4806, "text": "It will produce the following result −" }, { "code": null, "e": 5492, "s": 4845, "text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n" }, { "code": null, "e": 5512, "s": 5492, "text": " Academic Tutorials" }, { "code": null, "e": 5535, "s": 5512, "text": " Big Data & Analytics " }, { "code": null, "e": 5558, "s": 5535, "text": " Computer Programming " }, { "code": null, "e": 5577, "s": 5558, "text": " Computer Science " }, { "code": null, "e": 5589, "s": 5577, "text": " Databases " }, { "code": null, "e": 5598, "s": 5589, "text": " DevOps " }, { "code": null, "e": 5618, "s": 5598, "text": " Digital Marketing " }, { "code": null, "e": 5642, "s": 5618, "text": " Engineering Tutorials " }, { "code": null, "e": 5659, "s": 5642, "text": " Exams Syllabus " }, { "code": null, "e": 5678, "s": 5659, "text": " Famous Monuments " }, { "code": null, "e": 5700, "s": 5678, "text": " GATE Exams Tutorials" }, { "code": null, "e": 5722, "s": 5700, "text": " Latest Technologies " }, { "code": null, "e": 5741, "s": 5722, "text": " Machine Learning " }, { "code": null, "e": 5765, "s": 5741, "text": " Mainframe Development " }, { "code": null, "e": 5788, "s": 5765, "text": " Management Tutorials " }, { "code": null, "e": 5811, "s": 5788, "text": " Mathematics Tutorials" }, { "code": null, "e": 5836, "s": 5811, "text": " Microsoft Technologies " }, { "code": null, "e": 5853, "s": 5836, "text": " Misc tutorials " }, { "code": null, "e": 5874, "s": 5853, "text": " Mobile Development " }, { "code": null, "e": 5894, "s": 5874, "text": " Java Technologies " }, { "code": null, "e": 5916, "s": 5894, "text": " Python Technologies " }, { "code": null, "e": 5932, "s": 5916, "text": " SAP Tutorials " }, { "code": null, "e": 5953, "s": 5932, "text": "Programming Scripts " }, { "code": null, "e": 5972, "s": 5953, "text": " Selected Reading " }, { "code": null, "e": 5991, "s": 5972, "text": " Software Quality " }, { "code": null, "e": 6005, "s": 5991, "text": " Soft Skills " }, { "code": null, "e": 6025, "s": 6005, "text": " Telecom Tutorials " }, { "code": null, "e": 6042, "s": 6025, "text": " UPSC IAS Exams " }, { "code": null, "e": 6060, "s": 6042, "text": " Web Development " }, { "code": null, "e": 6079, "s": 6060, "text": " Sports Tutorials " }, { "code": null, "e": 6098, "s": 6079, "text": " XML Technologies " }, { "code": null, "e": 6114, "s": 6098, "text": " Multi-Language" }, { "code": null, "e": 6135, "s": 6114, "text": " Interview Questions" }, { "code": null, "e": 6152, "s": 6135, "text": "Selected Reading" }, { "code": null, "e": 6173, "s": 6152, "text": "UPSC IAS Exams Notes" }, { "code": null, "e": 6200, "s": 6173, "text": "Developer's Best Practices" }, { "code": null, "e": 6222, "s": 6200, "text": "Questions and Answers" }, { "code": null, "e": 6247, "s": 6222, "text": "Effective Resume Writing" }, { "code": null, "e": 6270, "s": 6247, "text": "HR Interview Questions" }, { "code": null, "e": 6288, "s": 6270, "text": "Computer Glossary" }, { "code": null, "e": 6299, "s": 6288, "text": "Who is Who" }, { "code": null, "e": 6306, "s": 6299, "text": " Print" }, { "code": null, "e": 6317, "s": 6306, "text": " Add Notes" } ]
How to Count The Occurrences of a List Item in Python | Towards Data Science
Counting the number of occurrences of list elements in Python is definitely a fairly common task. In today’s short guide we will explore a few different ways for counting list items. More specifically, we will explore how to count the number of occurrences of a single list item count the occurrences of multiple list items We will showcase how to achieve both using a specific list method or with the help of collections module. First, let’s create an example list that we’ll reference throughout this guide in order to demonstrate a few concepts. >>> my_lst = [1, 1, 2, 3, 1, 5, 6, 2, 3, 3]>>> my_lst[1, 1, 2, 3, 1, 5, 6, 2, 3, 3] The first option you have when it comes to counting the number of times a particular element appears in a list, is list.count() method. For instance, in order to count how many times 1 appears in list my_lst you simply need to run the following command >>> my_lst.count(1)3 Alternatively, you can even use the Counter class that comes with the collections module. collections.Counter class is a subclass of dict that is used to count hashable objects. Essentially, it is a collection whether the elements for which counts are observed are stored as dictionary keys and their corresponding counts are stored as dictionary values. >>> from collections import Counter>>>>>> Counter(my_lst)[1]3 Now if you want to count the number of times multiple items appear in a given list then again, you have a couple of options for doing so. The first option you have is to call list.count() within a for-loop. Let’s say you want to count the number of times that list elements 1, 3 and 5 appear in our list. You can do so, as shown below: >>> lookup = [1, 3, 5]>>> [my_lst.count(e) for e in lookup][3, 3, 1] Alternatively, you can use collections.Counter class which in my opinion is more suitable when it comes to counting the number of occurrences of multiple items. If you want to count the number of times every single element appears in the list then you can simply create an instance of Counter. >>> from collections import Counter>>>>>> Counter(my_lst)Counter({1: 3, 2: 2, 3: 3, 5: 1, 6: 1}) If you want to count the number of times a subset of elements appear in the list then the following command will do the trick: >>> from collections import Counter>>>>>> lookup = [1, 3, 5]>>> all_counts = Counter(my_lst)>>> counts = {k: all_counts[k] for k in lookup}>>> counts{1: 3, 3: 3, 5: 1} In today’s short guide we explored a couple of different ways for counting the number of occurrences of list items in Python. We showcased how to use the list method count() or the collections.Counter class in order to count the occurrences of one or multiple list items. Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium. gmyrianthous.medium.com You may also like
[ { "code": null, "e": 396, "s": 171, "text": "Counting the number of occurrences of list elements in Python is definitely a fairly common task. In today’s short guide we will explore a few different ways for counting list items. More specifically, we will explore how to" }, { "code": null, "e": 450, "s": 396, "text": "count the number of occurrences of a single list item" }, { "code": null, "e": 495, "s": 450, "text": "count the occurrences of multiple list items" }, { "code": null, "e": 601, "s": 495, "text": "We will showcase how to achieve both using a specific list method or with the help of collections module." }, { "code": null, "e": 720, "s": 601, "text": "First, let’s create an example list that we’ll reference throughout this guide in order to demonstrate a few concepts." }, { "code": null, "e": 804, "s": 720, "text": ">>> my_lst = [1, 1, 2, 3, 1, 5, 6, 2, 3, 3]>>> my_lst[1, 1, 2, 3, 1, 5, 6, 2, 3, 3]" }, { "code": null, "e": 1057, "s": 804, "text": "The first option you have when it comes to counting the number of times a particular element appears in a list, is list.count() method. For instance, in order to count how many times 1 appears in list my_lst you simply need to run the following command" }, { "code": null, "e": 1078, "s": 1057, "text": ">>> my_lst.count(1)3" }, { "code": null, "e": 1433, "s": 1078, "text": "Alternatively, you can even use the Counter class that comes with the collections module. collections.Counter class is a subclass of dict that is used to count hashable objects. Essentially, it is a collection whether the elements for which counts are observed are stored as dictionary keys and their corresponding counts are stored as dictionary values." }, { "code": null, "e": 1495, "s": 1433, "text": ">>> from collections import Counter>>>>>> Counter(my_lst)[1]3" }, { "code": null, "e": 1633, "s": 1495, "text": "Now if you want to count the number of times multiple items appear in a given list then again, you have a couple of options for doing so." }, { "code": null, "e": 1831, "s": 1633, "text": "The first option you have is to call list.count() within a for-loop. Let’s say you want to count the number of times that list elements 1, 3 and 5 appear in our list. You can do so, as shown below:" }, { "code": null, "e": 1900, "s": 1831, "text": ">>> lookup = [1, 3, 5]>>> [my_lst.count(e) for e in lookup][3, 3, 1]" }, { "code": null, "e": 2061, "s": 1900, "text": "Alternatively, you can use collections.Counter class which in my opinion is more suitable when it comes to counting the number of occurrences of multiple items." }, { "code": null, "e": 2194, "s": 2061, "text": "If you want to count the number of times every single element appears in the list then you can simply create an instance of Counter." }, { "code": null, "e": 2291, "s": 2194, "text": ">>> from collections import Counter>>>>>> Counter(my_lst)Counter({1: 3, 2: 2, 3: 3, 5: 1, 6: 1})" }, { "code": null, "e": 2418, "s": 2291, "text": "If you want to count the number of times a subset of elements appear in the list then the following command will do the trick:" }, { "code": null, "e": 2586, "s": 2418, "text": ">>> from collections import Counter>>>>>> lookup = [1, 3, 5]>>> all_counts = Counter(my_lst)>>> counts = {k: all_counts[k] for k in lookup}>>> counts{1: 3, 3: 3, 5: 1}" }, { "code": null, "e": 2858, "s": 2586, "text": "In today’s short guide we explored a couple of different ways for counting the number of occurrences of list items in Python. We showcased how to use the list method count() or the collections.Counter class in order to count the occurrences of one or multiple list items." }, { "code": null, "e": 3029, "s": 2858, "text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium." }, { "code": null, "e": 3053, "s": 3029, "text": "gmyrianthous.medium.com" } ]
ReactJS - Using CDN
Let us learn how to use content delivery network to include React in a simple web page. Open a terminal and go to your workspace. cd /go/to/your/workspace Next, create a folder, static_site and change directory to newly created folder. mkdir static_site cd static_site Next, create a new HTML file, hello.html. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Simple React app</title> </head> <body> </body> </html> Next, include React library. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Simple React app</title> </head> <body> <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script> </body> </html> Here, We are using unpkg CDN. unpkg is an open source, global content delivery network supporting npm packages. We are using unpkg CDN. unpkg is an open source, global content delivery network supporting npm packages. @17represent the version of the React library @17represent the version of the React library This is the development version of the React library with debugging option. To deploy the application in the production environment, use below scripts. This is the development version of the React library with debugging option. To deploy the application in the production environment, use below scripts. <script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script> Now, we are ready to use React library in our webpage. Next, introduce a div tag with id react-app. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React based application</title> </head> <body> <div id="react-app"></div> <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script> </body> </html> The react-app is a placeholder container and React will work inside the container. We can use any name for the placeholder container relevant to our application. Next, create a script section at the end of the document and use React feature to create an element. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React based application</title> </head> <body> <div id="react-app"></div> <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script> <script language="JavaScript"> element = React.createElement('h1', {}, 'Hello React!') ReactDOM.render(element, document.getElementById('react-app')); </script> </body> </html> Here, the application uses React.createElement and ReactDOM.render methods provided by React Library to dynamically create a HTML element and place it inside the react-app section. Next, serve the application using serve web server. serve ./hello.html Next, open the browser and enter http://localhost:5000 in the address bar and press enter. serve application will serve our webpage as shown below. We can use the same steps to use React in the existing website as well. This method is very easy to use and consume React library. It can be used to do simple to moderate feature in a website. It can be used in new as well as existing application along with other libraries. This method is suitable for static website with few dynamic section like contact form, simple payment option, etc., To create advanced single page application (SPA), we need to use React tools. Let us learn how to create a SPA using React tools in upcoming chapter. 20 Lectures 1.5 hours Anadi Sharma 60 Lectures 4.5 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 63 Lectures 9.5 hours TELCOMA Global 17 Lectures 2 hours Mohd Raqif Warsi Print Add Notes Bookmark this page
[ { "code": null, "e": 2121, "s": 2033, "text": "Let us learn how to use content delivery network to include React in a simple web page." }, { "code": null, "e": 2163, "s": 2121, "text": "Open a terminal and go to your workspace." }, { "code": null, "e": 2189, "s": 2163, "text": "cd /go/to/your/workspace\n" }, { "code": null, "e": 2270, "s": 2189, "text": "Next, create a folder, static_site and change directory to newly created folder." }, { "code": null, "e": 2305, "s": 2270, "text": "mkdir static_site \ncd static_site\n" }, { "code": null, "e": 2347, "s": 2305, "text": "Next, create a new HTML file, hello.html." }, { "code": null, "e": 2497, "s": 2347, "text": "<!DOCTYPE html> \n<html> \n <head> \n <meta charset=\"UTF-8\" /> \n <title>Simple React app</title> \n </head> \n <body> \n </body> \n</html>" }, { "code": null, "e": 2526, "s": 2497, "text": "Next, include React library." }, { "code": null, "e": 2873, "s": 2526, "text": "<!DOCTYPE html> \n<html> \n <head> \n <meta charset=\"UTF-8\" /> \n <title>Simple React app</title> \n </head> \n <body>\n <script src=\"https://unpkg.com/react@17/umd/react.development.js\" crossorigin></script> \n <script src=\"https://unpkg.com/react-dom@17/umd/react-dom.development.js\" crossorigin></script> \n </body> \n</html>" }, { "code": null, "e": 2879, "s": 2873, "text": "Here," }, { "code": null, "e": 2985, "s": 2879, "text": "We are using unpkg CDN. unpkg is an open source, global content delivery network supporting npm packages." }, { "code": null, "e": 3091, "s": 2985, "text": "We are using unpkg CDN. unpkg is an open source, global content delivery network supporting npm packages." }, { "code": null, "e": 3137, "s": 3091, "text": "@17represent the version of the React library" }, { "code": null, "e": 3183, "s": 3137, "text": "@17represent the version of the React library" }, { "code": null, "e": 3335, "s": 3183, "text": "This is the development version of the React library with debugging option. To deploy the application in the production environment, use below scripts." }, { "code": null, "e": 3487, "s": 3335, "text": "This is the development version of the React library with debugging option. To deploy the application in the production environment, use below scripts." }, { "code": null, "e": 3679, "s": 3487, "text": "<script src=\"https://unpkg.com/react@17/umd/react.production.min.js\" crossorigin></script> \n<script src=\"https://unpkg.com/react-dom@17/umd/react-dom.production.min.js\" crossorigin></script>\n" }, { "code": null, "e": 3734, "s": 3679, "text": "Now, we are ready to use React library in our webpage." }, { "code": null, "e": 3779, "s": 3734, "text": "Next, introduce a div tag with id react-app." }, { "code": null, "e": 4168, "s": 3779, "text": "<!DOCTYPE html> \n<html> \n <head> \n <meta charset=\"UTF-8\" /> \n <title>React based application</title> \n </head> \n <body> \n <div id=\"react-app\"></div> \n <script src=\"https://unpkg.com/react@17/umd/react.development.js\" crossorigin></script> \n <script src=\"https://unpkg.com/react-dom@17/umd/react-dom.development.js\" crossorigin></script> \n </body> \n</html>" }, { "code": null, "e": 4330, "s": 4168, "text": "The react-app is a placeholder container and React will work inside the container. We can use any name for the placeholder container relevant to our application." }, { "code": null, "e": 4431, "s": 4330, "text": "Next, create a script section at the end of the document and use React feature to create an element." }, { "code": null, "e": 5014, "s": 4431, "text": "<!DOCTYPE html> \n<html> \n <head> \n <meta charset=\"UTF-8\" /> \n <title>React based application</title> \n </head>\n <body> \n <div id=\"react-app\"></div> \n <script src=\"https://unpkg.com/react@17/umd/react.development.js\" crossorigin></script> \n <script src=\"https://unpkg.com/react-dom@17/umd/react-dom.development.js\" crossorigin></script> \n <script language=\"JavaScript\"> \n element = React.createElement('h1', {}, 'Hello React!') \n ReactDOM.render(element, document.getElementById('react-app')); \n </script> \n </body> \n</html>" }, { "code": null, "e": 5195, "s": 5014, "text": "Here, the application uses React.createElement and ReactDOM.render methods provided by React Library to dynamically create a HTML element and place it inside the react-app section." }, { "code": null, "e": 5247, "s": 5195, "text": "Next, serve the application using serve web server." }, { "code": null, "e": 5267, "s": 5247, "text": "serve ./hello.html\n" }, { "code": null, "e": 5415, "s": 5267, "text": "Next, open the browser and enter http://localhost:5000 in the address bar and press enter. serve application will serve our webpage as shown below." }, { "code": null, "e": 5956, "s": 5415, "text": "We can use the same steps to use React in the existing website as well. This method is very easy to use and consume React library. It can be used to do simple to moderate feature in a website. It can be used in new as well as existing application along with other libraries. This method is suitable for static website with few dynamic section like contact form, simple payment option, etc., To create advanced single page application (SPA), we need to use React tools. Let us learn how to create a SPA using React tools in upcoming chapter." }, { "code": null, "e": 5991, "s": 5956, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6005, "s": 5991, "text": " Anadi Sharma" }, { "code": null, "e": 6040, "s": 6005, "text": "\n 60 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6060, "s": 6040, "text": " Skillbakerystudios" }, { "code": null, "e": 6095, "s": 6060, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 6118, "s": 6095, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 6153, "s": 6118, "text": "\n 63 Lectures \n 9.5 hours \n" }, { "code": null, "e": 6169, "s": 6153, "text": " TELCOMA Global" }, { "code": null, "e": 6202, "s": 6169, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 6220, "s": 6202, "text": " Mohd Raqif Warsi" }, { "code": null, "e": 6227, "s": 6220, "text": " Print" }, { "code": null, "e": 6238, "s": 6227, "text": " Add Notes" } ]
How to draw an oval in HTML5 canvas?
You can try to run the following code to draw an oval in HTML5 canvas − <!DOCTYPE HTML> <html> <head> </head> <body> <canvas id="newCanvas" width="450" height="300"></canvas> <script> // canvas var c = document.getElementById('newCanvas'); var context = c.getContext('2d'); var cX = 0; var cY = 0; var radius = 40; context.save(); context.translate(c.width / 2, c.height / 2); context.scale(2, 1); context.beginPath(); context.arc(cX, cY, radius, 0, 2 * Math.PI, false); context.restore(); context.fillStyle = '#000000'; context.fill(); context.lineWidth = 2; context.strokeStyle = 'yellow'; context.stroke(); </script> </body> </html>
[ { "code": null, "e": 1134, "s": 1062, "text": "You can try to run the following code to draw an oval in HTML5 canvas −" }, { "code": null, "e": 1892, "s": 1134, "text": "<!DOCTYPE HTML>\n<html>\n <head>\n </head>\n <body>\n <canvas id=\"newCanvas\" width=\"450\" height=\"300\"></canvas>\n <script>\n // canvas\n\n var c = document.getElementById('newCanvas');\n var context = c.getContext('2d');\n var cX = 0;\n var cY = 0;\n var radius = 40;\n \n context.save();\n context.translate(c.width / 2, c.height / 2);\n context.scale(2, 1);\n context.beginPath();\n context.arc(cX, cY, radius, 0, 2 * Math.PI, false);\n context.restore();\n context.fillStyle = '#000000';\n context.fill();\n context.lineWidth = 2;\n context.strokeStyle = 'yellow';\n context.stroke();\n </script>\n </body>\n</html>" } ]
Perl m Function
This match operator is used to match any keyword in given expression. Parentheses after initial m can be any character and will be used to delimit the regular expression statement. Regular expression variables include $, which contains whatever the last grouping match matched; $&, which contains the entire matched string; $`, which contains everything before the matched string; and $', which contains everything after the matched string. Following is the simple syntax for this function − m// This function returns 0 on failure and 1 on success, Following is the example code showing its basic usage − #!/usr/bin/perl -w $string = "The food is in the salad bar"; $string =~ m/foo/; print "Before: $`\n"; print "Matched: $&\n"; print "After: $'\n"; When above code is executed, it produces the following result − Before: The Matched: foo After: d is in the salad bar 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2401, "s": 2220, "text": "This match operator is used to match any keyword in given expression. Parentheses after initial m can be any character and will be used to delimit the regular expression statement." }, { "code": null, "e": 2661, "s": 2401, "text": "Regular expression variables include $, which contains whatever the last grouping match matched; $&, which contains the entire matched string; $`, which contains everything before the matched string; and $', which contains everything after the matched string." }, { "code": null, "e": 2712, "s": 2661, "text": "Following is the simple syntax for this function −" }, { "code": null, "e": 2717, "s": 2712, "text": "m//\n" }, { "code": null, "e": 2770, "s": 2717, "text": "This function returns 0 on failure and 1 on success," }, { "code": null, "e": 2826, "s": 2770, "text": "Following is the example code showing its basic usage −" }, { "code": null, "e": 2973, "s": 2826, "text": "#!/usr/bin/perl -w\n\n$string = \"The food is in the salad bar\";\n$string =~ m/foo/;\nprint \"Before: $`\\n\";\nprint \"Matched: $&\\n\";\nprint \"After: $'\\n\";" }, { "code": null, "e": 3037, "s": 2973, "text": "When above code is executed, it produces the following result −" }, { "code": null, "e": 3093, "s": 3037, "text": "Before: The \nMatched: foo\nAfter: d is in the salad bar\n" }, { "code": null, "e": 3128, "s": 3093, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3142, "s": 3128, "text": " Devi Killada" }, { "code": null, "e": 3177, "s": 3142, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3197, "s": 3177, "text": " Harshit Srivastava" }, { "code": null, "e": 3230, "s": 3197, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 3246, "s": 3230, "text": " TELCOMA Global" }, { "code": null, "e": 3279, "s": 3246, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3296, "s": 3279, "text": " Mohammad Nauman" }, { "code": null, "e": 3329, "s": 3296, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 3352, "s": 3329, "text": " Stone River ELearning" }, { "code": null, "e": 3387, "s": 3352, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3410, "s": 3387, "text": " Stone River ELearning" }, { "code": null, "e": 3417, "s": 3410, "text": " Print" }, { "code": null, "e": 3428, "s": 3417, "text": " Add Notes" } ]
Mockito - First Application
Before going into the details of the Mockito Framework, let's see an application in action. In this example, we've created a mock of Stock Service to get the dummy price of some stocks and unit tested a java class named Portfolio. The process is discussed below in a step-by-step manner. Step 1 − Create a JAVA class to represent the Stock File: Stock.java public class Stock { private String stockId; private String name; private int quantity; public Stock(String stockId, String name, int quantity){ this.stockId = stockId; this.name = name; this.quantity = quantity; } public String getStockId() { return stockId; } public void setStockId(String stockId) { this.stockId = stockId; } public int getQuantity() { return quantity; } public String getTicker() { return name; } } Step 2 − Create an interface StockService to get the price of a stock File: StockService.java public interface StockService { public double getPrice(Stock stock); } Step 3 − Create a class Portfolio to represent the portfolio of any client File: Portfolio.java import java.util.List; public class Portfolio { private StockService stockService; private List<Stock> stocks; public StockService getStockService() { return stockService; } public void setStockService(StockService stockService) { this.stockService = stockService; } public List<Stock> getStocks() { return stocks; } public void setStocks(List<Stock> stocks) { this.stocks = stocks; } public double getMarketValue(){ double marketValue = 0.0; for(Stock stock:stocks){ marketValue += stockService.getPrice(stock) * stock.getQuantity(); } return marketValue; } } Step 4 − Test the Portfolio class Let's test the Portfolio class, by injecting in it a mock of stockservice. Mock will be created by Mockito. File: PortfolioTester.java package com.tutorialspoint.mock; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.*; public class PortfolioTester { Portfolio portfolio; StockService stockService; public static void main(String[] args){ PortfolioTester tester = new PortfolioTester(); tester.setUp(); System.out.println(tester.testMarketValue()?"pass":"fail"); } public void setUp(){ //Create a portfolio object which is to be tested portfolio = new Portfolio(); //Create the mock object of stock service stockService = mock(StockService.class); //set the stockService to the portfolio portfolio.setStockService(stockService); } public boolean testMarketValue(){ //Creates a list of stocks to be added to the portfolio List<Stock> stocks = new ArrayList<Stock>(); Stock googleStock = new Stock("1","Google", 10); Stock microsoftStock = new Stock("2","Microsoft",100); stocks.add(googleStock); stocks.add(microsoftStock); //add stocks to the portfolio portfolio.setStocks(stocks); //mock the behavior of stock service to return the value of various stocks when(stockService.getPrice(googleStock)).thenReturn(50.00); when(stockService.getPrice(microsoftStock)).thenReturn(1000.00); double marketValue = portfolio.getMarketValue(); return marketValue == 100500.0; } } Step 5 − Verify the result Compile the classes using javac compiler as follows − C:\Mockito_WORKSPACE>javac Stock.java StockService.java Portfolio.java PortfolioTester.java Now run the PortfolioTester to see the result − C:\Mockito_WORKSPACE>java PortfolioTester Verify the Output pass 31 Lectures 43 mins Abhinav Manchanda Print Add Notes Bookmark this page
[ { "code": null, "e": 2211, "s": 1980, "text": "Before going into the details of the Mockito Framework, let's see an application in action. In this example, we've created a mock of Stock Service to get the dummy price of some stocks and unit tested a java class named Portfolio." }, { "code": null, "e": 2268, "s": 2211, "text": "The process is discussed below in a step-by-step manner." }, { "code": null, "e": 2320, "s": 2268, "text": "Step 1 − Create a JAVA class to represent the Stock" }, { "code": null, "e": 2337, "s": 2320, "text": "File: Stock.java" }, { "code": null, "e": 2848, "s": 2337, "text": "public class Stock {\n private String stockId;\n private String name;\t\n private int quantity;\n\n public Stock(String stockId, String name, int quantity){\n this.stockId = stockId;\n this.name = name;\t\t\n this.quantity = quantity;\t\t\n }\n\n public String getStockId() {\n return stockId;\n }\n\n public void setStockId(String stockId) {\n this.stockId = stockId;\n }\n\n public int getQuantity() {\n return quantity;\n }\n\n public String getTicker() {\n return name;\n }\n}" }, { "code": null, "e": 2918, "s": 2848, "text": "Step 2 − Create an interface StockService to get the price of a stock" }, { "code": null, "e": 2942, "s": 2918, "text": "File: StockService.java" }, { "code": null, "e": 3016, "s": 2942, "text": "public interface StockService {\n public double getPrice(Stock stock);\n}" }, { "code": null, "e": 3091, "s": 3016, "text": "Step 3 − Create a class Portfolio to represent the portfolio of any client" }, { "code": null, "e": 3112, "s": 3091, "text": "File: Portfolio.java" }, { "code": null, "e": 3782, "s": 3112, "text": "import java.util.List;\n\npublic class Portfolio {\n private StockService stockService;\n private List<Stock> stocks;\n\n public StockService getStockService() {\n return stockService;\n }\n \n public void setStockService(StockService stockService) {\n this.stockService = stockService;\n }\n\n public List<Stock> getStocks() {\n return stocks;\n }\n\n public void setStocks(List<Stock> stocks) {\n this.stocks = stocks;\n }\n\n public double getMarketValue(){\n double marketValue = 0.0;\n \n for(Stock stock:stocks){\n marketValue += stockService.getPrice(stock) * stock.getQuantity();\n }\n return marketValue;\n }\n}" }, { "code": null, "e": 3816, "s": 3782, "text": "Step 4 − Test the Portfolio class" }, { "code": null, "e": 3924, "s": 3816, "text": "Let's test the Portfolio class, by injecting in it a mock of stockservice. Mock will be created by Mockito." }, { "code": null, "e": 3951, "s": 3924, "text": "File: PortfolioTester.java" }, { "code": null, "e": 5429, "s": 3951, "text": "package com.tutorialspoint.mock;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static org.mockito.Mockito.*;\n\npublic class PortfolioTester {\n\t\n Portfolio portfolio;\t\n StockService stockService;\n\t \n \n public static void main(String[] args){\n PortfolioTester tester = new PortfolioTester();\n tester.setUp();\n System.out.println(tester.testMarketValue()?\"pass\":\"fail\");\n }\n \n public void setUp(){\n //Create a portfolio object which is to be tested\t\t\n portfolio = new Portfolio();\t\t\n \n //Create the mock object of stock service\n stockService = mock(StockService.class);\t\t\n \n //set the stockService to the portfolio\n portfolio.setStockService(stockService);\n }\n \n public boolean testMarketValue(){\n \t \n //Creates a list of stocks to be added to the portfolio\n List<Stock> stocks = new ArrayList<Stock>();\n Stock googleStock = new Stock(\"1\",\"Google\", 10);\n Stock microsoftStock = new Stock(\"2\",\"Microsoft\",100);\t\n \n stocks.add(googleStock);\n stocks.add(microsoftStock);\n\n //add stocks to the portfolio\n portfolio.setStocks(stocks);\n\n //mock the behavior of stock service to return the value of various stocks\n when(stockService.getPrice(googleStock)).thenReturn(50.00);\n when(stockService.getPrice(microsoftStock)).thenReturn(1000.00);\t\t\n\n double marketValue = portfolio.getMarketValue();\t\t\n return marketValue == 100500.0;\n }\n}" }, { "code": null, "e": 5456, "s": 5429, "text": "Step 5 − Verify the result" }, { "code": null, "e": 5510, "s": 5456, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 5603, "s": 5510, "text": "C:\\Mockito_WORKSPACE>javac Stock.java StockService.java Portfolio.java PortfolioTester.java\n" }, { "code": null, "e": 5651, "s": 5603, "text": "Now run the PortfolioTester to see the result −" }, { "code": null, "e": 5694, "s": 5651, "text": "C:\\Mockito_WORKSPACE>java PortfolioTester\n" }, { "code": null, "e": 5712, "s": 5694, "text": "Verify the Output" }, { "code": null, "e": 5718, "s": 5712, "text": "pass\n" }, { "code": null, "e": 5750, "s": 5718, "text": "\n 31 Lectures \n 43 mins\n" }, { "code": null, "e": 5769, "s": 5750, "text": " Abhinav Manchanda" }, { "code": null, "e": 5776, "s": 5769, "text": " Print" }, { "code": null, "e": 5787, "s": 5776, "text": " Add Notes" } ]
D3.js randomNormal() Function - GeeksforGeeks
29 Jul, 2020 The randomNormal() function is used to return a function that gives a random number based on Normal distribution or Gaussian distribution. Syntax: d3.randomNormal(mu, sigma); Parameters: It takes the two parameters given above and described below. mu: It is the expected value of the number. If mu is not given then it is considered as 0. sigma: The number is generated with a certain standard deviation called sigma. Returns: It returns a function. Below given are a few examples of the above function. Example 1: When mu is given. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><style></style><body> <!-- Fetching from CDN of D3.js --> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"> </script> <script>// The ouput may be different on different machines. console.log(d3.randomNormal(10, 10)()) console.log(d3.randomNormal(10, 10)()) console.log(d3.randomNormal(10, 10)()) console.log(d3.randomNormal(10, 10)()) console.log(d3.randomNormal(10, 10)()) </script></body></html> Output: Example 2: When mu is not given. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><style></style><body> <!-- Fetching from CDN of D3.js --> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"> </script> <script>// The ouput may be different on different machines. console.log(d3.randomNormal(5)()) console.log(d3.randomNormal(5)()) console.log(d3.randomNormal(5)()) console.log(d3.randomNormal(5)()) console.log(d3.randomNormal(5)()) console.log(d3.randomNormal(5)()) </script></body></html> Output: D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request 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 Convert a string to an integer in JavaScript
[ { "code": null, "e": 24536, "s": 24508, "text": "\n29 Jul, 2020" }, { "code": null, "e": 24676, "s": 24536, "text": "The randomNormal() function is used to return a function that gives a random number based on Normal distribution or Gaussian distribution. " }, { "code": null, "e": 24684, "s": 24676, "text": "Syntax:" }, { "code": null, "e": 24712, "s": 24684, "text": "d3.randomNormal(mu, sigma);" }, { "code": null, "e": 24785, "s": 24712, "text": "Parameters: It takes the two parameters given above and described below." }, { "code": null, "e": 24876, "s": 24785, "text": "mu: It is the expected value of the number. If mu is not given then it is considered as 0." }, { "code": null, "e": 24955, "s": 24876, "text": "sigma: The number is generated with a certain standard deviation called sigma." }, { "code": null, "e": 24987, "s": 24955, "text": "Returns: It returns a function." }, { "code": null, "e": 25041, "s": 24987, "text": "Below given are a few examples of the above function." }, { "code": null, "e": 25070, "s": 25041, "text": "Example 1: When mu is given." }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head><style></style><body> <!-- Fetching from CDN of D3.js --> <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"> </script> <script>// The ouput may be different on different machines. console.log(d3.randomNormal(10, 10)()) console.log(d3.randomNormal(10, 10)()) console.log(d3.randomNormal(10, 10)()) console.log(d3.randomNormal(10, 10)()) console.log(d3.randomNormal(10, 10)()) </script></body></html>", "e": 25710, "s": 25070, "text": null }, { "code": null, "e": 25718, "s": 25710, "text": "Output:" }, { "code": null, "e": 25751, "s": 25718, "text": "Example 2: When mu is not given." }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head><style></style><body> <!-- Fetching from CDN of D3.js --> <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"> </script> <script>// The ouput may be different on different machines. console.log(d3.randomNormal(5)()) console.log(d3.randomNormal(5)()) console.log(d3.randomNormal(5)()) console.log(d3.randomNormal(5)()) console.log(d3.randomNormal(5)()) console.log(d3.randomNormal(5)()) </script></body></html>", "e": 26403, "s": 25751, "text": null }, { "code": null, "e": 26411, "s": 26403, "text": "Output:" }, { "code": null, "e": 26417, "s": 26411, "text": "D3.js" }, { "code": null, "e": 26428, "s": 26417, "text": "JavaScript" }, { "code": null, "e": 26445, "s": 26428, "text": "Web Technologies" }, { "code": null, "e": 26543, "s": 26445, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26588, "s": 26543, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26649, "s": 26588, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26721, "s": 26649, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26767, "s": 26721, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 26808, "s": 26767, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26850, "s": 26808, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26883, "s": 26850, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26926, "s": 26883, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26988, "s": 26926, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to use GridLayoutManager in RecyclerView?
This example demonstrate about How to use GridLayoutManager in RecyclerView Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <android.support.design.widget.CoordinatorLayout android:layout_width = "match_parent" android:layout_height = "match_parent" xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto"> <android.support.design.widget.AppBarLayout android:layout_width = "match_parent" android:layout_height = "wrap_content"> <android.support.v7.widget.Toolbar android:id = "@+id/appbarlayout_tool_bar" android:background = "@color/colorPrimary" android:layout_width = "match_parent" android:layout_height = "?attr/actionBarSize" app:layout_scrollFlags = "scroll|snap|enterAlways" app:theme = "@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:popupTheme = "@style/ThemeOverlay.AppCompat.Light" /> </android.support.design.widget.AppBarLayout> <android.support.v7.widget.RecyclerView android:id = "@+id/recycler_view" android:layout_width = "match_parent" android:layout_height = "match_parent" app:layout_behavior = "@string/appbar_scrolling_view_behavior"/> </android.support.design.widget.CoordinatorLayout> In the above code, we have taken recycerview. Step 3 − Add the following code to src/MainActivity.java <?xml version = "1.0" encoding = "utf-8"?> import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { TextView text; ArrayList<String> list = new ArrayList<>(); private RecyclerView recyclerView; private customAdapter mAdapter; private onClickInterface onclickInterface; @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.appbarlayout_tool_bar); toolbar.setTitle("This is toolbar."); setSupportActionBar(toolbar); onclickInterface = new onClickInterface() { @Override public void setClick(int abc) { list.remove(abc); Toast.makeText(MainActivity.this,"Position is"+abc,Toast.LENGTH_LONG).show(); mAdapter.notifyDataSetChanged(); } }; recyclerView = (RecyclerView) findViewById(R.id.recycler_view); GridLayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(),2); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); mAdapter = new customAdapter(this, list, onclickInterface); recyclerView.setAdapter(mAdapter); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.HORIZONTAL); recyclerView.addItemDecoration(dividerItemDecoration); list.add("sairamm"); list.add("Krishna"); list.add("prasad"); list.add("sairamm"); list.add("Krishna"); list.add("prasad"); list.add("sairamm"); list.add("Krishna"); list.add("prasad"); list.add("sairamm"); list.add("Krishna"); list.add("prasad"); list.add("Krishna"); list.add("prasad"); list.add("sairamm"); list.add("Krishna"); list.add("prasad"); list.add("sairamm"); list.add("Krishna"); list.add("prasad"); } } Step 4 − Add the following code to src/ customAdapter.java <?xml version = "1.0" encoding = "utf-8"?> import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; public class customAdapter extends RecyclerView.Adapter<customAdapter.MyViewHolder> { Context context; ArrayList<String> list; onClickInterface onClickInterface; public class MyViewHolder extends RecyclerView.ViewHolder { public TextView title; public MyViewHolder(View view) { super(view); title = (TextView) view.findViewById(R.id.title); } } public customAdapter(Context context, ArrayList<String> list, onClickInterface onClickInterface) { this.context = context; this.list = list; this.onClickInterface = onClickInterface; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, viewGroup, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) { myViewHolder.title.setText(list.get(i)); myViewHolder.title.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickInterface.setClick(i); } }); } @Override public int getItemCount() { return list.size(); } } Step 5 − Add the following code to res/layout/ list_row.xml. <?xml version = "1.0" encoding = "utf-8"?> <android.support.v7.widget.CardView xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "wrap_content" app:cardElevation = "10dp" app:cardCornerRadius = "20dp" tools:context = ".MainActivity"> <LinearLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:gravity = "center" android:orientation = "vertical"> <ImageView android:id = "@+id/imageView2" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:src = "@drawable/logo" /> <TextView android:id = "@+id/title" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:gravity = "center" android:textSize = "30sp" /> <TextView android:id = "@+id/textview2" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:gravity = "center" android:text = "Sairamkrishan" android:textSize = "30sp" /> </LinearLayout> </android.support.v7.widget.CardView> Step 6 − Add the following code to src/ onClickInterface. <?xml version = "1.0" encoding = "utf-8"?> public interface onClickInterface { void setClick(int abc); } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
[ { "code": null, "e": 1138, "s": 1062, "text": "This example demonstrate about How to use GridLayoutManager in RecyclerView" }, { "code": null, "e": 1267, "s": 1138, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1332, "s": 1267, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2547, "s": 1332, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.design.widget.CoordinatorLayout android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\">\n <android.support.design.widget.AppBarLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\">\n <android.support.v7.widget.Toolbar\n android:id = \"@+id/appbarlayout_tool_bar\"\n android:background = \"@color/colorPrimary\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"?attr/actionBarSize\"\n app:layout_scrollFlags = \"scroll|snap|enterAlways\"\n app:theme = \"@style/ThemeOverlay.AppCompat.Dark.ActionBar\"\n app:popupTheme = \"@style/ThemeOverlay.AppCompat.Light\" />\n </android.support.design.widget.AppBarLayout>\n <android.support.v7.widget.RecyclerView\n android:id = \"@+id/recycler_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n app:layout_behavior = \"@string/appbar_scrolling_view_behavior\"/>\n</android.support.design.widget.CoordinatorLayout>" }, { "code": null, "e": 2593, "s": 2547, "text": "In the above code, we have taken recycerview." }, { "code": null, "e": 2650, "s": 2593, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5207, "s": 2650, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\nimport android.annotation.TargetApi;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.v4.content.ContextCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.DefaultItemAnimator;\nimport android.support.v7.widget.DividerItemDecoration;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.support.v7.widget.Toolbar;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport java.util.ArrayList;\n\npublic class MainActivity extends AppCompatActivity {\n TextView text;\n ArrayList<String> list = new ArrayList<>();\n private RecyclerView recyclerView;\n private customAdapter mAdapter;\n private onClickInterface onclickInterface;\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.appbarlayout_tool_bar);\n toolbar.setTitle(\"This is toolbar.\");\n setSupportActionBar(toolbar);\n onclickInterface = new onClickInterface() {\n @Override\n public void setClick(int abc) {\n list.remove(abc);\n Toast.makeText(MainActivity.this,\"Position is\"+abc,Toast.LENGTH_LONG).show();\n mAdapter.notifyDataSetChanged();\n }\n };\n recyclerView = (RecyclerView) findViewById(R.id.recycler_view);\n GridLayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(),2);\n recyclerView.setLayoutManager(mLayoutManager);\n recyclerView.setItemAnimator(new DefaultItemAnimator());\n mAdapter = new customAdapter(this, list, onclickInterface);\n recyclerView.setAdapter(mAdapter);\n DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.HORIZONTAL);\n recyclerView.addItemDecoration(dividerItemDecoration);\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n }\n}" }, { "code": null, "e": 5266, "s": 5207, "text": "Step 4 − Add the following code to src/ customAdapter.java" }, { "code": null, "e": 6872, "s": 5266, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\nimport android.content.Context;\nimport android.support.annotation.NonNull;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\nimport java.util.ArrayList;\npublic class customAdapter extends RecyclerView.Adapter<customAdapter.MyViewHolder> {\n Context context;\n ArrayList<String> list;\n onClickInterface onClickInterface;\n public class MyViewHolder extends RecyclerView.ViewHolder {\n public TextView title;\n public MyViewHolder(View view) {\n super(view);\n title = (TextView) view.findViewById(R.id.title);\n }\n }\n public customAdapter(Context context, ArrayList<String> list, onClickInterface onClickInterface) {\n this.context = context;\n this.list = list;\n this.onClickInterface = onClickInterface;\n }\n @NonNull\n @Override\n public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {\n View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, viewGroup, false);\n return new MyViewHolder(itemView);\n }\n @Override\n public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) {\n myViewHolder.title.setText(list.get(i));\n myViewHolder.title.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onClickInterface.setClick(i);\n }\n });\n }\n @Override\n public int getItemCount() {\n return list.size();\n }\n}" }, { "code": null, "e": 6933, "s": 6872, "text": "Step 5 − Add the following code to res/layout/ list_row.xml." }, { "code": null, "e": 8279, "s": 6933, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.v7.widget.CardView xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n app:cardElevation = \"10dp\"\n app:cardCornerRadius = \"20dp\"\n tools:context = \".MainActivity\">\n <LinearLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:gravity = \"center\"\n android:orientation = \"vertical\">\n <ImageView\n android:id = \"@+id/imageView2\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:src = \"@drawable/logo\" />\n <TextView\n android:id = \"@+id/title\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:gravity = \"center\"\n android:textSize = \"30sp\" />\n <TextView\n android:id = \"@+id/textview2\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:gravity = \"center\"\n android:text = \"Sairamkrishan\"\n android:textSize = \"30sp\" />\n </LinearLayout>\n</android.support.v7.widget.CardView>" }, { "code": null, "e": 8337, "s": 8279, "text": "Step 6 − Add the following code to src/ onClickInterface." }, { "code": null, "e": 8445, "s": 8337, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\npublic interface onClickInterface {\n void setClick(int abc);\n}" }, { "code": null, "e": 8792, "s": 8445, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" } ]
Python | Checking triangular inequality on list of lists - GeeksforGeeks
03 Mar, 2019 Given a list of lists, the task is to find whether a sublist satisfies the triangle inequality. The triangle inequality states that for any triangle, the sum of the lengths of any two sides must be greater than or equal to the length of the remaining side. In other words, a triangle is valid if sum of its two sides is greater than the third side. If three sides are a, b and c, then three conditions should be met. a + b > c a + c > b b + c > a Method #1 : Using List comprehension # Python code to find whether a sublist # satisfies the triangle inequality. # List initializationInput = [[1, 3, 1], [4, 5, 6]] # Sorting sublistfor elem in Input: elem.sort() # Using list comprehensionOutput = [(p, q, r) for p, q, r in Input if (p + q)>= r] # Printing outputprint(Output) [(4, 5, 6)] Method #2 : Using Iteration # Python code to find whether a sublist# satisfies the triangle inequality. # List initializationInput = [[1, 1, 3], [4, 5, 6]] # Sorting sublist of list of listfor elem in Input: elem.sort() # Checking for triangular inequalityfor elem in Input: if elem[0] + elem[1] > elem[2]: print(elem) [4, 5, 6] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24412, "s": 24384, "text": "\n03 Mar, 2019" }, { "code": null, "e": 24508, "s": 24412, "text": "Given a list of lists, the task is to find whether a sublist satisfies the triangle inequality." }, { "code": null, "e": 24829, "s": 24508, "text": "The triangle inequality states that for any triangle, the sum of the lengths of any two sides must be greater than or equal to the length of the remaining side. In other words, a triangle is valid if sum of its two sides is greater than the third side. If three sides are a, b and c, then three conditions should be met." }, { "code": null, "e": 24864, "s": 24829, "text": "a + b > c \na + c > b \nb + c > a \n" }, { "code": null, "e": 24901, "s": 24864, "text": "Method #1 : Using List comprehension" }, { "code": "# Python code to find whether a sublist # satisfies the triangle inequality. # List initializationInput = [[1, 3, 1], [4, 5, 6]] # Sorting sublistfor elem in Input: elem.sort() # Using list comprehensionOutput = [(p, q, r) for p, q, r in Input if (p + q)>= r] # Printing outputprint(Output)", "e": 25199, "s": 24901, "text": null }, { "code": null, "e": 25212, "s": 25199, "text": "[(4, 5, 6)]\n" }, { "code": null, "e": 25241, "s": 25212, "text": " Method #2 : Using Iteration" }, { "code": "# Python code to find whether a sublist# satisfies the triangle inequality. # List initializationInput = [[1, 1, 3], [4, 5, 6]] # Sorting sublist of list of listfor elem in Input: elem.sort() # Checking for triangular inequalityfor elem in Input: if elem[0] + elem[1] > elem[2]: print(elem)", "e": 25548, "s": 25241, "text": null }, { "code": null, "e": 25559, "s": 25548, "text": "[4, 5, 6]\n" }, { "code": null, "e": 25580, "s": 25559, "text": "Python list-programs" }, { "code": null, "e": 25587, "s": 25580, "text": "Python" }, { "code": null, "e": 25603, "s": 25587, "text": "Python Programs" }, { "code": null, "e": 25701, "s": 25603, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25719, "s": 25701, "text": "Python Dictionary" }, { "code": null, "e": 25754, "s": 25719, "text": "Read a file line by line in Python" }, { "code": null, "e": 25786, "s": 25754, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25828, "s": 25786, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25854, "s": 25828, "text": "Python String | replace()" }, { "code": null, "e": 25876, "s": 25854, "text": "Defaultdict in Python" }, { "code": null, "e": 25922, "s": 25876, "text": "Python | Split string into list of characters" }, { "code": null, "e": 25961, "s": 25922, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25999, "s": 25961, "text": "Python | Convert a list to dictionary" } ]
MYBATIS - Quick Guide
MyBatis is an open source, lightweight, persistence framework. It is an alternative to JDBC and Hibernate. It automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. The mappings are decoupled from the application logic by packaging the SQL statements in XML configuration files. It abstracts almost all of the JDBC code, and reduces the burden of setting of parameters manually and retrieving the results. It provides a simple API to interact with the database. It also provides support for custom SQL, stored procedures and advanced mappings. It was formerly known as IBATIS, which was started by Clinton Begin in 2002. MyBatis 3 is the latest version. It is a total makeover of IBATIS. A significant difference between MyBatis and other persistence frameworks is that MyBatis emphasizes the use of SQL, while other frameworks such as Hibernate typically uses a custom query language i.e. the Hibernate Query Language (HQL) or Enterprise JavaBeans Query Language (EJB QL). MyBatis comes with the following design philosophies − Simplicity − MyBatis is widely regarded as one of the simplest persistence frameworks available today. Simplicity − MyBatis is widely regarded as one of the simplest persistence frameworks available today. Fast Development − MyBatis does all it can to facilitate hyper-fast development. Fast Development − MyBatis does all it can to facilitate hyper-fast development. Portability − MyBatis can be implemented for nearly any language or platform such as Java, Ruby, and C# for Microsoft .NET. Portability − MyBatis can be implemented for nearly any language or platform such as Java, Ruby, and C# for Microsoft .NET. Independent Interfaces − MyBatis provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources. Independent Interfaces − MyBatis provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources. Open source− MyBatis is free and an open source software. Open source− MyBatis is free and an open source software. MYBATIS offers the following advantages − Supports stored procedures − MyBatis encapsulates SQL in the form of stored procedures so that business logic can be kept out of the database, and the application is more portable and easier to deploy and test. Supports stored procedures − MyBatis encapsulates SQL in the form of stored procedures so that business logic can be kept out of the database, and the application is more portable and easier to deploy and test. Supports inline SQL − No pre-compiler is needed, and you can have the full access to all of the features of SQL. Supports inline SQL − No pre-compiler is needed, and you can have the full access to all of the features of SQL. Supports dynamic SQL − MyBatis provides features for dynamic building SQL queries based on parameters. Supports dynamic SQL − MyBatis provides features for dynamic building SQL queries based on parameters. Supports O/RM − MyBatis supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance. Supports O/RM − MyBatis supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance. MyBatis uses JAVA programming language while developing database oriented application. Before proceeding further, make sure that you understand the basics of procedural and object-oriented programming − control structures, data structures and variables, classes, objects, etc. To understand JAVA in detail you can go through our JAVA Tutorial. You would have to set up a proper environment for MyBatis before starting off with the actual development work. This chapter explains how to set up a working environment for MyBatis. Carry out the following simple steps to install MyBatis on your machine − Download the latest version of MyBatis from Download MYBATIS. Download the latest version of MyBatis from Download MYBATIS. Download the latest version of mysqlconnector from Download MySQL Connector. Download the latest version of mysqlconnector from Download MySQL Connector. Unzip the downloaded files to extract .jar files and keep them in appropriate folders/directory. Unzip the downloaded files to extract .jar files and keep them in appropriate folders/directory. Set CLASSPATH variable for the extracted .jar files appropriately. Set CLASSPATH variable for the extracted .jar files appropriately. Create an EMPLOYEE table in any MySQL database using the following syntax − mysql> DROP TABLE IF EXISTS details.student; CREATE TABLE details.student( ID int(10) NOT NULL AUTO_INCREMENT, NAME varchar(100) NOT NULL, BRANCH varchar(255) NOT NULL, PERCENTAGE int(3) NOT NULL, PHONE int(10) NOT NULL, EMAIL varchar(255) NOT NULL, PRIMARY KEY ( ID ) ); If you want to develop MyBatis Application using eclipse, carry out the following steps − <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>mybatisfinalexamples</groupId> <artifactId>mybatisfinalexamples</artifactId> <version>0.0.1-SNAPSHOT</version> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> </dependencies> </project> In the previous chapter, we have seen how to install MyBatis. This chapter discusses how to configure MyBatis using XML file. Since we are communicating with the database, we have to configure the details of the database. Configuration XML is the file used for the XML-based configuration. By using this file, you can configure various elements. The following programing is a typical structure of MyBatis configuration file. <configuration> <typeAliases> <typeAlias alias = "class_alias_Name" type = "absolute_clas_Name"/> </typeAliases> <environments default = "default_environment _name"> <environment id = "environment_id"> <transactionManager type = "JDBC/MANAGED"/> <dataSource type = "UNPOOLED/POOLED/JNDI"> <property name = "driver" value = "database_driver_class_name"/> <property name = "url" value = "database_url"/> <property name = "username" value = "database_user_name"/> <property name = "password" value = "database_password"/> </dataSource> </environment> </environments> <mappers> <mapper resource = "path of the configuration XML file"/> </mappers> </configuration> Let us discuss the important elements (tags) of the configuration XML file one by one. Within the environments element, we configure the environment of the database that we use in our application. In MyBatis, you can connect to multiple databases by configuring multiple environment elements. To configure the environment, we are provided with two sub tags namely transactionManager and dataSource. MyBatis supports two transaction managers namely JDBC and MANAGED If we use the transaction manager of type JDBC, the application is responsible for the transaction management operations, such as, commit, roll-back, etc... If we use the transaction manager of type JDBC, the application is responsible for the transaction management operations, such as, commit, roll-back, etc... If we use the transaction manager of type MANAGED, the application server is responsible to manage the connection life cycle. It is generally used with the Web Applications. If we use the transaction manager of type MANAGED, the application server is responsible to manage the connection life cycle. It is generally used with the Web Applications. It is used to configure the connection properties of the database, such as driver-name, url, user-name, and password of the database that we want to connect. It is of three types namely − UNPOOLED − For the dataSource type UNPOOLED, MyBatis simply opens and closes a connection for every database operation. It is a bit slower and generally used for the simple applications. UNPOOLED − For the dataSource type UNPOOLED, MyBatis simply opens and closes a connection for every database operation. It is a bit slower and generally used for the simple applications. POOLED − For the dataSource type POOLED, MyBatis will maintain a database connection pool. And, for every database operation, MyBatis uses one of these connections, and returns them to the pool after the completion of the operation. It reduces the initial connection and authentication time that required to create a new connection. POOLED − For the dataSource type POOLED, MyBatis will maintain a database connection pool. And, for every database operation, MyBatis uses one of these connections, and returns them to the pool after the completion of the operation. It reduces the initial connection and authentication time that required to create a new connection. JNDI − For the dataSource type JNDI, MyBatis will get the connection from the JNDI dataSource. JNDI − For the dataSource type JNDI, MyBatis will get the connection from the JNDI dataSource. Here is how you can use an environment tag in practice − <environments default = "development"> <environment id = "development"> <transactionManager type = "JDBC"/> <dataSource type = "POOLED"> <property name = "driver" value = "com.mysql.jdbc.Driver"/> <property name = "url" value = "jdbc:mysql://localhost:3306/details"/> <property name = "username" value = "root"/> <property name = "password" value = "password"/> </dataSource> </environment> </environments> Instead of specifying the absolute class name everywhere, we can use typeAliases, a shorter name for a Java type. Suppose, we have a class Student in Student.java file within the package named tutorials_point.com.mybatis_examples, then the absolute class name will be tutorials_point.com.mybatis_examples.Student. Instead of using this name to address the class every time, you can declare an alias to that class as shown below − <typeAliases> <typeAlias alias = "Student" type = "mybatis.Student"/> </typeAliases> Mapper XML file is the important file, which contains the mapped SQL statements. Mapper’s element is used to configure the location of these mappers xml files in the configuration file of MyBatis (this element contains four attributes namely resources, url, class, and name). For example, the name of the mapper xml file is Student.xml and it resides in the package named as mybatis,, then you can configure the mapper tag as shown below. <mappers> <mapper resource = "mybatis/Student.xml"/> </mappers> The attribute resource points to the classpath of the XML file. The attribute resource points to the classpath of the XML file. The attribute url points to the fully qualified path of the xml file. The attribute url points to the fully qualified path of the xml file. We can use mapper interfaces instead of xml file, the attribute class points to the class-path of the mapper interface. We can use mapper interfaces instead of xml file, the attribute class points to the class-path of the mapper interface. The attribute name points to the package name of the mapper interface. In the example provided in this chapter, we have specified the class path of the mapper XML using the resource attribute. The attribute name points to the package name of the mapper interface. In the example provided in this chapter, we have specified the class path of the mapper XML using the resource attribute. In addition to these, there are other elements that can be used in the configuration file of MyBatis documentation. Refer MyBatis documentation for the complete details. MySQL is one of the most popular open-source database systems available today. Let us create a SqlMapConfig.xml configuration file to connect to mysql database. The example given below are the dataSource properties (driver-name, url, user-name, and password) for MySQL database − We use the transaction manager of type JDBC, means we have to perform the operations, such as commit and roll-back manually, within the application. We use the dataSource of type UNPOOLED, which means new connection is created for each database operation. Therefore, it is recommended to close the connection manually after the completion of database operations. Below given is the XML configuration for the examples used in this tutorial. Copy the content given below in a text file and save it as SqlMapConfig.xml. We are going to use this file in all the examples given in this tutorial. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default = "development"> <environment id = "development"> <transactionManager type = "JDBC"/> <dataSource type = "POOLED"> <property name = "driver" value = "com.mysql.jdbc.Driver"/> <property name = "url" value = "jdbc:mysql://localhost:3306/details"/> <property name = "username" value = "root"/> <property name = "password" value = "password"/> </dataSource> </environment> </environments> <mappers> <mapper resource = "mybatis/Student.xml"/> </mappers> </configuration> In the previous chapter, we have seen how to configure MyBatis using an XML file. This chapter discusses the Mapper XML file and various mapped SQL statements provided by it. Before proceeding to mapped statements, assume that the following table named Student exists in the MYSQL database − +----+-------+--------+------------+-----------+---------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+-------+--------+------------+-----------+---------------+ | 1 | Shyam | it | 80 | 954788457 | [email protected] | +----+-------+--------+------------+-----------+---------------+ Also assume that POJO class also exists named Student with respect to the above table as shown below − public class Student { private int id; private String name; private String branch; private int percentage; private int phone; private String email; //Setters and getters } Mapper XML is an important file in MyBatis, which contains a set of statements to configure various SQL statements such as select, insert, update, and delete. These statements are known as Mapped Statements or Mapped SQL Statements. All the statements have unique id. To execute any of these statements you just need to pass the appropriate id to the methods in Java Application.(This is discussed clearly in later chapters). All the statements have unique id. To execute any of these statements you just need to pass the appropriate id to the methods in Java Application.(This is discussed clearly in later chapters). mapper XML file prevents the burden of writing SQL statements repeatedly in the application. In comparison to JDBC, almost 95% of the code is reduced using Mapper XML file in MyBatis. mapper XML file prevents the burden of writing SQL statements repeatedly in the application. In comparison to JDBC, almost 95% of the code is reduced using Mapper XML file in MyBatis. All these Mapped SQL statements are resided within the element named<mapper>. This element contains an attribute called ‘namespace’. All these Mapped SQL statements are resided within the element named<mapper>. This element contains an attribute called ‘namespace’. <mapper namespace = "Student"> //mapped statements and result maps <mapper> All the Mapped SQL statements are discussed below with examples. In MyBatis, to insert values into the table, we have to configure the insert mapped query. MyBatis provides various attributes for insert mapper, but largely we use id and parameter type. id is unique identifier used to identify the insert statement. On the other hand, parametertype is the class name or the alias of the parameter that will be passed into the statement. Below given is an example of insert mapped query − <insert id = "insert" parameterType = "Student"> INSERT INTO STUDENT1 (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL ) VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email}); </insert> In the given example, we use the parameter of type Student (class). The class student is a POJO class, which represents the Student record with name, branch, percentage, phone, and email as parameters. You can invoke the ‘insert’ mapped query using Java API as shown below − //Assume session is an SqlSession object. session.insert("Student.insert", student); To update values of an existing record using MyBatis, the mapped query update is configured. The attributes of update mapped query are same as the insert mapped query. Following is the example of the update mapped query − <update id = "update" parameterType = "Student"> UPDATE STUDENT SET EMAIL = #{email}, NAME = #{name}, BRANCH = #{branch}, PERCENTAGE = #{percentage}, PHONE = #{phone} WHERE ID = #{id}; </update> To invoke the update query, instantiate Student class, set the values for the variables representing columns which need to be updated, and pass this object as parameter to update() method. You can invoke the update mapped query using Java API as shown below − //Assume session is an SqlSession object. session.update("Student.update",student); To delete the values of an existing record using MyBatis, the mapped query ‘delete’ is configured. The attributes of ‘delete’ mapped query are same as the insert and update mapped queries. Following is the example of the delete mapped query − <delete id = "deleteById" parameterType = "int"> DELETE from STUDENT WHERE ID = #{id}; </delete> You can invoke the delete mapped query using the delete method of SqlSession interface provided by MyBatis Java API as shown below − //Assume session is an SqlSession object. session.delete("Student.deleteById", 18); To retrieve data, ‘select’ mapper statement is used. Following is the example of select mapped query to retrieve all the records in a table − <select id = "getAll" resultMap = "result"> SELECT * FROM STUDENT; </select> You can retrieve the data returned by the select query using the method selectList(). This method returns the data of the selected record in the form of List as shown below − List<Student> list = session.selectList("Student.getAll"); It is the most important and powerful elements in MyBatis. The results of SQL SELECT statements are mapped to Java objects (beans/POJO). Once the result map is defined, we can refer these from several SELECT statements. Following is the example of result Map query; it maps the results of the select queries to the Student class − <resultMap id = "result" type = "Student"> <result property = "id" column = "ID"/> <result property = "name" column = "NAME"/> <result property = "branch" column = "BRANCH"/> <result property = "percentage" column = "PERCENTAGE"/> <result property = "phone" column = "PHONE"/> <result property = "email" column = "EMAIL"/> </resultMap> <select id = "getAll" resultMap = "result"> SELECT * FROM STUDENT; </select> <select id = "getById" parameterType = "int" resultMap = "result"> SELECT * FROM STUDENT WHERE ID = #{id}; </select> Note − It is not mandatory to write the column attribute of the resultMap if both the property and the column name of the table are same. To perform any Create, Read, Update, and Delete (CRUD) operation using MyBATIS, you would need to create a Plain Old Java Objects (POJO) class corresponding to the table. This class describes the objects that will "model" database table rows. The POJO class would have implementation for all the methods required to perform desired operations. Create the STUDENT table in MySQL database as shown below − mysql> CREATE TABLE details.student( -> ID int(10) NOT NULL AUTO_INCREMENT, -> NAME varchar(100) NOT NULL, -> BRANCH varchar(255) NOT NULL, -> PERCENTAGE int(3) NOT NULL, -> PHONE int(11) NOT NULL, -> EMAIL varchar(255) NOT NULL, -> PRIMARY KEY (`ID`) -> ); Query OK, 0 rows affected (0.37 sec) Create a STUDENT class in STUDENT.java file as public class Student { private int id; private String name; private String branch; private int percentage; private int phone; private String email; public Student(String name, String branch, int percentage, int phone, String email) { super(); this.name = name; this.branch = branch; this.percentage = percentage; this.phone = phone; this.email = email; } } You can define methods to set individual fields in the table. The next chapter explains how to get the values of individual fields. To define SQL mapping statement using MyBatis, we would use <insert> tag. Inside this tag definition, we would define an "id." Further, the ‘id’ will be used in the mybatisInsert.java file for executing SQL INSERT query on database. Create student.xml file as shown below − <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace = "Student"> <insert id = "insert" parameterType = "Student"> INSERT INTO STUDENT (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL ) VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email}); <selectKey keyProperty = "id" resultType = "int" order = "AFTER"> select last_insert_id() as id </selectKey> </insert> </mapper> Here, parameteType − could take a value as string, int, float, double, or any class object based on requirement. In this example, we would pass Student object as a parameter, while calling insert method of SqlSession class. If your database table uses an IDENTITY, AUTO_INCREMENT, or SERIAL column, or you have defined a SEQUENCE/GENERATOR, you can use the <selectKey> element in an <insert> statement to use or return that database-generated value. This file would have application level logic to insert records in the Student table. Create and save mybatisInsert.java file as shown below − import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class mybatisInsert { public static void main(String args[]) throws IOException{ Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); //Create a new student object Student student = new Student("Mohammad","It", 80, 984803322, "[email protected]" ); //Insert student data session.insert("Student.insert", student); System.out.println("record inserted successfully"); session.commit(); session.close(); } } Here are the steps to compile and run the mybatisInsert.java file. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution. Create Student.xml as shown above. Create Student.xml as shown above. Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial. Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial. Create Student.java as shown above and compile it. Create Student.java as shown above and compile it. Create mybatisInsert.java as shown above and compile it. Create mybatisInsert.java as shown above and compile it. Execute mybatisInsert binary to run the program. Execute mybatisInsert binary to run the program. You would get the following result, and a record would be created in the STUDENT table. $java mybatisInsert Record Inserted Successfully If you check the STUDENT table, it should display the following result − mysql> select * from student; +----+----------+--------+------------+-----------+--------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+-----------+--------------------+ | 1 | Mohammad | It | 80 | 984803322 | [email protected] | +----+----------+--------+------------+-----------+--------------------+ 1 row in set (0.00 sec) We discussed in the last chapter, how to insert values into the STUDENT table using MyBatis by performing CREATE operation. This chapter explains how to read the data in a table using MyBatis. We have the following STUDENT table in MySQL − CREATE TABLE details.student( ID int(10) NOT NULL AUTO_INCREMENT, NAME varchar(100) NOT NULL, BRANCH varchar(255) NOT NULL, PERCENTAGE int(3) NOT NULL, PHONE int(11) NOT NULL, EMAIL varchar(255) NOT NULL, PRIMARY KEY (`ID`) ); Assume, this table has two record as − +----+----------+--------+------------+-----------+--------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+-----------+--------------------+ | 1 | Mohammad | It | 80 | 984803322 | [email protected] | | 2 | shyam | It | 75 | 984800000 | [email protected] | +----+----------+--------+------------+-----------+--------------------+ To perform read operation, we would modify the Student class in Student.java as − public class Student { private int id; private String name; private String branch; private int percentage; private int phone; private String email; public Student(int id, String name, String branch, int percentage, int phone, String email) { super(); this.id = id; this.name = name; this.branch = branch; this.percentage = percentage; this.phone = phone; this.email = email; } public Student() {} public int getId() { return id; } public String getName() { return name; } public int getPhone() { return phone; } public String getEmail() { return email; } public String getBranch() { return branch; } public int getPercentage() { return percentage; } } To define SQL mapping statement using MyBatis, we would add <select> tag in Student.xml file and inside this tag definition, we would define an "id" which will be used in mybatisRead.java file for executing SQL SELECT query on database. While reading the records, we can get all the records at once or we can get a particular record using the where clause. In the XML given below, you can observe both the queries. To retrieve a particular record, we need a unique key to represent that record. Therefore, we have also defined the resultmap "id" (unique key) of type Student to map the result of the select query with the variable of Student class. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace = "Student"> <resultMap id = "result" type = "Student"> <result property = "id" column = "ID"/> </resultMap> <select id = "getAll" resultMap = "result"> SELECT * FROM STUDENT; </select> <select id = "getById" parameterType = "int" resultMap = "result"> SELECT * FROM STUDENT WHERE ID = #{id}; </select> </mapper> This file has application level logic to read all the records from the Student table. Create and save mybatisRead_ALL.java file as shown below − import java.io.IOException; import java.io.Reader; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class mybatisRead_ALL { public static void main(String args[]) throws IOException{ Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); //select contact all contacts List<Student> student = session.selectList("Student.getAll"); for(Student st : student ){ System.out.println(st.getId()); System.out.println(st.getName()); System.out.println(st.getBranch()); System.out.println(st.getPercentage()); System.out.println(st.getEmail()); System.out.println(st.getPhone()); } System.out.println("Records Read Successfully "); session.commit(); session.close(); } } Here are the steps to compile and run the mybatisRead_ALL file. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution. Create Student.xml as shown above. Create Student.java as shown above and compile it. Create mybatisRead_ALL.java as shown above and compile it. Execute mybatisRead_ALL binary to run the program. You would get all the record of the student table as − ++++++++++++++ details of the student who's id is :1 +++++++++++++++++++ 1 Mohammad It 80 [email protected] 984803322 ++++++++++++++ details of the student who's id is :2 +++++++++++++++++++ 2 shyam It 75 [email protected] 984800000 Records Read Successfully Copy and save the following program with the name mybatisRead_byID − import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class mybatisRead_byID { public static void main(String args[]) throws IOException{ int i = 1; Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); //select a particular student by id Student student = (Student) session.selectOne("Student.getById", 2); //Print the student details System.out.println(student.getId()); System.out.println(student.getName()); System.out.println(student.getBranch()); System.out.println(student.getPercentage()); System.out.println(student.getEmail()); System.out.println(student.getPhone()); session.commit(); session.close(); } } Here are the steps to compile and run the mybatisRead_byID file. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution. Create Student.xml as shown above. Create Student.xml as shown above. Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial. Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial. Create Student.java as shown above and compile it. Create Student.java as shown above and compile it. Create mybatisRead_byID.java as shown above and compile it. Create mybatisRead_byID.java as shown above and compile it. Execute mybatisRead_byID binary to run the program. Execute mybatisRead_byID binary to run the program. You would get the following result, and a record would be read from the Student table as − 2 shyam It 75 [email protected] 984800000 We discussed, in the last chapter, how to perform READ operation on a table using MyBatis. This chapter explains how you can update records in a table using it. We have the following STUDENT table in MySQL − CREATE TABLE details.student( ID int(10) NOT NULL AUTO_INCREMENT, NAME varchar(100) NOT NULL, BRANCH varchar(255) NOT NULL, PERCENTAGE int(3) NOT NULL, PHONE int(11) NOT NULL, EMAIL varchar(255) NOT NULL, PRIMARY KEY (`ID`) ); Assume this table has two record as follows − mysql> select * from STUDENT; +----+----------+--------+------------+-----------+--------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+-----------+--------------------+ | 1 | Mohammad | It | 80 | 984803322 | [email protected] | | 2 | shyam | It | 75 | 984800000 | [email protected] | +----+----------+--------+------------+-----------+--------------------+ To perform update operation, you would need to modify Student.java file as − public class Student { private int id; private String name; private String branch; private int percentage; private int phone; private String email; public Student(int id, String name, String branch, int percentage, int phone, String email) { super(); this.id = id; this.name = name; this.setBranch(branch); this.setPercentage(percentage); this.phone = phone; this.email = email; } public Student() {} 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 getPhone() { return phone; } public void setPhone(int phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public int getPercentage() { return percentage; } public void setPercentage(int percentage) { this.percentage = percentage; } public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("Id = ").append(id).append(" - "); sb.append("Name = ").append(name).append(" - "); sb.append("Branch = ").append(branch).append(" - "); sb.append("Percentage = ").append(percentage).append(" - "); sb.append("Phone = ").append(phone).append(" - "); sb.append("Email = ").append(email); return sb.toString(); } } To define SQL mapping statement using MyBatis, we would add <update> tag in Student.xml and inside this tag definition, we would define an "id" which will be used in mybatisUpdate.java file for executing SQL UPDATE query on database. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace = "Student"> <resultMap id = "result" type = "Student"> <result property = "id" column = "ID"/> <result property = "name" column = "NAME"/> <result property = "branch" column = "BRANCH"/> <result property = "percentage" column = "PERCENTAGE"/> <result property = "phone" column = "PHONE"/> <result property = "email" column = "EMAIL"/> </resultMap> <select id = "getById" parameterType = "int" resultMap = "result"> SELECT * FROM STUDENT WHERE ID = #{id}; </select> <update id = "update" parameterType = "Student"> UPDATE STUDENT SET NAME = #{name}, BRANCH = #{branch}, PERCENTAGE = #{percentage}, PHONE = #{phone}, EMAIL = #{email} WHERE ID = #{id}; </update> </mapper> This file has application level logic to update records into the Student table − import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class mybatisUpdate { public static void main(String args[]) throws IOException{ Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); //select a particular student using id Student student = (Student) session.selectOne("Student.getById", 1); System.out.println("Current details of the student are" ); System.out.println(student.toString()); //Set new values to the mail and phone number of the student student.setEmail("[email protected]"); student.setPhone(90000000); //Update the student record session.update("Student.update",student); System.out.println("Record updated successfully"); session.commit(); session.close(); //verifying the record Student std = (Student) session.selectOne("Student.getById", 1); System.out.println("Details of the student after update operation" ); System.out.println(std.toString()); session.commit(); session.close(); } } Here are the steps to compile and run mybatisUpdate.java. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution. Create Student.xml as shown above. Create Student.xml as shown above. Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial. Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial. Create Student.java as shown above and compile it. Create Student.java as shown above and compile it. Create mybatisUpdate.java as shown above and compile it. Create mybatisUpdate.java as shown above and compile it. Execute mybatisUpdate binary to run the program. Execute mybatisUpdate binary to run the program. You would get following result. You can see the details of a particular record initially, and that record would be updated in STUDENT table and later, you can also see the updated record. Current details of the student are Id = 1 - Name = Mohammad - Branch = It - Percentage = 80 - Phone = 984802233 - Email = [email protected] Record updated successfully Details of the student after update operation Id = 1 - Name = Mohammad - Branch = It - Percentage = 80 - Phone = 90000000 - Email = [email protected] If you check the STUDENT table, it should display the following result − mysql> select * from student; +----+----------+--------+------------+-----------+----------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+-----------+----------------------+ | 1 | Mohammad | It | 80 | 90000000 | [email protected] | | 2 | shyam | It | 75 | 984800000 | [email protected] | +----+----------+--------+------------+-----------+----------------------+ 2 rows in set (0.00 sec) This chapter describes how to delete records from a table using MyBatis. We have the following STUDENT table in MySQL − CREATE TABLE details.student( ID int(10) NOT NULL AUTO_INCREMENT, NAME varchar(100) NOT NULL, BRANCH varchar(255) NOT NULL, PERCENTAGE int(3) NOT NULL, PHONE int(11) NOT NULL, EMAIL varchar(255) NOT NULL, PRIMARY KEY (`ID`) ); Assume, this table has two records as − mysql> select * from STUDENT; +----+----------+--------+------------+-----------+----------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+-----------+----------------------+ | 1 | Mohammad | It | 80 | 900000000 | [email protected] | | 2 | shyam | It | 75 | 984800000 | [email protected] | +----+----------+--------+------------+-----------+----------------------+ 2 rows in set (0.00 sec) To perform delete operation, you do not need to modify Student.java file. Let us keep it as it was in the last chapter. public class Student { private int id; private String name; private String branch; private int percentage; private int phone; private String email; public Student(int id, String name, String branch, int percentage, int phone, String email) { super(); this.id = id; this.name = name; this.setBranch(branch); this.setPercentage(percentage); this.phone = phone; this.email = email; } public Student() {} 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 getPhone() { return phone; } public void setPhone(int phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public int getPercentage() { return percentage; } public void setPercentage(int percentage) { this.percentage = percentage; } public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("Id = ").append(id).append(" - "); sb.append("Name = ").append(name).append(" - "); sb.append("Branch = ").append(branch).append(" - "); sb.append("Percentage = ").append(percentage).append(" - "); sb.append("Phone = ").append(phone).append(" - "); sb.append("Email = ").append(email); return sb.toString(); } } To define SQL mapping statement using MyBatis, we would use <delete> tag in Student.xml and inside this tag definition, we would define an "id" which will be used in mybatisDelete.java file for executing SQL DELETE query on database. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace = "Student"> <resultMap id = "result" type = "Student"> <result property = "id" column = "ID"/> </resultMap> <delete id = "deleteById" parameterType = "int"> DELETE from STUDENT WHERE ID = #{id}; </delete> </mapper> This file has application level logic to delete records from the Student table − import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class mybatisDelete { public static void main(String args[]) throws IOException{ Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); //Delete operation session.delete("Student.deleteById", 2); session.commit(); session.close(); System.out.println("Record deleted successfully"); } } Here are the steps to compile and run mybatisDelete.java. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution. Create Student.xml as shown above. Create Student.xml as shown above. Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial. Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial. Create Student.java as shown above and compile it. Create Student.java as shown above and compile it. Create mybatisDelete.java as shown above and compile it. Create mybatisDelete.java as shown above and compile it. Execute mybatisDelete binary to run the program. Execute mybatisDelete binary to run the program. You would get the following result, and a record with ID = 1 would be deleted from the STUDENT. Records Read Successfully If you check the STUDENT table, it should display the following result − mysql> select * from student; +----+----------+--------+------------+----------+----------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+----------+----------------------+ | 1 | Mohammad | It | 80 | 90000000 | [email protected] | +----+----------+--------+------------+----------+----------------------+ 1 row in set (0.00 sec) In the previous chapters, we have seen how to perform curd operations using MyBatis. There we used a Mapper XML file to store mapped SQL statements and a configuration XML file to configure MyBatis. To map SQL statements, MyBatis also provides annotations. So, this chapter discusses how to use MyBatis annotations. While working with annotations, instead of configuration XML file, we can use a java mapper interface to map and execute SQL queries. Assume, we have the following employee table in MySQL − CREATE TABLE details.student( ID int(10) NOT NULL AUTO_INCREMENT, NAME varchar(100) NOT NULL, BRANCH varchar(255) NOT NULL, PERCENTAGE int(3) NOT NULL, PHONE int(11) NOT NULL, EMAIL varchar(255) NOT NULL, PRIMARY KEY (`ID`) ); Query OK, 0 rows affected (0.37 sec) Assume this table has two records as − mysql> select * from STUDENT; +----+----------+--------+------------+-----------+--------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+-----------+--------------------+ | 1 | Mohammad | It | 80 | 984803322 | [email protected] | | 2 | Shyam | It | 75 | 984800000 | [email protected] | +----+----------+--------+------------+-----------+--------------------+ The POJO class would have implementation for all the methods required to perform desired operations. Create a Student class in Student.java file as − public class Student { private int id; private String name; private String branch; private int percentage; private int phone; private String email; public Student(int id, String name, String branch, int percentage, int phone, String email) { super(); this.id = id; this.name = name; this.branch = branch; this.percentage = percentage; this.phone = phone; this.email = email; } public Student() {} 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 getPhone() { return phone; } public void setPhone(int phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public int getPercentage() { return percentage; } public void setPercentage(int percentage) { this.percentage = percentage; } } This is the file, which contains the mapper interface where we declare the mapped statements using annotations instead of XML tags. For almost all of the XML-based mapper elements, MyBatis provides annotations. The following file named Student_mapper.java, contains a mapper interface. Within this file, you can see the annotations to perform CURD operations on the STUDENT table. import java.util.List; import org.apache.ibatis.annotations.*; public interface Student_mapper { final String getAll = "SELECT * FROM STUDENT"; final String getById = "SELECT * FROM STUDENT WHERE ID = #{id}"; final String deleteById = "DELETE from STUDENT WHERE ID = #{id}"; final String insert = "INSERT INTO STUDENT (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL ) VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email})"; final String update = "UPDATE STUDENT SET EMAIL = #{email}, NAME = #{name}, BRANCH = #{branch}, PERCENTAGE = #{percentage}, PHONE = #{phone} WHERE ID = #{id}"; @Select(getAll) @Results(value = { @Result(property = "id", column = "ID"), @Result(property = "name", column = "NAME"), @Result(property = "branch", column = "BRANCH"), @Result(property = "percentage", column = "PERCENTAGE"), @Result(property = "phone", column = "PHONE"), @Result(property = "email", column = "EMAIL") }) List getAll(); @Select(getById) @Results(value = { @Result(property = "id", column = "ID"), @Result(property = "name", column = "NAME"), @Result(property = "branch", column = "BRANCH"), @Result(property = "percentage", column = "PERCENTAGE"), @Result(property = "phone", column = "PHONE"), @Result(property = "email", column = "EMAIL") }) Student getById(int id); @Update(update) void update(Student student); @Delete(deleteById) void delete(int id); @Insert(insert) @Options(useGeneratedKeys = true, keyProperty = "id") void insert(Student student); } This file would have application level logic to insert records in the Student table. Create and save mybatisInsert.java file as shown below − import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class Annotations_Example { public static void main(String args[]) throws IOException{ Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); session.getConfiguration().addMapper(Student_mapper.class); Student_mapper mapper = session.getMapper(Student_mapper.class); //Create a new student object Student student = new Student(); //Set the values student.setName("zara"); student.setBranch("EEE"); student.setEmail("[email protected]"); student.setPercentage(90)); student.setPhone(123412341); //Insert student data mapper.insert(student); System.out.println("record inserted successfully"); session.commit(); session.close(); } } Here are the steps to compile and run the Annotations_Example.java file. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution. Create Student_mapper.java file as shown above and compile it. Create Student_mapper.java file as shown above and compile it. Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial. Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial. Create Student.java as shown above and compile it. Create Student.java as shown above and compile it. Create Annotations_Example.java as shown above and compile it. Create Annotations_Example.java as shown above and compile it. Execute Annotations_Example binary to run the program. Execute Annotations_Example binary to run the program. You would get the following result, and a record would be created in the STUDENT table. $java Annotations_Example Record Inserted Successfully If you check the STUDENT table, it should display the following result − mysql> select * from student; +----+----------+--------+------------+-----------+----------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+-----------+----------------------+ | 1 | Mohammad | It | 80 | 900000000 | [email protected] | | 2 | Shyam | It | 75 | 984800000 | [email protected] | | 3 | Zara | EEE | 90 | 123412341 | [email protected] | +----+----------+--------+------------+-----------+----------------------+ 3 rows in set (0.08 sec) In the same way, we can perform update, delete, and read operations using annotations by replacing the content of Annotations_Example.java with the respective snippets mentioned below − public static void main(String args[]) throws IOException{ Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); session.getConfiguration().addMapper(Student_mapper.class); Student_mapper mapper = session.getMapper(Student_mapper.class); //select a particular student using id Student student = mapper.getById(2); System.out.println("Current details of the student are "+student.toString()); //Set new values to the mail and phone number of the student student.setEmail("[email protected]"); student.setPhone(984802233); //Update the student record mapper.update(student); System.out.println("Record updated successfully"); session.commit(); session.close(); } public static void main(String args[]) throws IOException{ Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); session.getConfiguration().addMapper(Student_mapper.class); Student_mapper mapper = session.getMapper(Student_mapper.class); //Get the student details Student student = mapper.getById(2); System.out.println(student.getBranch()); System.out.println(student.getEmail()); System.out.println(student.getId()); System.out.println(student.getName()); System.out.println(student.getPercentage()); System.out.println(student.getPhone()); session.commit(); session.close(); } public static void main(String args[]) throws IOException{ Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); session.getConfiguration().addMapper(Student_mapper.class); Student_mapper mapper = session.getMapper(Student_mapper.class); mapper.delete(2); System.out.println("record deleted successfully"); session.commit(); session.close(); } You can call a stored procedure using MyBatis. First of all, let us understand how to create a stored procedure in MySQL. We have the following EMPLOYEE table in MySQL − CREATE TABLE details.student( ID int(10) NOT NULL AUTO_INCREMENT, NAME varchar(100) NOT NULL, BRANCH varchar(255) NOT NULL, PERCENTAGE int(3) NOT NULL, PHONE int(11) NOT NULL, EMAIL varchar(255) NOT NULL, PRIMARY KEY (`ID`) ); Let us create the following stored procedure in MySQL database − DELIMITER // DROP PROCEDURE IF EXISTS details.read_recordById // CREATE PROCEDURE details.read_recordById (IN emp_id INT) BEGIN SELECT * FROM STUDENT WHERE ID = emp_id; END// DELIMITER ; Assume the table named STUDENT has two records as − mysql> select * from STUDENT; +----+----------+--------+------------+-----------+----------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+-----------+----------------------+ | 1 | Mohammad | It | 80 | 900000000 | [email protected] | | 2 | Shyam | It | 75 | 984800000 | [email protected] | +----+----------+--------+------------+-----------+----------------------+ 2 rows in set (0.00 sec) To use stored procedure, you do not need to modify the Student.java file. Let us keep it as it was in the last chapter. public class Student { private int id; private String name; private String branch; private int percentage; private int phone; private String email; public Student(int id, String name, String branch, int percentage, int phone, String email) { super(); this.id = id; this.name = name; this.setBranch(branch); this.setPercentage(percentage); this.phone = phone; this.email = email; } public Student() {} 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 getPhone() { return phone; } public void setPhone(int phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public int getPercentage() { return percentage; } public void setPercentage(int percentage) { this.percentage = percentage; } public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("Id = ").append(id).append(" - "); sb.append("Name = ").append(name).append(" - "); sb.append("Branch = ").append(branch).append(" - "); sb.append("Percentage = ").append(percentage).append(" - "); sb.append("Phone = ").append(phone).append(" - "); sb.append("Email = ").append(email); return sb.toString(); } } Unlike IBATIS, there is no <procedure> tag in MyBatis. To map the results of the procedures, we have created a resultmap named Student and to call the stored procedure named read_recordById. We have defined a select tag with id callById, and we use the same id in the application to call the procedure. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace = "Student"> <resultMap id = "result" type = "Student"> <result property = "id" column = "ID"/> <result property = "name" column = "NAME"/> <result property = "branch" column = "BRANCH"/> <result property = "percentage" column = "PERCENTAGE"/> <result property = "phone" column = "PHONE"/> <result property = "email" column = "EMAIL"/> </resultMap> <select id = "callById" resultMap = "result" parameterType = "Student" statementType = "CALLABLE"> {call read_record_byid(#{id, jdbcType = INTEGER, mode = IN})} </select> </mapper> This file has application level logic to read the names of the employees from the Employee table using ResultMap − import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class getRecords { public static void main(String args[]) throws IOException{ Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); //select a particular student by id Student student = (Student) session.selectOne("Student.callById", 3); //Print the student details System.out.println("Details of the student are:: "); System.out.println("Id :"+student.getId()); System.out.println("Name :"+student.getName()); System.out.println("Branch :"+student.getBranch()); System.out.println("Percentage :"+student.getPercentage()); System.out.println("Email :"+student.getEmail()); System.out.println("Phone :"+student.getPhone()); session.commit(); session.close(); } } Here are the steps to compile and run the getRecords program. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution. Create Student.xml as shown above. Create Student.java as shown above and compile it. Create getRecords.java as shown above and compile it. Execute getRecords binary to run the program. You will get the following result − Details of the student are:: Id :2 Name :Shyam Branch :It Percentage :75 Email :[email protected] Phone :984800000 Dynamic SQL is a very powerful feature of MyBatis. It enables programmers to build queries based on the scenario dynamically. For example, if you want to search the Student data base, based on the name of the student in MyBatis, you have to write the query using the dynamic SQL. MyBatis uses a powerful Dynamic SQL language that can be used within any mapped SQL statement. Following are the OGNL based Dynamic SQL expressions provided by MyBatis. if choose (when, otherwise) trim (where, set) foreach The most common thing to do in dynamic SQL is conditionally include a part of a where clause. For example − <select id = "getRecByName" parameterType = "Student" resultType = "Student"> SELECT * FROM STUDENT <if test = "name != null"> WHERE name LIKE #{name} </if> </select> This statement provides an optional text search type of functionality. If you pass in no name, then all active records will be returned. But if you do pass in a name, it will look for a name with the given like condition. You can include multiple if conditions as − <select id = "getRecByName_Id" parameterType = "Student" resultType = "Student"> SELECT * FROM STUDENT <if test = "name != null"> WHERE name LIKE #{name} </if> <if test = "id != null"> AND id LIKE #{id} </if> </select> MyBatis offers a choose element, which is similar to Java's switch statement. It helps to choose only one case among many options. The following example will search only by name if it is provided, and if the name is not given, then only by id − <select id = "getRecByName_Id_phone" parameterType = "Student" resultType = "Student"> SELECT * FROM Student WHERE id != 0 <choose> <when test = "name != null"> AND name LIKE #{name} </when> <when test = "phone != null"> AND phone LIKE #{phone} </when> </choose> </select> Take a look at our previous examples to see what happens if none of the conditions are met. You would end up with an SQL that looks like this − SELECT * FROM Student WHERE This would fail, but MyBatis has a simple solution with one simple change, everything works fine − <select id = "getName_Id_phone" parameterType = "Student" resultType = "Student"> SELECT * FROM STUDENT <where> <if test = "id != null"> id = #{id} </if> <if test = "name != null"> AND name LIKE #{name} </if> </where> </select> The where element inserts a WHERE only when the containing tags return any content. Furthermore, if that content begins with AND or OR, it knows to strip it off. The foreach element allows you to specify a collection and declare item and index variables that can be used inside the body of the element. It also allows you to specify opening and closing strings, and add a separator to place in between iterations. You can build an IN condition as follows − <select id = "selectPostIn" resultType = "domain.blog.Post"> SELECT * FROM POST P WHERE ID in <foreach item = "item" index = "index" collection = "list" open = "(" separator = "," close = ")"> #{item} </foreach> </select> This is an example if using dynamic SQL. Consider, we have the following Student table in MySQL − CREATE TABLE details.student( ID int(10) NOT NULL AUTO_INCREMENT, NAME varchar(100) NOT NULL, BRANCH varchar(255) NOT NULL, PERCENTAGE int(3) NOT NULL, PHONE int(11) NOT NULL, EMAIL varchar(255) NOT NULL, PRIMARY KEY (`ID`) ); Query OK, 0 rows affected (0.37 sec) Let’s assume this table has two records as − mysql> select * from student; +----+----------+--------+------------+-----------+----------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+-----------+----------------------+ | 1 | Mohammad | It | 80 | 900000000 | [email protected] | | 2 | Shyam | It | 75 | 984800000 | [email protected] | +----+----------+--------+------------+-----------+----------------------+ 2 rows in set (0.00 sec) To perform read operation, let us have a Student class in Student.java as − public class Student { private int id; private String name; private String branch; private int percentage; private int phone; private String email; public Student(int id, String name, String branch, int percentage, int phone, String email) { super(); this.id = id; this.name = name; this.branch = branch; this.percentage = percentage; this.phone = phone; this.email = email; } public Student() {} 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 getPhone() { return phone; } public void setPhone(int phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public int getPercentage() { return percentage; } public void setPercentage(int percentage) { this.percentage = percentage; } } This file contains the result map named Student, to map the results of the SELECT Query. We will define an "id" which will be used in mybatisRead.java for executing Dynamic SQL SELECT query on database. <?xml version = "1.0" encoding = "UTF-8"?> &l;t!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace = "Student"> <resultMap id = "result" type = "Student"> <result property = "id" column = "ID"/> <result property = "name" column = "NAME"/> <result property = "branch" column = "BRANCH"/> <result property = "percentage" column = "PERCENTAGE"/> <result property = "phone" column = "PHONE"/> <result property = "email" column = "EMAIL"/> </resultMap> <select id = "getRecByName" parameterType = "Student" resultType = "Student"> SELECT * FROM STUDENT <if test = "name != null"> WHERE name LIKE #{name} </if> </select> </mapper> This file has application level logic to read conditional records from the Student table − import java.io.IOException; import java.io.Reader; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class GetRecordByName { public static void main(String args[]) throws IOException{ String req_name = "Mohammad"; Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); Student stud = new Student(); stud.setName(req_name); //select contact all contacts //List<Student> student = session.selectList("getRecByName",stud); stud.setId(1); List<Student> student = session.selectList("getRecByName_Id",stud); for(Student st : student ){ System.out.println("++++++++++++++details of the student named Mohammad are "+"+++++++++++++++++++" ); System.out.println("Id : "+st.getId()); System.out.println("Name : "+st.getName()); System.out.println("Branch : "+st.getBranch()); System.out.println("Percentage : "+st.getPercentage()); System.out.println("Email : "+st.getEmail()); System.out.println("Phone : "+st.getPhone()); } System.out.println("Records Read Successfully "); session.commit(); session.close(); } } Here are the steps to compile and run the above mentioned software. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution. Create Student.xml as shown above. Create Student.java as shown above and compile it. Create GetRecordByName.java as shown above and compile it. Execute GetRecordByName binary to run the program. You would get the following result, and a record would be read from the Student table. ++++++++++++++details of the student named Mohammad are +++++++++++++++++++ Id : 1 Name : Mohammad Branch : It Percentage : 80 Email : [email protected] Phone : 90000000 Records Read Successfully There are major differences between MyBatis and Hibernate. Both the technologies work well, given their specific domain. MyBatis is suggested in case − You want to create your own SQL's and you are willing to maintain them. Your environment is driven by relational data model. You have to work on existing and complex schemas. Use Hibernate, if the environment is driven by object model and needs to generate SQL automatically. Both Hibernate and MyBatis are open source Object Relational Mapping (ORM) tools available in the industry. Use of each of these tools depends on the context you are using them. The following table highlights the differences between MyBatis and Hibernate − Hibernate and MyBatis both are compatible with the SPRING framework, so it should not be a problem to choose one of them. Print Add Notes Bookmark this page
[ { "code": null, "e": 2185, "s": 1871, "text": "MyBatis is an open source, lightweight, persistence framework. It is an alternative to JDBC and Hibernate. It automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. The mappings are decoupled from the application logic by packaging the SQL statements in XML configuration files." }, { "code": null, "e": 2450, "s": 2185, "text": "It abstracts almost all of the JDBC code, and reduces the burden of setting of parameters manually and retrieving the results. It provides a simple API to interact with the database. It also provides support for custom SQL, stored procedures and advanced mappings." }, { "code": null, "e": 2594, "s": 2450, "text": "It was formerly known as IBATIS, which was started by Clinton Begin in 2002. MyBatis 3 is the latest version. It is a total makeover of IBATIS." }, { "code": null, "e": 2880, "s": 2594, "text": "A significant difference between MyBatis and other persistence frameworks is that MyBatis emphasizes the use of SQL, while other frameworks such as Hibernate typically uses a custom query language i.e. the Hibernate Query Language (HQL) or Enterprise JavaBeans Query Language (EJB QL)." }, { "code": null, "e": 2935, "s": 2880, "text": "MyBatis comes with the following design philosophies −" }, { "code": null, "e": 3038, "s": 2935, "text": "Simplicity − MyBatis is widely regarded as one of the simplest persistence frameworks available today." }, { "code": null, "e": 3141, "s": 3038, "text": "Simplicity − MyBatis is widely regarded as one of the simplest persistence frameworks available today." }, { "code": null, "e": 3223, "s": 3141, "text": "Fast Development − MyBatis does all it can to facilitate hyper-fast development." }, { "code": null, "e": 3305, "s": 3223, "text": "Fast Development − MyBatis does all it can to facilitate hyper-fast development." }, { "code": null, "e": 3429, "s": 3305, "text": "Portability − MyBatis can be implemented for nearly any language or platform such as Java, Ruby, and C# for Microsoft .NET." }, { "code": null, "e": 3553, "s": 3429, "text": "Portability − MyBatis can be implemented for nearly any language or platform such as Java, Ruby, and C# for Microsoft .NET." }, { "code": null, "e": 3731, "s": 3553, "text": "Independent Interfaces − MyBatis provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources." }, { "code": null, "e": 3909, "s": 3731, "text": "Independent Interfaces − MyBatis provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources." }, { "code": null, "e": 3967, "s": 3909, "text": "Open source− MyBatis is free and an open source software." }, { "code": null, "e": 4025, "s": 3967, "text": "Open source− MyBatis is free and an open source software." }, { "code": null, "e": 4067, "s": 4025, "text": "MYBATIS offers the following advantages −" }, { "code": null, "e": 4279, "s": 4067, "text": "Supports stored procedures − MyBatis encapsulates SQL in the form of stored procedures so that business logic can be kept out of the database, and the application is more portable and easier to deploy and test." }, { "code": null, "e": 4491, "s": 4279, "text": "Supports stored procedures − MyBatis encapsulates SQL in the form of stored procedures so that business logic can be kept out of the database, and the application is more portable and easier to deploy and test." }, { "code": null, "e": 4604, "s": 4491, "text": "Supports inline SQL − No pre-compiler is needed, and you can have the full access to all of the features of SQL." }, { "code": null, "e": 4717, "s": 4604, "text": "Supports inline SQL − No pre-compiler is needed, and you can have the full access to all of the features of SQL." }, { "code": null, "e": 4820, "s": 4717, "text": "Supports dynamic SQL − MyBatis provides features for dynamic building SQL queries based on parameters." }, { "code": null, "e": 4923, "s": 4820, "text": "Supports dynamic SQL − MyBatis provides features for dynamic building SQL queries based on parameters." }, { "code": null, "e": 5087, "s": 4923, "text": "Supports O/RM − MyBatis supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance." }, { "code": null, "e": 5251, "s": 5087, "text": "Supports O/RM − MyBatis supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance." }, { "code": null, "e": 5528, "s": 5251, "text": "MyBatis uses JAVA programming language while developing database oriented\napplication. Before proceeding further, make sure that you understand the basics of procedural and object-oriented programming − control structures, data structures and variables, classes, objects, etc." }, { "code": null, "e": 5595, "s": 5528, "text": "To understand JAVA in detail you can go through our JAVA Tutorial." }, { "code": null, "e": 5778, "s": 5595, "text": "You would have to set up a proper environment for MyBatis before starting off with the actual development work. This chapter explains how to set up a working environment for MyBatis." }, { "code": null, "e": 5852, "s": 5778, "text": "Carry out the following simple steps to install MyBatis on your machine −" }, { "code": null, "e": 5914, "s": 5852, "text": "Download the latest version of MyBatis from Download MYBATIS." }, { "code": null, "e": 5976, "s": 5914, "text": "Download the latest version of MyBatis from Download MYBATIS." }, { "code": null, "e": 6053, "s": 5976, "text": "Download the latest version of mysqlconnector from Download MySQL Connector." }, { "code": null, "e": 6130, "s": 6053, "text": "Download the latest version of mysqlconnector from Download MySQL Connector." }, { "code": null, "e": 6227, "s": 6130, "text": "Unzip the downloaded files to extract .jar files and keep them in appropriate folders/directory." }, { "code": null, "e": 6324, "s": 6227, "text": "Unzip the downloaded files to extract .jar files and keep them in appropriate folders/directory." }, { "code": null, "e": 6391, "s": 6324, "text": "Set CLASSPATH variable for the extracted .jar files appropriately." }, { "code": null, "e": 6458, "s": 6391, "text": "Set CLASSPATH variable for the extracted .jar files appropriately." }, { "code": null, "e": 6534, "s": 6458, "text": "Create an EMPLOYEE table in any MySQL database using the following syntax −" }, { "code": null, "e": 6833, "s": 6534, "text": "mysql> DROP TABLE IF EXISTS details.student;\nCREATE TABLE details.student(\n ID int(10) NOT NULL AUTO_INCREMENT, \n NAME varchar(100) NOT NULL,\n BRANCH varchar(255) NOT NULL,\n PERCENTAGE int(3) NOT NULL, \n PHONE int(10) NOT NULL,\n EMAIL varchar(255) NOT NULL,\n PRIMARY KEY ( ID )\n);\n" }, { "code": null, "e": 6923, "s": 6833, "text": "If you want to develop MyBatis Application using eclipse, carry out the following steps −" }, { "code": null, "e": 8057, "s": 6923, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\n <modelVersion>4.0.0</modelVersion>\n <groupId>mybatisfinalexamples</groupId>\n <artifactId>mybatisfinalexamples</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n \n <build>\n <sourceDirectory>src</sourceDirectory>\n\t\t\n <plugins>\n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.1</version>\n <configuration>\n <source>1.8</source>\n <target>1.8</target>\n </configuration>\n </plugin>\n </plugins>\n\t\t\n </build>\n \n <dependencies>\n\t\n <dependency>\n <groupId>org.mybatis</groupId>\n <artifactId>mybatis</artifactId>\n <version>3.3.0</version>\n </dependency>\t\n\t \n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <version>5.1.6</version>\n </dependency>\n\t\t\n </dependencies> \n\t\n</project>" }, { "code": null, "e": 8183, "s": 8057, "text": "In the previous chapter, we have seen how to install MyBatis. This chapter discusses how to configure MyBatis using XML file." }, { "code": null, "e": 8403, "s": 8183, "text": "Since we are communicating with the database, we have to configure the details of the database. Configuration XML is the file used for the XML-based configuration. By using this file, you can configure various elements." }, { "code": null, "e": 8482, "s": 8403, "text": "The following programing is a typical structure of MyBatis configuration file." }, { "code": null, "e": 9306, "s": 8482, "text": "<configuration>\n\n <typeAliases>\n <typeAlias alias = \"class_alias_Name\" type = \"absolute_clas_Name\"/>\n </typeAliases>\n\t\t\n <environments default = \"default_environment _name\">\n <environment id = \"environment_id\">\n <transactionManager type = \"JDBC/MANAGED\"/> \n\t\t\t\n <dataSource type = \"UNPOOLED/POOLED/JNDI\">\n <property name = \"driver\" value = \"database_driver_class_name\"/>\n <property name = \"url\" value = \"database_url\"/>\n <property name = \"username\" value = \"database_user_name\"/>\n <property name = \"password\" value = \"database_password\"/>\n </dataSource> \n\t\t\t\t\n </environment>\n </environments>\n\t\n <mappers>\n <mapper resource = \"path of the configuration XML file\"/>\n </mappers>\n \n</configuration>" }, { "code": null, "e": 9393, "s": 9306, "text": "Let us discuss the important elements (tags) of the configuration XML file one by one." }, { "code": null, "e": 9705, "s": 9393, "text": "Within the environments element, we configure the environment of the database that we use in our application. In MyBatis, you can connect to multiple databases by configuring multiple environment elements. To configure the environment, we are provided with two sub tags namely transactionManager and dataSource." }, { "code": null, "e": 9771, "s": 9705, "text": "MyBatis supports two transaction managers namely JDBC and MANAGED" }, { "code": null, "e": 9928, "s": 9771, "text": "If we use the transaction manager of type JDBC, the application is responsible for the transaction management operations, such as, commit, roll-back, etc..." }, { "code": null, "e": 10085, "s": 9928, "text": "If we use the transaction manager of type JDBC, the application is responsible for the transaction management operations, such as, commit, roll-back, etc..." }, { "code": null, "e": 10259, "s": 10085, "text": "If we use the transaction manager of type MANAGED, the application server is responsible to manage the connection life cycle. It is generally used with the Web Applications." }, { "code": null, "e": 10433, "s": 10259, "text": "If we use the transaction manager of type MANAGED, the application server is responsible to manage the connection life cycle. It is generally used with the Web Applications." }, { "code": null, "e": 10621, "s": 10433, "text": "It is used to configure the connection properties of the database, such as driver-name, url, user-name, and password of the database that we want to connect. It is of three types namely −" }, { "code": null, "e": 10808, "s": 10621, "text": "UNPOOLED − For the dataSource type UNPOOLED, MyBatis simply opens and closes a connection for every database operation. It is a bit slower and generally used for the simple applications." }, { "code": null, "e": 10995, "s": 10808, "text": "UNPOOLED − For the dataSource type UNPOOLED, MyBatis simply opens and closes a connection for every database operation. It is a bit slower and generally used for the simple applications." }, { "code": null, "e": 11328, "s": 10995, "text": "POOLED − For the dataSource type POOLED, MyBatis will maintain a database connection pool. And, for every database operation, MyBatis uses one of these connections, and returns them to the pool after the completion of the operation. It reduces the initial connection and authentication time that required to create a new connection." }, { "code": null, "e": 11661, "s": 11328, "text": "POOLED − For the dataSource type POOLED, MyBatis will maintain a database connection pool. And, for every database operation, MyBatis uses one of these connections, and returns them to the pool after the completion of the operation. It reduces the initial connection and authentication time that required to create a new connection." }, { "code": null, "e": 11756, "s": 11661, "text": "JNDI − For the dataSource type JNDI, MyBatis will get the connection from the JNDI dataSource." }, { "code": null, "e": 11851, "s": 11756, "text": "JNDI − For the dataSource type JNDI, MyBatis will get the connection from the JNDI dataSource." }, { "code": null, "e": 11908, "s": 11851, "text": "Here is how you can use an environment tag in practice −" }, { "code": null, "e": 12396, "s": 11908, "text": "<environments default = \"development\">\n <environment id = \"development\">\n <transactionManager type = \"JDBC\"/> \n <dataSource type = \"POOLED\">\n <property name = \"driver\" value = \"com.mysql.jdbc.Driver\"/>\n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/details\"/>\n <property name = \"username\" value = \"root\"/>\n <property name = \"password\" value = \"password\"/>\n </dataSource> \n </environment>\n</environments>" }, { "code": null, "e": 12826, "s": 12396, "text": "Instead of specifying the absolute class name everywhere, we can use typeAliases, a shorter name for a Java type. Suppose, we have a class Student in Student.java file within the package named tutorials_point.com.mybatis_examples, then the absolute class name will be tutorials_point.com.mybatis_examples.Student. Instead of using this name to address the class every time, you can declare an alias to that class as shown below −" }, { "code": null, "e": 12914, "s": 12826, "text": "<typeAliases>\n <typeAlias alias = \"Student\" type = \"mybatis.Student\"/>\n</typeAliases>" }, { "code": null, "e": 13190, "s": 12914, "text": "Mapper XML file is the important file, which contains the mapped SQL statements. Mapper’s element is used to configure the location of these mappers xml files in the configuration file of MyBatis (this element contains four attributes namely resources, url, class, and name)." }, { "code": null, "e": 13353, "s": 13190, "text": "For example, the name of the mapper xml file is Student.xml and it resides in the package named as mybatis,, then you can configure the mapper tag as shown below." }, { "code": null, "e": 13420, "s": 13353, "text": "<mappers>\n <mapper resource = \"mybatis/Student.xml\"/>\n</mappers>" }, { "code": null, "e": 13484, "s": 13420, "text": "The attribute resource points to the classpath of the XML file." }, { "code": null, "e": 13548, "s": 13484, "text": "The attribute resource points to the classpath of the XML file." }, { "code": null, "e": 13618, "s": 13548, "text": "The attribute url points to the fully qualified path of the xml file." }, { "code": null, "e": 13688, "s": 13618, "text": "The attribute url points to the fully qualified path of the xml file." }, { "code": null, "e": 13808, "s": 13688, "text": "We can use mapper interfaces instead of xml file, the attribute class points to the class-path of the mapper interface." }, { "code": null, "e": 13928, "s": 13808, "text": "We can use mapper interfaces instead of xml file, the attribute class points to the class-path of the mapper interface." }, { "code": null, "e": 14121, "s": 13928, "text": "The attribute name points to the package name of the mapper interface. In the example provided in this chapter, we have specified the class path of the mapper XML using the resource attribute." }, { "code": null, "e": 14314, "s": 14121, "text": "The attribute name points to the package name of the mapper interface. In the example provided in this chapter, we have specified the class path of the mapper XML using the resource attribute." }, { "code": null, "e": 14484, "s": 14314, "text": "In addition to these, there are other elements that can be used in the configuration file of MyBatis documentation. Refer MyBatis documentation for the complete details." }, { "code": null, "e": 14764, "s": 14484, "text": "MySQL is one of the most popular open-source database systems available today. Let us create a SqlMapConfig.xml configuration file to connect to mysql database. The example given below are the dataSource properties (driver-name, url, user-name, and password) for MySQL database −" }, { "code": null, "e": 14913, "s": 14764, "text": "We use the transaction manager of type JDBC, means we have to perform the operations, such as commit and roll-back manually, within the application." }, { "code": null, "e": 15127, "s": 14913, "text": "We use the dataSource of type UNPOOLED, which means new connection is created for each database operation. Therefore, it is recommended to close the connection manually after the completion of database operations." }, { "code": null, "e": 15355, "s": 15127, "text": "Below given is the XML configuration for the examples used in this tutorial. Copy the content given below in a text file and save it as SqlMapConfig.xml. We are going to use this file in all the examples given in this tutorial." }, { "code": null, "e": 16150, "s": 15355, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<!DOCTYPE configuration PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-config.dtd\">\n<configuration>\n\t\t\n <environments default = \"development\">\n <environment id = \"development\">\n <transactionManager type = \"JDBC\"/> \n\t\t\t\n <dataSource type = \"POOLED\">\n <property name = \"driver\" value = \"com.mysql.jdbc.Driver\"/>\n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/details\"/>\n <property name = \"username\" value = \"root\"/>\n <property name = \"password\" value = \"password\"/>\n </dataSource> \n \n </environment>\n </environments>\n\t\n <mappers>\n <mapper resource = \"mybatis/Student.xml\"/>\n </mappers>\n \n</configuration>" }, { "code": null, "e": 16325, "s": 16150, "text": "In the previous chapter, we have seen how to configure MyBatis using an XML file. This chapter discusses the Mapper XML file and various mapped SQL statements provided by it." }, { "code": null, "e": 16442, "s": 16325, "text": "Before proceeding to mapped statements, assume that the following table named Student exists in the MYSQL database −" }, { "code": null, "e": 16768, "s": 16442, "text": "+----+-------+--------+------------+-----------+---------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+-------+--------+------------+-----------+---------------+\n| 1 | Shyam | it | 80 | 954788457 | [email protected] |\n+----+-------+--------+------------+-----------+---------------+\n" }, { "code": null, "e": 16871, "s": 16768, "text": "Also assume that POJO class also exists named Student with respect to the above table as shown below −" }, { "code": null, "e": 17071, "s": 16871, "text": "public class Student {\n private int id;\n private String name;\n private String branch;\n private int percentage;\n private int phone;\n private String email;\n \n //Setters and getters \n}" }, { "code": null, "e": 17304, "s": 17071, "text": "Mapper XML is an important file in MyBatis, which contains a set of statements to configure various SQL statements such as select, insert, update, and delete. These statements are known as Mapped Statements or Mapped SQL Statements." }, { "code": null, "e": 17497, "s": 17304, "text": "All the statements have unique id. To execute any of these statements you just need to pass the appropriate id to the methods in Java Application.(This is discussed clearly in later chapters)." }, { "code": null, "e": 17690, "s": 17497, "text": "All the statements have unique id. To execute any of these statements you just need to pass the appropriate id to the methods in Java Application.(This is discussed clearly in later chapters)." }, { "code": null, "e": 17874, "s": 17690, "text": "mapper XML file prevents the burden of writing SQL statements repeatedly in the application. In comparison to JDBC, almost 95% of the code is reduced using Mapper XML file in MyBatis." }, { "code": null, "e": 18058, "s": 17874, "text": "mapper XML file prevents the burden of writing SQL statements repeatedly in the application. In comparison to JDBC, almost 95% of the code is reduced using Mapper XML file in MyBatis." }, { "code": null, "e": 18191, "s": 18058, "text": "All these Mapped SQL statements are resided within the element named<mapper>. This element contains an attribute called ‘namespace’." }, { "code": null, "e": 18324, "s": 18191, "text": "All these Mapped SQL statements are resided within the element named<mapper>. This element contains an attribute called ‘namespace’." }, { "code": null, "e": 18404, "s": 18324, "text": "<mapper namespace = \"Student\">\n //mapped statements and result maps\n<mapper> " }, { "code": null, "e": 18469, "s": 18404, "text": "All the Mapped SQL statements are discussed below with examples." }, { "code": null, "e": 18657, "s": 18469, "text": "In MyBatis, to insert values into the table, we have to configure the insert mapped query. MyBatis provides various attributes for insert mapper, but largely we use id and parameter type." }, { "code": null, "e": 18892, "s": 18657, "text": "id is unique identifier used to identify the insert statement. On the other hand, parametertype is the class name or the alias of the parameter that will be passed into the statement. Below given is an example of insert mapped query −" }, { "code": null, "e": 19089, "s": 18892, "text": "<insert id = \"insert\" parameterType = \"Student\">\n INSERT INTO STUDENT1 (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL ) \n VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email}); \n</insert>" }, { "code": null, "e": 19291, "s": 19089, "text": "In the given example, we use the parameter of type Student (class). The class student is a POJO class, which represents the Student record with name, branch, percentage, phone, and email as parameters." }, { "code": null, "e": 19364, "s": 19291, "text": "You can invoke the ‘insert’ mapped query using Java API as shown below −" }, { "code": null, "e": 19452, "s": 19364, "text": "//Assume session is an SqlSession object. \nsession.insert(\"Student.insert\", student);\n" }, { "code": null, "e": 19674, "s": 19452, "text": "To update values of an existing record using MyBatis, the mapped query update is configured. The attributes of update mapped query are same as the insert mapped query. Following is the example of the update mapped query −" }, { "code": null, "e": 19872, "s": 19674, "text": "<update id = \"update\" parameterType = \"Student\">\n UPDATE STUDENT SET EMAIL = #{email}, NAME = #{name}, BRANCH = #{branch}, PERCENTAGE = #{percentage}, PHONE = #{phone} WHERE ID = #{id};\n</update>" }, { "code": null, "e": 20132, "s": 19872, "text": "To invoke the update query, instantiate Student class, set the values for the variables representing columns which need to be updated, and pass this object as parameter to update() method. You can invoke the update mapped query using Java API as shown below −" }, { "code": null, "e": 20219, "s": 20132, "text": "//Assume session is an SqlSession object. \nsession.update(\"Student.update\",student);\n" }, { "code": null, "e": 20462, "s": 20219, "text": "To delete the values of an existing record using MyBatis, the mapped query ‘delete’ is configured. The attributes of ‘delete’ mapped query are same as the insert and update mapped queries. Following is the example of the delete mapped query −" }, { "code": null, "e": 20562, "s": 20462, "text": "<delete id = \"deleteById\" parameterType = \"int\">\n DELETE from STUDENT WHERE ID = #{id};\n</delete>" }, { "code": null, "e": 20695, "s": 20562, "text": "You can invoke the delete mapped query using the delete method of SqlSession interface provided by MyBatis Java API as shown below −" }, { "code": null, "e": 20782, "s": 20695, "text": "//Assume session is an SqlSession object. \nsession.delete(\"Student.deleteById\", 18);\n" }, { "code": null, "e": 20924, "s": 20782, "text": "To retrieve data, ‘select’ mapper statement is used. Following is the example of select mapped query to retrieve all the records in a table −" }, { "code": null, "e": 21005, "s": 20924, "text": "<select id = \"getAll\" resultMap = \"result\">\n SELECT * FROM STUDENT; \n</select>" }, { "code": null, "e": 21180, "s": 21005, "text": "You can retrieve the data returned by the select query using the method selectList(). This method returns the data of the selected record in the form of List as shown below −" }, { "code": null, "e": 21240, "s": 21180, "text": "List<Student> list = session.selectList(\"Student.getAll\");\n" }, { "code": null, "e": 21571, "s": 21240, "text": "It is the most important and powerful elements in MyBatis. The results of SQL SELECT statements are mapped to Java objects (beans/POJO). Once the result map is defined, we can refer these from several SELECT statements. Following is the example of result Map query; it maps the results of the select queries to the Student class −" }, { "code": null, "e": 22128, "s": 21571, "text": "<resultMap id = \"result\" type = \"Student\">\n <result property = \"id\" column = \"ID\"/>\n <result property = \"name\" column = \"NAME\"/>\n <result property = \"branch\" column = \"BRANCH\"/>\n <result property = \"percentage\" column = \"PERCENTAGE\"/>\n <result property = \"phone\" column = \"PHONE\"/>\n <result property = \"email\" column = \"EMAIL\"/>\n</resultMap>\n\n<select id = \"getAll\" resultMap = \"result\">\n SELECT * FROM STUDENT; \n</select>\n\n<select id = \"getById\" parameterType = \"int\" resultMap = \"result\">\n SELECT * FROM STUDENT WHERE ID = #{id};\n</select>" }, { "code": null, "e": 22266, "s": 22128, "text": "Note − It is not mandatory to write the column attribute of the resultMap if both the property and the column name of the table are same." }, { "code": null, "e": 22509, "s": 22266, "text": "To perform any Create, Read, Update, and Delete (CRUD) operation using MyBATIS, you would need to create a Plain Old Java Objects (POJO) class corresponding to the table. This class describes the objects that will \"model\" database table rows." }, { "code": null, "e": 22610, "s": 22509, "text": "The POJO class would have implementation for all the methods required to perform desired operations." }, { "code": null, "e": 22670, "s": 22610, "text": "Create the STUDENT table in MySQL database as shown below −" }, { "code": null, "e": 23005, "s": 22670, "text": "mysql> CREATE TABLE details.student(\n -> ID int(10) NOT NULL AUTO_INCREMENT,\n -> NAME varchar(100) NOT NULL,\n -> BRANCH varchar(255) NOT NULL,\n -> PERCENTAGE int(3) NOT NULL,\n -> PHONE int(11) NOT NULL,\n -> EMAIL varchar(255) NOT NULL,\n -> PRIMARY KEY (`ID`)\n -> \n);\nQuery OK, 0 rows affected (0.37 sec)\n" }, { "code": null, "e": 23052, "s": 23005, "text": "Create a STUDENT class in STUDENT.java file as" }, { "code": null, "e": 23474, "s": 23052, "text": "public class Student {\n private int id;\n private String name;\n private String branch;\n private int percentage;\n private int phone;\n private String email;\n\n public Student(String name, String branch, int percentage, int phone, String email) {\n super();\n this.name = name;\n this.branch = branch;\n this.percentage = percentage;\n this.phone = phone;\n this.email = email;\n }\n \n}" }, { "code": null, "e": 23606, "s": 23474, "text": "You can define methods to set individual fields in the table. The next chapter explains how to get the values of individual fields." }, { "code": null, "e": 23880, "s": 23606, "text": "To define SQL mapping statement using MyBatis, we would use <insert> tag. Inside this tag definition, we would define an \"id.\" Further, the ‘id’ will be used in the mybatisInsert.java file for executing SQL INSERT query on database. Create student.xml file as shown below −" }, { "code": null, "e": 24421, "s": 23880, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n\t\n<mapper namespace = \"Student\">\n\n <insert id = \"insert\" parameterType = \"Student\">\n INSERT INTO STUDENT (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL ) VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email});\n\t\t\t\n <selectKey keyProperty = \"id\" resultType = \"int\" order = \"AFTER\">\n select last_insert_id() as id\n </selectKey> \n\t\t\t\n </insert>\n \t\n</mapper>" }, { "code": null, "e": 24645, "s": 24421, "text": "Here, parameteType − could take a value as string, int, float, double, or any class object based on requirement. In this example, we would pass Student object as a parameter, while calling insert method of SqlSession class." }, { "code": null, "e": 24871, "s": 24645, "text": "If your database table uses an IDENTITY, AUTO_INCREMENT, or SERIAL column, or you have defined a SEQUENCE/GENERATOR, you can use the <selectKey> element in an <insert> statement to use or return that database-generated value." }, { "code": null, "e": 25013, "s": 24871, "text": "This file would have application level logic to insert records in the Student table. Create and save mybatisInsert.java file as shown below −" }, { "code": null, "e": 25938, "s": 25013, "text": "import java.io.IOException;\nimport java.io.Reader;\n\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.session.SqlSessionFactoryBuilder;\n\npublic class mybatisInsert { \n\n public static void main(String args[]) throws IOException{\n \n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession();\n \n //Create a new student object\n Student student = new Student(\"Mohammad\",\"It\", 80, 984803322, \"[email protected]\" ); \n \n //Insert student data \n session.insert(\"Student.insert\", student);\n System.out.println(\"record inserted successfully\");\n session.commit();\n session.close();\n\t\t\t\n }\n \n}" }, { "code": null, "e": 26111, "s": 25938, "text": "Here are the steps to compile and run the mybatisInsert.java file. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution." }, { "code": null, "e": 26146, "s": 26111, "text": "Create Student.xml as shown above." }, { "code": null, "e": 26181, "s": 26146, "text": "Create Student.xml as shown above." }, { "code": null, "e": 26276, "s": 26181, "text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial." }, { "code": null, "e": 26371, "s": 26276, "text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial." }, { "code": null, "e": 26422, "s": 26371, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 26473, "s": 26422, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 26530, "s": 26473, "text": "Create mybatisInsert.java as shown above and compile it." }, { "code": null, "e": 26587, "s": 26530, "text": "Create mybatisInsert.java as shown above and compile it." }, { "code": null, "e": 26636, "s": 26587, "text": "Execute mybatisInsert binary to run the program." }, { "code": null, "e": 26685, "s": 26636, "text": "Execute mybatisInsert binary to run the program." }, { "code": null, "e": 26773, "s": 26685, "text": "You would get the following result, and a record would be created in the STUDENT table." }, { "code": null, "e": 26823, "s": 26773, "text": "$java mybatisInsert\nRecord Inserted Successfully\n" }, { "code": null, "e": 26896, "s": 26823, "text": "If you check the STUDENT table, it should display the following result −" }, { "code": null, "e": 27316, "s": 26896, "text": "mysql> select * from student;\n+----+----------+--------+------------+-----------+--------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+-----------+--------------------+\n| 1 | Mohammad | It | 80 | 984803322 | [email protected] |\n+----+----------+--------+------------+-----------+--------------------+\n1 row in set (0.00 sec)\n" }, { "code": null, "e": 27509, "s": 27316, "text": "We discussed in the last chapter, how to insert values into the STUDENT table using MyBatis by performing CREATE operation. This chapter explains how to read the data in a table using MyBatis." }, { "code": null, "e": 27556, "s": 27509, "text": "We have the following STUDENT table in MySQL −" }, { "code": null, "e": 27805, "s": 27556, "text": "CREATE TABLE details.student(\n ID int(10) NOT NULL AUTO_INCREMENT,\n NAME varchar(100) NOT NULL,\n BRANCH varchar(255) NOT NULL,\n PERCENTAGE int(3) NOT NULL,\n PHONE int(11) NOT NULL,\n EMAIL varchar(255) NOT NULL,\n PRIMARY KEY (`ID`)\n);\n" }, { "code": null, "e": 27844, "s": 27805, "text": "Assume, this table has two record as −" }, { "code": null, "e": 28283, "s": 27844, "text": "+----+----------+--------+------------+-----------+--------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+-----------+--------------------+\n| 1 | Mohammad | It | 80 | 984803322 | [email protected] |\n| 2 | shyam | It | 75 | 984800000 | [email protected] |\n+----+----------+--------+------------+-----------+--------------------+\n" }, { "code": null, "e": 28365, "s": 28283, "text": "To perform read operation, we would modify the Student class in Student.java as −" }, { "code": null, "e": 29177, "s": 28365, "text": "public class Student {\n private int id;\n private String name;\n private String branch;\n private int percentage;\n private int phone;\n private String email;\n\n public Student(int id, String name, String branch, int percentage, int phone, String email) {\n super();\n this.id = id;\n this.name = name;\n this.branch = branch;\n this.percentage = percentage;\n this.phone = phone;\n this.email = email;\n }\n\t\n public Student() {}\n\n public int getId() {\n return id;\n }\n\t\t\n public String getName() {\n return name;\n }\n\t\n public int getPhone() {\n return phone;\n }\n\t\n public String getEmail() {\n return email;\n }\n \n public String getBranch() {\n return branch;\n }\n\n public int getPercentage() {\n return percentage;\n }\t\n\t\n}" }, { "code": null, "e": 29593, "s": 29177, "text": "To define SQL mapping statement using MyBatis, we would add <select> tag in Student.xml file and inside this tag definition, we would define an \"id\" which will be used in mybatisRead.java file for executing SQL SELECT query on database. While reading the records, we can get all the records at once or we can get a particular record using the where clause. In the XML given below, you can observe both the queries." }, { "code": null, "e": 29827, "s": 29593, "text": "To retrieve a particular record, we need a unique key to represent that record. Therefore, we have also defined the resultmap \"id\" (unique key) of type Student to map the result of the select query with the variable of Student class." }, { "code": null, "e": 30369, "s": 29827, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n\t\n<mapper namespace = \"Student\">\t\n\n <resultMap id = \"result\" type = \"Student\">\n <result property = \"id\" column = \"ID\"/>\t \n </resultMap>\n\t\n <select id = \"getAll\" resultMap = \"result\">\n SELECT * FROM STUDENT; \n </select>\n \n <select id = \"getById\" parameterType = \"int\" resultMap = \"result\">\n SELECT * FROM STUDENT WHERE ID = #{id};\n </select>\n \t\n</mapper>" }, { "code": null, "e": 30514, "s": 30369, "text": "This file has application level logic to read all the records from the Student table. Create and save mybatisRead_ALL.java file as shown below −" }, { "code": null, "e": 31697, "s": 30514, "text": "import java.io.IOException;\nimport java.io.Reader;\nimport java.util.List;\n\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.session.SqlSessionFactoryBuilder;\n\npublic class mybatisRead_ALL { \n\n public static void main(String args[]) throws IOException{\n\n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession();\n \n //select contact all contacts\t\t\n List<Student> student = session.selectList(\"Student.getAll\");\n \n for(Student st : student ){ \t \n System.out.println(st.getId());\n System.out.println(st.getName());\n System.out.println(st.getBranch());\n System.out.println(st.getPercentage()); \n System.out.println(st.getEmail()); \n System.out.println(st.getPhone()); \n } \n\t\t\n System.out.println(\"Records Read Successfully \"); \n session.commit(); \n session.close();\t\t\t\n }\n} " }, { "code": null, "e": 31867, "s": 31697, "text": "Here are the steps to compile and run the mybatisRead_ALL file. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution." }, { "code": null, "e": 31902, "s": 31867, "text": "Create Student.xml as shown above." }, { "code": null, "e": 31953, "s": 31902, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 32012, "s": 31953, "text": "Create mybatisRead_ALL.java as shown above and compile it." }, { "code": null, "e": 32063, "s": 32012, "text": "Execute mybatisRead_ALL binary to run the program." }, { "code": null, "e": 32118, "s": 32063, "text": "You would get all the record of the student table as −" }, { "code": null, "e": 32380, "s": 32118, "text": "++++++++++++++ details of the student who's id is :1 +++++++++++++++++++\n1\nMohammad\nIt\n80\[email protected]\n984803322\n++++++++++++++ details of the student who's id is :2\n+++++++++++++++++++\n2\nshyam\nIt\n75\[email protected]\n984800000\nRecords Read Successfully \n" }, { "code": null, "e": 32449, "s": 32380, "text": "Copy and save the following program with the name mybatisRead_byID −" }, { "code": null, "e": 33566, "s": 32449, "text": "import java.io.IOException;\nimport java.io.Reader;\n\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.session.SqlSessionFactoryBuilder;\n\npublic class mybatisRead_byID { \n\n public static void main(String args[]) throws IOException{\n \n int i = 1;\n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession(); \n\t \n //select a particular student by id\t\n Student student = (Student) session.selectOne(\"Student.getById\", 2); \n\t \n //Print the student details\n System.out.println(student.getId());\n System.out.println(student.getName());\n System.out.println(student.getBranch());\n System.out.println(student.getPercentage()); \n System.out.println(student.getEmail()); \n System.out.println(student.getPhone());\n\t\t\n session.commit();\n session.close();\n\t\t\t\n }\n \n}" }, { "code": null, "e": 33737, "s": 33566, "text": "Here are the steps to compile and run the mybatisRead_byID file. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution." }, { "code": null, "e": 33772, "s": 33737, "text": "Create Student.xml as shown above." }, { "code": null, "e": 33807, "s": 33772, "text": "Create Student.xml as shown above." }, { "code": null, "e": 33901, "s": 33807, "text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial." }, { "code": null, "e": 33995, "s": 33901, "text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial." }, { "code": null, "e": 34046, "s": 33995, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 34097, "s": 34046, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 34157, "s": 34097, "text": "Create mybatisRead_byID.java as shown above and compile it." }, { "code": null, "e": 34217, "s": 34157, "text": "Create mybatisRead_byID.java as shown above and compile it." }, { "code": null, "e": 34269, "s": 34217, "text": "Execute mybatisRead_byID binary to run the program." }, { "code": null, "e": 34321, "s": 34269, "text": "Execute mybatisRead_byID binary to run the program." }, { "code": null, "e": 34412, "s": 34321, "text": "You would get the following result, and a record would be read from the Student table as −" }, { "code": null, "e": 34453, "s": 34412, "text": "2\nshyam\nIt\n75\[email protected]\n984800000\n" }, { "code": null, "e": 34614, "s": 34453, "text": "We discussed, in the last chapter, how to perform READ operation on a table using MyBatis. This chapter explains how you can update records in a table using it." }, { "code": null, "e": 34661, "s": 34614, "text": "We have the following STUDENT table in MySQL −" }, { "code": null, "e": 34910, "s": 34661, "text": "CREATE TABLE details.student(\n ID int(10) NOT NULL AUTO_INCREMENT,\n NAME varchar(100) NOT NULL,\n BRANCH varchar(255) NOT NULL,\n PERCENTAGE int(3) NOT NULL,\n PHONE int(11) NOT NULL,\n EMAIL varchar(255) NOT NULL,\n PRIMARY KEY (`ID`)\n);\n" }, { "code": null, "e": 34956, "s": 34910, "text": "Assume this table has two record as follows −" }, { "code": null, "e": 35425, "s": 34956, "text": "mysql> select * from STUDENT;\n+----+----------+--------+------------+-----------+--------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+-----------+--------------------+\n| 1 | Mohammad | It | 80 | 984803322 | [email protected] |\n| 2 | shyam | It | 75 | 984800000 | [email protected] |\n+----+----------+--------+------------+-----------+--------------------+\n" }, { "code": null, "e": 35502, "s": 35425, "text": "To perform update operation, you would need to modify Student.java file as −" }, { "code": null, "e": 37198, "s": 35502, "text": "public class Student {\n\n private int id;\n private String name;\n private String branch;\n private int percentage;\n private int phone;\n private String email;\n\n public Student(int id, String name, String branch, int percentage, int phone, String email) {\n super();\n this.id = id;\n this.name = name;\n this.setBranch(branch);\n this.setPercentage(percentage);\n this.phone = phone;\n this.email = email;\n }\n\t\n public Student() {}\n\n public int getId() {\n return id;\n }\n\t\n public void setId(int id) {\n this.id = id;\n }\n\t\n public String getName() {\n return name;\n }\n\t\n public void setName(String name) {\n this.name = name;\n }\n\t\n public int getPhone() {\n return phone;\n }\n\t\n public void setPhone(int phone) {\n this.phone = phone;\n }\n\t\n public String getEmail() {\n return email;\n }\n\t\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getBranch() {\n return branch;\n }\n\n public void setBranch(String branch) {\n this.branch = branch;\n }\n\n public int getPercentage() {\n return percentage;\n }\n\n public void setPercentage(int percentage) {\n this.percentage = percentage;\n }\n\t\n public String toString(){\n StringBuilder sb = new StringBuilder();\n\t\t\n sb.append(\"Id = \").append(id).append(\" - \");\n sb.append(\"Name = \").append(name).append(\" - \");\n sb.append(\"Branch = \").append(branch).append(\" - \");\n sb.append(\"Percentage = \").append(percentage).append(\" - \");\n sb.append(\"Phone = \").append(phone).append(\" - \");\n sb.append(\"Email = \").append(email);\n\t\t\n return sb.toString();\n }\n\t\n}" }, { "code": null, "e": 37432, "s": 37198, "text": "To define SQL mapping statement using MyBatis, we would add <update> tag in Student.xml and inside this tag definition, we would define an \"id\" which will be used in mybatisUpdate.java file for executing SQL UPDATE query on database." }, { "code": null, "e": 38404, "s": 37432, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n\t\n<mapper namespace = \"Student\">\t\n <resultMap id = \"result\" type = \"Student\">\n <result property = \"id\" column = \"ID\"/>\n <result property = \"name\" column = \"NAME\"/>\n <result property = \"branch\" column = \"BRANCH\"/>\n <result property = \"percentage\" column = \"PERCENTAGE\"/>\n <result property = \"phone\" column = \"PHONE\"/>\n <result property = \"email\" column = \"EMAIL\"/>\n </resultMap>\n \n <select id = \"getById\" parameterType = \"int\" resultMap = \"result\">\n SELECT * FROM STUDENT WHERE ID = #{id};\n </select>\n \t\n <update id = \"update\" parameterType = \"Student\">\n UPDATE STUDENT SET NAME = #{name}, \n BRANCH = #{branch}, \n PERCENTAGE = #{percentage}, \n PHONE = #{phone}, \n EMAIL = #{email} \n WHERE ID = #{id};\n </update>\n \t\n</mapper>" }, { "code": null, "e": 38485, "s": 38404, "text": "This file has application level logic to update records into the Student table −" }, { "code": null, "e": 39945, "s": 38485, "text": "import java.io.IOException;\nimport java.io.Reader;\n\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.session.SqlSessionFactoryBuilder;\n\npublic class mybatisUpdate { \n\n public static void main(String args[]) throws IOException{\n \n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession();\n \n //select a particular student using id\t\t\n Student student = (Student) session.selectOne(\"Student.getById\", 1);\n System.out.println(\"Current details of the student are\" );\n System.out.println(student.toString()); \n \n //Set new values to the mail and phone number of the student\n student.setEmail(\"[email protected]\");\n student.setPhone(90000000);\n \n //Update the student record\n session.update(\"Student.update\",student);\n System.out.println(\"Record updated successfully\"); \n session.commit(); \n session.close();\t \n\t \n //verifying the record \n Student std = (Student) session.selectOne(\"Student.getById\", 1);\n System.out.println(\"Details of the student after update operation\" );\n System.out.println(std.toString()); \n session.commit(); \n session.close();\n\t\t\t\n }\n}" }, { "code": null, "e": 40109, "s": 39945, "text": "Here are the steps to compile and run mybatisUpdate.java. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution." }, { "code": null, "e": 40144, "s": 40109, "text": "Create Student.xml as shown above." }, { "code": null, "e": 40179, "s": 40144, "text": "Create Student.xml as shown above." }, { "code": null, "e": 40273, "s": 40179, "text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial." }, { "code": null, "e": 40367, "s": 40273, "text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial." }, { "code": null, "e": 40418, "s": 40367, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 40469, "s": 40418, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 40526, "s": 40469, "text": "Create mybatisUpdate.java as shown above and compile it." }, { "code": null, "e": 40583, "s": 40526, "text": "Create mybatisUpdate.java as shown above and compile it." }, { "code": null, "e": 40632, "s": 40583, "text": "Execute mybatisUpdate binary to run the program." }, { "code": null, "e": 40681, "s": 40632, "text": "Execute mybatisUpdate binary to run the program." }, { "code": null, "e": 40869, "s": 40681, "text": "You would get following result. You can see the details of a particular record initially, and that record would be updated in STUDENT table and later, you can also see the updated record." }, { "code": null, "e": 41192, "s": 40869, "text": "Current details of the student are\nId = 1 - Name = Mohammad - Branch = It - Percentage = 80 - Phone = 984802233 - Email = [email protected]\nRecord updated successfully\nDetails of the student after update operation\nId = 1 - Name = Mohammad - Branch = It - Percentage = 80 - Phone = 90000000 - Email = [email protected]\n" }, { "code": null, "e": 41265, "s": 41192, "text": "If you check the STUDENT table, it should display the following result −" }, { "code": null, "e": 41771, "s": 41265, "text": "mysql> select * from student;\n+----+----------+--------+------------+-----------+----------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+-----------+----------------------+\n| 1 | Mohammad | It | 80 | 90000000 | [email protected] |\n| 2 | shyam | It | 75 | 984800000 | [email protected] |\n+----+----------+--------+------------+-----------+----------------------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 41844, "s": 41771, "text": "This chapter describes how to delete records from a table using MyBatis." }, { "code": null, "e": 41891, "s": 41844, "text": "We have the following STUDENT table in MySQL −" }, { "code": null, "e": 42140, "s": 41891, "text": "CREATE TABLE details.student(\n ID int(10) NOT NULL AUTO_INCREMENT,\n NAME varchar(100) NOT NULL,\n BRANCH varchar(255) NOT NULL,\n PERCENTAGE int(3) NOT NULL,\n PHONE int(11) NOT NULL,\n EMAIL varchar(255) NOT NULL,\n PRIMARY KEY (`ID`)\n);\n" }, { "code": null, "e": 42180, "s": 42140, "text": "Assume, this table has two records as −" }, { "code": null, "e": 42686, "s": 42180, "text": "mysql> select * from STUDENT;\n+----+----------+--------+------------+-----------+----------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+-----------+----------------------+\n| 1 | Mohammad | It | 80 | 900000000 | [email protected] |\n| 2 | shyam | It | 75 | 984800000 | [email protected] |\n+----+----------+--------+------------+-----------+----------------------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 42806, "s": 42686, "text": "To perform delete operation, you do not need to modify Student.java file. Let us keep it as it was in the last chapter." }, { "code": null, "e": 44501, "s": 42806, "text": "public class Student {\n\n private int id;\n private String name;\n private String branch;\n private int percentage;\n private int phone;\n private String email;\n\n public Student(int id, String name, String branch, int percentage, int phone, String email) {\n super();\n this.id = id;\n this.name = name;\n this.setBranch(branch);\n this.setPercentage(percentage);\n this.phone = phone;\n this.email = email;\n }\n\t\n public Student() {}\n\n public int getId() {\n return id;\n }\n\t\n public void setId(int id) {\n this.id = id;\n }\n\t\n public String getName() {\n return name;\n }\n\t\n public void setName(String name) {\n this.name = name;\n }\n\t\n public int getPhone() {\n return phone;\n }\n\t\n public void setPhone(int phone) {\n this.phone = phone;\n }\n\t\n public String getEmail() {\n return email;\n }\n\t\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getBranch() {\n return branch;\n }\n\n public void setBranch(String branch) {\n this.branch = branch;\n }\n\n public int getPercentage() {\n return percentage;\n }\n\n public void setPercentage(int percentage) {\n this.percentage = percentage;\n }\n\t\n public String toString(){\n StringBuilder sb = new StringBuilder();\n\t\t\n sb.append(\"Id = \").append(id).append(\" - \");\n sb.append(\"Name = \").append(name).append(\" - \");\n sb.append(\"Branch = \").append(branch).append(\" - \");\n sb.append(\"Percentage = \").append(percentage).append(\" - \");\n sb.append(\"Phone = \").append(phone).append(\" - \");\n sb.append(\"Email = \").append(email);\n\t\t\n return sb.toString();\n }\n\t\n}" }, { "code": null, "e": 44735, "s": 44501, "text": "To define SQL mapping statement using MyBatis, we would use <delete> tag in Student.xml and inside this tag definition, we would define an \"id\" which will be used in mybatisDelete.java file for executing SQL DELETE query on database." }, { "code": null, "e": 45161, "s": 44735, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n\t\n<mapper namespace = \"Student\">\t\n <resultMap id = \"result\" type = \"Student\">\n <result property = \"id\" column = \"ID\"/>\t \n </resultMap>\n\t\n <delete id = \"deleteById\" parameterType = \"int\">\n DELETE from STUDENT WHERE ID = #{id};\n </delete>\n \t\n</mapper>" }, { "code": null, "e": 45242, "s": 45161, "text": "This file has application level logic to delete records from the Student table −" }, { "code": null, "e": 46022, "s": 45242, "text": "import java.io.IOException;\nimport java.io.Reader;\n\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.session.SqlSessionFactoryBuilder;\n\npublic class mybatisDelete { \n\n public static void main(String args[]) throws IOException{\n \n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession(); \n\t \n //Delete operation\n session.delete(\"Student.deleteById\", 2); \n session.commit();\n session.close(); \n System.out.println(\"Record deleted successfully\");\n\t\t\t\n }\n \n}" }, { "code": null, "e": 46186, "s": 46022, "text": "Here are the steps to compile and run mybatisDelete.java. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution." }, { "code": null, "e": 46221, "s": 46186, "text": "Create Student.xml as shown above." }, { "code": null, "e": 46256, "s": 46221, "text": "Create Student.xml as shown above." }, { "code": null, "e": 46350, "s": 46256, "text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial." }, { "code": null, "e": 46444, "s": 46350, "text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial." }, { "code": null, "e": 46495, "s": 46444, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 46546, "s": 46495, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 46603, "s": 46546, "text": "Create mybatisDelete.java as shown above and compile it." }, { "code": null, "e": 46660, "s": 46603, "text": "Create mybatisDelete.java as shown above and compile it." }, { "code": null, "e": 46709, "s": 46660, "text": "Execute mybatisDelete binary to run the program." }, { "code": null, "e": 46758, "s": 46709, "text": "Execute mybatisDelete binary to run the program." }, { "code": null, "e": 46854, "s": 46758, "text": "You would get the following result, and a record with ID = 1 would be deleted from the STUDENT." }, { "code": null, "e": 46881, "s": 46854, "text": "Records Read Successfully\n" }, { "code": null, "e": 46954, "s": 46881, "text": "If you check the STUDENT table, it should display the following result −" }, { "code": null, "e": 47379, "s": 46954, "text": "mysql> select * from student;\n+----+----------+--------+------------+----------+----------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+----------+----------------------+\n| 1 | Mohammad | It | 80 | 90000000 | [email protected] |\n+----+----------+--------+------------+----------+----------------------+\n1 row in set (0.00 sec)\n" }, { "code": null, "e": 47578, "s": 47379, "text": "In the previous chapters, we have seen how to perform curd operations using MyBatis. There we used a Mapper XML file to store mapped SQL statements and a configuration XML file to configure MyBatis." }, { "code": null, "e": 47695, "s": 47578, "text": "To map SQL statements, MyBatis also provides annotations. So, this chapter discusses how to use MyBatis annotations." }, { "code": null, "e": 47829, "s": 47695, "text": "While working with annotations, instead of configuration XML file, we can use a java mapper interface to map and execute SQL queries." }, { "code": null, "e": 47885, "s": 47829, "text": "Assume, we have the following employee table in MySQL −" }, { "code": null, "e": 48171, "s": 47885, "text": "CREATE TABLE details.student(\n ID int(10) NOT NULL AUTO_INCREMENT,\n NAME varchar(100) NOT NULL,\n BRANCH varchar(255) NOT NULL,\n PERCENTAGE int(3) NOT NULL,\n PHONE int(11) NOT NULL,\n EMAIL varchar(255) NOT NULL,\n PRIMARY KEY (`ID`)\n);\nQuery OK, 0 rows affected (0.37 sec)\n" }, { "code": null, "e": 48210, "s": 48171, "text": "Assume this table has two records as −" }, { "code": null, "e": 48679, "s": 48210, "text": "mysql> select * from STUDENT;\n+----+----------+--------+------------+-----------+--------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+-----------+--------------------+\n| 1 | Mohammad | It | 80 | 984803322 | [email protected] |\n| 2 | Shyam | It | 75 | 984800000 | [email protected] |\n+----+----------+--------+------------+-----------+--------------------+\n" }, { "code": null, "e": 48780, "s": 48679, "text": "The POJO class would have implementation for all the methods required to perform desired operations." }, { "code": null, "e": 48829, "s": 48780, "text": "Create a Student class in Student.java file as −" }, { "code": null, "e": 50073, "s": 48829, "text": "public class Student {\n private int id;\n private String name;\n private String branch;\n private int percentage;\n private int phone;\n private String email;\n\n public Student(int id, String name, String branch, int percentage, int phone, String email) {\n super();\n this.id = id;\n this.name = name;\n this.branch = branch;\n this.percentage = percentage;\n this.phone = phone;\n this.email = email;\n }\n\t\n public Student() {}\n\n public int getId() {\n return id;\n }\n\t\n public void setId(int id) {\n this.id = id;\n }\n\t\n public String getName() {\n return name;\n }\n\t\n public void setName(String name) {\n this.name = name;\n }\n\t\n public int getPhone() {\n return phone;\n }\n\t\n public void setPhone(int phone) {\n this.phone = phone;\n }\n\t\n public String getEmail() {\n return email;\n }\n\t\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getBranch() {\n return branch;\n }\n\n public void setBranch(String branch) {\n this.branch = branch;\n }\n\n public int getPercentage() {\n return percentage;\n }\n\n public void setPercentage(int percentage) {\n this.percentage = percentage;\n }\t\n \n}" }, { "code": null, "e": 50454, "s": 50073, "text": "This is the file, which contains the mapper interface where we declare the mapped statements using annotations instead of XML tags. For almost all of the XML-based mapper elements, MyBatis provides annotations. The following file named Student_mapper.java, contains a mapper interface. Within this file, you can see the annotations to perform CURD operations on the STUDENT table." }, { "code": null, "e": 52086, "s": 50454, "text": "import java.util.List;\n\nimport org.apache.ibatis.annotations.*;\n\npublic interface Student_mapper {\n\t\n final String getAll = \"SELECT * FROM STUDENT\"; \n final String getById = \"SELECT * FROM STUDENT WHERE ID = #{id}\";\n final String deleteById = \"DELETE from STUDENT WHERE ID = #{id}\";\n final String insert = \"INSERT INTO STUDENT (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL ) VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email})\";\n final String update = \"UPDATE STUDENT SET EMAIL = #{email}, NAME = #{name}, BRANCH = #{branch}, PERCENTAGE = #{percentage}, PHONE = #{phone} WHERE ID = #{id}\";\n \n @Select(getAll)\n @Results(value = {\n @Result(property = \"id\", column = \"ID\"),\n @Result(property = \"name\", column = \"NAME\"),\n @Result(property = \"branch\", column = \"BRANCH\"),\n @Result(property = \"percentage\", column = \"PERCENTAGE\"), \n @Result(property = \"phone\", column = \"PHONE\"),\n @Result(property = \"email\", column = \"EMAIL\")\n })\n \n List getAll();\n \n @Select(getById)\n @Results(value = {\n @Result(property = \"id\", column = \"ID\"),\n @Result(property = \"name\", column = \"NAME\"),\n @Result(property = \"branch\", column = \"BRANCH\"),\n @Result(property = \"percentage\", column = \"PERCENTAGE\"), \n @Result(property = \"phone\", column = \"PHONE\"),\n @Result(property = \"email\", column = \"EMAIL\")\n })\n \n Student getById(int id);\n\n @Update(update)\n void update(Student student);\n\n @Delete(deleteById)\n void delete(int id);\n \n @Insert(insert)\n @Options(useGeneratedKeys = true, keyProperty = \"id\")\n void insert(Student student);\n}" }, { "code": null, "e": 52228, "s": 52086, "text": "This file would have application level logic to insert records in the Student table. Create and save mybatisInsert.java file as shown below −" }, { "code": null, "e": 53443, "s": 52228, "text": "import java.io.IOException;\nimport java.io.Reader;\n\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.session.SqlSessionFactoryBuilder;\n\npublic class Annotations_Example { \n\n public static void main(String args[]) throws IOException{\n \n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession();\n session.getConfiguration().addMapper(Student_mapper.class);\n \n Student_mapper mapper = session.getMapper(Student_mapper.class); \n \n //Create a new student object\n Student student = new Student();\n \n //Set the values \n student.setName(\"zara\");\n student.setBranch(\"EEE\");\n student.setEmail(\"[email protected]\");\n student.setPercentage(90));\n student.setPhone(123412341);\n \n //Insert student data \n mapper.insert(student);\n System.out.println(\"record inserted successfully\");\n session.commit();\n session.close();\n\t\t\t\n }\n \n}" }, { "code": null, "e": 53622, "s": 53443, "text": "Here are the steps to compile and run the Annotations_Example.java file. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution." }, { "code": null, "e": 53685, "s": 53622, "text": "Create Student_mapper.java file as shown above and compile it." }, { "code": null, "e": 53748, "s": 53685, "text": "Create Student_mapper.java file as shown above and compile it." }, { "code": null, "e": 53842, "s": 53748, "text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial." }, { "code": null, "e": 53936, "s": 53842, "text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial." }, { "code": null, "e": 53987, "s": 53936, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 54038, "s": 53987, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 54101, "s": 54038, "text": "Create Annotations_Example.java as shown above and compile it." }, { "code": null, "e": 54164, "s": 54101, "text": "Create Annotations_Example.java as shown above and compile it." }, { "code": null, "e": 54219, "s": 54164, "text": "Execute Annotations_Example binary to run the program." }, { "code": null, "e": 54274, "s": 54219, "text": "Execute Annotations_Example binary to run the program." }, { "code": null, "e": 54362, "s": 54274, "text": "You would get the following result, and a record would be created in the STUDENT table." }, { "code": null, "e": 54418, "s": 54362, "text": "$java Annotations_Example\nRecord Inserted Successfully\n" }, { "code": null, "e": 54491, "s": 54418, "text": "If you check the STUDENT table, it should display the following result −" }, { "code": null, "e": 55072, "s": 54491, "text": "mysql> select * from student;\n+----+----------+--------+------------+-----------+----------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+-----------+----------------------+\n| 1 | Mohammad | It | 80 | 900000000 | [email protected] |\n| 2 | Shyam | It | 75 | 984800000 | [email protected] |\n| 3 | Zara | EEE | 90 | 123412341 | [email protected] |\n+----+----------+--------+------------+-----------+----------------------+\n3 rows in set (0.08 sec)\n" }, { "code": null, "e": 55258, "s": 55072, "text": "In the same way, we can perform update, delete, and read operations using annotations by replacing the content of Annotations_Example.java with the respective snippets mentioned below −" }, { "code": null, "e": 56165, "s": 55258, "text": "public static void main(String args[]) throws IOException{\n \n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession(); \n session.getConfiguration().addMapper(Student_mapper.class);\n Student_mapper mapper = session.getMapper(Student_mapper.class); \n \n //select a particular student using id\t\t\n Student student = mapper.getById(2);\n System.out.println(\"Current details of the student are \"+student.toString()); \n \n //Set new values to the mail and phone number of the student\n student.setEmail(\"[email protected]\");\n student.setPhone(984802233);\n \n //Update the student record\n mapper.update(student);\n System.out.println(\"Record updated successfully\"); \n session.commit(); \n session.close();\n\n}\t" }, { "code": null, "e": 56973, "s": 56165, "text": "public static void main(String args[]) throws IOException{\n \n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession();\n session.getConfiguration().addMapper(Student_mapper.class); \n Student_mapper mapper = session.getMapper(Student_mapper.class);\n \n //Get the student details\n Student student = mapper.getById(2);\n System.out.println(student.getBranch());\n System.out.println(student.getEmail());\n System.out.println(student.getId());\n System.out.println(student.getName());\n System.out.println(student.getPercentage());\n System.out.println(student.getPhone()); \n session.commit();\n session.close();\n\t\t\t\n}" }, { "code": null, "e": 57527, "s": 56973, "text": "public static void main(String args[]) throws IOException{\n \n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession();\n session.getConfiguration().addMapper(Student_mapper.class);\n \n Student_mapper mapper = session.getMapper(Student_mapper.class);\n mapper.delete(2);\n System.out.println(\"record deleted successfully\");\n session.commit();\n session.close(); \n\t\t\t\n}" }, { "code": null, "e": 57649, "s": 57527, "text": "You can call a stored procedure using MyBatis. First of all, let us understand how to create a stored procedure in MySQL." }, { "code": null, "e": 57697, "s": 57649, "text": "We have the following EMPLOYEE table in MySQL −" }, { "code": null, "e": 57946, "s": 57697, "text": "CREATE TABLE details.student(\n ID int(10) NOT NULL AUTO_INCREMENT,\n NAME varchar(100) NOT NULL,\n BRANCH varchar(255) NOT NULL,\n PERCENTAGE int(3) NOT NULL,\n PHONE int(11) NOT NULL,\n EMAIL varchar(255) NOT NULL,\n PRIMARY KEY (`ID`)\n);\n" }, { "code": null, "e": 58011, "s": 57946, "text": "Let us create the following stored procedure in MySQL database −" }, { "code": null, "e": 58224, "s": 58011, "text": "DELIMITER //\n DROP PROCEDURE IF EXISTS details.read_recordById //\n CREATE PROCEDURE details.read_recordById (IN emp_id INT)\n\t\n BEGIN \n SELECT * FROM STUDENT WHERE ID = emp_id; \n END// \n\t\nDELIMITER ;\n" }, { "code": null, "e": 58276, "s": 58224, "text": "Assume the table named STUDENT has two records as −" }, { "code": null, "e": 58782, "s": 58276, "text": "mysql> select * from STUDENT;\n+----+----------+--------+------------+-----------+----------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+-----------+----------------------+\n| 1 | Mohammad | It | 80 | 900000000 | [email protected] |\n| 2 | Shyam | It | 75 | 984800000 | [email protected] |\n+----+----------+--------+------------+-----------+----------------------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 58902, "s": 58782, "text": "To use stored procedure, you do not need to modify the Student.java file. Let us keep it as it was in the last chapter." }, { "code": null, "e": 60597, "s": 58902, "text": "public class Student {\n\n private int id;\n private String name;\n private String branch;\n private int percentage;\n private int phone;\n private String email;\n\n public Student(int id, String name, String branch, int percentage, int phone, String email) {\n super();\n this.id = id;\n this.name = name;\n this.setBranch(branch);\n this.setPercentage(percentage);\n this.phone = phone;\n this.email = email;\n }\n\t\n public Student() {}\n\n public int getId() {\n return id;\n }\n\t\n public void setId(int id) {\n this.id = id;\n }\n\t\n public String getName() {\n return name;\n }\n\t\n public void setName(String name) {\n this.name = name;\n }\n\t\n public int getPhone() {\n return phone;\n }\n\t\n public void setPhone(int phone) {\n this.phone = phone;\n }\n\t\n public String getEmail() {\n return email;\n }\n\t\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getBranch() {\n return branch;\n }\n\n public void setBranch(String branch) {\n this.branch = branch;\n }\n\n public int getPercentage() {\n return percentage;\n }\n\n public void setPercentage(int percentage) {\n this.percentage = percentage;\n }\n\t\n public String toString(){\n StringBuilder sb = new StringBuilder();\n\t\t\n sb.append(\"Id = \").append(id).append(\" - \");\n sb.append(\"Name = \").append(name).append(\" - \");\n sb.append(\"Branch = \").append(branch).append(\" - \");\n sb.append(\"Percentage = \").append(percentage).append(\" - \");\n sb.append(\"Phone = \").append(phone).append(\" - \");\n sb.append(\"Email = \").append(email);\n\t\t\n return sb.toString();\n }\n\t\n}" }, { "code": null, "e": 60900, "s": 60597, "text": "Unlike IBATIS, there is no <procedure> tag in MyBatis. To map the results of the procedures, we have created a resultmap named Student and to call the stored procedure named read_recordById. We have defined a select tag with id callById, and we use the same id in the application to call the procedure." }, { "code": null, "e": 61675, "s": 60900, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n\t\n<mapper namespace = \"Student\">\t\n\t\t\n <resultMap id = \"result\" type = \"Student\">\n <result property = \"id\" column = \"ID\"/>\n <result property = \"name\" column = \"NAME\"/>\n <result property = \"branch\" column = \"BRANCH\"/>\n <result property = \"percentage\" column = \"PERCENTAGE\"/>\n <result property = \"phone\" column = \"PHONE\"/>\n <result property = \"email\" column = \"EMAIL\"/>\n </resultMap> \n \n <select id = \"callById\" resultMap = \"result\" parameterType = \"Student\" statementType = \"CALLABLE\">\n {call read_record_byid(#{id, jdbcType = INTEGER, mode = IN})}\n </select> \n \t\n</mapper>" }, { "code": null, "e": 61790, "s": 61675, "text": "This file has application level logic to read the names of the employees from the Employee table using ResultMap −" }, { "code": null, "e": 63002, "s": 61790, "text": "import java.io.IOException;\nimport java.io.Reader;\n\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.session.SqlSessionFactoryBuilder;\n\npublic class getRecords { \n\n public static void main(String args[]) throws IOException{\n \n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession();\n \n //select a particular student by id\t\n Student student = (Student) session.selectOne(\"Student.callById\", 3);\n \n //Print the student details\n System.out.println(\"Details of the student are:: \");\n System.out.println(\"Id :\"+student.getId());\n System.out.println(\"Name :\"+student.getName());\n System.out.println(\"Branch :\"+student.getBranch());\n System.out.println(\"Percentage :\"+student.getPercentage()); \n System.out.println(\"Email :\"+student.getEmail()); \n System.out.println(\"Phone :\"+student.getPhone());\n session.commit();\n session.close();\n\t\t\t\n }\n \n}" }, { "code": null, "e": 63170, "s": 63002, "text": "Here are the steps to compile and run the getRecords program. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution." }, { "code": null, "e": 63205, "s": 63170, "text": "Create Student.xml as shown above." }, { "code": null, "e": 63256, "s": 63205, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 63310, "s": 63256, "text": "Create getRecords.java as shown above and compile it." }, { "code": null, "e": 63356, "s": 63310, "text": "Execute getRecords binary to run the program." }, { "code": null, "e": 63392, "s": 63356, "text": "You will get the following result −" }, { "code": null, "e": 63507, "s": 63392, "text": "Details of the student are:: \nId :2\nName :Shyam\nBranch :It\nPercentage :75\nEmail :[email protected]\nPhone :984800000\n" }, { "code": null, "e": 63787, "s": 63507, "text": "Dynamic SQL is a very powerful feature of MyBatis. It enables programmers to build queries based on the scenario dynamically. For example, if you want to search the Student data base, based on the name of the student in MyBatis, you have to write the query using the dynamic SQL." }, { "code": null, "e": 63956, "s": 63787, "text": "MyBatis uses a powerful Dynamic SQL language that can be used within any mapped SQL statement. Following are the OGNL based Dynamic SQL expressions provided by MyBatis." }, { "code": null, "e": 63959, "s": 63956, "text": "if" }, { "code": null, "e": 63984, "s": 63959, "text": "choose (when, otherwise)" }, { "code": null, "e": 64002, "s": 63984, "text": "trim (where, set)" }, { "code": null, "e": 64010, "s": 64002, "text": "foreach" }, { "code": null, "e": 64118, "s": 64010, "text": "The most common thing to do in dynamic SQL is conditionally include a part of a where clause. For example −" }, { "code": null, "e": 64305, "s": 64118, "text": "<select id = \"getRecByName\" parameterType = \"Student\" resultType = \"Student\">\n\n SELECT * FROM STUDENT\t\t \n <if test = \"name != null\">\n WHERE name LIKE #{name}\n </if> \n</select>" }, { "code": null, "e": 64527, "s": 64305, "text": "This statement provides an optional text search type of functionality. If you pass in no name, then all active records will be returned. But if you do pass in a name, it will look for a name with the given like condition." }, { "code": null, "e": 64571, "s": 64527, "text": "You can include multiple if conditions as −" }, { "code": null, "e": 64823, "s": 64571, "text": "<select id = \"getRecByName_Id\" parameterType = \"Student\" resultType = \"Student\">\n\n SELECT * FROM STUDENT\t\t \n <if test = \"name != null\">\n WHERE name LIKE #{name}\n </if>\n\n <if test = \"id != null\">\n AND id LIKE #{id}\n </if> \n</select>" }, { "code": null, "e": 64954, "s": 64823, "text": "MyBatis offers a choose element, which is similar to Java's switch statement. It helps to choose only one case among many options." }, { "code": null, "e": 65068, "s": 64954, "text": "The following example will search only by name if it is provided, and if the name is not given, then only by id −" }, { "code": null, "e": 65398, "s": 65068, "text": "<select id = \"getRecByName_Id_phone\" parameterType = \"Student\" resultType = \"Student\">\n SELECT * FROM Student WHERE id != 0\n\t\n <choose>\n <when test = \"name != null\">\n AND name LIKE #{name}\n </when> \n\n <when test = \"phone != null\">\n AND phone LIKE #{phone}\n </when>\n </choose>\n\t\n</select>" }, { "code": null, "e": 65542, "s": 65398, "text": "Take a look at our previous examples to see what happens if none of the conditions are met. You would end up with an SQL that looks like this −" }, { "code": null, "e": 65571, "s": 65542, "text": "SELECT * FROM Student\nWHERE\n" }, { "code": null, "e": 65670, "s": 65571, "text": "This would fail, but MyBatis has a simple solution with one simple change, everything works fine −" }, { "code": null, "e": 65955, "s": 65670, "text": "<select id = \"getName_Id_phone\" parameterType = \"Student\" resultType = \"Student\">\n SELECT * FROM STUDENT\n\t\n <where>\n <if test = \"id != null\">\n id = #{id}\n </if>\n\n <if test = \"name != null\">\n AND name LIKE #{name}\n </if>\n </where>\n\t\t\n</select>" }, { "code": null, "e": 66117, "s": 65955, "text": "The where element inserts a WHERE only when the containing tags return any content. Furthermore, if that content begins with AND or OR, it knows to strip it off." }, { "code": null, "e": 66258, "s": 66117, "text": "The foreach element allows you to specify a collection and declare item and index variables that can be used inside the body of the element." }, { "code": null, "e": 66413, "s": 66258, "text": "It also allows you to specify opening and closing strings, and add a separator to place in between iterations. You can build an IN condition as follows −" }, { "code": null, "e": 66666, "s": 66413, "text": "<select id = \"selectPostIn\" resultType = \"domain.blog.Post\">\n SELECT *\n FROM POST P\n WHERE ID in\n\t\n <foreach item = \"item\" index = \"index\" collection = \"list\"\n open = \"(\" separator = \",\" close = \")\">\n #{item}\n </foreach>\n\t\n</select>" }, { "code": null, "e": 66764, "s": 66666, "text": "This is an example if using dynamic SQL. Consider, we have the following Student table in MySQL −" }, { "code": null, "e": 67050, "s": 66764, "text": "CREATE TABLE details.student(\n ID int(10) NOT NULL AUTO_INCREMENT,\n NAME varchar(100) NOT NULL,\n BRANCH varchar(255) NOT NULL,\n PERCENTAGE int(3) NOT NULL,\n PHONE int(11) NOT NULL,\n EMAIL varchar(255) NOT NULL,\n PRIMARY KEY (`ID`)\n);\nQuery OK, 0 rows affected (0.37 sec)\n" }, { "code": null, "e": 67095, "s": 67050, "text": "Let’s assume this table has two records as −" }, { "code": null, "e": 67601, "s": 67095, "text": "mysql> select * from student;\n+----+----------+--------+------------+-----------+----------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+-----------+----------------------+\n| 1 | Mohammad | It | 80 | 900000000 | [email protected] |\n| 2 | Shyam | It | 75 | 984800000 | [email protected] |\n+----+----------+--------+------------+-----------+----------------------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 67677, "s": 67601, "text": "To perform read operation, let us have a Student class in Student.java as −" }, { "code": null, "e": 68922, "s": 67677, "text": "public class Student {\n private int id;\n private String name;\n private String branch;\n private int percentage;\n private int phone;\n private String email;\n\n public Student(int id, String name, String branch, int percentage, int phone, String email) {\n super();\n this.id = id;\n this.name = name;\n this.branch = branch;\n this.percentage = percentage;\n this.phone = phone;\n this.email = email;\n }\n\t\n public Student() {}\n\n public int getId() {\n return id;\n }\n\t\n public void setId(int id) {\n this.id = id;\n }\n\t\n public String getName() {\n return name;\n }\n\t\n public void setName(String name) {\n this.name = name;\n }\n\t\n public int getPhone() {\n return phone;\n }\n\t\n public void setPhone(int phone) {\n this.phone = phone;\n }\n\t\n public String getEmail() {\n return email;\n }\n\t\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getBranch() {\n return branch;\n }\n\n public void setBranch(String branch) {\n this.branch = branch;\n }\n\n public int getPercentage() {\n return percentage;\n }\n\n public void setPercentage(int percentage) {\n this.percentage = percentage;\n }\t\n \n}" }, { "code": null, "e": 69125, "s": 68922, "text": "This file contains the result map named Student, to map the results of the SELECT Query. We will define an \"id\" which will be used in mybatisRead.java for executing Dynamic SQL SELECT query on database." }, { "code": null, "e": 69921, "s": 69125, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n&l;t!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n\t\n<mapper namespace = \"Student\">\t\n\n <resultMap id = \"result\" type = \"Student\">\n <result property = \"id\" column = \"ID\"/>\n <result property = \"name\" column = \"NAME\"/>\n <result property = \"branch\" column = \"BRANCH\"/>\n <result property = \"percentage\" column = \"PERCENTAGE\"/>\n <result property = \"phone\" column = \"PHONE\"/>\n <result property = \"email\" column = \"EMAIL\"/>\n </resultMap>\t \n\n <select id = \"getRecByName\" parameterType = \"Student\" resultType = \"Student\">\n SELECT * FROM STUDENT\t\t \n\t\t\n <if test = \"name != null\">\n WHERE name LIKE #{name}\n </if>\n\t\t\n </select>\n\t\n</mapper>" }, { "code": null, "e": 70012, "s": 69921, "text": "This file has application level logic to read conditional records from the Student table −" }, { "code": null, "e": 71631, "s": 70012, "text": "import java.io.IOException;\nimport java.io.Reader;\nimport java.util.List;\n\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.session.SqlSessionFactoryBuilder;\n\npublic class GetRecordByName { \n\n public static void main(String args[]) throws IOException{\n\t \n String req_name = \"Mohammad\";\n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession();\n Student stud = new Student();\n stud.setName(req_name);\n \n //select contact all contacts\t\t\n //List<Student> student = session.selectList(\"getRecByName\",stud);\n \n stud.setId(1);\n List<Student> student = session.selectList(\"getRecByName_Id\",stud);\n \n for(Student st : student ){ \t \n \t \t \n System.out.println(\"++++++++++++++details of the student named Mohammad are \"+\"+++++++++++++++++++\" );\n \t \n System.out.println(\"Id : \"+st.getId());\n System.out.println(\"Name : \"+st.getName());\n System.out.println(\"Branch : \"+st.getBranch());\n System.out.println(\"Percentage : \"+st.getPercentage()); \n System.out.println(\"Email : \"+st.getEmail()); \n System.out.println(\"Phone : \"+st.getPhone()); \t \n \t \n } \n \n System.out.println(\"Records Read Successfully \"); \n session.commit(); \n session.close();\t\t\t\n }\n}" }, { "code": null, "e": 71805, "s": 71631, "text": "Here are the steps to compile and run the above mentioned software. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution." }, { "code": null, "e": 71840, "s": 71805, "text": "Create Student.xml as shown above." }, { "code": null, "e": 71891, "s": 71840, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 71950, "s": 71891, "text": "Create GetRecordByName.java as shown above and compile it." }, { "code": null, "e": 72001, "s": 71950, "text": "Execute GetRecordByName binary to run the program." }, { "code": null, "e": 72088, "s": 72001, "text": "You would get the following result, and a record would be read from the Student table." }, { "code": null, "e": 72295, "s": 72088, "text": "++++++++++++++details of the student named Mohammad are +++++++++++++++++++\nId : 1\nName : Mohammad\nBranch : It\nPercentage : 80\nEmail : [email protected]\nPhone : 90000000\nRecords Read Successfully \n" }, { "code": null, "e": 72447, "s": 72295, "text": "There are major differences between MyBatis and Hibernate. Both the technologies work well, given their specific domain. MyBatis is suggested in case −" }, { "code": null, "e": 72519, "s": 72447, "text": "You want to create your own SQL's and you are willing to maintain them." }, { "code": null, "e": 72572, "s": 72519, "text": "Your environment is driven by relational data model." }, { "code": null, "e": 72622, "s": 72572, "text": "You have to work on existing and complex schemas." }, { "code": null, "e": 72723, "s": 72622, "text": "Use Hibernate, if the environment is driven by object model and needs to generate SQL automatically." }, { "code": null, "e": 72901, "s": 72723, "text": "Both Hibernate and MyBatis are open source Object Relational Mapping (ORM) tools available in the industry. Use of each of these tools depends on the context you are using them." }, { "code": null, "e": 72980, "s": 72901, "text": "The following table highlights the differences between MyBatis and Hibernate −" }, { "code": null, "e": 73102, "s": 72980, "text": "Hibernate and MyBatis both are compatible with the SPRING framework, so it should not be a problem to choose one of them." }, { "code": null, "e": 73109, "s": 73102, "text": " Print" }, { "code": null, "e": 73120, "s": 73109, "text": " Add Notes" } ]
Number of Islands in Python
Suppose we have a grid, there are few 0s and few 1s. We have to count the number of islands. An island is place that is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. We can assume that all four edges of the grid are all surrounded by water. Suppose the grid is like − There are three islands. To solve this, we will follow these steps − There will be two methods, one will be used to count number of islands called numIslands() and makeWater(). The makeWater() will be like − if number of rows in the grid is 0, then return 0 n = row count and m := column count, and ans := 0 for i in range 0 to n – 1for j in range 0 to mif grid[i, j] = 1, then ans := ans + 1makeWater(i, j, n, m, grid) for j in range 0 to mif grid[i, j] = 1, then ans := ans + 1makeWater(i, j, n, m, grid) if grid[i, j] = 1, then ans := ans + 1 makeWater(i, j, n, m, grid) the makeWater() will take the indices i, j, row and col count n and m, and grid if i <0 or j < 0 or i >= n or j >= m, then return from this method if grid[i, j] = 0, then return otherwise make grid[i, j] := 0 call makeWater(i + 1, j, n, m, grid) call makeWater(i, j + 1, n, m, grid) Let us see the following implementation to get better understanding − Live Demo class Solution(object): def numIslands(self, grid): if len(grid) == 0: return 0 n= len(grid) m = len(grid[0]) ans = 0 for i in range(n): for j in range(m): if grid[i][j] == "1": ans+=1 self.make_water(i,j,n,m,grid) return ans def make_water(self,i,j,n,m,grid): if i<0 or j<0 or i>=n or j>=m: return if grid[i][j] == "0": return else: grid[i][j]="0" self.make_water(i+1,j,n,m,grid) self.make_water(i,j+1,n,m,grid) self.make_water(i-1,j,n,m,grid) self.make_water(i,j-1,n,m,grid) ob1 = Solution() print(ob1.numIslands([["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"], ["0","0","0","1","1"]])) [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]] 3
[ { "code": null, "e": 1348, "s": 1062, "text": "Suppose we have a grid, there are few 0s and few 1s. We have to count the number of islands. An island is place that is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. We can assume that all four edges of the grid are all surrounded by water." }, { "code": null, "e": 1375, "s": 1348, "text": "Suppose the grid is like −" }, { "code": null, "e": 1400, "s": 1375, "text": "There are three islands." }, { "code": null, "e": 1444, "s": 1400, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1583, "s": 1444, "text": "There will be two methods, one will be used to count number of islands called numIslands() and makeWater(). The makeWater() will be like −" }, { "code": null, "e": 1633, "s": 1583, "text": "if number of rows in the grid is 0, then return 0" }, { "code": null, "e": 1683, "s": 1633, "text": "n = row count and m := column count, and ans := 0" }, { "code": null, "e": 1795, "s": 1683, "text": "for i in range 0 to n – 1for j in range 0 to mif grid[i, j] = 1, then ans := ans + 1makeWater(i, j, n, m, grid)" }, { "code": null, "e": 1882, "s": 1795, "text": "for j in range 0 to mif grid[i, j] = 1, then ans := ans + 1makeWater(i, j, n, m, grid)" }, { "code": null, "e": 1921, "s": 1882, "text": "if grid[i, j] = 1, then ans := ans + 1" }, { "code": null, "e": 1949, "s": 1921, "text": "makeWater(i, j, n, m, grid)" }, { "code": null, "e": 2029, "s": 1949, "text": "the makeWater() will take the indices i, j, row and col count n and m, and grid" }, { "code": null, "e": 2096, "s": 2029, "text": "if i <0 or j < 0 or i >= n or j >= m, then return from this method" }, { "code": null, "e": 2158, "s": 2096, "text": "if grid[i, j] = 0, then return otherwise make grid[i, j] := 0" }, { "code": null, "e": 2195, "s": 2158, "text": "call makeWater(i + 1, j, n, m, grid)" }, { "code": null, "e": 2232, "s": 2195, "text": "call makeWater(i, j + 1, n, m, grid)" }, { "code": null, "e": 2302, "s": 2232, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2313, "s": 2302, "text": " Live Demo" }, { "code": null, "e": 3089, "s": 2313, "text": "class Solution(object):\n def numIslands(self, grid):\n if len(grid) == 0:\n return 0\n n= len(grid)\n m = len(grid[0])\n ans = 0\n for i in range(n):\n for j in range(m):\n if grid[i][j] == \"1\":\n ans+=1\n self.make_water(i,j,n,m,grid)\n return ans\n def make_water(self,i,j,n,m,grid):\n if i<0 or j<0 or i>=n or j>=m:\n return\n if grid[i][j] == \"0\":\n return\n else:\n grid[i][j]=\"0\"\n self.make_water(i+1,j,n,m,grid)\n self.make_water(i,j+1,n,m,grid)\n self.make_water(i-1,j,n,m,grid)\n self.make_water(i,j-1,n,m,grid)\nob1 = Solution()\nprint(ob1.numIslands([[\"1\",\"1\",\"0\",\"0\",\"0\"],[\"1\",\"1\",\"0\",\"0\",\"0\"],[\"0\",\"0\",\"1\",\"0\",\"0\"],\n[\"0\",\"0\",\"0\",\"1\",\"1\"]]))" }, { "code": null, "e": 3179, "s": 3089, "text": "[[\"1\",\"1\",\"0\",\"0\",\"0\"],[\"1\",\"1\",\"0\",\"0\",\"0\"],[\"0\",\"0\",\"1\",\"0\",\"0\"],[\"0\",\"0\",\"0\",\"1\",\"1\"]]" }, { "code": null, "e": 3181, "s": 3179, "text": "3" } ]
strtoumax() function in C++ - GeeksforGeeks
31 Aug, 2018 The strtoumax() function in C++ interprets the contents of a string as an integral number of the specified base and return its value as an uintmax_t(maximum width unsigned integer). This function also sets an end pointer that points to the first character after the last valid numeric character of the string, if there is no such character then the pointer is set to null. The return value is set to garbage value when a negative number is entered as a string. This function is defined in cinttypes header file. Syntax: uintmax_t strtoumax(const char* str, char** end, int base) Parameter: The function accepts three mandatory parameters which are described below: str: specifies a string consist of an integral number. end: specifies a reference to object of type char*. The value of end is set by the function to the next character in str after the last valid numeric character. This parameter can also be a null pointer, in case if it is not used. base: specifies the numerical base (radix) that determines the valid characters and their interpretation in the string Return Type : The strtoimax() function returns two values which are described below: If valid conversion occur then the function returns the converted integral number as integer value. If no valid conversion could be performed and if the string includes minus sign with the corresponding integer number then the garbage value is returned by the function otherwise a zero value is returned (0) Below programs illustrate the above function: Program 1 : // C++ program to illustrate the// strtoumax() function#include <iostream>#include<cinttypes>#include<cstring> using namespace std; // Driver codeint main(){ int base = 10; char str[] = "999999abcdefg"; char* end; uintmax_t num; num = strtoumax(str, &end, base); cout << "Given String = " << str << endl; cout << "Number with base 10 in string " << num << endl; cout << "End String points to " << end << endl << endl; // in this case the end pointer points to null // here base change to char16 base = 2; strcpy(str, "10010"); cout << "Given String = " << str << endl; num = strtoumax(str, &end, base); cout << "Number with base 2 in string " << num << endl; if (*end) { cout << end; } else { cout << "Null pointer"; } return 0;} Given String = 999999abcdefg Number with base 10 in string 999999 End String points to abcdefg Given String = 10010 Number with base 2 in string 18 Null pointer Program 2 : // C++ program to illustrate the// strtoumax() function#include <iostream>#include<cinttypes>#include<cstring> using namespace std; // Driver codeint main(){ int base = 10; char str[] = "-10000"; char* end; uintmax_t num; // if negative value is converted then it gives garbage value num = strtoumax(str, &end, base); cout << "Given String = " << str << endl; cout << "Garbage value stored in num " << num << endl; if (*end) { cout << "End String points to " << end; } else { cout << "Null pointer" << endl << endl; } // in this case no numeric character is there // so the function returns 0 base = 10; strcpy(str, "abcd"); cout << "Given String = " << str << endl; num = strtoumax(str, &end, base); cout << "Number with base 10 in string " << num << endl; if (*end) { cout << "End String points to " << end; } else { cout << "Null pointer"; } return 0;} Given String = -10000 Garbage value stored in num 18446744073709541616 Null pointer Given String = abcd Number with base 10 in string 0 End String points to abcd CPP-Functions STL C Language C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C Arrow operator -> in C/C++ with Examples 'this' pointer in C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Inheritance in C++ Constructors in C++
[ { "code": null, "e": 23817, "s": 23789, "text": "\n31 Aug, 2018" }, { "code": null, "e": 24329, "s": 23817, "text": "The strtoumax() function in C++ interprets the contents of a string as an integral number of the specified base and return its value as an uintmax_t(maximum width unsigned integer). This function also sets an end pointer that points to the first character after the last valid numeric character of the string, if there is no such character then the pointer is set to null. The return value is set to garbage value when a negative number is entered as a string. This function is defined in cinttypes header file." }, { "code": null, "e": 24337, "s": 24329, "text": "Syntax:" }, { "code": null, "e": 24396, "s": 24337, "text": "uintmax_t strtoumax(const char* str, char** end, int base)" }, { "code": null, "e": 24482, "s": 24396, "text": "Parameter: The function accepts three mandatory parameters which are described below:" }, { "code": null, "e": 24537, "s": 24482, "text": "str: specifies a string consist of an integral number." }, { "code": null, "e": 24768, "s": 24537, "text": "end: specifies a reference to object of type char*. The value of end is set by the function to the next character in str after the last valid numeric character. This parameter can also be a null pointer, in case if it is not used." }, { "code": null, "e": 24887, "s": 24768, "text": "base: specifies the numerical base (radix) that determines the valid characters and their interpretation in the string" }, { "code": null, "e": 24972, "s": 24887, "text": "Return Type : The strtoimax() function returns two values which are described below:" }, { "code": null, "e": 25072, "s": 24972, "text": "If valid conversion occur then the function returns the converted integral number as integer value." }, { "code": null, "e": 25280, "s": 25072, "text": "If no valid conversion could be performed and if the string includes minus sign with the corresponding integer number then the garbage value is returned by the function otherwise a zero value is returned (0)" }, { "code": null, "e": 25326, "s": 25280, "text": "Below programs illustrate the above function:" }, { "code": null, "e": 25338, "s": 25326, "text": "Program 1 :" }, { "code": "// C++ program to illustrate the// strtoumax() function#include <iostream>#include<cinttypes>#include<cstring> using namespace std; // Driver codeint main(){ int base = 10; char str[] = \"999999abcdefg\"; char* end; uintmax_t num; num = strtoumax(str, &end, base); cout << \"Given String = \" << str << endl; cout << \"Number with base 10 in string \" << num << endl; cout << \"End String points to \" << end << endl << endl; // in this case the end pointer points to null // here base change to char16 base = 2; strcpy(str, \"10010\"); cout << \"Given String = \" << str << endl; num = strtoumax(str, &end, base); cout << \"Number with base 2 in string \" << num << endl; if (*end) { cout << end; } else { cout << \"Null pointer\"; } return 0;}", "e": 26156, "s": 25338, "text": null }, { "code": null, "e": 26319, "s": 26156, "text": "Given String = 999999abcdefg\nNumber with base 10 in string 999999\nEnd String points to abcdefg\n\nGiven String = 10010\nNumber with base 2 in string 18\nNull pointer\n" }, { "code": null, "e": 26331, "s": 26319, "text": "Program 2 :" }, { "code": "// C++ program to illustrate the// strtoumax() function#include <iostream>#include<cinttypes>#include<cstring> using namespace std; // Driver codeint main(){ int base = 10; char str[] = \"-10000\"; char* end; uintmax_t num; // if negative value is converted then it gives garbage value num = strtoumax(str, &end, base); cout << \"Given String = \" << str << endl; cout << \"Garbage value stored in num \" << num << endl; if (*end) { cout << \"End String points to \" << end; } else { cout << \"Null pointer\" << endl << endl; } // in this case no numeric character is there // so the function returns 0 base = 10; strcpy(str, \"abcd\"); cout << \"Given String = \" << str << endl; num = strtoumax(str, &end, base); cout << \"Number with base 10 in string \" << num << endl; if (*end) { cout << \"End String points to \" << end; } else { cout << \"Null pointer\"; } return 0;}", "e": 27303, "s": 26331, "text": null }, { "code": null, "e": 27467, "s": 27303, "text": "Given String = -10000\nGarbage value stored in num 18446744073709541616\nNull pointer\n\nGiven String = abcd\nNumber with base 10 in string 0\nEnd String points to abcd\n" }, { "code": null, "e": 27481, "s": 27467, "text": "CPP-Functions" }, { "code": null, "e": 27485, "s": 27481, "text": "STL" }, { "code": null, "e": 27496, "s": 27485, "text": "C Language" }, { "code": null, "e": 27500, "s": 27496, "text": "C++" }, { "code": null, "e": 27504, "s": 27500, "text": "STL" }, { "code": null, "e": 27508, "s": 27504, "text": "CPP" }, { "code": null, "e": 27606, "s": 27508, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27615, "s": 27606, "text": "Comments" }, { "code": null, "e": 27628, "s": 27615, "text": "Old Comments" }, { "code": null, "e": 27666, "s": 27628, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27692, "s": 27666, "text": "Exception Handling in C++" }, { "code": null, "e": 27712, "s": 27692, "text": "Multithreading in C" }, { "code": null, "e": 27753, "s": 27712, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27775, "s": 27753, "text": "'this' pointer in C++" }, { "code": null, "e": 27793, "s": 27775, "text": "Vector in C++ STL" }, { "code": null, "e": 27839, "s": 27793, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 27882, "s": 27839, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 27901, "s": 27882, "text": "Inheritance in C++" } ]
Ways to copy a vector in C++
There are different ways to copy a vector in C++. std:: copy is inbuilt to copy the elements from one vector to another. std::copy(first_iterator_o, last_iterator_o, back_inserter()): first_iteratot_0 = First iterator of first vector. last_iteratot_0 = Last iterator of first vector. back_inserter() = To insert values from back. Begin Declare v1 of vector type. Initialize some values into v1 vector in array pattern. Declare v2 of vector type. Call copy(v1.begin(), v1.end(), back_inserter(v2)) to copy all elements of v1 to v2. Print “v1 vector elements are :”. for (int i=0;i<1.size; i++) print the all element of v2 vector. Print “v2 vector elements are :”. for (int i=0;i<2.size; i++) print the all element of v2 vector. End. Live Demo #include<iostream> #include<vector> #include<algorithm> // for copy. #include<iterator> // for back_inserter using namespace std; int main() { vector<int> v1{ 7, 6, 4, 5 }; vector<int> v2; copy(v1.begin(), v1.end(), back_inserter(v2)); cout << "v1 vector elements are : "; for (int i=0; i<v1.size(); i++) cout << v1[i] << " "; cout << endl; cout << "v2 vector elements are : "; for (int i=0; i<v2.size(); i++) cout << v2[i] << " "; cout<< endl; return 0; } v1 vector elements are : 7 6 4 5 v2 vector elements are : 7 6 4 5 This is also used to copy values from vector 1 to vector 2. std::assign(first_iterator_o, last_iterator_o): first_iteratot_0 = First iterator of first vector. last_iteratot_0 = Last iterator of first vector. Begin Initialize a vector v1 with its elements. Declare another vector v2. Call assign() to copy the elements of v1 to v2. Print the elements of v1. Print the elements of v2. End. Live Demo #include<iostream> #include<vector> // for vector #include<iostream> #include<vector>// for vector #include<algorithm>// for copy() and assign() #include<iterator>// for back_inserter using namespace std; int main() { vector<int> v1{7,6,4,5}; vector<int> v2; v2.assign(v1.begin(), v1.end()); cout << "v1 vector elements are : "; for (int i=0; i<v1.size(); i++) cout << v1[i] << " "; cout << endl; cout << "v2 vector elements are : "; for (int i=0; i<v2.size(); i++) cout << v2[i] << " "; cout<< endl; return 0; } v1 vector elements are : 7 6 4 5 v2 vector elements are : 7 6 4 5 It is a simple way to copy values from vector 1 to vector 2 Begin Initialize a vector v1 with its elements. Declare another vector v2. Call assignment operator “=” to copy the elements of v1 to v2. Print the elements of v1. Print the elements of v2. End. Live Demo #include<iostream> #include<vector> // for vector #include<algorithm>// for copy() and assign() #include<iterator>// for back_inserter using namespace std; int main() { vector<int> v1{7,6,4,5}; vector<int> v2; v2 = v1 ; cout << "v1 vector elements are : "; for (int i=0; i<v1.size(); i++) cout << v1[i] << " "; cout << endl; cout << "v2 vector elements are : "; for (int i=0; i<v2.size(); i++) cout << v2[i] << " "; cout<< endl; return 0; } v1 vector elements are : 7 6 4 5 v2 vector elements are : 7 6 4 5 Begin Initialize a vector v1 with its elements. Declare another vector v2. Make a for loop to copy elements of first vector into second vector by Iterative method using push_back(). Print the elements of v1. Print the elements of v2. End. Live Demo #include<iostream> #include<vector> // for vector #include<iostream> #include<vector>// for vector #include<algorithm>// for copy() and assign() #include<iterator>// for back_inserter using namespace std; int main() { vector<int> v1{7,6,4,5}; vector<int> v2; for (int i=0; i<v1.size(); i++) v2.push_back(v1[i]); cout << "v1 vector elements are : "; for (int i=0; i<v1.size(); i++) cout << v1[i] << " "; cout << endl; cout << "v2 vector elements are : "; for (int i=0; i<v2.size(); i++) cout << v2[i] << " "; cout<< endl; return 0; } v1 vector elements are : 7 6 4 5 v2 vector elements are : 7 6 4 5 Begin Initialize a vector v1 with its elements. Declare another vector v2 and copying elements of first vector to second vector using constructor method and they are deeply copied. Print the elements of v1. Print the elements of v2. End. Live Demo #include<iostream> #include<vector>// for vector #include<algorithm>// for copy() and assign() #include<iterator>// for back_inserter using namespace std; int main() { vector<int> v1{7,6,4,5}; vector<int> v2(v1); cout << "v1 vector elements are : "; for (int i=0; i<v1.size(); i++) cout << v1[i] << " "; cout << endl; cout << "v2 vector elements are : "; for (int i=0; i<v2.size(); i++) cout << v2[i] << " "; cout<< endl; return 0; } v1 vector elements are : 7 6 4 5 v2 vector elements are : 7 6 4 5
[ { "code": null, "e": 1112, "s": 1062, "text": "There are different ways to copy a vector in C++." }, { "code": null, "e": 1183, "s": 1112, "text": "std:: copy is inbuilt to copy the elements from one vector to another." }, { "code": null, "e": 1392, "s": 1183, "text": "std::copy(first_iterator_o, last_iterator_o, back_inserter()):\nfirst_iteratot_0 = First iterator of first vector.\nlast_iteratot_0 = Last iterator of first vector.\nback_inserter() = To insert values from back." }, { "code": null, "e": 1836, "s": 1392, "text": "Begin\n Declare v1 of vector type.\n Initialize some values into v1 vector in array pattern.\n Declare v2 of vector type.\n Call copy(v1.begin(), v1.end(), back_inserter(v2)) to copy all\n elements of v1 to v2.\n Print “v1 vector elements are :”.\n for (int i=0;i<1.size; i++)\n print the all element of v2 vector.\n Print “v2 vector elements are :”.\n for (int i=0;i<2.size; i++)\n print the all element of v2 vector.\nEnd." }, { "code": null, "e": 1847, "s": 1836, "text": " Live Demo" }, { "code": null, "e": 2355, "s": 1847, "text": "#include<iostream>\n#include<vector>\n#include<algorithm> // for copy.\n#include<iterator> // for back_inserter\nusing namespace std;\nint main() {\n vector<int> v1{ 7, 6, 4, 5 };\n vector<int> v2;\n copy(v1.begin(), v1.end(), back_inserter(v2));\n cout << \"v1 vector elements are : \";\n for (int i=0; i<v1.size(); i++)\n cout << v1[i] << \" \";\n cout << endl;\n cout << \"v2 vector elements are : \";\n for (int i=0; i<v2.size(); i++)\n cout << v2[i] << \" \";\n cout<< endl;\n return 0;\n}" }, { "code": null, "e": 2421, "s": 2355, "text": "v1 vector elements are : 7 6 4 5\nv2 vector elements are : 7 6 4 5" }, { "code": null, "e": 2481, "s": 2421, "text": "This is also used to copy values from vector 1 to vector 2." }, { "code": null, "e": 2629, "s": 2481, "text": "std::assign(first_iterator_o, last_iterator_o):\nfirst_iteratot_0 = First iterator of first vector.\nlast_iteratot_0 = Last iterator of first vector." }, { "code": null, "e": 2824, "s": 2629, "text": "Begin\n Initialize a vector v1 with its elements.\n Declare another vector v2.\n Call assign() to copy the elements of v1 to v2.\n Print the elements of v1.\n Print the elements of v2.\nEnd." }, { "code": null, "e": 2835, "s": 2824, "text": " Live Demo" }, { "code": null, "e": 3399, "s": 2835, "text": "#include<iostream> #include<vector> // for vector #include<iostream>\n#include<vector>// for vector\n#include<algorithm>// for copy() and assign()\n#include<iterator>// for back_inserter\nusing namespace std;\nint main() {\n vector<int> v1{7,6,4,5};\n vector<int> v2;\n v2.assign(v1.begin(), v1.end());\n cout << \"v1 vector elements are : \";\n for (int i=0; i<v1.size(); i++)\n cout << v1[i] << \" \";\n cout << endl;\n cout << \"v2 vector elements are : \";\n for (int i=0; i<v2.size(); i++)\n cout << v2[i] << \" \";\n cout<< endl;\n return 0;\n}" }, { "code": null, "e": 3465, "s": 3399, "text": "v1 vector elements are : 7 6 4 5 v2 vector elements are : 7 6 4 5" }, { "code": null, "e": 3525, "s": 3465, "text": "It is a simple way to copy values from vector 1 to vector 2" }, { "code": null, "e": 3735, "s": 3525, "text": "Begin\n Initialize a vector v1 with its elements.\n Declare another vector v2.\n Call assignment operator “=” to copy the elements of v1 to v2.\n Print the elements of v1.\n Print the elements of v2.\nEnd." }, { "code": null, "e": 3746, "s": 3735, "text": " Live Demo" }, { "code": null, "e": 4238, "s": 3746, "text": "#include<iostream>\n#include<vector> // for vector\n#include<algorithm>// for copy() and assign()\n#include<iterator>// for back_inserter\nusing namespace std;\nint main() {\n vector<int> v1{7,6,4,5};\n vector<int> v2;\n v2 = v1 ;\n cout << \"v1 vector elements are : \";\n for (int i=0; i<v1.size(); i++)\n cout << v1[i] << \" \";\n cout << endl;\n cout << \"v2 vector elements are : \";\n for (int i=0; i<v2.size(); i++)\n cout << v2[i] << \" \";\n cout<< endl;\n return 0;\n}" }, { "code": null, "e": 4304, "s": 4238, "text": "v1 vector elements are : 7 6 4 5\nv2 vector elements are : 7 6 4 5" }, { "code": null, "e": 4558, "s": 4304, "text": "Begin\n Initialize a vector v1 with its elements.\n Declare another vector v2.\n Make a for loop to copy elements of first vector into second vector by Iterative method using push_back().\n Print the elements of v1.\n Print the elements of v2.\nEnd." }, { "code": null, "e": 4569, "s": 4558, "text": " Live Demo" }, { "code": null, "e": 5162, "s": 4569, "text": "#include<iostream> #include<vector> // for vector\n#include<iostream>\n#include<vector>// for vector\n#include<algorithm>// for copy() and assign()\n#include<iterator>// for back_inserter\nusing namespace std;\nint main() {\n vector<int> v1{7,6,4,5};\n vector<int> v2;\n for (int i=0; i<v1.size(); i++)\n v2.push_back(v1[i]);\n cout << \"v1 vector elements are : \";\n for (int i=0; i<v1.size(); i++)\n cout << v1[i] << \" \";\n cout << endl;\n cout << \"v2 vector elements are : \";\n for (int i=0; i<v2.size(); i++)\n cout << v2[i] << \" \";\n cout<< endl;\n return 0;\n}" }, { "code": null, "e": 5228, "s": 5162, "text": "v1 vector elements are : 7 6 4 5\nv2 vector elements are : 7 6 4 5" }, { "code": null, "e": 5478, "s": 5228, "text": "Begin\n Initialize a vector v1 with its elements.\n Declare another vector v2 and copying elements of first vector to second vector using constructor method and they are deeply copied.\n Print the elements of v1.\n Print the elements of v2.\nEnd." }, { "code": null, "e": 5489, "s": 5478, "text": " Live Demo" }, { "code": null, "e": 5971, "s": 5489, "text": "#include<iostream>\n#include<vector>// for vector\n#include<algorithm>// for copy() and assign()\n#include<iterator>// for back_inserter\nusing namespace std;\nint main() {\n vector<int> v1{7,6,4,5};\n vector<int> v2(v1);\n cout << \"v1 vector elements are : \";\n for (int i=0; i<v1.size(); i++)\n cout << v1[i] << \" \";\n cout << endl;\n cout << \"v2 vector elements are : \";\n for (int i=0; i<v2.size(); i++)\n cout << v2[i] << \" \";\n cout<< endl;\n return 0;\n}" }, { "code": null, "e": 6037, "s": 5971, "text": "v1 vector elements are : 7 6 4 5\nv2 vector elements are : 7 6 4 5" } ]
General Aptitude - GeeksforGeeks
22 Jan, 2014 Profit = Price - Cost = 50q - 5q2 The above function will be maximum for the values on which its first derivative becomes 0. 50 - 10*q = 0 50 = 10 * q q = 5. The value of above expression is maximum at q = 5. Probability that the absorber is reliable = 0.96*0.6 + 0.72*0.4 = 0.576 + 0.288 Probability that the absorber is from y and reliable = (Probability that is made by Y) X (Probability that it is reliable) = 0.4 * 0.72 = 0.288 The probability that randomly picked reliable absorber is from y = (Probability that the absorber is from y and reliable) / (>Probability that the absorber is reliable ) = (0.288)/ (0.576 + 0.288) = 0.334 Let us consider below example These eight data points have the mean (average) of 5: When we add 7 to all numbers, mean becomes 12 so P is TRUE. If we double all numbers mean becomes double, so R is also TRUE. Standard Deviation is square root of variance. Variance is sum of squares of differences between all numbers and means. Deviation for above example First, calculate the deviations of each data point from the mean, and square the result of each: If we add 7 to all numbers, standard deviation won't change as 7 is added to mean also. So Q is FALSE. If we double all entries, standard deviation also becomes double. So S is false. It is given that Log(P) = (1/2)Log(Q) = (1/3)Log(R) Let Log(P) = (1/2)Log(Q) = (1/3)Log(R) = C Let the base of log be B P = BC Q = B2C R = B3C Which means Q2 = PR Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Must Do Coding Questions for Product Based Companies SQL Query to Convert VARCHAR to INT How to Update Multiple Columns in Single Update Statement in SQL? Difference between var, let and const keywords in JavaScript Array of Objects in C++ with Examples How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python C Program to read contents of Whole File Insert Image in a Jupyter Notebook How to Replace Values in a List in Python?
[ { "code": null, "e": 27530, "s": 27502, "text": "\n22 Jan, 2014" }, { "code": null, "e": 27771, "s": 27530, "text": "Profit = Price - Cost\n = 50q - 5q2\nThe above function will be maximum for the values on which its first derivative becomes 0.\n 50 - 10*q = 0\n 50 = 10 * q\n q = 5.\nThe value of above expression is maximum at q = 5. " }, { "code": null, "e": 28299, "s": 27771, "text": "Probability that the absorber is reliable = 0.96*0.6 + 0.72*0.4 \n = 0.576 + 0.288\n\n\nProbability that the absorber is from y and reliable = \n (Probability that is made by Y) X (Probability that it is reliable)\n = 0.4 * 0.72 \n = 0.288\n\nThe probability that randomly picked reliable absorber is from y = \n (Probability that the absorber is from y and reliable) / (>Probability that the absorber is reliable )\n = (0.288)/ (0.576 + 0.288) \n = 0.334 " }, { "code": null, "e": 28957, "s": 28299, "text": "Let us consider below example\n\n\nThese eight data points have the mean (average) of 5:\n\n\nWhen we add 7 to all numbers, mean becomes 12 so P is TRUE.\n\nIf we double all numbers mean becomes double, so R is also\nTRUE.\n\nStandard Deviation is square root of variance.\nVariance is sum of squares of differences between all numbers\nand means.\n\nDeviation for above example\nFirst, calculate the deviations of each data point from the mean, \nand square the result of each:\n\n\n\n\n\n\n\nIf we add 7 to all numbers, standard deviation won't change \nas 7 is added to mean also. So Q is FALSE.\n\nIf we double all entries, standard deviation also becomes \ndouble. So S is false. " }, { "code": null, "e": 29124, "s": 28957, "text": "It is given that Log(P) = (1/2)Log(Q) = (1/3)Log(R)\n\nLet Log(P) = (1/2)Log(Q) = (1/3)Log(R) = C\n\nLet the base of log be B\n\nP = BC\nQ = B2C\nR = B3C\n\nWhich means Q2 = PR" }, { "code": null, "e": 29222, "s": 29124, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 29231, "s": 29222, "text": "Comments" }, { "code": null, "e": 29244, "s": 29231, "text": "Old Comments" }, { "code": null, "e": 29297, "s": 29244, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 29333, "s": 29297, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 29399, "s": 29333, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 29460, "s": 29399, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29498, "s": 29460, "text": "Array of Objects in C++ with Examples" }, { "code": null, "e": 29560, "s": 29498, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 29640, "s": 29560, "text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python" }, { "code": null, "e": 29681, "s": 29640, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 29716, "s": 29681, "text": "Insert Image in a Jupyter Notebook" } ]
Intellij Idea - Create First Java Project
It is time we got a hands-on experience with IntelliJ. In this chapter, we will create our first Java Project. We will write and execute the traditional Hello World program. This chapter explains the compilation and running of Java application. For anything related to development, a developer has to create a new project with IntelliJ. Let us follow these steps to create a project − Launch IntelliJ. Launch IntelliJ. Go to File → New → Project menu. Go to File → New → Project menu. Select the Java project and appropriate SDK and click on the Next button. Select the Java project and appropriate SDK and click on the Next button. If you want to create a Java class with the main method, then select Create Project from the template checkbox. If you want to create a Java class with the main method, then select Create Project from the template checkbox. Select the command line app from the dialog box shown below and continue. Select the command line app from the dialog box shown below and continue. Enter the project name and the directory location. Enter the project name and the directory location. Click on the Finish button. Click on the Finish button. A package is created under Java project and can be created separately, or at the same time of creating a class. Let us follow these steps to create a package − Go to the project perspective. Go to the project perspective. Right-click on Project, select the New->Module option. Right-click on Project, select the New->Module option. The new module window will be similar to the new project. Select the Java option and appropriate SDK and click on the Next button. The new module window will be similar to the new project. Select the Java option and appropriate SDK and click on the Next button. Enter the module name. Enter the module name. Click on the Finish button. Click on the Finish button. In this section, we will learn how to create a Java class. A Java class can be created under a Java module. Follow these steps to create a module − Go to the Project perspective. Go to the Project perspective. Expand Project and select the src directory from the module. Expand Project and select the src directory from the module. Right click on it; select the New->Java Class option. Right click on it; select the New->Java Class option. Enter the class name in the dialog-box and click on the OK button. Enter the class name in the dialog-box and click on the OK button. It will open the Editor window with the class declaration. It will open the Editor window with the class declaration. We will now see how to run a Java application. Follow these steps and see how it runs − Let us write a simple code, which will print a message on the console. Enter the following code in the Editor window − Let us write a simple code, which will print a message on the console. Enter the following code in the Editor window − public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World !!!"); } } Go to the Run menu and select the Run option. Go to the Run menu and select the Run option. Select the Class name and click on Run. Select the Class name and click on Run. If there are no compilation errors, then it will show output at the bottom of the window. If there are no compilation errors, then it will show output at the bottom of the window. Print Add Notes Bookmark this page
[ { "code": null, "e": 2334, "s": 2089, "text": "It is time we got a hands-on experience with IntelliJ. In this chapter, we will create our first Java Project. We will write and execute the traditional Hello World program. This chapter explains the compilation and running of Java application." }, { "code": null, "e": 2474, "s": 2334, "text": "For anything related to development, a developer has to create a new project with IntelliJ. Let us follow these steps to create a project −" }, { "code": null, "e": 2491, "s": 2474, "text": "Launch IntelliJ." }, { "code": null, "e": 2508, "s": 2491, "text": "Launch IntelliJ." }, { "code": null, "e": 2541, "s": 2508, "text": "Go to File → New → Project menu." }, { "code": null, "e": 2574, "s": 2541, "text": "Go to File → New → Project menu." }, { "code": null, "e": 2648, "s": 2574, "text": "Select the Java project and appropriate SDK and click on the Next button." }, { "code": null, "e": 2722, "s": 2648, "text": "Select the Java project and appropriate SDK and click on the Next button." }, { "code": null, "e": 2834, "s": 2722, "text": "If you want to create a Java class with the main method, then select Create Project from the template checkbox." }, { "code": null, "e": 2946, "s": 2834, "text": "If you want to create a Java class with the main method, then select Create Project from the template checkbox." }, { "code": null, "e": 3020, "s": 2946, "text": "Select the command line app from the dialog box shown below and continue." }, { "code": null, "e": 3094, "s": 3020, "text": "Select the command line app from the dialog box shown below and continue." }, { "code": null, "e": 3145, "s": 3094, "text": "Enter the project name and the directory location." }, { "code": null, "e": 3196, "s": 3145, "text": "Enter the project name and the directory location." }, { "code": null, "e": 3224, "s": 3196, "text": "Click on the Finish button." }, { "code": null, "e": 3252, "s": 3224, "text": "Click on the Finish button." }, { "code": null, "e": 3412, "s": 3252, "text": "A package is created under Java project and can be created separately, or at the same time of creating a class. Let us follow these steps to create a package −" }, { "code": null, "e": 3443, "s": 3412, "text": "Go to the project perspective." }, { "code": null, "e": 3474, "s": 3443, "text": "Go to the project perspective." }, { "code": null, "e": 3529, "s": 3474, "text": "Right-click on Project, select the New->Module option." }, { "code": null, "e": 3584, "s": 3529, "text": "Right-click on Project, select the New->Module option." }, { "code": null, "e": 3715, "s": 3584, "text": "The new module window will be similar to the new project. Select the Java option and appropriate SDK and click on the Next button." }, { "code": null, "e": 3846, "s": 3715, "text": "The new module window will be similar to the new project. Select the Java option and appropriate SDK and click on the Next button." }, { "code": null, "e": 3869, "s": 3846, "text": "Enter the module name." }, { "code": null, "e": 3892, "s": 3869, "text": "Enter the module name." }, { "code": null, "e": 3920, "s": 3892, "text": "Click on the Finish button." }, { "code": null, "e": 3948, "s": 3920, "text": "Click on the Finish button." }, { "code": null, "e": 4096, "s": 3948, "text": "In this section, we will learn how to create a Java class. A Java class can be created under a Java module. Follow these steps to create a module −" }, { "code": null, "e": 4127, "s": 4096, "text": "Go to the Project perspective." }, { "code": null, "e": 4158, "s": 4127, "text": "Go to the Project perspective." }, { "code": null, "e": 4219, "s": 4158, "text": "Expand Project and select the src directory from the module." }, { "code": null, "e": 4280, "s": 4219, "text": "Expand Project and select the src directory from the module." }, { "code": null, "e": 4334, "s": 4280, "text": "Right click on it; select the New->Java Class option." }, { "code": null, "e": 4388, "s": 4334, "text": "Right click on it; select the New->Java Class option." }, { "code": null, "e": 4455, "s": 4388, "text": "Enter the class name in the dialog-box and click on the OK button." }, { "code": null, "e": 4522, "s": 4455, "text": "Enter the class name in the dialog-box and click on the OK button." }, { "code": null, "e": 4581, "s": 4522, "text": "It will open the Editor window with the class declaration." }, { "code": null, "e": 4640, "s": 4581, "text": "It will open the Editor window with the class declaration." }, { "code": null, "e": 4728, "s": 4640, "text": "We will now see how to run a Java application. Follow these steps and see how it runs −" }, { "code": null, "e": 4847, "s": 4728, "text": "Let us write a simple code, which will print a message on the console. Enter the following code in the Editor window −" }, { "code": null, "e": 4966, "s": 4847, "text": "Let us write a simple code, which will print a message on the console. Enter the following code in the Editor window −" }, { "code": null, "e": 5093, "s": 4966, "text": "public class HelloWorld { \n public static void main(String[] args) { \n System.out.println(\"Hello, World !!!\"); \n } \n}" }, { "code": null, "e": 5139, "s": 5093, "text": "Go to the Run menu and select the Run option." }, { "code": null, "e": 5185, "s": 5139, "text": "Go to the Run menu and select the Run option." }, { "code": null, "e": 5225, "s": 5185, "text": "Select the Class name and click on Run." }, { "code": null, "e": 5265, "s": 5225, "text": "Select the Class name and click on Run." }, { "code": null, "e": 5355, "s": 5265, "text": "If there are no compilation errors, then it will show output at the bottom of the window." }, { "code": null, "e": 5445, "s": 5355, "text": "If there are no compilation errors, then it will show output at the bottom of the window." }, { "code": null, "e": 5452, "s": 5445, "text": " Print" }, { "code": null, "e": 5463, "s": 5452, "text": " Add Notes" } ]
Check if a string is Isogram or not in Python
Suppose we have a string s. We have to check whether the given string is isogram or not. The isogram is a string where the occurrence of each letter is exactly one. So, if the input is like s = "education", then the output will be True because all characters in "education" occurs exactly once. To solve this, we will follow these steps − char_list := a new list for each char in word, doif char is non numeric, thenif char is in char_list, thenreturn Falseinsert char at the end of char_list if char is non numeric, thenif char is in char_list, thenreturn Falseinsert char at the end of char_list if char is in char_list, thenreturn False return False insert char at the end of char_list return True Let us see the following implementation to get better understanding − Live Demo def solve(word): char_list = [] for char in word: if char.isalpha(): if char in char_list: return False char_list.append(char) return True s = "education" print(solve(s)) "education" True
[ { "code": null, "e": 1227, "s": 1062, "text": "Suppose we have a string s. We have to check whether the given string is isogram or not. The isogram is a string where the occurrence of each letter is exactly one." }, { "code": null, "e": 1357, "s": 1227, "text": "So, if the input is like s = \"education\", then the output will be True because all characters in \"education\" occurs exactly once." }, { "code": null, "e": 1401, "s": 1357, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1425, "s": 1401, "text": "char_list := a new list" }, { "code": null, "e": 1555, "s": 1425, "text": "for each char in word, doif char is non numeric, thenif char is in char_list, thenreturn Falseinsert char at the end of char_list" }, { "code": null, "e": 1660, "s": 1555, "text": "if char is non numeric, thenif char is in char_list, thenreturn Falseinsert char at the end of char_list" }, { "code": null, "e": 1702, "s": 1660, "text": "if char is in char_list, thenreturn False" }, { "code": null, "e": 1715, "s": 1702, "text": "return False" }, { "code": null, "e": 1751, "s": 1715, "text": "insert char at the end of char_list" }, { "code": null, "e": 1763, "s": 1751, "text": "return True" }, { "code": null, "e": 1833, "s": 1763, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1844, "s": 1833, "text": " Live Demo" }, { "code": null, "e": 2063, "s": 1844, "text": "def solve(word):\n char_list = []\n for char in word:\n if char.isalpha():\n if char in char_list:\n return False\n char_list.append(char)\n return True\ns = \"education\"\nprint(solve(s))" }, { "code": null, "e": 2075, "s": 2063, "text": "\"education\"" }, { "code": null, "e": 2080, "s": 2075, "text": "True" } ]
HTTP headers | Referer - GeeksforGeeks
22 Nov, 2019 The HTTP Referer header is a request-type header that identifies the address of the previous web page, which is linked to the current web page or resource being requested. The usage of this header increases the risk of privacy and security breaches on a website but it allows websites and web servers to identify where the traffic is coming from. The Referer can not be sent by the browsers if the resource is the local file or data. Syntax: Referer: <url> Directives: The HTTP Referer header accepts a single directive as mentioned above and described below: <url>: This directive is the address(partial or full) of the previous World Wide Web page which was followed by a link to the currently requested page. Below examples illustrates the HTTP Referer header: Examples: In this example, geeksforgeeks.org is the address of the previous web page.Referer: https://www.geeksforgeeks.org/ Referer: https://www.geeksforgeeks.org/ In this example, google.com is the address of the previous web page.Referer: https://www.google.com/ Referer: https://www.google.com/ To check the Referer in action go to Inspect Element -> Network check the request header for Referer like below. Referer header is highlighted.Supported Browsers: The browsers are compatible with HTTP header Referer are listed below: Google Chrome Internet Explorer Microsoft Edge Firefox Opera Safari HTTP-headers Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Front End Developer Skills That You Need in 2022 How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to set the default value for an HTML <select> element ? How to create footer to stay at the bottom of a Web page? Node.js fs.readFileSync() Method How to set input type date in dd-mm-yyyy format using HTML ? File uploading in React.js
[ { "code": null, "e": 24195, "s": 24167, "text": "\n22 Nov, 2019" }, { "code": null, "e": 24629, "s": 24195, "text": "The HTTP Referer header is a request-type header that identifies the address of the previous web page, which is linked to the current web page or resource being requested. The usage of this header increases the risk of privacy and security breaches on a website but it allows websites and web servers to identify where the traffic is coming from. The Referer can not be sent by the browsers if the resource is the local file or data." }, { "code": null, "e": 24637, "s": 24629, "text": "Syntax:" }, { "code": null, "e": 24652, "s": 24637, "text": "Referer: <url>" }, { "code": null, "e": 24755, "s": 24652, "text": "Directives: The HTTP Referer header accepts a single directive as mentioned above and described below:" }, { "code": null, "e": 24907, "s": 24755, "text": "<url>: This directive is the address(partial or full) of the previous World Wide Web page which was followed by a link to the currently requested page." }, { "code": null, "e": 24959, "s": 24907, "text": "Below examples illustrates the HTTP Referer header:" }, { "code": null, "e": 24969, "s": 24959, "text": "Examples:" }, { "code": null, "e": 25084, "s": 24969, "text": "In this example, geeksforgeeks.org is the address of the previous web page.Referer: https://www.geeksforgeeks.org/" }, { "code": null, "e": 25124, "s": 25084, "text": "Referer: https://www.geeksforgeeks.org/" }, { "code": null, "e": 25225, "s": 25124, "text": "In this example, google.com is the address of the previous web page.Referer: https://www.google.com/" }, { "code": null, "e": 25258, "s": 25225, "text": "Referer: https://www.google.com/" }, { "code": null, "e": 25492, "s": 25258, "text": "To check the Referer in action go to Inspect Element -> Network check the request header for Referer like below. Referer header is highlighted.Supported Browsers: The browsers are compatible with HTTP header Referer are listed below:" }, { "code": null, "e": 25506, "s": 25492, "text": "Google Chrome" }, { "code": null, "e": 25524, "s": 25506, "text": "Internet Explorer" }, { "code": null, "e": 25539, "s": 25524, "text": "Microsoft Edge" }, { "code": null, "e": 25547, "s": 25539, "text": "Firefox" }, { "code": null, "e": 25553, "s": 25547, "text": "Opera" }, { "code": null, "e": 25560, "s": 25553, "text": "Safari" }, { "code": null, "e": 25573, "s": 25560, "text": "HTTP-headers" }, { "code": null, "e": 25580, "s": 25573, "text": "Picked" }, { "code": null, "e": 25597, "s": 25580, "text": "Web Technologies" }, { "code": null, "e": 25695, "s": 25597, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25704, "s": 25695, "text": "Comments" }, { "code": null, "e": 25717, "s": 25704, "text": "Old Comments" }, { "code": null, "e": 25773, "s": 25717, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 25816, "s": 25773, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 25877, "s": 25816, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 25922, "s": 25877, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 25994, "s": 25922, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26054, "s": 25994, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 26112, "s": 26054, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 26145, "s": 26112, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 26206, "s": 26145, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
How to use Pytorch as a general optimizer | by Conor Mc. | Towards Data Science
Pytorch is really fun to work with and if you are looking for a framework to get started with neural networks I highly recommend it — see my short tutorial on how to get up and running with a basic neural net in Pytorch here. What many people don’t realise however is that Pytorch can be used for general gradient optimization. In other words, you can use Pytorch to find the minium or maximum of arbitrarily complex optimization objectives. But, why would you want to do this? I can think of at least three good reasons (there are many more). You are already familiar with Pytorch and don’t want to have to learn another optimization frameworkYou want to optimize over the outcomes of a Pytorch model — i.e. you want to use optimize over the predictions of a Pytorch Neural net (e.g. a first stage neural net might predict the propensity of a customer to engage in a particular high-value action and the optimizer is used to determine which action is best given some contraints such as marketing budget).You want to use the advanced optimizers defined in Pytorch such as Adam. You are already familiar with Pytorch and don’t want to have to learn another optimization framework You want to optimize over the outcomes of a Pytorch model — i.e. you want to use optimize over the predictions of a Pytorch Neural net (e.g. a first stage neural net might predict the propensity of a customer to engage in a particular high-value action and the optimizer is used to determine which action is best given some contraints such as marketing budget). You want to use the advanced optimizers defined in Pytorch such as Adam. Well ... you don’t actually have to implement anything, if you are familiar with Pytorch already you simply write a Pytorch custom module in the same way you would for a neural network and Pytorch will take care of everything else. Let’s see a worked example. To demonstate we’ll define a simple function — an expoential decay function. Let’s define the data — the scaler floats a, k, b are the unknown parameters of the function and the objective of the optimization will be to estimate these parameters. import numpy as npimport torchimport matplotlib.pyplot as pltfrom torch import nnfrom torch.functional import Ffrom copy import copyimport seaborn as snssns.set_style("whitegrid")n = 1000noise = torch.Tensor(np.random.normal(0, 0.02, size=n))x = torch.arange(n)a, k, b = 0.7, .01, 0.2y = a * np.exp(-k * x) + b + noiseplt.figure(figsize=(14, 7))plt.scatter(x, y, alpha=0.4) Next, let’s define the model and the training loop: class Model(nn.Module): """Custom Pytorch model for gradient optimization. """ def __init__(self): super().__init__() # initialize weights with random numbers weights = torch.distributions.Uniform(0, 0.1).sample((3,)) # make weights torch parameters self.weights = nn.Parameter(weights) def forward(self, X): """Implement function to be optimised. In this case, an exponential decay function (a + exp(-k * X) + b), """ a, k, b = self.weights return a * torch.exp(-k * X) + b def training_loop(model, optimizer, n=1000): "Training loop for torch model." losses = [] for i in range(n): preds = model(x) loss = F.mse_loss(preds, y).sqrt() loss.backward() optimizer.step() optimizer.zero_grad() losses.append(loss) return losses If you are familiar with Pytorch there is nothing too fancy going on here. The key thing that we are doing here is defining our own weights and manually registering these as Pytorch parameters — that is what these lines do: weights = torch.distributions.Uniform(0, 0.1).sample((3,))# make weights torch parametersself.weights = nn.Parameter(weights) The lines below detemine the function to be optimised. You can replace these with the definition of the function you want to minimise. a, k, b = self.weightsreturn a * torch.exp(-k * X) + b By calling nn.Parameter the weight we define will behave and function in the same way as standard Pytorch parameters — i.e they can calculate gradients and be updated in response to a loss function. The training loop is simply iterating over n epochs, each time estimating the mean squared error and updating the gradients. Time to run the model, we’ll use Adam for the optimization. # instantiate modelm = Model()# Instantiate optimizeropt = torch.optim.Adam(m.parameters(), lr=0.001)losses = training_loop(m, opt)plt.figure(figsize=(14, 7))plt.plot(losses)print(m.weights) The plot above shows the loss function over 1000 epochs — you can see that after ~600 it is showing no signs of further improvement. The estimated weights for a, k, b are 0.697, 0.0099, 0.1996, so extremely close to the parameters that define the function and we can use the trained model to estimate the function: preds = m(x)plt.figure(figsize=(14, 7))plt.scatter(x, preds.detach().numpy())plt.scatter(x, y, alpha=.3) You can see that with the optimised parameters we can now fit the exponential decay of the data. Whilst you could do the same thing with curve_fit from scipy I think the greater flexibility to fit more complex functions with Pytorch is worth investing the time to learn. Summary Whilst most people will use Pytorch for building neural networks, the flexibility of the framework makes it extremely versatile. In this post, we have fit a simple curve defined by the exponential decay function, but there is no reason why the same building blocks cannot be extended to arbitrarily complex optimization functions. Hope this was helpful, let me know if you have any thoughts, comments or questions below. Thanks for reading!
[ { "code": null, "e": 397, "s": 171, "text": "Pytorch is really fun to work with and if you are looking for a framework to get started with neural networks I highly recommend it — see my short tutorial on how to get up and running with a basic neural net in Pytorch here." }, { "code": null, "e": 715, "s": 397, "text": "What many people don’t realise however is that Pytorch can be used for general gradient optimization. In other words, you can use Pytorch to find the minium or maximum of arbitrarily complex optimization objectives. But, why would you want to do this? I can think of at least three good reasons (there are many more)." }, { "code": null, "e": 1249, "s": 715, "text": "You are already familiar with Pytorch and don’t want to have to learn another optimization frameworkYou want to optimize over the outcomes of a Pytorch model — i.e. you want to use optimize over the predictions of a Pytorch Neural net (e.g. a first stage neural net might predict the propensity of a customer to engage in a particular high-value action and the optimizer is used to determine which action is best given some contraints such as marketing budget).You want to use the advanced optimizers defined in Pytorch such as Adam." }, { "code": null, "e": 1350, "s": 1249, "text": "You are already familiar with Pytorch and don’t want to have to learn another optimization framework" }, { "code": null, "e": 1712, "s": 1350, "text": "You want to optimize over the outcomes of a Pytorch model — i.e. you want to use optimize over the predictions of a Pytorch Neural net (e.g. a first stage neural net might predict the propensity of a customer to engage in a particular high-value action and the optimizer is used to determine which action is best given some contraints such as marketing budget)." }, { "code": null, "e": 1785, "s": 1712, "text": "You want to use the advanced optimizers defined in Pytorch such as Adam." }, { "code": null, "e": 2045, "s": 1785, "text": "Well ... you don’t actually have to implement anything, if you are familiar with Pytorch already you simply write a Pytorch custom module in the same way you would for a neural network and Pytorch will take care of everything else. Let’s see a worked example." }, { "code": null, "e": 2291, "s": 2045, "text": "To demonstate we’ll define a simple function — an expoential decay function. Let’s define the data — the scaler floats a, k, b are the unknown parameters of the function and the objective of the optimization will be to estimate these parameters." }, { "code": null, "e": 2665, "s": 2291, "text": "import numpy as npimport torchimport matplotlib.pyplot as pltfrom torch import nnfrom torch.functional import Ffrom copy import copyimport seaborn as snssns.set_style(\"whitegrid\")n = 1000noise = torch.Tensor(np.random.normal(0, 0.02, size=n))x = torch.arange(n)a, k, b = 0.7, .01, 0.2y = a * np.exp(-k * x) + b + noiseplt.figure(figsize=(14, 7))plt.scatter(x, y, alpha=0.4)" }, { "code": null, "e": 2717, "s": 2665, "text": "Next, let’s define the model and the training loop:" }, { "code": null, "e": 3607, "s": 2717, "text": "class Model(nn.Module): \"\"\"Custom Pytorch model for gradient optimization. \"\"\" def __init__(self): super().__init__() # initialize weights with random numbers weights = torch.distributions.Uniform(0, 0.1).sample((3,)) # make weights torch parameters self.weights = nn.Parameter(weights) def forward(self, X): \"\"\"Implement function to be optimised. In this case, an exponential decay function (a + exp(-k * X) + b), \"\"\" a, k, b = self.weights return a * torch.exp(-k * X) + b def training_loop(model, optimizer, n=1000): \"Training loop for torch model.\" losses = [] for i in range(n): preds = model(x) loss = F.mse_loss(preds, y).sqrt() loss.backward() optimizer.step() optimizer.zero_grad() losses.append(loss) return losses" }, { "code": null, "e": 3831, "s": 3607, "text": "If you are familiar with Pytorch there is nothing too fancy going on here. The key thing that we are doing here is defining our own weights and manually registering these as Pytorch parameters — that is what these lines do:" }, { "code": null, "e": 3957, "s": 3831, "text": "weights = torch.distributions.Uniform(0, 0.1).sample((3,))# make weights torch parametersself.weights = nn.Parameter(weights)" }, { "code": null, "e": 4092, "s": 3957, "text": "The lines below detemine the function to be optimised. You can replace these with the definition of the function you want to minimise." }, { "code": null, "e": 4147, "s": 4092, "text": "a, k, b = self.weightsreturn a * torch.exp(-k * X) + b" }, { "code": null, "e": 4471, "s": 4147, "text": "By calling nn.Parameter the weight we define will behave and function in the same way as standard Pytorch parameters — i.e they can calculate gradients and be updated in response to a loss function. The training loop is simply iterating over n epochs, each time estimating the mean squared error and updating the gradients." }, { "code": null, "e": 4531, "s": 4471, "text": "Time to run the model, we’ll use Adam for the optimization." }, { "code": null, "e": 4722, "s": 4531, "text": "# instantiate modelm = Model()# Instantiate optimizeropt = torch.optim.Adam(m.parameters(), lr=0.001)losses = training_loop(m, opt)plt.figure(figsize=(14, 7))plt.plot(losses)print(m.weights)" }, { "code": null, "e": 5037, "s": 4722, "text": "The plot above shows the loss function over 1000 epochs — you can see that after ~600 it is showing no signs of further improvement. The estimated weights for a, k, b are 0.697, 0.0099, 0.1996, so extremely close to the parameters that define the function and we can use the trained model to estimate the function:" }, { "code": null, "e": 5142, "s": 5037, "text": "preds = m(x)plt.figure(figsize=(14, 7))plt.scatter(x, preds.detach().numpy())plt.scatter(x, y, alpha=.3)" }, { "code": null, "e": 5413, "s": 5142, "text": "You can see that with the optimised parameters we can now fit the exponential decay of the data. Whilst you could do the same thing with curve_fit from scipy I think the greater flexibility to fit more complex functions with Pytorch is worth investing the time to learn." }, { "code": null, "e": 5421, "s": 5413, "text": "Summary" }, { "code": null, "e": 5752, "s": 5421, "text": "Whilst most people will use Pytorch for building neural networks, the flexibility of the framework makes it extremely versatile. In this post, we have fit a simple curve defined by the exponential decay function, but there is no reason why the same building blocks cannot be extended to arbitrarily complex optimization functions." }, { "code": null, "e": 5842, "s": 5752, "text": "Hope this was helpful, let me know if you have any thoughts, comments or questions below." } ]
Creating a Virtual Background App... | by Swati Modi | Aug, 2020 | Towards Data Science | Towards Data Science
This is the Part 2 of the MediaPipe Series I am writing. Previously, we saw how to get started with MediaPipe and use it with your own tflite model. If you haven’t read it yet, check it out here. We had tried using the portrait segmentation tflite model in the existing segmentation pipeline with the calculators already present in MediaPipe After getting bored with this Blue Background, I decided to have some fun with it by having some Zoom like Virtual Backgrounds like beautiful stars or some crazy clouds instead :) For this, I wrote a custom calculator and used it with the existing pipeline. So today I’ll show how did I go about making this App Before we get started, I would suggest you to go through this part of the documentation which explains the Flow of a basic calculator. https://google.github.io/mediapipe/framework_concepts/calculators.html Now, let’s get started with the code $ git clone https://github.com/SwatiModi/portrait-segmentation-mediapipe.git So earlier, the rendering/coloring was done by the RecolorCalculator , it used to take image and mask gpu buffer as input and returned gpu buffer rendered output (rendered using opengl) Here, for replacing the Background with an Image(jpg/png), I have used OpenCV operations. NOTE : OpenCV operations are performed on CPU — ImageFrame datatype where as opengl operations are performed on GPU — Image-buffer datatype portrait_segmentation.pbtxt We will replace the RecolorCalculator with the BackgroundMaskingCalculator node { calculator: "BackgroundMaskingCalculator" input_stream: "IMAGE_CPU:mask_embedded_input_video_cpu" input_stream: "MASK_CPU:portrait_mask_cpu" output_stream: "OUTPUT_VIDEO:output_video_cpu" } This calculator takes transformed Image and the Mask (Both ImageFrame Datatype) as input and changes the background with given image. For converting the Image and Mask GpuBuffer to ImageFrame, I used the GpuBufferToImageFrameCalculator. In this we will write the logic of processing and creating the background masking effect background_masking_calculator.cc place this background_masking_calculator.cc in mediapipe/calculators/image/ a. Extending the Base Calculator b. GetContract() Here we are just verifying our inputs and their data types c. Open() Prepares the calculator’s per-graph-run state. d. Process() Taking the inputs, converting to OpenCV Mat and further processing for desired output BUILD file in mediapipe/calculators/image We need to do this so the calculator is available and accessible while compilation and execution the deps (dependencies) you see here are the imports you are using in your calculator The name used here is referred in graph BUILD file as well BUILD file in graphs/portrait_segmentation Add background_masking_calculator to deps and remove recolor_calculator which we are not using now Now we are ready to build, we just have to add the asset(image to be masked on the background) NOTE: This asset reading method is straight forward when trying on Desktop but quite different for the Android Build. So we will look at the Desktop and Android build one by one In the background_masking_calculator.cc , read the asset file as Now, we are ready to build bazel build -c opt --copt -DMESA_EGL_NO_X11_HEADERS --copt -DEGL_NO_X11 mediapipe/examples/desktop/portrait_segmentation:portrait_segmentation_gpu The build will finish successfully in around 10–15 minutes INFO: Build completed successfully, 635 total actions Now, you can run the Pipeline using the following GLOG_logtostderr=1 bazel-bin/mediapipe/examples/desktop/portrait_segmentation/portrait_segmentation_gpu --calculator_graph_config_file=mediapipe/graphs/portrait_segmentation/portrait_segmentation.pbtxt the webcam starts and you’ll be able to see the output window Add the following code to the BUILD file in testdata folder (folder containing the background asset images) exports_files( srcs = glob(["**"]),) Adding the files to android_library along with the tflite model Modify in android project BUILD file in examples/android/..../portraitsegmentationgpu/ Here, first using the MediaPipe’s PathToResourceAsFile method, we try to look if the asset is available and if available we read it using it’s value as path to file On a side note, this method was a part of resource_util.h present in mediapipe/util/ folder. So whenever you import a new file into your calculator, make sure to add it to BUILD file mentioned in pt. 4 # BUILD bazel build -c opt --config=android_arm64 mediapipe/examples/android/src/java/com/google/mediapipe/apps/portraitsegmentationgpu# On successfully building the APK, it printsINFO: Elapsed time: 1499.898s, Critical Path: 753.09sINFO: 2002 processes: 1849 linux-sandbox, 1 local, 152 worker.INFO: Build completed successfully, 2140 total actions This would take around 20–25 minutes when building for the first time because it downloads all the external dependencies for the Build. Next time it uses the cached dependencies, so it builds much faster. # INSTALLadb install bazel-bin/mediapipe/examples/android/src/java/com/google/mediapipe/apps/portraitsegmentationgpu/portraitsegmentationgpu.apk Now, you are ready to run the APK and test it. Here we successfully added our own calculator and modified the pipeline and graph according by first testing it on Desktop and then finally on Android with minimal changes. Feel free to ask any questions in the comments or you can reach me out personally. You can find more about me on swatimodi.com https://blog.gofynd.com/mediapipe-with-custom-tflite-model-d3ea0427b3c1https://mediapipe.readthedocs.io/en/latest/framework_concepts.htmlhttps://mediapipe.readthedocs.io/en/latest/calculator.htmlhttps://github.com/google/mediapipe/issuesGrab the code from here — https://github.com/SwatiModi/virtual-background-app https://blog.gofynd.com/mediapipe-with-custom-tflite-model-d3ea0427b3c1 https://mediapipe.readthedocs.io/en/latest/framework_concepts.html https://mediapipe.readthedocs.io/en/latest/calculator.html https://github.com/google/mediapipe/issues Grab the code from here — https://github.com/SwatiModi/virtual-background-app
[ { "code": null, "e": 228, "s": 171, "text": "This is the Part 2 of the MediaPipe Series I am writing." }, { "code": null, "e": 367, "s": 228, "text": "Previously, we saw how to get started with MediaPipe and use it with your own tflite model. If you haven’t read it yet, check it out here." }, { "code": null, "e": 513, "s": 367, "text": "We had tried using the portrait segmentation tflite model in the existing segmentation pipeline with the calculators already present in MediaPipe" }, { "code": null, "e": 693, "s": 513, "text": "After getting bored with this Blue Background, I decided to have some fun with it by having some Zoom like Virtual Backgrounds like beautiful stars or some crazy clouds instead :)" }, { "code": null, "e": 771, "s": 693, "text": "For this, I wrote a custom calculator and used it with the existing pipeline." }, { "code": null, "e": 825, "s": 771, "text": "So today I’ll show how did I go about making this App" }, { "code": null, "e": 960, "s": 825, "text": "Before we get started, I would suggest you to go through this part of the documentation which explains the Flow of a basic calculator." }, { "code": null, "e": 1031, "s": 960, "text": "https://google.github.io/mediapipe/framework_concepts/calculators.html" }, { "code": null, "e": 1068, "s": 1031, "text": "Now, let’s get started with the code" }, { "code": null, "e": 1145, "s": 1068, "text": "$ git clone https://github.com/SwatiModi/portrait-segmentation-mediapipe.git" }, { "code": null, "e": 1331, "s": 1145, "text": "So earlier, the rendering/coloring was done by the RecolorCalculator , it used to take image and mask gpu buffer as input and returned gpu buffer rendered output (rendered using opengl)" }, { "code": null, "e": 1421, "s": 1331, "text": "Here, for replacing the Background with an Image(jpg/png), I have used OpenCV operations." }, { "code": null, "e": 1561, "s": 1421, "text": "NOTE : OpenCV operations are performed on CPU — ImageFrame datatype where as opengl operations are performed on GPU — Image-buffer datatype" }, { "code": null, "e": 1589, "s": 1561, "text": "portrait_segmentation.pbtxt" }, { "code": null, "e": 1664, "s": 1589, "text": "We will replace the RecolorCalculator with the BackgroundMaskingCalculator" }, { "code": null, "e": 1866, "s": 1664, "text": "node { calculator: \"BackgroundMaskingCalculator\" input_stream: \"IMAGE_CPU:mask_embedded_input_video_cpu\" input_stream: \"MASK_CPU:portrait_mask_cpu\" output_stream: \"OUTPUT_VIDEO:output_video_cpu\" }" }, { "code": null, "e": 2000, "s": 1866, "text": "This calculator takes transformed Image and the Mask (Both ImageFrame Datatype) as input and changes the background with given image." }, { "code": null, "e": 2103, "s": 2000, "text": "For converting the Image and Mask GpuBuffer to ImageFrame, I used the GpuBufferToImageFrameCalculator." }, { "code": null, "e": 2192, "s": 2103, "text": "In this we will write the logic of processing and creating the background masking effect" }, { "code": null, "e": 2225, "s": 2192, "text": "background_masking_calculator.cc" }, { "code": null, "e": 2301, "s": 2225, "text": "place this background_masking_calculator.cc in mediapipe/calculators/image/" }, { "code": null, "e": 2334, "s": 2301, "text": "a. Extending the Base Calculator" }, { "code": null, "e": 2351, "s": 2334, "text": "b. GetContract()" }, { "code": null, "e": 2410, "s": 2351, "text": "Here we are just verifying our inputs and their data types" }, { "code": null, "e": 2420, "s": 2410, "text": "c. Open()" }, { "code": null, "e": 2467, "s": 2420, "text": "Prepares the calculator’s per-graph-run state." }, { "code": null, "e": 2480, "s": 2467, "text": "d. Process()" }, { "code": null, "e": 2566, "s": 2480, "text": "Taking the inputs, converting to OpenCV Mat and further processing for desired output" }, { "code": null, "e": 2608, "s": 2566, "text": "BUILD file in mediapipe/calculators/image" }, { "code": null, "e": 2705, "s": 2608, "text": "We need to do this so the calculator is available and accessible while compilation and execution" }, { "code": null, "e": 2791, "s": 2705, "text": "the deps (dependencies) you see here are the imports you are using in your calculator" }, { "code": null, "e": 2850, "s": 2791, "text": "The name used here is referred in graph BUILD file as well" }, { "code": null, "e": 2893, "s": 2850, "text": "BUILD file in graphs/portrait_segmentation" }, { "code": null, "e": 2992, "s": 2893, "text": "Add background_masking_calculator to deps and remove recolor_calculator which we are not using now" }, { "code": null, "e": 3087, "s": 2992, "text": "Now we are ready to build, we just have to add the asset(image to be masked on the background)" }, { "code": null, "e": 3205, "s": 3087, "text": "NOTE: This asset reading method is straight forward when trying on Desktop but quite different for the Android Build." }, { "code": null, "e": 3265, "s": 3205, "text": "So we will look at the Desktop and Android build one by one" }, { "code": null, "e": 3330, "s": 3265, "text": "In the background_masking_calculator.cc , read the asset file as" }, { "code": null, "e": 3357, "s": 3330, "text": "Now, we are ready to build" }, { "code": null, "e": 3505, "s": 3357, "text": "bazel build -c opt --copt -DMESA_EGL_NO_X11_HEADERS --copt -DEGL_NO_X11 mediapipe/examples/desktop/portrait_segmentation:portrait_segmentation_gpu" }, { "code": null, "e": 3564, "s": 3505, "text": "The build will finish successfully in around 10–15 minutes" }, { "code": null, "e": 3618, "s": 3564, "text": "INFO: Build completed successfully, 635 total actions" }, { "code": null, "e": 3668, "s": 3618, "text": "Now, you can run the Pipeline using the following" }, { "code": null, "e": 3872, "s": 3668, "text": "GLOG_logtostderr=1 bazel-bin/mediapipe/examples/desktop/portrait_segmentation/portrait_segmentation_gpu --calculator_graph_config_file=mediapipe/graphs/portrait_segmentation/portrait_segmentation.pbtxt" }, { "code": null, "e": 3934, "s": 3872, "text": "the webcam starts and you’ll be able to see the output window" }, { "code": null, "e": 4042, "s": 3934, "text": "Add the following code to the BUILD file in testdata folder (folder containing the background asset images)" }, { "code": null, "e": 4082, "s": 4042, "text": "exports_files( srcs = glob([\"**\"]),)" }, { "code": null, "e": 4146, "s": 4082, "text": "Adding the files to android_library along with the tflite model" }, { "code": null, "e": 4233, "s": 4146, "text": "Modify in android project BUILD file in examples/android/..../portraitsegmentationgpu/" }, { "code": null, "e": 4398, "s": 4233, "text": "Here, first using the MediaPipe’s PathToResourceAsFile method, we try to look if the asset is available and if available we read it using it’s value as path to file" }, { "code": null, "e": 4600, "s": 4398, "text": "On a side note, this method was a part of resource_util.h present in mediapipe/util/ folder. So whenever you import a new file into your calculator, make sure to add it to BUILD file mentioned in pt. 4" }, { "code": null, "e": 4950, "s": 4600, "text": "# BUILD bazel build -c opt --config=android_arm64 mediapipe/examples/android/src/java/com/google/mediapipe/apps/portraitsegmentationgpu# On successfully building the APK, it printsINFO: Elapsed time: 1499.898s, Critical Path: 753.09sINFO: 2002 processes: 1849 linux-sandbox, 1 local, 152 worker.INFO: Build completed successfully, 2140 total actions" }, { "code": null, "e": 5155, "s": 4950, "text": "This would take around 20–25 minutes when building for the first time because it downloads all the external dependencies for the Build. Next time it uses the cached dependencies, so it builds much faster." }, { "code": null, "e": 5300, "s": 5155, "text": "# INSTALLadb install bazel-bin/mediapipe/examples/android/src/java/com/google/mediapipe/apps/portraitsegmentationgpu/portraitsegmentationgpu.apk" }, { "code": null, "e": 5347, "s": 5300, "text": "Now, you are ready to run the APK and test it." }, { "code": null, "e": 5520, "s": 5347, "text": "Here we successfully added our own calculator and modified the pipeline and graph according by first testing it on Desktop and then finally on Android with minimal changes." }, { "code": null, "e": 5603, "s": 5520, "text": "Feel free to ask any questions in the comments or you can reach me out personally." }, { "code": null, "e": 5647, "s": 5603, "text": "You can find more about me on swatimodi.com" }, { "code": null, "e": 5962, "s": 5647, "text": "https://blog.gofynd.com/mediapipe-with-custom-tflite-model-d3ea0427b3c1https://mediapipe.readthedocs.io/en/latest/framework_concepts.htmlhttps://mediapipe.readthedocs.io/en/latest/calculator.htmlhttps://github.com/google/mediapipe/issuesGrab the code from here — https://github.com/SwatiModi/virtual-background-app" }, { "code": null, "e": 6034, "s": 5962, "text": "https://blog.gofynd.com/mediapipe-with-custom-tflite-model-d3ea0427b3c1" }, { "code": null, "e": 6101, "s": 6034, "text": "https://mediapipe.readthedocs.io/en/latest/framework_concepts.html" }, { "code": null, "e": 6160, "s": 6101, "text": "https://mediapipe.readthedocs.io/en/latest/calculator.html" }, { "code": null, "e": 6203, "s": 6160, "text": "https://github.com/google/mediapipe/issues" } ]
Fuzzy C-Means Clustering —Is it Better than K-Means Clustering? | by Satyam Kumar | Towards Data Science
Clustering is an unsupervised machine learning technique that divides the population into several groups or clusters such that data points in the same group are similar to each other, and data points in different groups are dissimilar. In other words, clusters are formed in such a way that: Data points in the same cluster are close to each other and hence they are very similar Data points in different clusters are far apart and are different from each other. Clustering is used to identify some segments or groups in your dataset. Clustering can be divided into two subgroups: In hard clustering, each data point is clustered or grouped to any one cluster. For each data point, it may either completely belong to a cluster or not. As observed in the above diagram, the data points are divided into two clusters, each point belonging to either of the two clusters. K-Means Clustering is a hard clustering algorithm. It clusters data points into k-clusters. To get a deep dive understanding of the K-Means algorithm, read the below article: towardsdatascience.com In soft clustering, instead of putting each data points into separate clusters, a probability of that point to be in that cluster assigned. In soft clustering or fuzzy clustering, each data point can belong to multiple clusters along with its probability score or likelihood. One of the widely used soft clustering algorithms is the Fuzzy C-means clustering (FCM) Algorithm. Fuzzy C-Means clustering is a soft clustering approach, where each data point is assigned a likelihood or probability score to belong to that cluster. The step-wise approach of the Fuzzy c-means clustering algorithm is: Fix the value of c (number of clusters), and select a value of m (generally 1.25<m<2), and initialize partition matrix U. Calculate cluster centers (centroid). Here,μ: Fuzzy membership valuem: fuzziness parameter Update Partition Matrix Repeat the above steps until convergence. To implement the fuzzy c-means algorithm, we have an open-sourced Python package, that can be installed using PyPl: pip install fuzzy-c-means Fuzzy c-means is a Python module that can implement the fuzzy c-means algorithm. This module has an API similar to that of Scikit-learn. !pip install fuzzy-c-means Collecting fuzzy-c-means Downloading https://files.pythonhosted.org/packages/cc/34/64498f52ddfb0a22a22f2cfcc0b293c6864f6fcc664a53b4cce9302b59fc/fuzzy_c_means-1.2.4-py3-none-any.whl Requirement already satisfied: jaxlib<0.2.0,>=0.1.57 in /usr/local/lib/python3.7/dist-packages (from fuzzy-c-means) (0.1.64+cuda110) Requirement already satisfied: jax<0.3.0,>=0.2.7 in /usr/local/lib/python3.7/dist-packages (from fuzzy-c-means) (0.2.11) Requirement already satisfied: numpy>=1.16 in /usr/local/lib/python3.7/dist-packages (from jaxlib<0.2.0,>=0.1.57->fuzzy-c-means) (1.19.5) Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from jaxlib<0.2.0,>=0.1.57->fuzzy-c-means) (1.4.1) Requirement already satisfied: flatbuffers in /usr/local/lib/python3.7/dist-packages (from jaxlib<0.2.0,>=0.1.57->fuzzy-c-means) (1.12) Requirement already satisfied: absl-py in /usr/local/lib/python3.7/dist-packages (from jaxlib<0.2.0,>=0.1.57->fuzzy-c-means) (0.12.0) Requirement already satisfied: opt-einsum in /usr/local/lib/python3.7/dist-packages (from jax<0.3.0,>=0.2.7->fuzzy-c-means) (3.3.0) Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from absl-py->jaxlib<0.2.0,>=0.1.57->fuzzy-c-means) (1.15.0) Installing collected packages: fuzzy-c-means Successfully installed fuzzy-c-means-1.2.4 import numpy as np from fcmeans import FCM from matplotlib import pyplot as plt n_samples = 5000 X = np.concatenate(( np.random.normal((-2, -2), size=(n_samples, 2)), np.random.normal((2, 2), size=(n_samples, 2)) )) fcm = FCM(n_clusters=2) fcm.fit(X) # outputs fcm_centers = fcm.centers fcm_labels = fcm.predict(X) # plot result f, axes = plt.subplots(1, 2, figsize=(11,5)) axes[0].scatter(X[:,0], X[:,1], alpha=.1) axes[1].scatter(X[:,0], X[:,1], c=fcm_labels, alpha=.1) axes[1].scatter(fcm_centers[:,0], fcm_centers[:,1], marker="+", s=500, c='w') plt.show() Fuzzy c-means clustering has can be considered a better algorithm compared to the k-Means algorithm. Unlike the k-Means algorithm where the data points exclusively belong to one cluster, in the case of the fuzzy c-means algorithm, the data point can belong to more than one cluster with a likelihood. Fuzzy c-means clustering gives comparatively better results for overlapped data sets. [1] Fuzzy Clustering Wikipedia (18 Jan 2021): https://en.wikipedia.org/wiki/Fuzzy_clustering [2] Fuzzy c-means Documentation: https://pypi.org/project/fuzzy-c-means/ Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you. satyam-kumar.medium.com Thank You for Reading
[ { "code": null, "e": 408, "s": 172, "text": "Clustering is an unsupervised machine learning technique that divides the population into several groups or clusters such that data points in the same group are similar to each other, and data points in different groups are dissimilar." }, { "code": null, "e": 464, "s": 408, "text": "In other words, clusters are formed in such a way that:" }, { "code": null, "e": 552, "s": 464, "text": "Data points in the same cluster are close to each other and hence they are very similar" }, { "code": null, "e": 635, "s": 552, "text": "Data points in different clusters are far apart and are different from each other." }, { "code": null, "e": 753, "s": 635, "text": "Clustering is used to identify some segments or groups in your dataset. Clustering can be divided into two subgroups:" }, { "code": null, "e": 1040, "s": 753, "text": "In hard clustering, each data point is clustered or grouped to any one cluster. For each data point, it may either completely belong to a cluster or not. As observed in the above diagram, the data points are divided into two clusters, each point belonging to either of the two clusters." }, { "code": null, "e": 1215, "s": 1040, "text": "K-Means Clustering is a hard clustering algorithm. It clusters data points into k-clusters. To get a deep dive understanding of the K-Means algorithm, read the below article:" }, { "code": null, "e": 1238, "s": 1215, "text": "towardsdatascience.com" }, { "code": null, "e": 1514, "s": 1238, "text": "In soft clustering, instead of putting each data points into separate clusters, a probability of that point to be in that cluster assigned. In soft clustering or fuzzy clustering, each data point can belong to multiple clusters along with its probability score or likelihood." }, { "code": null, "e": 1613, "s": 1514, "text": "One of the widely used soft clustering algorithms is the Fuzzy C-means clustering (FCM) Algorithm." }, { "code": null, "e": 1833, "s": 1613, "text": "Fuzzy C-Means clustering is a soft clustering approach, where each data point is assigned a likelihood or probability score to belong to that cluster. The step-wise approach of the Fuzzy c-means clustering algorithm is:" }, { "code": null, "e": 1955, "s": 1833, "text": "Fix the value of c (number of clusters), and select a value of m (generally 1.25<m<2), and initialize partition matrix U." }, { "code": null, "e": 1993, "s": 1955, "text": "Calculate cluster centers (centroid)." }, { "code": null, "e": 2046, "s": 1993, "text": "Here,μ: Fuzzy membership valuem: fuzziness parameter" }, { "code": null, "e": 2070, "s": 2046, "text": "Update Partition Matrix" }, { "code": null, "e": 2112, "s": 2070, "text": "Repeat the above steps until convergence." }, { "code": null, "e": 2228, "s": 2112, "text": "To implement the fuzzy c-means algorithm, we have an open-sourced Python package, that can be installed using PyPl:" }, { "code": null, "e": 2254, "s": 2228, "text": "pip install fuzzy-c-means" }, { "code": null, "e": 2391, "s": 2254, "text": "Fuzzy c-means is a Python module that can implement the fuzzy c-means algorithm. This module has an API similar to that of Scikit-learn." }, { "code": null, "e": 2419, "s": 2391, "text": "!pip install fuzzy-c-means\n" }, { "code": null, "e": 3755, "s": 2419, "text": "Collecting fuzzy-c-means\n Downloading https://files.pythonhosted.org/packages/cc/34/64498f52ddfb0a22a22f2cfcc0b293c6864f6fcc664a53b4cce9302b59fc/fuzzy_c_means-1.2.4-py3-none-any.whl\nRequirement already satisfied: jaxlib<0.2.0,>=0.1.57 in /usr/local/lib/python3.7/dist-packages (from fuzzy-c-means) (0.1.64+cuda110)\nRequirement already satisfied: jax<0.3.0,>=0.2.7 in /usr/local/lib/python3.7/dist-packages (from fuzzy-c-means) (0.2.11)\nRequirement already satisfied: numpy>=1.16 in /usr/local/lib/python3.7/dist-packages (from jaxlib<0.2.0,>=0.1.57->fuzzy-c-means) (1.19.5)\nRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from jaxlib<0.2.0,>=0.1.57->fuzzy-c-means) (1.4.1)\nRequirement already satisfied: flatbuffers in /usr/local/lib/python3.7/dist-packages (from jaxlib<0.2.0,>=0.1.57->fuzzy-c-means) (1.12)\nRequirement already satisfied: absl-py in /usr/local/lib/python3.7/dist-packages (from jaxlib<0.2.0,>=0.1.57->fuzzy-c-means) (0.12.0)\nRequirement already satisfied: opt-einsum in /usr/local/lib/python3.7/dist-packages (from jax<0.3.0,>=0.2.7->fuzzy-c-means) (3.3.0)\nRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from absl-py->jaxlib<0.2.0,>=0.1.57->fuzzy-c-means) (1.15.0)\nInstalling collected packages: fuzzy-c-means\nSuccessfully installed fuzzy-c-means-1.2.4\n" }, { "code": null, "e": 3836, "s": 3755, "text": "import numpy as np\nfrom fcmeans import FCM\nfrom matplotlib import pyplot as plt\n" }, { "code": null, "e": 3982, "s": 3836, "text": "n_samples = 5000\n\nX = np.concatenate((\n np.random.normal((-2, -2), size=(n_samples, 2)),\n np.random.normal((2, 2), size=(n_samples, 2))\n))\n" }, { "code": null, "e": 4018, "s": 3982, "text": "fcm = FCM(n_clusters=2)\nfcm.fit(X)\n" }, { "code": null, "e": 4330, "s": 4018, "text": "# outputs\nfcm_centers = fcm.centers\nfcm_labels = fcm.predict(X)\n\n# plot result\nf, axes = plt.subplots(1, 2, figsize=(11,5))\naxes[0].scatter(X[:,0], X[:,1], alpha=.1)\naxes[1].scatter(X[:,0], X[:,1], c=fcm_labels, alpha=.1)\naxes[1].scatter(fcm_centers[:,0], fcm_centers[:,1], marker=\"+\", s=500, c='w')\nplt.show()\n" }, { "code": null, "e": 4719, "s": 4332, "text": "Fuzzy c-means clustering has can be considered a better algorithm compared to the k-Means algorithm. Unlike the k-Means algorithm where the data points exclusively belong to one cluster, in the case of the fuzzy c-means algorithm, the data point can belong to more than one cluster with a likelihood. Fuzzy c-means clustering gives comparatively better results for overlapped data sets." }, { "code": null, "e": 4812, "s": 4719, "text": "[1] Fuzzy Clustering Wikipedia (18 Jan 2021): https://en.wikipedia.org/wiki/Fuzzy_clustering" }, { "code": null, "e": 4885, "s": 4812, "text": "[2] Fuzzy c-means Documentation: https://pypi.org/project/fuzzy-c-means/" }, { "code": null, "e": 5074, "s": 4885, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 5098, "s": 5074, "text": "satyam-kumar.medium.com" } ]
Create a Numpy array filled with all zeros | Python - GeeksforGeeks
24 Oct, 2019 In this article, we will learn how to create a Numpy array filled with all zeros, given the shape and type of array. We can use Numpy.zeros() method to do this task. This method takes three parameters, discussed below – shape : integer or sequence of integers order : C_contiguous or F_contiguous C-contiguous order in memory(last index varies the fastest) C order means that operating row-rise on the array will be slightly quicker FORTRAN-contiguous order in memory (first index varies the fastest). F order means that column-wise operations will be faster. dtype : [optional, float(byDeafult)] Data type of returned array. Example #1: # Python Program to create array with all zerosimport numpy as geek a = geek.zeros(3, dtype = int) print("Matrix a : \n", a) b = geek.zeros([3, 3], dtype = int) print("\nMatrix b : \n", b) Output: Matrix a : [0 0 0] Matrix b : [[0 0 0] [0 0 0] [0 0 0]] Example #2: # Python Program to create array with all zerosimport numpy as geek c = geek.zeros([5, 3]) print("\nMatrix c : \n", c) d = geek.zeros([5, 2], dtype = float) print("\nMatrix d : \n", d) Output: Matrix c : [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] Matrix d : [[ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.]] Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n24 Oct, 2019" }, { "code": null, "e": 25672, "s": 25555, "text": "In this article, we will learn how to create a Numpy array filled with all zeros, given the shape and type of array." }, { "code": null, "e": 25775, "s": 25672, "text": "We can use Numpy.zeros() method to do this task. This method takes three parameters, discussed below –" }, { "code": null, "e": 26222, "s": 25775, "text": "shape : integer or sequence of integers\norder : C_contiguous or F_contiguous\n C-contiguous order in memory(last index varies the fastest)\n C order means that operating row-rise on the array will be slightly quicker\n FORTRAN-contiguous order in memory (first index varies the fastest).\n F order means that column-wise operations will be faster. \ndtype : [optional, float(byDeafult)] Data type of returned array. \n" }, { "code": null, "e": 26234, "s": 26222, "text": "Example #1:" }, { "code": "# Python Program to create array with all zerosimport numpy as geek a = geek.zeros(3, dtype = int) print(\"Matrix a : \\n\", a) b = geek.zeros([3, 3], dtype = int) print(\"\\nMatrix b : \\n\", b) ", "e": 26428, "s": 26234, "text": null }, { "code": null, "e": 26436, "s": 26428, "text": "Output:" }, { "code": null, "e": 26501, "s": 26436, "text": "Matrix a : \n [0 0 0]\n\nMatrix b : \n [[0 0 0]\n [0 0 0]\n [0 0 0]]\n\n" }, { "code": null, "e": 26513, "s": 26501, "text": "Example #2:" }, { "code": "# Python Program to create array with all zerosimport numpy as geek c = geek.zeros([5, 3]) print(\"\\nMatrix c : \\n\", c) d = geek.zeros([5, 2], dtype = float) print(\"\\nMatrix d : \\n\", d) ", "e": 26703, "s": 26513, "text": null }, { "code": null, "e": 26711, "s": 26703, "text": "Output:" }, { "code": null, "e": 26872, "s": 26711, "text": "Matrix c : \n [[ 0. 0. 0.]\n [ 0. 0. 0.]\n [ 0. 0. 0.]\n [ 0. 0. 0.]\n [ 0. 0. 0.]]\n\nMatrix d : \n [[ 0. 0.]\n [ 0. 0.]\n [ 0. 0.]\n [ 0. 0.]\n [ 0. 0.]]\n\n" }, { "code": null, "e": 26885, "s": 26872, "text": "Python-numpy" }, { "code": null, "e": 26892, "s": 26885, "text": "Python" }, { "code": null, "e": 26990, "s": 26892, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27022, "s": 26990, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27064, "s": 27022, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27106, "s": 27064, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27162, "s": 27106, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27189, "s": 27162, "text": "Python Classes and Objects" }, { "code": null, "e": 27220, "s": 27189, "text": "Python | os.path.join() method" }, { "code": null, "e": 27259, "s": 27220, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27288, "s": 27259, "text": "Create a directory in Python" }, { "code": null, "e": 27310, "s": 27288, "text": "Defaultdict in Python" } ]
Find the number of stair steps - GeeksforGeeks
07 Apr, 2021 Given the total number of bricks T, find the number of stair steps that can be formed by using given bricks such that if step S has bricks B, then step S+1 should have exactly B+1 bricks and total number of bricks used should be less than or equal to number of bricks available. Note: Number of bricks required to make step 1 of stair is 2, i.e step S = 1 must have exactly B = 2 bricks. Examples: Input : 15 Output : 4 Bricks should be arranged in this pattern to solve for T = 15: Explanation: Number of bricks at step increases by one. At Step 1, Number of bricks = 2, Total = 2 At step 2, Number of bricks = 3, Total = 5 At step 3, Number of bricks = 4, Total = 9 At step 4, Number of bricks = 5, Total = 14 If we add 6 more bricks to form new step, then the total number of bricks available will surpass. Hence, number of steps that can be formed are 4 and number of bricks used are 14 and we are left with 1 brick which is useless. Input : 40 Output : 7 Bricks should be arranged in this pattern to solve for T = 40: Explanation: At Step 1, Number of bricks = 2, Total = 2 At step 2, Number of bricks = 3, Total = 5 At step 3, Number of bricks = 4, Total = 9 At step 4, Number of bricks = 5, Total = 14 At step 5, Number of bricks = 6, Total = 20 At step 6, Number of bricks = 7, Total = 27 At step 7, Number of bricks = 8, Total = 35 If we add 9 more bricks to form new step, then the total number of bricks available will surpass. Hence, number of steps that can be formed are 7 and number of bricks used are 35 and we are left with 5 bricks which are useless. Approach: We are interested in the number of steps and we know that each step Si uses exactly Bi number of bricks. We can represent this problem as an equation: n * (n + 1) / 2 = T (For Natural number series starting from 1, 2, 3, 4, 5 ...) n * (n + 1) = 2 * T n-1 will represent our final solution because our series in problem starts from 2, 3, 4, 5...Now, we just have to solve this equation and for that we can exploit binary search to find the solution to this equation. Lower and Higher bounds of binary search are 1 and T. Below is the implementation for the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find the number of steps#include <bits/stdc++.h>using namespace std; // Modified Binary search function// to solve the equationint solve(int low, int high, int T){ while (low <= high) { int mid = (low + high) / 2; // if mid is solution to equation if ((mid * (mid + 1)) == T) return mid; // if our solution to equation // lies between mid and mid-1 if (mid > 0 && (mid * (mid + 1)) > T && (mid * (mid - 1)) <= T) return mid - 1; // if solution to equation is // greater than mid if ((mid * (mid + 1)) > T) high = mid - 1; // if solution to equation is less // than mid else low = mid + 1; } return -1;} // driver functionint main(){ int T = 15; // call binary search method to // solve for limits 1 to T int ans = solve(1, T, 2 * T); // Because our pattern starts from 2, 3, 4, 5... // so, we subtract 1 from ans if (ans != -1) ans--; cout << "Number of stair steps = " << ans << endl; return 0;} // Java program to find the number of stepsimport java.util.*;import java.lang.*; public class GfG { // Modified Binary search function // to solve the equation public static int solve(int low, int high, int T) { while (low <= high) { int mid = (low + high) / 2; // if mid is solution to equation if ((mid * (mid + 1)) == T) return mid; // if our solution to equation // lies between mid and mid-1 if (mid > 0 && (mid * (mid + 1)) > T && (mid * (mid - 1)) <= T) return mid - 1; // if solution to equation is // greater than mid if ((mid * (mid + 1)) > T) high = mid - 1; // if solution to equation is less // than mid else low = mid + 1; } return -1; } // driver function public static void main(String argc[]) { int T = 15; // call binary search method to // solve for limits 1 to T int ans = solve(1, T, 2 * T); // Because our pattern starts from 2, 3, 4, 5... // so, we subtract 1 from ans if (ans != -1) ans--; System.out.println("Number of stair steps = " + ans); }} /* This code is Contributed by Sagar Shukla */ # Python3 code to find the number of steps # Modified Binary search function# to solve the equationdef solve( low, high, T ): while low <= high: mid = int((low + high) / 2) # if mid is solution to equation if (mid * (mid + 1)) == T: return mid # if our solution to equation # lies between mid and mid-1 if (mid > 0 and (mid * (mid + 1)) > T and (mid * (mid - 1)) <= T) : return mid - 1 # if solution to equation is # greater than mid if (mid * (mid + 1)) > T: high = mid - 1; # if solution to equation is # less than mid else: low = mid + 1 return -1 # driver codeT = 15 # call binary search method to# solve for limits 1 to Tans = solve(1, T, 2 * T) # Because our pattern starts from 2, 3, 4, 5...# so, we subtract 1 from ansif ans != -1: ans-= 1 print("Number of stair steps = ", ans) # This code is contributed by "Sharad_Bhardwaj". // C# program to find the number of stepsusing System; public class GfG { // Modified Binary search function // to solve the equation public static int solve(int low, int high, int T) { while (low <= high) { int mid = (low + high) / 2; // if mid is solution to equation if ((mid * (mid + 1)) == T) return mid; // if our solution to equation // lies between mid and mid-1 if (mid > 0 && (mid * (mid + 1)) > T && (mid * (mid - 1)) <= T) return mid - 1; // if solution to equation is // greater than mid if ((mid * (mid + 1)) > T) high = mid - 1; // if solution to equation is less // than mid else low = mid + 1; } return -1; } // Driver function public static void Main() { int T = 15; // call binary search method to // solve for limits 1 to T int ans = solve(1, T, 2 * T); // Because our pattern starts //from 2, 3, 4, 5... // so, we subtract 1 from ans if (ans != -1) ans--; Console.WriteLine("Number of stair steps = " + ans); }} /* This code is Contributed by vt_m */ <?php// PHP program to find the// number of steps // Modified Binary search function// to solve the equationfunction solve($low, $high, $T){ while ($low <= $high) { $mid = ($low + $high) / 2; // if mid is solution // to equation if (($mid * ($mid + 1)) == $T) return $mid; // if our solution to equation // lies between mid and mid-1 if ($mid > 0 && ($mid * ($mid + 1)) > $T && ($mid * ($mid - 1)) <= $T ) return $mid - 1; // if solution to equation is // greater than mid if (($mid * ($mid + 1)) > $T) $high = $mid - 1; // if solution to // equation is less // than mid else $low = $mid + 1; } return -1;} // Driver Code $T = 15; // call binary search // method to solve // for limits 1 to T $ans = solve(1, $T, 2 * $T); // Because our pattern // starts from 2, 3, 4, 5... // so, we subtract 1 from ans if ($ans != -1) $ans--; echo "Number of stair steps = ", $ans, "\n"; // This code is contributed by aj_36?> <script> // JavaScript program to find the number of steps // Modified Binary search function// to solve the equationfunction solve(low, high, T){ while (low <= high) { let mid = Math.floor((low + high) / 2); // If mid is solution to equation if ((mid * (mid + 1)) == T) return mid; // If our solution to equation // lies between mid and mid-1 if (mid > 0 && (mid * (mid + 1)) > T && (mid * (mid - 1)) <= T) return mid - 1; // If solution to equation is // greater than mid if ((mid * (mid + 1)) > T) high = mid - 1; // If solution to equation is less // than mid else low = mid + 1; } return -1;} // Driver codelet T = 15; // Call binary search method to// solve for limits 1 to Tlet ans = solve(1, T, 2 * T); // Because our pattern starts from 2, 3, 4, 5...// so, we subtract 1 from ansif (ans != -1) ans--; document.write("Number of stair steps = " + ans); // This code is contributed by Surbhi Tyagi. </script> Output: Number of stair steps = 4 This article is contributed by Abhishek rajput. jit_t surbhityagi15 Mathematical Technical Scripter Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Operators in C / C++ The Knight's tour problem | Backtracking-1 Program for factorial of a number Program for Decimal to Binary Conversion Program to find sum of elements in a given array Program to print prime numbers from 1 to N.
[ { "code": null, "e": 25921, "s": 25893, "text": "\n07 Apr, 2021" }, { "code": null, "e": 26201, "s": 25921, "text": "Given the total number of bricks T, find the number of stair steps that can be formed by using given bricks such that if step S has bricks B, then step S+1 should have exactly B+1 bricks and total number of bricks used should be less than or equal to number of bricks available. " }, { "code": null, "e": 26310, "s": 26201, "text": "Note: Number of bricks required to make step 1 of stair is 2, i.e step S = 1 must have exactly B = 2 bricks." }, { "code": null, "e": 26322, "s": 26310, "text": "Examples: " }, { "code": null, "e": 26408, "s": 26322, "text": "Input : 15\nOutput : 4\nBricks should be arranged in this pattern to solve for T = 15:" }, { "code": null, "e": 26954, "s": 26408, "text": "Explanation:\nNumber of bricks at step increases by one.\nAt Step 1, Number of bricks = 2, Total = 2\nAt step 2, Number of bricks = 3, Total = 5\nAt step 3, Number of bricks = 4, Total = 9\nAt step 4, Number of bricks = 5, Total = 14\n\nIf we add 6 more bricks to form new step, \nthen the total number of bricks available will surpass. \nHence, number of steps that can be formed are 4 and\nnumber of bricks used are 14 and we are left with \n1 brick which is useless.\n\nInput : 40\nOutput : 7\nBricks should be arranged in this pattern to solve for T = 40:" }, { "code": null, "e": 27503, "s": 26954, "text": "Explanation:\nAt Step 1, Number of bricks = 2, Total = 2\nAt step 2, Number of bricks = 3, Total = 5\nAt step 3, Number of bricks = 4, Total = 9\nAt step 4, Number of bricks = 5, Total = 14\nAt step 5, Number of bricks = 6, Total = 20\nAt step 6, Number of bricks = 7, Total = 27\nAt step 7, Number of bricks = 8, Total = 35\n\nIf we add 9 more bricks to form new step,\nthen the total number of bricks available will surpass.\nHence, number of steps that can be formed are 7 and \nnumber of bricks used are 35 and we are left with \n5 bricks which are useless." }, { "code": null, "e": 28033, "s": 27503, "text": "Approach: We are interested in the number of steps and we know that each step Si uses exactly Bi number of bricks. We can represent this problem as an equation: n * (n + 1) / 2 = T (For Natural number series starting from 1, 2, 3, 4, 5 ...) n * (n + 1) = 2 * T n-1 will represent our final solution because our series in problem starts from 2, 3, 4, 5...Now, we just have to solve this equation and for that we can exploit binary search to find the solution to this equation. Lower and Higher bounds of binary search are 1 and T." }, { "code": null, "e": 28087, "s": 28033, "text": "Below is the implementation for the above approach: " }, { "code": null, "e": 28091, "s": 28087, "text": "C++" }, { "code": null, "e": 28096, "s": 28091, "text": "Java" }, { "code": null, "e": 28104, "s": 28096, "text": "Python3" }, { "code": null, "e": 28107, "s": 28104, "text": "C#" }, { "code": null, "e": 28111, "s": 28107, "text": "PHP" }, { "code": null, "e": 28122, "s": 28111, "text": "Javascript" }, { "code": "// C++ program to find the number of steps#include <bits/stdc++.h>using namespace std; // Modified Binary search function// to solve the equationint solve(int low, int high, int T){ while (low <= high) { int mid = (low + high) / 2; // if mid is solution to equation if ((mid * (mid + 1)) == T) return mid; // if our solution to equation // lies between mid and mid-1 if (mid > 0 && (mid * (mid + 1)) > T && (mid * (mid - 1)) <= T) return mid - 1; // if solution to equation is // greater than mid if ((mid * (mid + 1)) > T) high = mid - 1; // if solution to equation is less // than mid else low = mid + 1; } return -1;} // driver functionint main(){ int T = 15; // call binary search method to // solve for limits 1 to T int ans = solve(1, T, 2 * T); // Because our pattern starts from 2, 3, 4, 5... // so, we subtract 1 from ans if (ans != -1) ans--; cout << \"Number of stair steps = \" << ans << endl; return 0;}", "e": 29246, "s": 28122, "text": null }, { "code": "// Java program to find the number of stepsimport java.util.*;import java.lang.*; public class GfG { // Modified Binary search function // to solve the equation public static int solve(int low, int high, int T) { while (low <= high) { int mid = (low + high) / 2; // if mid is solution to equation if ((mid * (mid + 1)) == T) return mid; // if our solution to equation // lies between mid and mid-1 if (mid > 0 && (mid * (mid + 1)) > T && (mid * (mid - 1)) <= T) return mid - 1; // if solution to equation is // greater than mid if ((mid * (mid + 1)) > T) high = mid - 1; // if solution to equation is less // than mid else low = mid + 1; } return -1; } // driver function public static void main(String argc[]) { int T = 15; // call binary search method to // solve for limits 1 to T int ans = solve(1, T, 2 * T); // Because our pattern starts from 2, 3, 4, 5... // so, we subtract 1 from ans if (ans != -1) ans--; System.out.println(\"Number of stair steps = \" + ans); }} /* This code is Contributed by Sagar Shukla */", "e": 30607, "s": 29246, "text": null }, { "code": "# Python3 code to find the number of steps # Modified Binary search function# to solve the equationdef solve( low, high, T ): while low <= high: mid = int((low + high) / 2) # if mid is solution to equation if (mid * (mid + 1)) == T: return mid # if our solution to equation # lies between mid and mid-1 if (mid > 0 and (mid * (mid + 1)) > T and (mid * (mid - 1)) <= T) : return mid - 1 # if solution to equation is # greater than mid if (mid * (mid + 1)) > T: high = mid - 1; # if solution to equation is # less than mid else: low = mid + 1 return -1 # driver codeT = 15 # call binary search method to# solve for limits 1 to Tans = solve(1, T, 2 * T) # Because our pattern starts from 2, 3, 4, 5...# so, we subtract 1 from ansif ans != -1: ans-= 1 print(\"Number of stair steps = \", ans) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 31656, "s": 30607, "text": null }, { "code": "// C# program to find the number of stepsusing System; public class GfG { // Modified Binary search function // to solve the equation public static int solve(int low, int high, int T) { while (low <= high) { int mid = (low + high) / 2; // if mid is solution to equation if ((mid * (mid + 1)) == T) return mid; // if our solution to equation // lies between mid and mid-1 if (mid > 0 && (mid * (mid + 1)) > T && (mid * (mid - 1)) <= T) return mid - 1; // if solution to equation is // greater than mid if ((mid * (mid + 1)) > T) high = mid - 1; // if solution to equation is less // than mid else low = mid + 1; } return -1; } // Driver function public static void Main() { int T = 15; // call binary search method to // solve for limits 1 to T int ans = solve(1, T, 2 * T); // Because our pattern starts //from 2, 3, 4, 5... // so, we subtract 1 from ans if (ans != -1) ans--; Console.WriteLine(\"Number of stair steps = \" + ans); }} /* This code is Contributed by vt_m */", "e": 32976, "s": 31656, "text": null }, { "code": "<?php// PHP program to find the// number of steps // Modified Binary search function// to solve the equationfunction solve($low, $high, $T){ while ($low <= $high) { $mid = ($low + $high) / 2; // if mid is solution // to equation if (($mid * ($mid + 1)) == $T) return $mid; // if our solution to equation // lies between mid and mid-1 if ($mid > 0 && ($mid * ($mid + 1)) > $T && ($mid * ($mid - 1)) <= $T ) return $mid - 1; // if solution to equation is // greater than mid if (($mid * ($mid + 1)) > $T) $high = $mid - 1; // if solution to // equation is less // than mid else $low = $mid + 1; } return -1;} // Driver Code $T = 15; // call binary search // method to solve // for limits 1 to T $ans = solve(1, $T, 2 * $T); // Because our pattern // starts from 2, 3, 4, 5... // so, we subtract 1 from ans if ($ans != -1) $ans--; echo \"Number of stair steps = \", $ans, \"\\n\"; // This code is contributed by aj_36?>", "e": 34113, "s": 32976, "text": null }, { "code": "<script> // JavaScript program to find the number of steps // Modified Binary search function// to solve the equationfunction solve(low, high, T){ while (low <= high) { let mid = Math.floor((low + high) / 2); // If mid is solution to equation if ((mid * (mid + 1)) == T) return mid; // If our solution to equation // lies between mid and mid-1 if (mid > 0 && (mid * (mid + 1)) > T && (mid * (mid - 1)) <= T) return mid - 1; // If solution to equation is // greater than mid if ((mid * (mid + 1)) > T) high = mid - 1; // If solution to equation is less // than mid else low = mid + 1; } return -1;} // Driver codelet T = 15; // Call binary search method to// solve for limits 1 to Tlet ans = solve(1, T, 2 * T); // Because our pattern starts from 2, 3, 4, 5...// so, we subtract 1 from ansif (ans != -1) ans--; document.write(\"Number of stair steps = \" + ans); // This code is contributed by Surbhi Tyagi. </script>", "e": 35197, "s": 34113, "text": null }, { "code": null, "e": 35206, "s": 35197, "text": "Output: " }, { "code": null, "e": 35232, "s": 35206, "text": "Number of stair steps = 4" }, { "code": null, "e": 35281, "s": 35232, "text": "This article is contributed by Abhishek rajput. " }, { "code": null, "e": 35287, "s": 35281, "text": "jit_t" }, { "code": null, "e": 35301, "s": 35287, "text": "surbhityagi15" }, { "code": null, "e": 35314, "s": 35301, "text": "Mathematical" }, { "code": null, "e": 35333, "s": 35314, "text": "Technical Scripter" }, { "code": null, "e": 35346, "s": 35333, "text": "Mathematical" }, { "code": null, "e": 35444, "s": 35346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35468, "s": 35444, "text": "Merge two sorted arrays" }, { "code": null, "e": 35511, "s": 35468, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 35525, "s": 35511, "text": "Prime Numbers" }, { "code": null, "e": 35598, "s": 35525, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 35619, "s": 35598, "text": "Operators in C / C++" }, { "code": null, "e": 35662, "s": 35619, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 35696, "s": 35662, "text": "Program for factorial of a number" }, { "code": null, "e": 35737, "s": 35696, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 35786, "s": 35737, "text": "Program to find sum of elements in a given array" } ]
Variables in Java - GeeksforGeeks
19 Apr, 2022 Variable in Java is a data container that saves the data values during Java program execution. Every variable is assigned a data type that designates the type and quantity of value it can hold. Variable is a memory location name of the data. A variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is only a name given to a memory location, all the operations done on the variable effects that memory location. In Java, all the variables must be declared before use. We can declare variables in java as pictorially depicted below as a visual aid. From the image, it can be easily perceived that while declaring a variable, we need to take care of two things that are: 1. Datatype: Type of data that can be stored in this variable. 2. Dataname: Name was given to the variable. In this way, a name can only be given to a memory location. It can be assigned values in two ways: Variable Initialization Assigning value by taking input It can be perceived with the help of 3 components that are as follows: datatype: Type of data that can be stored in this variable. variable_name: Name given to the variable. value: It is the initial value stored in the variable. Illustrations: float simpleInterest; // Declaring float variable int time = 10, speed = 20; // Declaring and Initializing integer variable char var = 'h'; // Declaring and Initializing character variable Now let us discuss different types of variables which are listed as follows: Local VariablesInstance VariablesStatic Variables Local Variables Instance Variables Static Variables Let us discuss the traits of every variable been up here in detail. 1. Local Variables A variable defined within a block or method or constructor is called a local variable. These variables are created when the block is entered, or the function is called and destroyed after exiting from the block or when the call returns from the function. The scope of these variables exists only within the block in which the variable is declared. i.e., we can access these variables only within that block. Initialization of the local variable is mandatory before using it in the defined scope. Java /*package whatever //do not write package name here */// Contributed by Shubham Jainimport java.io.*; class GFG { public static void main(String[] args) { int var = 10; // Declared a Local Variable // This variable is local to this main method only System.out.println("Local Variable: " + var); }} Local Variable: 10 2. Instance Variables Instance variables are non-static variables and are declared in a class outside any method, constructor, or block. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed. Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier, then the default access specifier will be used. Initialization of Instance Variable is not Mandatory. Its default value is 0 Instance Variable can be accessed only by creating objects. Java /*package whatever //do not write package name here */ import java.io.*; class GFG { public String geek; // Declared Instance Variable public GFG() { // Default Constructor this.geek = "Shubham Jain"; // initializing Instance Variable }//Main Method public static void main(String[] args) { // Object Creation GFG name = new GFG(); // Displaying O/P System.out.println("Geek name is: " + name.geek); }} Geek name is: Shubham Jain 3. Static Variables Static variables are also known as Class variables. These variables are declared similarly as instance variables. The difference is that static variables are declared using the static keyword within a class outside any method constructor or block. Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create. Static variables are created at the start of program execution and destroyed automatically when execution ends. Initialization of Static Variable is not Mandatory. Its default value is 0 If we access the static variable like the Instance variable (through an object), the compiler will show the warning message, which won’t halt the program. The compiler will replace the object name with the class name automatically. If we access the static variable without the class name, the compiler will automatically append the class name. Java /*package whatever //do not write package name here */ import java.io.*; class GFG { public static String geek = "Shubham Jain"; //Declared static variable public static void main (String[] args) { //geek variable can be accessed withod object creation //Displaying O/P //GFG.geek --> using the static variable System.out.println("Geek Name is : "+GFG.geek); }} Geek Name is : Shubham Jain Now let us do discuss the differences between the Instance variable Vs. the Static variables Each object will have its copy of the instance variable, whereas We can only have one copy of a static variable per class irrespective of how many objects we create. Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of the instance variable. In the case of static, changes will be reflected in other objects as static variables are common to all objects of a class. We can access instance variables through object references, and Static Variables can be accessed directly using the class name. Syntax: Static and instance variables class GFG { // Static variable static int a; // Instance variable int b; } YouTubeGeeksforGeeks507K subscribersVariables in Java | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:24•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=snIUtdg0K30" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Must Read: Rules of Variable Declaration in Java Scope of Variables in Java Comparison of static keyword in C++ and Java Are static local variables allowed in Java? Instance Variable Hiding in Java 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Pradeep-Kumar JohnsonJ jamshaidiqbal120 kushvillia piyush bharti causalcau nishkarshgandhi amanmalakar007 jainshubham766 simmytarika5 java-basics Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Stream In Java How to iterate any Map in Java Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 30195, "s": 30167, "text": "\n19 Apr, 2022" }, { "code": null, "e": 30437, "s": 30195, "text": "Variable in Java is a data container that saves the data values during Java program execution. Every variable is assigned a data type that designates the type and quantity of value it can hold. Variable is a memory location name of the data." }, { "code": null, "e": 30532, "s": 30437, "text": "A variable is a name given to a memory location. It is the basic unit of storage in a program." }, { "code": null, "e": 30604, "s": 30532, "text": "The value stored in a variable can be changed during program execution." }, { "code": null, "e": 30728, "s": 30604, "text": "A variable is only a name given to a memory location, all the operations done on the variable effects that memory location." }, { "code": null, "e": 30784, "s": 30728, "text": "In Java, all the variables must be declared before use." }, { "code": null, "e": 30864, "s": 30784, "text": "We can declare variables in java as pictorially depicted below as a visual aid." }, { "code": null, "e": 30985, "s": 30864, "text": "From the image, it can be easily perceived that while declaring a variable, we need to take care of two things that are:" }, { "code": null, "e": 31049, "s": 30985, "text": "1. Datatype: Type of data that can be stored in this variable. " }, { "code": null, "e": 31095, "s": 31049, "text": "2. Dataname: Name was given to the variable. " }, { "code": null, "e": 31195, "s": 31095, "text": "In this way, a name can only be given to a memory location. It can be assigned values in two ways: " }, { "code": null, "e": 31219, "s": 31195, "text": "Variable Initialization" }, { "code": null, "e": 31251, "s": 31219, "text": "Assigning value by taking input" }, { "code": null, "e": 31322, "s": 31251, "text": "It can be perceived with the help of 3 components that are as follows:" }, { "code": null, "e": 31382, "s": 31322, "text": "datatype: Type of data that can be stored in this variable." }, { "code": null, "e": 31425, "s": 31382, "text": "variable_name: Name given to the variable." }, { "code": null, "e": 31480, "s": 31425, "text": "value: It is the initial value stored in the variable." }, { "code": null, "e": 31496, "s": 31480, "text": "Illustrations: " }, { "code": null, "e": 31547, "s": 31496, "text": "float simpleInterest; \n// Declaring float variable" }, { "code": null, "e": 31622, "s": 31547, "text": "int time = 10, speed = 20; \n// Declaring and Initializing integer variable" }, { "code": null, "e": 31688, "s": 31622, "text": "char var = 'h'; \n// Declaring and Initializing character variable" }, { "code": null, "e": 31766, "s": 31688, "text": "Now let us discuss different types of variables which are listed as follows: " }, { "code": null, "e": 31816, "s": 31766, "text": "Local VariablesInstance VariablesStatic Variables" }, { "code": null, "e": 31832, "s": 31816, "text": "Local Variables" }, { "code": null, "e": 31851, "s": 31832, "text": "Instance Variables" }, { "code": null, "e": 31868, "s": 31851, "text": "Static Variables" }, { "code": null, "e": 31936, "s": 31868, "text": "Let us discuss the traits of every variable been up here in detail." }, { "code": null, "e": 31956, "s": 31936, "text": "1. Local Variables " }, { "code": null, "e": 32044, "s": 31956, "text": "A variable defined within a block or method or constructor is called a local variable. " }, { "code": null, "e": 32212, "s": 32044, "text": "These variables are created when the block is entered, or the function is called and destroyed after exiting from the block or when the call returns from the function." }, { "code": null, "e": 32365, "s": 32212, "text": "The scope of these variables exists only within the block in which the variable is declared. i.e., we can access these variables only within that block." }, { "code": null, "e": 32453, "s": 32365, "text": "Initialization of the local variable is mandatory before using it in the defined scope." }, { "code": null, "e": 32458, "s": 32453, "text": "Java" }, { "code": "/*package whatever //do not write package name here */// Contributed by Shubham Jainimport java.io.*; class GFG { public static void main(String[] args) { int var = 10; // Declared a Local Variable // This variable is local to this main method only System.out.println(\"Local Variable: \" + var); }}", "e": 32786, "s": 32458, "text": null }, { "code": null, "e": 32805, "s": 32786, "text": "Local Variable: 10" }, { "code": null, "e": 32827, "s": 32805, "text": "2. Instance Variables" }, { "code": null, "e": 32943, "s": 32827, "text": "Instance variables are non-static variables and are declared in a class outside any method, constructor, or block. " }, { "code": null, "e": 33101, "s": 32943, "text": "As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed." }, { "code": null, "e": 33269, "s": 33101, "text": "Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier, then the default access specifier will be used." }, { "code": null, "e": 33346, "s": 33269, "text": "Initialization of Instance Variable is not Mandatory. Its default value is 0" }, { "code": null, "e": 33406, "s": 33346, "text": "Instance Variable can be accessed only by creating objects." }, { "code": null, "e": 33411, "s": 33406, "text": "Java" }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { public String geek; // Declared Instance Variable public GFG() { // Default Constructor this.geek = \"Shubham Jain\"; // initializing Instance Variable }//Main Method public static void main(String[] args) { // Object Creation GFG name = new GFG(); // Displaying O/P System.out.println(\"Geek name is: \" + name.geek); }}", "e": 33874, "s": 33411, "text": null }, { "code": null, "e": 33901, "s": 33874, "text": "Geek name is: Shubham Jain" }, { "code": null, "e": 33921, "s": 33901, "text": "3. Static Variables" }, { "code": null, "e": 33974, "s": 33921, "text": "Static variables are also known as Class variables. " }, { "code": null, "e": 34170, "s": 33974, "text": "These variables are declared similarly as instance variables. The difference is that static variables are declared using the static keyword within a class outside any method constructor or block." }, { "code": null, "e": 34298, "s": 34170, "text": "Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create." }, { "code": null, "e": 34410, "s": 34298, "text": "Static variables are created at the start of program execution and destroyed automatically when execution ends." }, { "code": null, "e": 34485, "s": 34410, "text": "Initialization of Static Variable is not Mandatory. Its default value is 0" }, { "code": null, "e": 34717, "s": 34485, "text": "If we access the static variable like the Instance variable (through an object), the compiler will show the warning message, which won’t halt the program. The compiler will replace the object name with the class name automatically." }, { "code": null, "e": 34829, "s": 34717, "text": "If we access the static variable without the class name, the compiler will automatically append the class name." }, { "code": null, "e": 34834, "s": 34829, "text": "Java" }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { public static String geek = \"Shubham Jain\"; //Declared static variable public static void main (String[] args) { //geek variable can be accessed withod object creation //Displaying O/P //GFG.geek --> using the static variable System.out.println(\"Geek Name is : \"+GFG.geek); }}", "e": 35247, "s": 34834, "text": null }, { "code": null, "e": 35275, "s": 35247, "text": "Geek Name is : Shubham Jain" }, { "code": null, "e": 35368, "s": 35275, "text": "Now let us do discuss the differences between the Instance variable Vs. the Static variables" }, { "code": null, "e": 35534, "s": 35368, "text": "Each object will have its copy of the instance variable, whereas We can only have one copy of a static variable per class irrespective of how many objects we create." }, { "code": null, "e": 35809, "s": 35534, "text": "Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of the instance variable. In the case of static, changes will be reflected in other objects as static variables are common to all objects of a class." }, { "code": null, "e": 35937, "s": 35809, "text": "We can access instance variables through object references, and Static Variables can be accessed directly using the class name." }, { "code": null, "e": 35975, "s": 35937, "text": "Syntax: Static and instance variables" }, { "code": null, "e": 36081, "s": 35975, "text": "class GFG\n{\n // Static variable\n static int a; \n \n // Instance variable\n int b; \n} " }, { "code": null, "e": 36897, "s": 36081, "text": "YouTubeGeeksforGeeks507K subscribersVariables in Java | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:24•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=snIUtdg0K30\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 36909, "s": 36897, "text": "Must Read: " }, { "code": null, "e": 36947, "s": 36909, "text": "Rules of Variable Declaration in Java" }, { "code": null, "e": 36974, "s": 36947, "text": "Scope of Variables in Java" }, { "code": null, "e": 37019, "s": 36974, "text": "Comparison of static keyword in C++ and Java" }, { "code": null, "e": 37063, "s": 37019, "text": "Are static local variables allowed in Java?" }, { "code": null, "e": 37096, "s": 37063, "text": "Instance Variable Hiding in Java" }, { "code": null, "e": 37518, "s": 37096, "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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 37532, "s": 37518, "text": "Pradeep-Kumar" }, { "code": null, "e": 37541, "s": 37532, "text": "JohnsonJ" }, { "code": null, "e": 37558, "s": 37541, "text": "jamshaidiqbal120" }, { "code": null, "e": 37569, "s": 37558, "text": "kushvillia" }, { "code": null, "e": 37583, "s": 37569, "text": "piyush bharti" }, { "code": null, "e": 37593, "s": 37583, "text": "causalcau" }, { "code": null, "e": 37609, "s": 37593, "text": "nishkarshgandhi" }, { "code": null, "e": 37624, "s": 37609, "text": "amanmalakar007" }, { "code": null, "e": 37639, "s": 37624, "text": "jainshubham766" }, { "code": null, "e": 37652, "s": 37639, "text": "simmytarika5" }, { "code": null, "e": 37664, "s": 37652, "text": "java-basics" }, { "code": null, "e": 37669, "s": 37664, "text": "Java" }, { "code": null, "e": 37688, "s": 37669, "text": "School Programming" }, { "code": null, "e": 37693, "s": 37688, "text": "Java" }, { "code": null, "e": 37791, "s": 37693, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37835, "s": 37791, "text": "Split() String method in Java with examples" }, { "code": null, "e": 37871, "s": 37835, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 37896, "s": 37871, "text": "Reverse a string in Java" }, { "code": null, "e": 37911, "s": 37896, "text": "Stream In Java" }, { "code": null, "e": 37942, "s": 37911, "text": "How to iterate any Map in Java" }, { "code": null, "e": 37960, "s": 37942, "text": "Python Dictionary" }, { "code": null, "e": 37976, "s": 37960, "text": "Arrays in C/C++" }, { "code": null, "e": 37995, "s": 37976, "text": "Inheritance in C++" }, { "code": null, "e": 38020, "s": 37995, "text": "Reverse a string in Java" } ]
Find maximum number | Practice | GeeksforGeeks
Given a number N, write a program to find a maximum number that can be formed using all of the digits of this number. Note: The given number can be very large, so the input is taken as a String. Example 1: Input: N = "38293367" Output: 98763332 Explanation: 98763332 is the largest number that can be formed by rearranging the digits of N. Example 2: Input: N = "1203465" Output: 6543210 Explanation: 6543210 is the largest number that can be formed by rearranging the digits of N. Your Task: You don't need to read input or print anything. Your task is to complete the function findMax() which takes a String N as input and returns the answer. Expected Time Complexity: O(|N|) Expected Auxiliary Space: O(constant) Constraints: 1 <= |N| <= 105 +1 imohdalam2 months ago JAVA | O(n) class Solution { static String findMax(String N) { int n = N.length(); int[] arr = new int[n]; StringBuilder ans = new StringBuilder(); for(int i=0; i<n; i++){ char ch = N.charAt(i); int temp = ch - '0'; arr[i] = temp; } Arrays.sort(arr); for(int i=n-1; i>=0; i--) ans.append(arr[i]); return ans + ""; } }; 0 asifsaba5812 months ago string Reverse(string n){ int startIdx=0; int endIdx=n.size()-1; while(startIdx<=endIdx){ int temp=n[startIdx]; n[startIdx]=n[endIdx]; n[endIdx]=temp; startIdx++; endIdx--; } return n; } string findMax(string N) { sort(N.begin(),N.end()); return Reverse(N); } +1 technophyle13 months ago Easy Code with Expected Time Complexity and Space Complexity :) string findMax(string N) { // code here string res=""; vector<int> v(10,0); for(char x:N) v[x-'0']++; for(int i=9;i>=0;i--) { while(v[i]>0) { res+=to_string(i); v[i]--; } } return res; } One Line Code :) string findMax(string N) { // code here sort(N.begin(),N.end(),greater<char>()); return N; } 0 19bcs1187 This comment was deleted. 0 tyagis46063 months ago C++ solution string findMax(string N) { // code here sort(N.begin(),N.end()); reverse(N.begin(),N.end()); return N; } +2 shubhamkhavare3 months ago Simple Java Solution: char[] c1 = N.toCharArray(); Arrays.sort(c1); String s = new String(); for(int i = c1.length-1 ; i >= 0 ; i--) { s += c1[i]; } return s; 0 abhishekguptaaa4 months ago satisfying the expected TC and SC: class Solution { public: string findMax(string N) { int arr[10]={0}; for(int i=0;i<N.length();i++) { arr[N[i]-'0']++; } string res; for(int i=9;i>=0;i--) { if(arr[i]>0) { while(arr[i]>0) { res+=to_string(i); arr[i]--; } } } return res; }}; 0 krithikanithyanandam14 months ago #Python3 one line solution def findMax(self, N): return (''.join(sorted(N)))[::-1] 0 amiransarimy4 months ago Python One Line Solutions class Solution: def findMax(self, N): return ''.join(reversed(sorted(N))) 0 gauravpoharkar634 months ago Java Solution: class Solution { static String findMax(String N) { // code here String s=""; char [] arr=N.toCharArray(); Arrays.sort(arr); for(int i =(arr.length-1);i>=0;i--) s+=arr[i]; return s; }}; 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": 433, "s": 238, "text": "Given a number N, write a program to find a maximum number that can be formed using all of the digits of this number.\nNote: The given number can be very large, so the input is taken as a String." }, { "code": null, "e": 446, "s": 435, "text": "Example 1:" }, { "code": null, "e": 581, "s": 446, "text": "Input:\nN = \"38293367\"\nOutput:\n98763332 \nExplanation:\n98763332 is the largest number that\ncan be formed by rearranging the\ndigits of N." }, { "code": null, "e": 592, "s": 581, "text": "Example 2:" }, { "code": null, "e": 723, "s": 592, "text": "Input:\nN = \"1203465\"\nOutput:\n6543210\nExplanation:\n6543210 is the largest number that\ncan be formed by rearranging the\ndigits of N." }, { "code": null, "e": 888, "s": 725, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function findMax() which takes a String N as input and returns the answer." }, { "code": null, "e": 961, "s": 890, "text": "Expected Time Complexity: O(|N|)\nExpected Auxiliary Space: O(constant)" }, { "code": null, "e": 992, "s": 963, "text": "Constraints:\n1 <= |N| <= 105" }, { "code": null, "e": 995, "s": 992, "text": "+1" }, { "code": null, "e": 1017, "s": 995, "text": "imohdalam2 months ago" }, { "code": null, "e": 1029, "s": 1017, "text": "JAVA | O(n)" }, { "code": null, "e": 1501, "s": 1029, "text": "class Solution {\n static String findMax(String N) {\n \n int n = N.length();\n int[] arr = new int[n];\n StringBuilder ans = new StringBuilder();\n \n for(int i=0; i<n; i++){\n char ch = N.charAt(i);\n int temp = ch - '0';\n arr[i] = temp;\n }\n \n Arrays.sort(arr);\n \n for(int i=n-1; i>=0; i--)\n ans.append(arr[i]);\n \n return ans + \"\";\n }\n};" }, { "code": null, "e": 1503, "s": 1501, "text": "0" }, { "code": null, "e": 1527, "s": 1503, "text": "asifsaba5812 months ago" }, { "code": null, "e": 1983, "s": 1527, "text": " string Reverse(string n){\n \n \n int startIdx=0;\n \n int endIdx=n.size()-1;\n \n while(startIdx<=endIdx){\n \n int temp=n[startIdx];\n \n n[startIdx]=n[endIdx];\n \n n[endIdx]=temp;\n \n startIdx++;\n \n endIdx--;\n }\n \n return n;\n \n }\n \n string findMax(string N) {\n \n sort(N.begin(),N.end());\n \n return Reverse(N);\n }" }, { "code": null, "e": 1986, "s": 1983, "text": "+1" }, { "code": null, "e": 2011, "s": 1986, "text": "technophyle13 months ago" }, { "code": null, "e": 2075, "s": 2011, "text": "Easy Code with Expected Time Complexity and Space Complexity :)" }, { "code": null, "e": 2400, "s": 2075, "text": "string findMax(string N)\n {\n // code here\n string res=\"\";\n vector<int> v(10,0);\n for(char x:N)\n \tv[x-'0']++;\n for(int i=9;i>=0;i--)\n {\n while(v[i]>0)\n {\n \tres+=to_string(i);\n \tv[i]--;\n }\n }\n return res;\n }" }, { "code": null, "e": 2417, "s": 2400, "text": "One Line Code :)" }, { "code": null, "e": 2536, "s": 2417, "text": "string findMax(string N)\n {\n // code here\n sort(N.begin(),N.end(),greater<char>());\n return N;\n }" }, { "code": null, "e": 2538, "s": 2536, "text": "0" }, { "code": null, "e": 2548, "s": 2538, "text": "19bcs1187" }, { "code": null, "e": 2574, "s": 2548, "text": "This comment was deleted." }, { "code": null, "e": 2576, "s": 2574, "text": "0" }, { "code": null, "e": 2599, "s": 2576, "text": "tyagis46063 months ago" }, { "code": null, "e": 2613, "s": 2599, "text": "C++ solution " }, { "code": null, "e": 2744, "s": 2613, "text": "string findMax(string N) { // code here sort(N.begin(),N.end()); reverse(N.begin(),N.end()); return N; }" }, { "code": null, "e": 2747, "s": 2744, "text": "+2" }, { "code": null, "e": 2774, "s": 2747, "text": "shubhamkhavare3 months ago" }, { "code": null, "e": 2796, "s": 2774, "text": "Simple Java Solution:" }, { "code": null, "e": 2979, "s": 2796, "text": "char[] c1 = N.toCharArray(); Arrays.sort(c1); String s = new String(); for(int i = c1.length-1 ; i >= 0 ; i--) { s += c1[i]; } return s;" }, { "code": null, "e": 2981, "s": 2979, "text": "0" }, { "code": null, "e": 3009, "s": 2981, "text": "abhishekguptaaa4 months ago" }, { "code": null, "e": 3044, "s": 3009, "text": "satisfying the expected TC and SC:" }, { "code": null, "e": 3516, "s": 3044, "text": "class Solution { public: string findMax(string N) { int arr[10]={0}; for(int i=0;i<N.length();i++) { arr[N[i]-'0']++; } string res; for(int i=9;i>=0;i--) { if(arr[i]>0) { while(arr[i]>0) { res+=to_string(i); arr[i]--; } } } return res; }};" }, { "code": null, "e": 3518, "s": 3516, "text": "0" }, { "code": null, "e": 3552, "s": 3518, "text": "krithikanithyanandam14 months ago" }, { "code": null, "e": 3643, "s": 3552, "text": "#Python3 one line solution\ndef findMax(self, N):\n return (''.join(sorted(N)))[::-1]" }, { "code": null, "e": 3645, "s": 3643, "text": "0" }, { "code": null, "e": 3670, "s": 3645, "text": "amiransarimy4 months ago" }, { "code": null, "e": 3696, "s": 3670, "text": "Python One Line Solutions" }, { "code": null, "e": 3782, "s": 3698, "text": "class Solution:\n def findMax(self, N):\n return ''.join(reversed(sorted(N)))" }, { "code": null, "e": 3784, "s": 3782, "text": "0" }, { "code": null, "e": 3813, "s": 3784, "text": "gauravpoharkar634 months ago" }, { "code": null, "e": 3828, "s": 3813, "text": "Java Solution:" }, { "code": null, "e": 4060, "s": 3830, "text": "class Solution { static String findMax(String N) { // code here String s=\"\"; char [] arr=N.toCharArray(); Arrays.sort(arr); for(int i =(arr.length-1);i>=0;i--) s+=arr[i]; return s; }};" }, { "code": null, "e": 4206, "s": 4060, "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": 4242, "s": 4206, "text": " Login to access your submissions. " }, { "code": null, "e": 4252, "s": 4242, "text": "\nProblem\n" }, { "code": null, "e": 4262, "s": 4252, "text": "\nContest\n" }, { "code": null, "e": 4325, "s": 4262, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4473, "s": 4325, "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": 4681, "s": 4473, "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": 4787, "s": 4681, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Fernet (symmetric encryption) using Cryptography module in Python - GeeksforGeeks
28 Sep, 2020 Cryptography is the practice of securing useful information while transmitting from one computer to another or storing data on a computer. Cryptography deals with the encryption of plaintext into ciphertext and decryption of ciphertext into plaintext. Python supports a cryptography package that helps us encrypt and decrypt data. The fernet module of the cryptography package has inbuilt functions for the generation of the key, encryption of plaintext into ciphertext, and decryption of ciphertext into plaintext using the encrypt and decrypt methods respectively. The fernet module guarantees that data encrypted using it cannot be further manipulated or read without the key. Methods Used: generate_key() : This method generates a new fernet key. The key must be kept safe as it is the most important component to decrypt the ciphertext. If the key is lost then the user can no longer decrypt the message. Also if an intruder or hacker gets access to the key they can not only read the data but also forge the data. encrypt(data) : It encrypts data passed as a parameter to the method. The outcome of this encryption is known as a “Fernet token” which is basically the ciphertext. The encrypted token also contains the current timestamp when it was generated in plaintext. The encrypt method throws an exception if the data is not in bytes. Parameters: data (bytes) – The plaintext to be encrypted. Return value: A ciphertext that cannot be read or altered without the key. It is URL-safe base64-encoded and is referred to as Fernet token. decrypt(token,ttl=None) : This method decrypts the Fernet token passed as a parameter to the method. On successful decryption the original plaintext is obtained as a result, otherwise an exception is thrown. Parameters: token (bytes) – The Fernet token (ciphertext) is passed for decryption. ttl (int) – Optionally, one may provide an integer as second parameter in the decrypt method. The ttl denotes the time about how long a token is valid. If the token is older than ttl seconds (from the time it was originally created) an exception is thrown. If ttl is not passed as a parameter, then age of the token is not considered. If the token is somehow invalid, an exception is thrown. Returns value: Returns the original plaintext. Steps to write the program: At first, the cryptography package needs to be installed using the following command: pip install cryptography Python3 # Fernet module is imported from the # cryptography packagefrom cryptography.fernet import Fernet # key is generatedkey = Fernet.generate_key() # value of key is assigned to a variablef = Fernet(key) # the plaintext is converted to ciphertexttoken = f.encrypt(b"welcome to geeksforgeeks") # display the ciphertextprint(token) # decrypting the ciphertextd = f.decrypt(token) # display the plaintextprint(d) Output: b’gAAAAABfYMSL3Cjz8I8Sg7NwatdtTvOtqHtPrNDGXTGx4w1gW-9yvrMBUFz3bAWnwVk2WjcOrhjfAzyX7Z6M1IDbcRDhxPvd2dKPjypVv9hLQ1lARWdf-RE=’b’welcome to geeksforgeeks’ The decrypted output has a ‘b’ in front of the original message which indicates the byte format. However, this can be removed using the decode() method while printing the original message. The program below implements the decode() method. Python3 # Fernet module is imported from the # cryptography packagefrom cryptography.fernet import Fernet # key is generatedkey = Fernet.generate_key() # value of key is assigned to a variablef = Fernet(key) # the plaintext is converted to ciphertexttoken = f.encrypt(b"welcome to geeksforgeeks") # display the ciphertextprint(token) # decrypting the ciphertextd = f.decrypt(token) # display the plaintext and the decode() method # converts it from byte to stringprint(d.decode()) Output: b’gAAAAABfYMTfbEYTSsU6BCyXr9ArUIbpELTu5axUtWRfIxc4zzv3AktmOwdNSd1rH_zrL4Qz7tDi1K067kLx0Ma3S828nSTJlP9Y7L0_ZfVyCelZlayGK3k=’welcome to geeksforgeeks cryptography python-modules python-utility Python cryptography Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe 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 Convert integer to string in Python
[ { "code": null, "e": 25923, "s": 25895, "text": "\n28 Sep, 2020" }, { "code": null, "e": 26604, "s": 25923, "text": "Cryptography is the practice of securing useful information while transmitting from one computer to another or storing data on a computer. Cryptography deals with the encryption of plaintext into ciphertext and decryption of ciphertext into plaintext. Python supports a cryptography package that helps us encrypt and decrypt data. The fernet module of the cryptography package has inbuilt functions for the generation of the key, encryption of plaintext into ciphertext, and decryption of ciphertext into plaintext using the encrypt and decrypt methods respectively. The fernet module guarantees that data encrypted using it cannot be further manipulated or read without the key. " }, { "code": null, "e": 26618, "s": 26604, "text": "Methods Used:" }, { "code": null, "e": 26944, "s": 26618, "text": "generate_key() : This method generates a new fernet key. The key must be kept safe as it is the most important component to decrypt the ciphertext. If the key is lost then the user can no longer decrypt the message. Also if an intruder or hacker gets access to the key they can not only read the data but also forge the data." }, { "code": null, "e": 27269, "s": 26944, "text": "encrypt(data) : It encrypts data passed as a parameter to the method. The outcome of this encryption is known as a “Fernet token” which is basically the ciphertext. The encrypted token also contains the current timestamp when it was generated in plaintext. The encrypt method throws an exception if the data is not in bytes." }, { "code": null, "e": 27281, "s": 27269, "text": "Parameters:" }, { "code": null, "e": 27327, "s": 27281, "text": "data (bytes) – The plaintext to be encrypted." }, { "code": null, "e": 27468, "s": 27327, "text": "Return value: A ciphertext that cannot be read or altered without the key. It is URL-safe base64-encoded and is referred to as Fernet token." }, { "code": null, "e": 27676, "s": 27468, "text": "decrypt(token,ttl=None) : This method decrypts the Fernet token passed as a parameter to the method. On successful decryption the original plaintext is obtained as a result, otherwise an exception is thrown." }, { "code": null, "e": 27688, "s": 27676, "text": "Parameters:" }, { "code": null, "e": 27760, "s": 27688, "text": "token (bytes) – The Fernet token (ciphertext) is passed for decryption." }, { "code": null, "e": 28152, "s": 27760, "text": "ttl (int) – Optionally, one may provide an integer as second parameter in the decrypt method. The ttl denotes the time about how long a token is valid. If the token is older than ttl seconds (from the time it was originally created) an exception is thrown. If ttl is not passed as a parameter, then age of the token is not considered. If the token is somehow invalid, an exception is thrown." }, { "code": null, "e": 28200, "s": 28152, "text": "Returns value: Returns the original plaintext." }, { "code": null, "e": 28228, "s": 28200, "text": "Steps to write the program:" }, { "code": null, "e": 28314, "s": 28228, "text": "At first, the cryptography package needs to be installed using the following command:" }, { "code": null, "e": 28340, "s": 28314, "text": "pip install cryptography\n" }, { "code": null, "e": 28348, "s": 28340, "text": "Python3" }, { "code": "# Fernet module is imported from the # cryptography packagefrom cryptography.fernet import Fernet # key is generatedkey = Fernet.generate_key() # value of key is assigned to a variablef = Fernet(key) # the plaintext is converted to ciphertexttoken = f.encrypt(b\"welcome to geeksforgeeks\") # display the ciphertextprint(token) # decrypting the ciphertextd = f.decrypt(token) # display the plaintextprint(d)", "e": 28760, "s": 28348, "text": null }, { "code": null, "e": 28768, "s": 28760, "text": "Output:" }, { "code": null, "e": 28919, "s": 28768, "text": "b’gAAAAABfYMSL3Cjz8I8Sg7NwatdtTvOtqHtPrNDGXTGx4w1gW-9yvrMBUFz3bAWnwVk2WjcOrhjfAzyX7Z6M1IDbcRDhxPvd2dKPjypVv9hLQ1lARWdf-RE=’b’welcome to geeksforgeeks’" }, { "code": null, "e": 29159, "s": 28919, "text": "The decrypted output has a ‘b’ in front of the original message which indicates the byte format. However, this can be removed using the decode() method while printing the original message. The program below implements the decode() method. " }, { "code": null, "e": 29167, "s": 29159, "text": "Python3" }, { "code": "# Fernet module is imported from the # cryptography packagefrom cryptography.fernet import Fernet # key is generatedkey = Fernet.generate_key() # value of key is assigned to a variablef = Fernet(key) # the plaintext is converted to ciphertexttoken = f.encrypt(b\"welcome to geeksforgeeks\") # display the ciphertextprint(token) # decrypting the ciphertextd = f.decrypt(token) # display the plaintext and the decode() method # converts it from byte to stringprint(d.decode())", "e": 29648, "s": 29167, "text": null }, { "code": null, "e": 29656, "s": 29648, "text": "Output:" }, { "code": null, "e": 29804, "s": 29656, "text": "b’gAAAAABfYMTfbEYTSsU6BCyXr9ArUIbpELTu5axUtWRfIxc4zzv3AktmOwdNSd1rH_zrL4Qz7tDi1K067kLx0Ma3S828nSTJlP9Y7L0_ZfVyCelZlayGK3k=’welcome to geeksforgeeks" }, { "code": null, "e": 29817, "s": 29804, "text": "cryptography" }, { "code": null, "e": 29832, "s": 29817, "text": "python-modules" }, { "code": null, "e": 29847, "s": 29832, "text": "python-utility" }, { "code": null, "e": 29854, "s": 29847, "text": "Python" }, { "code": null, "e": 29867, "s": 29854, "text": "cryptography" }, { "code": null, "e": 29965, "s": 29867, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29983, "s": 29965, "text": "Python Dictionary" }, { "code": null, "e": 30015, "s": 29983, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30037, "s": 30015, "text": "Enumerate() in Python" }, { "code": null, "e": 30079, "s": 30037, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30109, "s": 30079, "text": "Iterate over a list in Python" }, { "code": null, "e": 30135, "s": 30109, "text": "Python String | replace()" }, { "code": null, "e": 30164, "s": 30135, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30208, "s": 30164, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30245, "s": 30208, "text": "Create a Pandas DataFrame from Lists" } ]
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java - GeeksforGeeks
20 Nov, 2017 Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article.1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the map and “null” is map is empty. Syntax : public Map.Entry pollFirstEntry() Parameters: NA Return Value: Retrieves and removes the least key-value if map is filled else returns null. Exception: NA // Java code to demonstrate the working// of pollFirstEntry()import java.io.*;import java.util.*;public class pollFirstEntry { public static void main(String[] args) { // Declaring the tree map of String and Integer TreeMap<String, Integer> tmp = new TreeMap<String, Integer>(); // Trying to retrieve and remove in empty map // returns null System.out.println ("The smallest key value pair is : " + tmp.pollFirstEntry()); // assigning the values in the tree map // using put() tmp.put("Geeks", 1); tmp.put("for", 4); tmp.put("geeks", 1); // Printing the initial map System.out.println ("The initial Map before deletion is : " + tmp); // Use of pollFirstEntry() // Removes the first entry and returns the least key // lexicographically smallest in case of String // prints Geeks-1 System.out.println ("The smallest key value pair is : " + tmp.pollFirstEntry()); // Printing the map after deletion System.out.println ("The resultant Map after deletion is : " + tmp); }} Output: The smallest key value pair is : null The initial Map before deletion is : {Geeks=1, for=4, geeks=1} The smallest key value pair is : Geeks=1 The resultant Map after deletion is : {for=4, geeks=1} 2. pollLastEntry() : It removes and retrieves a key-value pair with the largest key value in the map and “null” is map is empty. Syntax : public Map.Entry pollLastEntry() Parameters: NA Return Value: Retrieves and removes the largest key-value if map is filled else returns null. Exception: NA // Java code to demonstrate the working// of pollLastEntry()import java.io.*;import java.util.*;public class pollLastEntry { public static void main(String[] args) { // Declaring the tree map of String and Integer TreeMap<String, Integer> tmp = new TreeMap<String, Integer>(); // Trying to retrieve and remove in empty map // returns null System.out.println ("The largest key value pair is : " + tmp.pollFirstEntry()); // assigning the values in the tree map // using put() tmp.put("Geeks", 1); tmp.put("for", 4); tmp.put("geeks", 1); // Printing the initial map System.out.println ("The initial Map before deletion is : " + tmp); // Use of pollLastEntry() // Removes the last(max) entry and returns the max key // lexicographically greatest in case of String // prints geeks-1 System.out.println ("The largest key value pair is : " + tmp.pollLastEntry()); // Printing the map after deletion System.out.println ("The resultant Map after deletion is : " + tmp); }} Output: The largest key value pair is : null The initial Map before deletion is : {Geeks=1, for=4, geeks=1} The largest key value pair is : geeks=1 The resultant Map after deletion is : {Geeks=1, for=4} Practical Application : There are many applications that can be thought using the concept of deque or priority queueing. One such example is shown in the code below. // Java code to demonstrate the application// of pollLastEntry() and pollFirstEntry()import java.io.*;import java.util.*;public class pollAppli { public static void main(String[] args) { // Declaring the tree map of Integer and String TreeMap<Integer, String> que = new TreeMap<Integer, String>(); // assigning the values in que // using put() que.put(10, "astha"); que.put(4, "shambhavi"); que.put(7, "manjeet"); que.put(8, "nikhil"); // Defining the priority // takes highest value, if priority is high // else takes lowest value String prio = "high"; // Printing the initial queue System.out.println("The initial queue is : " + que); if (prio == "high") { System.out.println ("The largest valued person is : " + que.pollLastEntry()); System.out.println ("The resultant queue after deletion is : " + que); } else { System.out.println ("The lowest valued person is : " + que.pollFirstEntry()); System.out.println ("The resultant queue after deletion is : " + que); } }} Output: The initial queue is : {4=shambhavi, 7=manjeet, 8=nikhil, 10=astha} The largest valued person is : 10=astha The resultant queue after deletion is : {4=shambhavi, 7=manjeet, 8=nikhil} Java - util 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 Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25250, "s": 25222, "text": "\n20 Nov, 2017" }, { "code": null, "e": 25629, "s": 25250, "text": "Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article.1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the map and “null” is map is empty." }, { "code": null, "e": 25795, "s": 25629, "text": "Syntax : \npublic Map.Entry pollFirstEntry()\nParameters:\nNA\nReturn Value:\nRetrieves and removes the least key-value if map is filled else returns null.\nException:\nNA\n" }, { "code": "// Java code to demonstrate the working// of pollFirstEntry()import java.io.*;import java.util.*;public class pollFirstEntry { public static void main(String[] args) { // Declaring the tree map of String and Integer TreeMap<String, Integer> tmp = new TreeMap<String, Integer>(); // Trying to retrieve and remove in empty map // returns null System.out.println (\"The smallest key value pair is : \" + tmp.pollFirstEntry()); // assigning the values in the tree map // using put() tmp.put(\"Geeks\", 1); tmp.put(\"for\", 4); tmp.put(\"geeks\", 1); // Printing the initial map System.out.println (\"The initial Map before deletion is : \" + tmp); // Use of pollFirstEntry() // Removes the first entry and returns the least key // lexicographically smallest in case of String // prints Geeks-1 System.out.println (\"The smallest key value pair is : \" + tmp.pollFirstEntry()); // Printing the map after deletion System.out.println (\"The resultant Map after deletion is : \" + tmp); }}", "e": 26945, "s": 25795, "text": null }, { "code": null, "e": 26953, "s": 26945, "text": "Output:" }, { "code": null, "e": 27151, "s": 26953, "text": "The smallest key value pair is : null\nThe initial Map before deletion is : {Geeks=1, for=4, geeks=1}\nThe smallest key value pair is : Geeks=1\nThe resultant Map after deletion is : {for=4, geeks=1}\n" }, { "code": null, "e": 27280, "s": 27151, "text": "2. pollLastEntry() : It removes and retrieves a key-value pair with the largest key value in the map and “null” is map is empty." }, { "code": null, "e": 27447, "s": 27280, "text": "Syntax : \npublic Map.Entry pollLastEntry()\nParameters:\nNA\nReturn Value:\nRetrieves and removes the largest key-value if map is filled else returns null.\nException:\nNA\n" }, { "code": "// Java code to demonstrate the working// of pollLastEntry()import java.io.*;import java.util.*;public class pollLastEntry { public static void main(String[] args) { // Declaring the tree map of String and Integer TreeMap<String, Integer> tmp = new TreeMap<String, Integer>(); // Trying to retrieve and remove in empty map // returns null System.out.println (\"The largest key value pair is : \" + tmp.pollFirstEntry()); // assigning the values in the tree map // using put() tmp.put(\"Geeks\", 1); tmp.put(\"for\", 4); tmp.put(\"geeks\", 1); // Printing the initial map System.out.println (\"The initial Map before deletion is : \" + tmp); // Use of pollLastEntry() // Removes the last(max) entry and returns the max key // lexicographically greatest in case of String // prints geeks-1 System.out.println (\"The largest key value pair is : \" + tmp.pollLastEntry()); // Printing the map after deletion System.out.println (\"The resultant Map after deletion is : \" + tmp); }}", "e": 28593, "s": 27447, "text": null }, { "code": null, "e": 28601, "s": 28593, "text": "Output:" }, { "code": null, "e": 28797, "s": 28601, "text": "The largest key value pair is : null\nThe initial Map before deletion is : {Geeks=1, for=4, geeks=1}\nThe largest key value pair is : geeks=1\nThe resultant Map after deletion is : {Geeks=1, for=4}\n" }, { "code": null, "e": 28963, "s": 28797, "text": "Practical Application : There are many applications that can be thought using the concept of deque or priority queueing. One such example is shown in the code below." }, { "code": "// Java code to demonstrate the application// of pollLastEntry() and pollFirstEntry()import java.io.*;import java.util.*;public class pollAppli { public static void main(String[] args) { // Declaring the tree map of Integer and String TreeMap<Integer, String> que = new TreeMap<Integer, String>(); // assigning the values in que // using put() que.put(10, \"astha\"); que.put(4, \"shambhavi\"); que.put(7, \"manjeet\"); que.put(8, \"nikhil\"); // Defining the priority // takes highest value, if priority is high // else takes lowest value String prio = \"high\"; // Printing the initial queue System.out.println(\"The initial queue is : \" + que); if (prio == \"high\") { System.out.println (\"The largest valued person is : \" + que.pollLastEntry()); System.out.println (\"The resultant queue after deletion is : \" + que); } else { System.out.println (\"The lowest valued person is : \" + que.pollFirstEntry()); System.out.println (\"The resultant queue after deletion is : \" + que); } }}", "e": 30165, "s": 28963, "text": null }, { "code": null, "e": 30173, "s": 30165, "text": "Output:" }, { "code": null, "e": 30357, "s": 30173, "text": "The initial queue is : {4=shambhavi, 7=manjeet, 8=nikhil, 10=astha}\nThe largest valued person is : 10=astha\nThe resultant queue after deletion is : {4=shambhavi, 7=manjeet, 8=nikhil}\n" }, { "code": null, "e": 30377, "s": 30357, "text": "Java - util package" }, { "code": null, "e": 30382, "s": 30377, "text": "Java" }, { "code": null, "e": 30387, "s": 30382, "text": "Java" }, { "code": null, "e": 30485, "s": 30387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30500, "s": 30485, "text": "Stream In Java" }, { "code": null, "e": 30521, "s": 30500, "text": "Constructors in Java" }, { "code": null, "e": 30540, "s": 30521, "text": "Exceptions in Java" }, { "code": null, "e": 30570, "s": 30540, "text": "Functional Interfaces in Java" }, { "code": null, "e": 30616, "s": 30570, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30633, "s": 30616, "text": "Generics in Java" }, { "code": null, "e": 30654, "s": 30633, "text": "Introduction to Java" }, { "code": null, "e": 30697, "s": 30654, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 30733, "s": 30697, "text": "Internal Working of HashMap in Java" } ]
compgen command in Linux with Examples - GeeksforGeeks
22 Jun, 2020 compgen is a bash built-in command which is used to list all the commands that could be executed in the Linux system. This command could also be used to count the total number of commands present in the terminal or even to look for a command with the specific keyword. This command is even used to print the bash details like bash builtin functions and stuff. 1. To list all commands available to be directly executed. compgen -c This will list all the commands available to you for direct use. 2. To search for commands having a specific keyword compgen -c | grep gnome This will search the commands having the keyword gnome in them. 3. To count total number of commands available for use compgen -c | wc -l This command will count the total number of commands that could be used. 4. To list all the bash alias compgen -a This command will list all the bash alias present in your system. 5. To list all the bash built-ins compgen -b This command will list all the bash built-ins present in your system. 6. To list all the bash keywords compgen -k This command will list all the bash keywords present in your system. 7. To list all the bash functions. compgen -A function This command will list all the bash functions present in your system. linux-command Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25751, "s": 25720, "text": " \n22 Jun, 2020\n" }, { "code": null, "e": 26111, "s": 25751, "text": "compgen is a bash built-in command which is used to list all the commands that could be executed in the Linux system. This command could also be used to count the total number of commands present in the terminal or even to look for a command with the specific keyword. This command is even used to print the bash details like bash builtin functions and stuff." }, { "code": null, "e": 26170, "s": 26111, "text": "1. To list all commands available to be directly executed." }, { "code": null, "e": 26181, "s": 26170, "text": "compgen -c" }, { "code": null, "e": 26246, "s": 26181, "text": "This will list all the commands available to you for direct use." }, { "code": null, "e": 26298, "s": 26246, "text": "2. To search for commands having a specific keyword" }, { "code": null, "e": 26322, "s": 26298, "text": "compgen -c | grep gnome" }, { "code": null, "e": 26386, "s": 26322, "text": "This will search the commands having the keyword gnome in them." }, { "code": null, "e": 26441, "s": 26386, "text": "3. To count total number of commands available for use" }, { "code": null, "e": 26460, "s": 26441, "text": "compgen -c | wc -l" }, { "code": null, "e": 26533, "s": 26460, "text": "This command will count the total number of commands that could be used." }, { "code": null, "e": 26563, "s": 26533, "text": "4. To list all the bash alias" }, { "code": null, "e": 26574, "s": 26563, "text": "compgen -a" }, { "code": null, "e": 26640, "s": 26574, "text": "This command will list all the bash alias present in your system." }, { "code": null, "e": 26674, "s": 26640, "text": "5. To list all the bash built-ins" }, { "code": null, "e": 26685, "s": 26674, "text": "compgen -b" }, { "code": null, "e": 26755, "s": 26685, "text": "This command will list all the bash built-ins present in your system." }, { "code": null, "e": 26788, "s": 26755, "text": "6. To list all the bash keywords" }, { "code": null, "e": 26799, "s": 26788, "text": "compgen -k" }, { "code": null, "e": 26868, "s": 26799, "text": "This command will list all the bash keywords present in your system." }, { "code": null, "e": 26903, "s": 26868, "text": "7. To list all the bash functions." }, { "code": null, "e": 26923, "s": 26903, "text": "compgen -A function" }, { "code": null, "e": 26993, "s": 26923, "text": "This command will list all the bash functions present in your system." }, { "code": null, "e": 27009, "s": 26993, "text": "\nlinux-command\n" }, { "code": null, "e": 27022, "s": 27009, "text": "\nLinux-Unix\n" }, { "code": null, "e": 27227, "s": 27022, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 27262, "s": 27227, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27296, "s": 27262, "text": "mv command in Linux with examples" }, { "code": null, "e": 27322, "s": 27296, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27351, "s": 27322, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27388, "s": 27351, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27425, "s": 27388, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27467, "s": 27425, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 27493, "s": 27467, "text": "Thread functions in C/C++" }, { "code": null, "e": 27529, "s": 27493, "text": "uniq Command in LINUX with examples" } ]
Python - Write Bytes to File - GeeksforGeeks
26 Nov, 2020 Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps: Open filePerform operationClose file Open file Perform operation Close file There are four basic modes in which a file can be opened― read, write, append, and exclusive creations. In addition, Python allows you to specify two modes in which a file can be handled― binary and text. Binary mode is used for handling all kinds of non-text data like image files and executable files. Python stores files in the form of bytes on the disk. So, when a file is opened in text mode, these files are decoded from bytes to return string objects. While files opened in binary mode return contents as bytes objects (sequences of single bytes) without any decoding. Let us see how to write bytes to a file in Python. First, open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file. Python3 some_bytes = b'\xC3\xA9' # Open in "wb" mode to# write a new file, or # "ab" mode to appendwith open("my_file.txt", "wb") as binary_file: # Write bytes to file binary_file.write(some_bytes) Output: my_file.txt In the above example, we opened a file in binary write mode and then wrote some bytes contents as bytes in the binary file. Alternatively, open() and close() can be called explicitly as shown below. However, this method requires you to perform error handling yourself, that is, ensure that the file is always closed, even if there is an error during writing. So, using the “with” statement is better in this regard as it will automatically close the file when the block ends. Python3 some_bytes = b'\x21' # Open file in binary write modebinary_file = open("my_file.txt", "wb") # Write bytes to filebinary_file.write(some_bytes) # Close filebinary_file.close() Output: my_file.txt Also, some_bytes can be in the form of bytearray which is mutable, or bytes object which is immutable as shown below. Python3 # Create bytearray # (sequence of values in # the range 0-255 in binary form) # ASCII for A,B,C,Dbyte_arr = [65,66,67,68] some_bytes = bytearray(byte_arr) # Bytearray allows modification# ASCII for exclamation marksome_bytes.append(33) # Bytearray can be cast to bytesimmutable_bytes = bytes(some_bytes) # Write bytes to filewith open("my_file.txt", "wb") as binary_file: binary_file.write(immutable_bytes) Output: my_file.txt python-file-handling Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25562, "s": 25534, "text": "\n26 Nov, 2020" }, { "code": null, "e": 25781, "s": 25562, "text": "Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps:" }, { "code": null, "e": 25818, "s": 25781, "text": "Open filePerform operationClose file" }, { "code": null, "e": 25828, "s": 25818, "text": "Open file" }, { "code": null, "e": 25846, "s": 25828, "text": "Perform operation" }, { "code": null, "e": 25857, "s": 25846, "text": "Close file" }, { "code": null, "e": 26161, "s": 25857, "text": "There are four basic modes in which a file can be opened― read, write, append, and exclusive creations. In addition, Python allows you to specify two modes in which a file can be handled― binary and text. Binary mode is used for handling all kinds of non-text data like image files and executable files." }, { "code": null, "e": 26484, "s": 26161, "text": "Python stores files in the form of bytes on the disk. So, when a file is opened in text mode, these files are decoded from bytes to return string objects. While files opened in binary mode return contents as bytes objects (sequences of single bytes) without any decoding. Let us see how to write bytes to a file in Python." }, { "code": null, "e": 26660, "s": 26484, "text": "First, open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file. " }, { "code": null, "e": 26668, "s": 26660, "text": "Python3" }, { "code": "some_bytes = b'\\xC3\\xA9' # Open in \"wb\" mode to# write a new file, or # \"ab\" mode to appendwith open(\"my_file.txt\", \"wb\") as binary_file: # Write bytes to file binary_file.write(some_bytes)", "e": 26869, "s": 26668, "text": null }, { "code": null, "e": 26877, "s": 26869, "text": "Output:" }, { "code": null, "e": 26889, "s": 26877, "text": "my_file.txt" }, { "code": null, "e": 27013, "s": 26889, "text": "In the above example, we opened a file in binary write mode and then wrote some bytes contents as bytes in the binary file." }, { "code": null, "e": 27365, "s": 27013, "text": "Alternatively, open() and close() can be called explicitly as shown below. However, this method requires you to perform error handling yourself, that is, ensure that the file is always closed, even if there is an error during writing. So, using the “with” statement is better in this regard as it will automatically close the file when the block ends." }, { "code": null, "e": 27373, "s": 27365, "text": "Python3" }, { "code": "some_bytes = b'\\x21' # Open file in binary write modebinary_file = open(\"my_file.txt\", \"wb\") # Write bytes to filebinary_file.write(some_bytes) # Close filebinary_file.close()", "e": 27552, "s": 27373, "text": null }, { "code": null, "e": 27560, "s": 27552, "text": "Output:" }, { "code": null, "e": 27572, "s": 27560, "text": "my_file.txt" }, { "code": null, "e": 27690, "s": 27572, "text": "Also, some_bytes can be in the form of bytearray which is mutable, or bytes object which is immutable as shown below." }, { "code": null, "e": 27698, "s": 27690, "text": "Python3" }, { "code": "# Create bytearray # (sequence of values in # the range 0-255 in binary form) # ASCII for A,B,C,Dbyte_arr = [65,66,67,68] some_bytes = bytearray(byte_arr) # Bytearray allows modification# ASCII for exclamation marksome_bytes.append(33) # Bytearray can be cast to bytesimmutable_bytes = bytes(some_bytes) # Write bytes to filewith open(\"my_file.txt\", \"wb\") as binary_file: binary_file.write(immutable_bytes)", "e": 28112, "s": 27698, "text": null }, { "code": null, "e": 28120, "s": 28112, "text": "Output:" }, { "code": null, "e": 28132, "s": 28120, "text": "my_file.txt" }, { "code": null, "e": 28153, "s": 28132, "text": "python-file-handling" }, { "code": null, "e": 28160, "s": 28153, "text": "Python" }, { "code": null, "e": 28258, "s": 28160, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28290, "s": 28258, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28332, "s": 28290, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28374, "s": 28332, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28430, "s": 28374, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28457, "s": 28430, "text": "Python Classes and Objects" }, { "code": null, "e": 28488, "s": 28457, "text": "Python | os.path.join() method" }, { "code": null, "e": 28527, "s": 28488, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28556, "s": 28527, "text": "Create a directory in Python" }, { "code": null, "e": 28578, "s": 28556, "text": "Defaultdict in Python" } ]
Iterator Functions in Python | Set 2 (islice(), starmap(), tee()..) - GeeksforGeeks
04 Feb, 2020 Iterator Functions in Python | Set 1 1. islice(iterable, start, stop, step) :- This iterator selectively prints the values mentioned in its iterable container passed as argument. This iterator takes 4 arguments, iterable container, starting pos., ending position and step. 2. starmap(func., tuple list) :- This iterator takes a function and tuple list as argument and returns the value according to the function from each tuple of list. # Python code to demonstrate the working of # islice() and starmap() # importing "itertools" for iterator operationsimport itertools # initializing list li = [2, 4, 5, 7, 8, 10, 20] # initializing tuple listli1 = [ (1, 10, 5), (8, 4, 1), (5, 4, 9), (11, 10 , 1) ] # using islice() to slice the list acc. to need# starts printing from 2nd index till 6th skipping 2print ("The sliced list values are : ",end="")print (list(itertools.islice(li,1, 6, 2))) # using starmap() for selection value acc. to function# selects min of all tuple valuesprint ("The values acc. to function are : ",end="")print (list(itertools.starmap(min,li1))) Output: The sliced list values are : [4, 7, 10] The values acc. to function are : [1, 1, 4, 1] 3. takewhile(func, iterable) :- This iterator is opposite of dropwhile(), it prints the values till the function returns false for 1st time. 4. tee(iterator, count) :- This iterator splits the container into a number of iterators mentioned in the argument. # Python code to demonstrate the working of # takewhile() and tee() # importing "itertools" for iterator operationsimport itertools # initializing list li = [2, 4, 6, 7, 8, 10, 20] # storing list in iteratoriti = iter(li) # using takewhile() to print values till condition is false.print ("The list values till 1st false value are : ",end="")print (list(itertools.takewhile(lambda x : x%2==0,li ))) # using tee() to make a list of iterators# makes list of 3 iterators having same values.it = itertools.tee(iti, 3) # printing the values of iteratorsprint ("The iterators are : ")for i in range (0,3): print (list(it[i])) Output: The list values till 1st false value are : [2, 4, 6] The iterators are : [2, 4, 6, 7, 8, 10, 20] [2, 4, 6, 7, 8, 10, 20] [2, 4, 6, 7, 8, 10, 20] 5. zip_longest( iterable1, iterable2, fillval.) :- This iterator prints the values of iterables alternatively in sequence. If one of the iterables is printed fully, remaining values are filled by the values assigned to fillvalue. # Python code to demonstrate the working of # zip_longest() # importing "itertools" for iterator operationsimport itertools # using zip_longest() to combine two iterables.print ("The combined values of iterables is : ")print (*(itertools.zip_longest('GesoGes','ekfrek',fillvalue='_' ))) Output: The combined values of iterables is : ('G', 'e') ('e', 'k') ('s', 'f') ('o', 'r') ('G', 'e') ('e', 'k') ('s', '_') Combinatoric Iterators 1. product(iter1, iter2) :- This iterator prints the cartesian product of the two iterable containers passed as arguments. 2. permutations(iter, group_size) :- This iterator prints all possible permutation of all elements of iterable. The size of each permuted group is decided by group_size argument. # Python code to demonstrate the working of # product() and permutations() # importing "itertools" for iterator operationsimport itertools # using product() to print the cartesian productprint ("The cartesian product of the containers is : ")print (list(itertools.product('AB','12'))) # using permutations to compute all possible permutationsprint ("All the permutations of the given container is : ")print (list(itertools.permutations('GfG',2))) Output: The cartesian product of the containers is : [('A', '1'), ('A', '2'), ('B', '1'), ('B', '2')] All the permutations of the given container is : [('G', 'f'), ('G', 'G'), ('f', 'G'), ('f', 'G'), ('G', 'G'), ('G', 'f')] 3. combinations(iterable, group_size) :- This iterator prints all the possible combinations(without replacement) of the container passed in arguments in the specified group size in sorted order. 4. combinations_with_replacement(iterable, group_size) :- This iterator prints all the possible combinations(with replacement) of the container passed in arguments in the specified group size in sorted order. # Python code to demonstrate the working of # combination() and combination_with_replacement() # importing "itertools" for iterator operationsimport itertools # using combinations() to print every combination# (without replacement)print ("All the combination of container in sorted order(without replacement) is : ")print (list(itertools.combinations('1234',2))) # using combinations_with_replacement() to print every combination# with replacementprint ("All the combination of container in sorted order(with replacement) is : ")print (list(itertools.combinations_with_replacement('GfG',2))) Output: All the combination of container in sorted order(without replacement) is : [('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')] All the combination of container in sorted order(with replacement) is : [('G', 'G'), ('G', 'f'), ('G', 'G'), ('f', 'f'), ('f', 'G'), ('G', 'G')] Infinite Iterators 1. count(start, step) :- This iterator starts printing from the “start” number and prints infinitely. If steps are mentioned, the numbers are skipped else step is 1 by default. Example : iterator.count(5,2) prints -- 5,7,9,11...infinitely 2. cycle(iterable) :- This iterator prints all values in order from the passed container. It restarts printing from beginning again when all elements are printed in a cyclic manner. Example : iterator.cycle([1,2,3,4]) prints -- 1,2,3,4,1,2,3,4,1...infinitely 3. repeat(val, num) :- This iterator repeatedly prints the passed value infinite number of times. If num. is mentioned, them till that number. # Python code to demonstrate the working of # repeat() # importing "itertools" for iterator operationsimport itertools # using repeat() to repeatedly print numberprint ("Printing the numbers repeatedly : ")print (list(itertools.repeat(25,4))) Output: Printing the numbers repeatedly : [25, 25, 25, 25] YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Iterator Functions - Part 2 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:32•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=cgrDYgW0C3o" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? 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": 25773, "s": 25745, "text": "\n04 Feb, 2020" }, { "code": null, "e": 25810, "s": 25773, "text": "Iterator Functions in Python | Set 1" }, { "code": null, "e": 26046, "s": 25810, "text": "1. islice(iterable, start, stop, step) :- This iterator selectively prints the values mentioned in its iterable container passed as argument. This iterator takes 4 arguments, iterable container, starting pos., ending position and step." }, { "code": null, "e": 26210, "s": 26046, "text": "2. starmap(func., tuple list) :- This iterator takes a function and tuple list as argument and returns the value according to the function from each tuple of list." }, { "code": "# Python code to demonstrate the working of # islice() and starmap() # importing \"itertools\" for iterator operationsimport itertools # initializing list li = [2, 4, 5, 7, 8, 10, 20] # initializing tuple listli1 = [ (1, 10, 5), (8, 4, 1), (5, 4, 9), (11, 10 , 1) ] # using islice() to slice the list acc. to need# starts printing from 2nd index till 6th skipping 2print (\"The sliced list values are : \",end=\"\")print (list(itertools.islice(li,1, 6, 2))) # using starmap() for selection value acc. to function# selects min of all tuple valuesprint (\"The values acc. to function are : \",end=\"\")print (list(itertools.starmap(min,li1)))", "e": 26848, "s": 26210, "text": null }, { "code": null, "e": 26856, "s": 26848, "text": "Output:" }, { "code": null, "e": 26944, "s": 26856, "text": "The sliced list values are : [4, 7, 10]\nThe values acc. to function are : [1, 1, 4, 1]\n" }, { "code": null, "e": 27085, "s": 26944, "text": "3. takewhile(func, iterable) :- This iterator is opposite of dropwhile(), it prints the values till the function returns false for 1st time." }, { "code": null, "e": 27201, "s": 27085, "text": "4. tee(iterator, count) :- This iterator splits the container into a number of iterators mentioned in the argument." }, { "code": "# Python code to demonstrate the working of # takewhile() and tee() # importing \"itertools\" for iterator operationsimport itertools # initializing list li = [2, 4, 6, 7, 8, 10, 20] # storing list in iteratoriti = iter(li) # using takewhile() to print values till condition is false.print (\"The list values till 1st false value are : \",end=\"\")print (list(itertools.takewhile(lambda x : x%2==0,li ))) # using tee() to make a list of iterators# makes list of 3 iterators having same values.it = itertools.tee(iti, 3) # printing the values of iteratorsprint (\"The iterators are : \")for i in range (0,3): print (list(it[i]))", "e": 27830, "s": 27201, "text": null }, { "code": null, "e": 27838, "s": 27830, "text": "Output:" }, { "code": null, "e": 27985, "s": 27838, "text": "The list values till 1st false value are : [2, 4, 6]\nThe iterators are : \n[2, 4, 6, 7, 8, 10, 20]\n[2, 4, 6, 7, 8, 10, 20]\n[2, 4, 6, 7, 8, 10, 20]\n" }, { "code": null, "e": 28215, "s": 27985, "text": "5. zip_longest( iterable1, iterable2, fillval.) :- This iterator prints the values of iterables alternatively in sequence. If one of the iterables is printed fully, remaining values are filled by the values assigned to fillvalue." }, { "code": "# Python code to demonstrate the working of # zip_longest() # importing \"itertools\" for iterator operationsimport itertools # using zip_longest() to combine two iterables.print (\"The combined values of iterables is : \")print (*(itertools.zip_longest('GesoGes','ekfrek',fillvalue='_' )))", "e": 28505, "s": 28215, "text": null }, { "code": null, "e": 28513, "s": 28505, "text": "Output:" }, { "code": null, "e": 28631, "s": 28513, "text": "The combined values of iterables is : \n('G', 'e') ('e', 'k') ('s', 'f') ('o', 'r') ('G', 'e') ('e', 'k') ('s', '_')\n" }, { "code": null, "e": 28654, "s": 28631, "text": "Combinatoric Iterators" }, { "code": null, "e": 28777, "s": 28654, "text": "1. product(iter1, iter2) :- This iterator prints the cartesian product of the two iterable containers passed as arguments." }, { "code": null, "e": 28956, "s": 28777, "text": "2. permutations(iter, group_size) :- This iterator prints all possible permutation of all elements of iterable. The size of each permuted group is decided by group_size argument." }, { "code": "# Python code to demonstrate the working of # product() and permutations() # importing \"itertools\" for iterator operationsimport itertools # using product() to print the cartesian productprint (\"The cartesian product of the containers is : \")print (list(itertools.product('AB','12'))) # using permutations to compute all possible permutationsprint (\"All the permutations of the given container is : \")print (list(itertools.permutations('GfG',2)))", "e": 29406, "s": 28956, "text": null }, { "code": null, "e": 29414, "s": 29406, "text": "Output:" }, { "code": null, "e": 29633, "s": 29414, "text": "The cartesian product of the containers is : \n[('A', '1'), ('A', '2'), ('B', '1'), ('B', '2')]\nAll the permutations of the given container is : \n[('G', 'f'), ('G', 'G'), ('f', 'G'), ('f', 'G'), ('G', 'G'), ('G', 'f')]\n" }, { "code": null, "e": 29828, "s": 29633, "text": "3. combinations(iterable, group_size) :- This iterator prints all the possible combinations(without replacement) of the container passed in arguments in the specified group size in sorted order." }, { "code": null, "e": 30037, "s": 29828, "text": "4. combinations_with_replacement(iterable, group_size) :- This iterator prints all the possible combinations(with replacement) of the container passed in arguments in the specified group size in sorted order." }, { "code": "# Python code to demonstrate the working of # combination() and combination_with_replacement() # importing \"itertools\" for iterator operationsimport itertools # using combinations() to print every combination# (without replacement)print (\"All the combination of container in sorted order(without replacement) is : \")print (list(itertools.combinations('1234',2))) # using combinations_with_replacement() to print every combination# with replacementprint (\"All the combination of container in sorted order(with replacement) is : \")print (list(itertools.combinations_with_replacement('GfG',2)))", "e": 30632, "s": 30037, "text": null }, { "code": null, "e": 30640, "s": 30632, "text": "Output:" }, { "code": null, "e": 30936, "s": 30640, "text": "All the combination of container in sorted order(without replacement) is : \n[('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')]\nAll the combination of container in sorted order(with replacement) is : \n[('G', 'G'), ('G', 'f'), ('G', 'G'), ('f', 'f'), ('f', 'G'), ('G', 'G')]\n" }, { "code": null, "e": 30955, "s": 30936, "text": "Infinite Iterators" }, { "code": null, "e": 31132, "s": 30955, "text": "1. count(start, step) :- This iterator starts printing from the “start” number and prints infinitely. If steps are mentioned, the numbers are skipped else step is 1 by default." }, { "code": null, "e": 31142, "s": 31132, "text": "Example :" }, { "code": null, "e": 31195, "s": 31142, "text": "iterator.count(5,2) prints -- 5,7,9,11...infinitely\n" }, { "code": null, "e": 31377, "s": 31195, "text": "2. cycle(iterable) :- This iterator prints all values in order from the passed container. It restarts printing from beginning again when all elements are printed in a cyclic manner." }, { "code": null, "e": 31387, "s": 31377, "text": "Example :" }, { "code": null, "e": 31455, "s": 31387, "text": "iterator.cycle([1,2,3,4]) prints -- 1,2,3,4,1,2,3,4,1...infinitely\n" }, { "code": null, "e": 31598, "s": 31455, "text": "3. repeat(val, num) :- This iterator repeatedly prints the passed value infinite number of times. If num. is mentioned, them till that number." }, { "code": "# Python code to demonstrate the working of # repeat() # importing \"itertools\" for iterator operationsimport itertools # using repeat() to repeatedly print numberprint (\"Printing the numbers repeatedly : \")print (list(itertools.repeat(25,4)))", "e": 31843, "s": 31598, "text": null }, { "code": null, "e": 31851, "s": 31843, "text": "Output:" }, { "code": null, "e": 31904, "s": 31851, "text": "Printing the numbers repeatedly : \n[25, 25, 25, 25]\n" }, { "code": null, "e": 32760, "s": 31904, "text": "YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Iterator Functions - Part 2 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:32•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=cgrDYgW0C3o\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 33061, "s": 32760, "text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 33186, "s": 33061, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 33193, "s": 33186, "text": "Python" }, { "code": null, "e": 33291, "s": 33193, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33309, "s": 33291, "text": "Python Dictionary" }, { "code": null, "e": 33344, "s": 33309, "text": "Read a file line by line in Python" }, { "code": null, "e": 33376, "s": 33344, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33418, "s": 33376, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 33444, "s": 33418, "text": "Python String | replace()" }, { "code": null, "e": 33473, "s": 33444, "text": "*args and **kwargs in Python" }, { "code": null, "e": 33517, "s": 33473, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 33554, "s": 33517, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 33590, "s": 33554, "text": "Convert integer to string in Python" } ]
Introduction to Resampling methods - GeeksforGeeks
26 Apr, 2022 While reading about Machine Learning and Data Science we often come across a term called Imbalanced Class Distribution , generally happens when observations in one of the classes are much higher or lower than any other classes. As Machine Learning algorithms tend to increase accuracy by reducing the error, they do not consider the class distribution. This problem is prevalent in examples such as Fraud Detection, Anomaly Detection, Facial recognition etc.Two common methods of Resampling are – Cross ValidationBootstrapping Cross Validation Bootstrapping Cross-Validation is used to estimate the test error associated with a model to evaluate its performance.Validation set approach: This is the most basic approach. It simply involves randomly dividing the dataset into two parts: first a training set and second a validation set or hold-out set. The model is fit on the training set and the fitted model is used to make predictions on the validation set. Leave-one-out-cross-validation: LOOCV is a better option than the validation set approach. Instead of splitting the entire dataset into two halves only one observation is used for validation and the rest is used to fit the model. k-fold cross-validation – This approach involves randomly dividing the set of observations into k folds of nearly equal size. The first fold is treated as a validation set and the model is fit on the remaining folds. The procedure is then repeated k times, where a different group each time is treated as the validation set. Bootstrap is a powerful statistical tool used to quantify the uncertainty of a given model. However, the real power of bootstrap is that it could get applied to a wide range of models where the variability is hard to obtain or not output automatically.Challenges: Algorithms in Machine Learning tend to produce unsatisfactory classifiers when handled with unbalanced datasets. For example, Movie Review datasets Total Observations : 100 Positive Dataset : 90 Negative Dataset : 10 Event rate : 2% The main problem here is how to get a balanced dataset.Challenges with standard ML algorithms: Standard ML techniques such as Decision Tree and Logistic Regression have a bias towards the majority class, and they tend to ignore the minority class. They tend only to predict the majority class, hence, having major misclassification of the minority class in comparison with the majority class.Evaluation of classification algorithm is measured by confusion matrix. A way to evaluate the results is by the confusion matrix, which shows the correct and incorrect predictions for each class. In the first row, the first column indicates how many classes “True” got predicted correctly, and the second column, how many classes “True” were predicted as “False”. In the second row, we note that all class “False” entries were predicted as class “True”. Therefore, the higher the diagonal values of the confusion matrix, the better the correct prediction. Handling Approach: Random Over-sampling: It aims to balance class distribution by randomly increasing minority class examples by replicating them.For example – Total Observations : 100 Positive Dataset : 90 Negative Dataset : 10 Event Rate : 2% We replicate Negative Dataset 15 times Positive Dataset: 90 Negative Dataset after Replicating: 150 Total Observations: 190 Event Rate : 150/240= 63% SMOTE (Synthetic Minority Oversampling Technique) synthesises new minority instances between existing minority instances. It randomly picks up the minority class and calculates the K-nearest neighbour for that particular point. Finally, the synthetic points are added between the neighbours and the chosen spot. Random Under-Sampling: It aims to balance class distribution by randomly eliminating majority class examples.For Example – Total Observations : 100 Positive Dataset : 90 Negative Dataset : 10 Event rate : 2% We take 10% samples of Positive Dataset and combine it with Negative Dataset. Positive Dataset after Random Under-Sampling : 10% of 90 = 9 Total observation after combining it with Negative Dataset: 10+9=19 Event Rate after Under-Sampling : 10/19 = 53% When instances of two different classes are very close to each other, we remove the instances of the majority class to increase the spaces between the two classes. This helps in the classification process. Cluster-based Over Sampling: K means clustering algorithm is independently applied to both the class instances such as to identify clusters in the datasets. All clusters are oversampled such that clusters of the same class have the same size.For Example – Total Observations : 100 Positive Dataset : 90 Negative Dataset : 10 Event Rate : 2% Majority Class Cluster: Cluster 1: 20 Observations Cluster 2: 30 Observations Cluster 3: 12 Observations Cluster 4: 18 Observations Cluster 5: 10 ObservationsMinority Class Cluster: Cluster 1: 8 Observations Cluster 2: 12 ObservationsAfter oversampling all clusters of the same class have the same number of observations.Majority Class Cluster: Cluster 1: 20 Observations Cluster 2: 20 Observations Cluster 3: 20 Observations Cluster 4: 20 Observations Cluster 5: 20 ObservationsMinority Class Cluster: Cluster 1: 15 Observations Cluster 2: 15 Observations Below is the implementation of some resampling techniques: You can download the dataset from the given link below : Dataset download Python3 # importing librariesimport pandas as pdimport numpy as npimport seaborn as snsfrom sklearn.preprocessing import StandardScalerfrom imblearn.under_sampling import RandomUnderSampler, TomekLinksfrom imblearn.over_sampling import RandomOverSampler, SMOTE Python3 dataset = pd.read_csv(r'C:\Users\Abhishek\Desktop\creditcard.csv') print("The Number of Samples in the dataset: ", len(dataset))print('Class 0 :', round(dataset['Class'].value_counts()[0] /len(dataset) * 100, 2), '% of the dataset') print('Class 1(Fraud) :', round(dataset['Class'].value_counts()[1] /len(dataset) * 100, 2), '% of the dataset') Python3 X_data = dataset.iloc[:, :-1]Y_data = dataset.iloc[:, -1:] rus = RandomUnderSampler(random_state = 42)X_res, y_res = rus.fit_resample(X_data, Y_data) X_res = pd.DataFrame(X_res)Y_res = pd.DataFrame(y_res) print("After Under Sampling Of Major Class Total Samples are :", len(Y_res))print('Class 0 :', round(Y_res[0].value_counts()[0] /len(Y_res) * 100, 2), '% of the dataset') print('Class 1(Fraud) :', round(Y_res[0].value_counts()[1] /len(Y_res) * 100, 2), '% of the dataset') Python3 tl = TomekLinks() X_res, y_res = tl.fit_resample(X_data, Y_data) X_res = pd.DataFrame(X_res)Y_res = pd.DataFrame(y_res) print("After TomekLinks Under Sampling Of Major Class Total Samples are :", len(Y_res))print('Class 0 :', round(Y_res[0].value_counts()[0] /len(Y_res) * 100, 2), '% of the dataset') print('Class 1(Fraud) :', round(Y_res[0].value_counts()[1] /len(Y_res) * 100, 2), '% of the dataset') Python3 ros = RandomOverSampler(random_state = 42) X_res, y_res = ros.fit_resample(X_data, Y_data) X_res = pd.DataFrame(X_res)Y_res = pd.DataFrame(y_res) print("After Over Sampling Of Minor Class Total Samples are :", len(Y_res))print('Class 0 :', round(Y_res[0].value_counts()[0] /len(Y_res) * 100, 2), '% of the dataset') print('Class 1(Fraud) :', round(Y_res[0].value_counts()[1] /len(Y_res) * 100, 2), '% of the dataset') Python3 sm = SMOTE(random_state = 42) X_res, y_res = sm.fit_resample(X_data, Y_data) X_res = pd.DataFrame(X_res)Y_res = pd.DataFrame(y_res) print("After SMOTE Over Sampling Of Minor Class Total Samples are :", len(Y_res))print('Class 0 :', round(Y_res[0].value_counts()[0] /len(Y_res) * 100, 2), '% of the dataset') print('Class 1(Fraud) :', round(Y_res[0].value_counts()[1] /len(Y_res) * 100, 2), '% of the dataset') SohomPramanick sumitgumber28 data-science Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning k-nearest neighbor algorithm in Python Markov Decision Process Singular Value Decomposition (SVD) Q-Learning in Python SARSA Reinforcement Learning
[ { "code": null, "e": 25589, "s": 25561, "text": "\n26 Apr, 2022" }, { "code": null, "e": 26087, "s": 25589, "text": "While reading about Machine Learning and Data Science we often come across a term called Imbalanced Class Distribution , generally happens when observations in one of the classes are much higher or lower than any other classes. As Machine Learning algorithms tend to increase accuracy by reducing the error, they do not consider the class distribution. This problem is prevalent in examples such as Fraud Detection, Anomaly Detection, Facial recognition etc.Two common methods of Resampling are – " }, { "code": null, "e": 26117, "s": 26087, "text": "Cross ValidationBootstrapping" }, { "code": null, "e": 26134, "s": 26117, "text": "Cross Validation" }, { "code": null, "e": 26148, "s": 26134, "text": "Bootstrapping" }, { "code": null, "e": 26552, "s": 26148, "text": "Cross-Validation is used to estimate the test error associated with a model to evaluate its performance.Validation set approach: This is the most basic approach. It simply involves randomly dividing the dataset into two parts: first a training set and second a validation set or hold-out set. The model is fit on the training set and the fitted model is used to make predictions on the validation set. " }, { "code": null, "e": 26784, "s": 26552, "text": "Leave-one-out-cross-validation: LOOCV is a better option than the validation set approach. Instead of splitting the entire dataset into two halves only one observation is used for validation and the rest is used to fit the model. " }, { "code": null, "e": 27111, "s": 26784, "text": "k-fold cross-validation – This approach involves randomly dividing the set of observations into k folds of nearly equal size. The first fold is treated as a validation set and the model is fit on the remaining folds. The procedure is then repeated k times, where a different group each time is treated as the validation set. " }, { "code": null, "e": 27527, "s": 27113, "text": "Bootstrap is a powerful statistical tool used to quantify the uncertainty of a given model. However, the real power of bootstrap is that it could get applied to a wide range of models where the variability is hard to obtain or not output automatically.Challenges: Algorithms in Machine Learning tend to produce unsatisfactory classifiers when handled with unbalanced datasets. For example, Movie Review datasets " }, { "code": null, "e": 27612, "s": 27527, "text": "Total Observations : 100\nPositive Dataset : 90\nNegative Dataset : 10\nEvent rate : 2%" }, { "code": null, "e": 28077, "s": 27612, "text": "The main problem here is how to get a balanced dataset.Challenges with standard ML algorithms: Standard ML techniques such as Decision Tree and Logistic Regression have a bias towards the majority class, and they tend to ignore the minority class. They tend only to predict the majority class, hence, having major misclassification of the minority class in comparison with the majority class.Evaluation of classification algorithm is measured by confusion matrix. " }, { "code": null, "e": 28580, "s": 28077, "text": "A way to evaluate the results is by the confusion matrix, which shows the correct and incorrect predictions for each class. In the first row, the first column indicates how many classes “True” got predicted correctly, and the second column, how many classes “True” were predicted as “False”. In the second row, we note that all class “False” entries were predicted as class “True”. Therefore, the higher the diagonal values of the confusion matrix, the better the correct prediction. Handling Approach:" }, { "code": null, "e": 28721, "s": 28580, "text": "Random Over-sampling: It aims to balance class distribution by randomly increasing minority class examples by replicating them.For example –" }, { "code": null, "e": 28806, "s": 28721, "text": "Total Observations : 100\nPositive Dataset : 90\nNegative Dataset : 10\nEvent Rate : 2%" }, { "code": null, "e": 28846, "s": 28806, "text": "We replicate Negative Dataset 15 times " }, { "code": null, "e": 28957, "s": 28846, "text": "Positive Dataset: 90\nNegative Dataset after Replicating: 150\nTotal Observations: 190\nEvent Rate : 150/240= 63%" }, { "code": null, "e": 29269, "s": 28957, "text": "SMOTE (Synthetic Minority Oversampling Technique) synthesises new minority instances between existing minority instances. It randomly picks up the minority class and calculates the K-nearest neighbour for that particular point. Finally, the synthetic points are added between the neighbours and the chosen spot." }, { "code": null, "e": 29393, "s": 29269, "text": "Random Under-Sampling: It aims to balance class distribution by randomly eliminating majority class examples.For Example – " }, { "code": null, "e": 29736, "s": 29393, "text": "Total Observations : 100\nPositive Dataset : 90\nNegative Dataset : 10\nEvent rate : 2%\n\nWe take 10% samples of Positive Dataset and combine it with Negative Dataset.\n\nPositive Dataset after Random Under-Sampling : 10% of 90 = 9 \n\nTotal observation after combining it with Negative Dataset: 10+9=19\n\nEvent Rate after Under-Sampling : 10/19 = 53%" }, { "code": null, "e": 29942, "s": 29736, "text": "When instances of two different classes are very close to each other, we remove the instances of the majority class to increase the spaces between the two classes. This helps in the classification process." }, { "code": null, "e": 30199, "s": 29942, "text": "Cluster-based Over Sampling: K means clustering algorithm is independently applied to both the class instances such as to identify clusters in the datasets. All clusters are oversampled such that clusters of the same class have the same size.For Example – " }, { "code": null, "e": 30284, "s": 30199, "text": "Total Observations : 100\nPositive Dataset : 90\nNegative Dataset : 10\nEvent Rate : 2%" }, { "code": null, "e": 30975, "s": 30284, "text": "Majority Class Cluster: Cluster 1: 20 Observations Cluster 2: 30 Observations Cluster 3: 12 Observations Cluster 4: 18 Observations Cluster 5: 10 ObservationsMinority Class Cluster: Cluster 1: 8 Observations Cluster 2: 12 ObservationsAfter oversampling all clusters of the same class have the same number of observations.Majority Class Cluster: Cluster 1: 20 Observations Cluster 2: 20 Observations Cluster 3: 20 Observations Cluster 4: 20 Observations Cluster 5: 20 ObservationsMinority Class Cluster: Cluster 1: 15 Observations Cluster 2: 15 Observations Below is the implementation of some resampling techniques: You can download the dataset from the given link below : Dataset download" }, { "code": null, "e": 30983, "s": 30975, "text": "Python3" }, { "code": "# importing librariesimport pandas as pdimport numpy as npimport seaborn as snsfrom sklearn.preprocessing import StandardScalerfrom imblearn.under_sampling import RandomUnderSampler, TomekLinksfrom imblearn.over_sampling import RandomOverSampler, SMOTE", "e": 31236, "s": 30983, "text": null }, { "code": null, "e": 31244, "s": 31236, "text": "Python3" }, { "code": "dataset = pd.read_csv(r'C:\\Users\\Abhishek\\Desktop\\creditcard.csv') print(\"The Number of Samples in the dataset: \", len(dataset))print('Class 0 :', round(dataset['Class'].value_counts()[0] /len(dataset) * 100, 2), '% of the dataset') print('Class 1(Fraud) :', round(dataset['Class'].value_counts()[1] /len(dataset) * 100, 2), '% of the dataset')", "e": 31648, "s": 31244, "text": null }, { "code": null, "e": 31656, "s": 31648, "text": "Python3" }, { "code": "X_data = dataset.iloc[:, :-1]Y_data = dataset.iloc[:, -1:] rus = RandomUnderSampler(random_state = 42)X_res, y_res = rus.fit_resample(X_data, Y_data) X_res = pd.DataFrame(X_res)Y_res = pd.DataFrame(y_res) print(\"After Under Sampling Of Major Class Total Samples are :\", len(Y_res))print('Class 0 :', round(Y_res[0].value_counts()[0] /len(Y_res) * 100, 2), '% of the dataset') print('Class 1(Fraud) :', round(Y_res[0].value_counts()[1] /len(Y_res) * 100, 2), '% of the dataset')", "e": 32182, "s": 31656, "text": null }, { "code": null, "e": 32190, "s": 32182, "text": "Python3" }, { "code": "tl = TomekLinks() X_res, y_res = tl.fit_resample(X_data, Y_data) X_res = pd.DataFrame(X_res)Y_res = pd.DataFrame(y_res) print(\"After TomekLinks Under Sampling Of Major Class Total Samples are :\", len(Y_res))print('Class 0 :', round(Y_res[0].value_counts()[0] /len(Y_res) * 100, 2), '% of the dataset') print('Class 1(Fraud) :', round(Y_res[0].value_counts()[1] /len(Y_res) * 100, 2), '% of the dataset')", "e": 32642, "s": 32190, "text": null }, { "code": null, "e": 32650, "s": 32642, "text": "Python3" }, { "code": "ros = RandomOverSampler(random_state = 42) X_res, y_res = ros.fit_resample(X_data, Y_data) X_res = pd.DataFrame(X_res)Y_res = pd.DataFrame(y_res) print(\"After Over Sampling Of Minor Class Total Samples are :\", len(Y_res))print('Class 0 :', round(Y_res[0].value_counts()[0] /len(Y_res) * 100, 2), '% of the dataset') print('Class 1(Fraud) :', round(Y_res[0].value_counts()[1] /len(Y_res) * 100, 2), '% of the dataset')", "e": 33115, "s": 32650, "text": null }, { "code": null, "e": 33123, "s": 33115, "text": "Python3" }, { "code": "sm = SMOTE(random_state = 42) X_res, y_res = sm.fit_resample(X_data, Y_data) X_res = pd.DataFrame(X_res)Y_res = pd.DataFrame(y_res) print(\"After SMOTE Over Sampling Of Minor Class Total Samples are :\", len(Y_res))print('Class 0 :', round(Y_res[0].value_counts()[0] /len(Y_res) * 100, 2), '% of the dataset') print('Class 1(Fraud) :', round(Y_res[0].value_counts()[1] /len(Y_res) * 100, 2), '% of the dataset')", "e": 33583, "s": 33123, "text": null }, { "code": null, "e": 33598, "s": 33583, "text": "SohomPramanick" }, { "code": null, "e": 33612, "s": 33598, "text": "sumitgumber28" }, { "code": null, "e": 33625, "s": 33612, "text": "data-science" }, { "code": null, "e": 33642, "s": 33625, "text": "Machine Learning" }, { "code": null, "e": 33659, "s": 33642, "text": "Machine Learning" }, { "code": null, "e": 33757, "s": 33659, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33798, "s": 33757, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 33831, "s": 33798, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 33859, "s": 33831, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 33895, "s": 33859, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 33950, "s": 33895, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 33989, "s": 33950, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 34013, "s": 33989, "text": "Markov Decision Process" }, { "code": null, "e": 34048, "s": 34013, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 34069, "s": 34048, "text": "Q-Learning in Python" } ]
Program to print the series 1, 9, 17, 33, 49, 73, 97... till N terms - GeeksforGeeks
24 Nov, 2021 Given a number N, the task is to print the first N terms of the series: Examples: Input: N = 7 Output: 1, 9, 17, 33, 49, 73, 97Input: N = 3 Output: 1, 9, 17 Approach: From the given series, find the formula for Nth term: 1st term = 1 2nd term = 9 = 2 * 4 + 1 3rd term = 17 = 2 * 9 - 1 4th term = 33 = 2 * 16 + 1 5th term = 49 = 2 * 25 - 1 6th term = 73 = 2 * 36 + 1 . . Nth term = (2 * N2 + (-1)N) Therefore: Nth term of the series *** QuickLaTeX cannot compile formula: *** Error message: Error: Nothing to show, formula is empty Then iterate over numbers in the range [1, N] to find all the terms using the above formula and print them.Below is the implementation of the above approach: CPP Java Python3 C# Javascript // C++ implementation of the above approach #include "bits/stdc++.h"using namespace std; // Function to print the seriesvoid printSeries(int N){ int ith_term = 0; // Generate the ith term and // print it for (int i = 1; i <= N; i++) { ith_term = i % 2 == 0 ? 2 * i * i + 1 : 2 * i * i - 1; cout << ith_term << ", "; }} // Driver Codeint main(){ int N = 7; printSeries(N); return 0;} // Java implementation of the above approachimport java.util.*; class GFG{ // Function to print the seriesstatic void printSeries(int N){ int ith_term = 0; // Generate the ith term and // print it for (int i = 1; i <= N; i++) { ith_term = i % 2 == 0 ? 2 * i * i + 1 : 2 * i * i - 1; System.out.print(ith_term+ ", "); }} // Driver Codepublic static void main(String[] args){ int N = 7; printSeries(N);}} // This code is contributed by PrinciRaj1992 # Python implementation of the above approach # Function to print seriesdef printSeries(N): ith_term = 0; # Generate the ith term and # print for i in range(1,N+1): ith_term = 0; if(i % 2 == 0): ith_term = 2 * i * i + 1; else: ith_term = 2 * i * i - 1; print(ith_term,end= ", "); # Driver Codeif __name__ == '__main__': N = 7; printSeries(N); # This code is contributed by Princi Singh // C# implementation of the above approachusing System; class GFG{ // Function to print the seriesstatic void printSeries(int N){ int ith_term = 0; // Generate the ith term and // print it for (int i = 1; i <= N; i++) { ith_term = i % 2 == 0? 2 * i * i + 1: 2 * i * i - 1; Console.Write(ith_term+ ", "); }} // Driver Codepublic static void Main(){ int N = 7; printSeries(N);}} // This code is contributed by AbhiThakur <script>// javascript implementation of the above approach // Function to print the seriesfunction printSeries( N){ let ith_term = 0; // Generate the ith term and // print it for (let i = 1; i <= N; i++) { ith_term = i % 2 == 0 ? 2 * i * i + 1 : 2 * i * i - 1; document.write( ith_term + ", "); }} // Driver Code let N = 7; printSeries(N); // This code is contributed by gauravrajput1 </script> 1, 9, 17, 33, 49, 73, 97, Time Complexity: O(N) Auxiliary Space: O(1) princiraj1992 abhaysingh290895 princi singh GauravRajput1 sweetyty khushboogoyal499 rishavmahato348 series series-sum Mathematical School Programming Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 25937, "s": 25909, "text": "\n24 Nov, 2021" }, { "code": null, "e": 26010, "s": 25937, "text": "Given a number N, the task is to print the first N terms of the series: " }, { "code": null, "e": 26022, "s": 26010, "text": "Examples: " }, { "code": null, "e": 26099, "s": 26022, "text": "Input: N = 7 Output: 1, 9, 17, 33, 49, 73, 97Input: N = 3 Output: 1, 9, 17 " }, { "code": null, "e": 26167, "s": 26101, "text": "Approach: From the given series, find the formula for Nth term: " }, { "code": null, "e": 26344, "s": 26167, "text": "1st term = 1\n2nd term = 9 = 2 * 4 + 1\n3rd term = 17 = 2 * 9 - 1\n4th term = 33 = 2 * 16 + 1\n5th term = 49 = 2 * 25 - 1\n6th term = 73 = 2 * 36 + 1\n.\n.\nNth term = (2 * N2 + (-1)N)" }, { "code": null, "e": 26357, "s": 26344, "text": "Therefore: " }, { "code": null, "e": 26381, "s": 26357, "text": "Nth term of the series " }, { "code": null, "e": 26484, "s": 26381, "text": "*** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n" }, { "code": null, "e": 26644, "s": 26484, "text": "Then iterate over numbers in the range [1, N] to find all the terms using the above formula and print them.Below is the implementation of the above approach: " }, { "code": null, "e": 26648, "s": 26644, "text": "CPP" }, { "code": null, "e": 26653, "s": 26648, "text": "Java" }, { "code": null, "e": 26661, "s": 26653, "text": "Python3" }, { "code": null, "e": 26664, "s": 26661, "text": "C#" }, { "code": null, "e": 26675, "s": 26664, "text": "Javascript" }, { "code": "// C++ implementation of the above approach #include \"bits/stdc++.h\"using namespace std; // Function to print the seriesvoid printSeries(int N){ int ith_term = 0; // Generate the ith term and // print it for (int i = 1; i <= N; i++) { ith_term = i % 2 == 0 ? 2 * i * i + 1 : 2 * i * i - 1; cout << ith_term << \", \"; }} // Driver Codeint main(){ int N = 7; printSeries(N); return 0;}", "e": 27144, "s": 26675, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*; class GFG{ // Function to print the seriesstatic void printSeries(int N){ int ith_term = 0; // Generate the ith term and // print it for (int i = 1; i <= N; i++) { ith_term = i % 2 == 0 ? 2 * i * i + 1 : 2 * i * i - 1; System.out.print(ith_term+ \", \"); }} // Driver Codepublic static void main(String[] args){ int N = 7; printSeries(N);}} // This code is contributed by PrinciRaj1992", "e": 27681, "s": 27144, "text": null }, { "code": "# Python implementation of the above approach # Function to print seriesdef printSeries(N): ith_term = 0; # Generate the ith term and # print for i in range(1,N+1): ith_term = 0; if(i % 2 == 0): ith_term = 2 * i * i + 1; else: ith_term = 2 * i * i - 1; print(ith_term,end= \", \"); # Driver Codeif __name__ == '__main__': N = 7; printSeries(N); # This code is contributed by Princi Singh", "e": 28147, "s": 27681, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function to print the seriesstatic void printSeries(int N){ int ith_term = 0; // Generate the ith term and // print it for (int i = 1; i <= N; i++) { ith_term = i % 2 == 0? 2 * i * i + 1: 2 * i * i - 1; Console.Write(ith_term+ \", \"); }} // Driver Codepublic static void Main(){ int N = 7; printSeries(N);}} // This code is contributed by AbhiThakur", "e": 28636, "s": 28147, "text": null }, { "code": "<script>// javascript implementation of the above approach // Function to print the seriesfunction printSeries( N){ let ith_term = 0; // Generate the ith term and // print it for (let i = 1; i <= N; i++) { ith_term = i % 2 == 0 ? 2 * i * i + 1 : 2 * i * i - 1; document.write( ith_term + \", \"); }} // Driver Code let N = 7; printSeries(N); // This code is contributed by gauravrajput1 </script>", "e": 29123, "s": 28636, "text": null }, { "code": null, "e": 29149, "s": 29123, "text": "1, 9, 17, 33, 49, 73, 97," }, { "code": null, "e": 29173, "s": 29151, "text": "Time Complexity: O(N)" }, { "code": null, "e": 29195, "s": 29173, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 29209, "s": 29195, "text": "princiraj1992" }, { "code": null, "e": 29226, "s": 29209, "text": "abhaysingh290895" }, { "code": null, "e": 29239, "s": 29226, "text": "princi singh" }, { "code": null, "e": 29253, "s": 29239, "text": "GauravRajput1" }, { "code": null, "e": 29262, "s": 29253, "text": "sweetyty" }, { "code": null, "e": 29279, "s": 29262, "text": "khushboogoyal499" }, { "code": null, "e": 29295, "s": 29279, "text": "rishavmahato348" }, { "code": null, "e": 29302, "s": 29295, "text": "series" }, { "code": null, "e": 29313, "s": 29302, "text": "series-sum" }, { "code": null, "e": 29326, "s": 29313, "text": "Mathematical" }, { "code": null, "e": 29345, "s": 29326, "text": "School Programming" }, { "code": null, "e": 29358, "s": 29345, "text": "Mathematical" }, { "code": null, "e": 29365, "s": 29358, "text": "series" }, { "code": null, "e": 29463, "s": 29365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29507, "s": 29463, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 29549, "s": 29507, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 29580, "s": 29549, "text": "Modular multiplicative inverse" }, { "code": null, "e": 29651, "s": 29580, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 29676, "s": 29651, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 29694, "s": 29676, "text": "Python Dictionary" }, { "code": null, "e": 29710, "s": 29694, "text": "Arrays in C/C++" }, { "code": null, "e": 29729, "s": 29710, "text": "Inheritance in C++" }, { "code": null, "e": 29754, "s": 29729, "text": "Reverse a string in Java" } ]
BufferedWriter newLine() method in Java with Examples - GeeksforGeeks
28 May, 2020 The newLine() method of BufferedWriter class in Java is used to separate the next line as a new line. It is used as a write separator in buffered writer stream. Syntax: public void newLine() throws IOException Parameters: This method does not accept any parameter. Return value: This method does not return any value. Exceptions: This method throws IOException if an I/O error occurs. Below programs illustrate newLine() method in BufferedWriter class in IO package: Program 1: // Java program to illustrate// BufferedWriter newLine() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write "A" to buffer writer buffWriter.write(65); // Revoke newLine() method buffWriter.newLine(); // Write "B" to buffer writer buffWriter.write(66); buffWriter.flush(); System.out.println( stringWriter.getBuffer()); }} A B Program 2: // Java program to illustrate// BufferedWriter newLine() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write "GEEKS" to buffered writer buffWriter.write( "GEEKSFORGEEKS", 0, 5); // Revoke newLine() method buffWriter.newLine(); // Write "GEEKSFORGEEKS" // to buffered writer buffWriter.write( "GEEKSFORGEEKS", 0, 13); buffWriter.flush(); System.out.println( stringWriter.getBuffer()); }} GEEKS GEEKSFORGEEKS References:https://docs.oracle.com/javase/10/docs/api/java/io/BufferedWriter.html#newLine() Java-Functions Java-IO 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 Generics in Java Different ways of Reading a text file in Java Internal Working of HashMap in Java Introduction to Java Comparator Interface in Java with Examples Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n28 May, 2020" }, { "code": null, "e": 25386, "s": 25225, "text": "The newLine() method of BufferedWriter class in Java is used to separate the next line as a new line. It is used as a write separator in buffered writer stream." }, { "code": null, "e": 25394, "s": 25386, "text": "Syntax:" }, { "code": null, "e": 25448, "s": 25394, "text": "public void newLine()\n throws IOException\n" }, { "code": null, "e": 25503, "s": 25448, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 25556, "s": 25503, "text": "Return value: This method does not return any value." }, { "code": null, "e": 25623, "s": 25556, "text": "Exceptions: This method throws IOException if an I/O error occurs." }, { "code": null, "e": 25705, "s": 25623, "text": "Below programs illustrate newLine() method in BufferedWriter class in IO package:" }, { "code": null, "e": 25716, "s": 25705, "text": "Program 1:" }, { "code": "// Java program to illustrate// BufferedWriter newLine() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write \"A\" to buffer writer buffWriter.write(65); // Revoke newLine() method buffWriter.newLine(); // Write \"B\" to buffer writer buffWriter.write(66); buffWriter.flush(); System.out.println( stringWriter.getBuffer()); }}", "e": 26455, "s": 25716, "text": null }, { "code": null, "e": 26460, "s": 26455, "text": "A\nB\n" }, { "code": null, "e": 26471, "s": 26460, "text": "Program 2:" }, { "code": "// Java program to illustrate// BufferedWriter newLine() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write \"GEEKS\" to buffered writer buffWriter.write( \"GEEKSFORGEEKS\", 0, 5); // Revoke newLine() method buffWriter.newLine(); // Write \"GEEKSFORGEEKS\" // to buffered writer buffWriter.write( \"GEEKSFORGEEKS\", 0, 13); buffWriter.flush(); System.out.println( stringWriter.getBuffer()); }}", "e": 27301, "s": 26471, "text": null }, { "code": null, "e": 27322, "s": 27301, "text": "GEEKS\nGEEKSFORGEEKS\n" }, { "code": null, "e": 27414, "s": 27322, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/io/BufferedWriter.html#newLine()" }, { "code": null, "e": 27429, "s": 27414, "text": "Java-Functions" }, { "code": null, "e": 27445, "s": 27429, "text": "Java-IO package" }, { "code": null, "e": 27450, "s": 27445, "text": "Java" }, { "code": null, "e": 27455, "s": 27450, "text": "Java" }, { "code": null, "e": 27553, "s": 27455, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27568, "s": 27553, "text": "Stream In Java" }, { "code": null, "e": 27589, "s": 27568, "text": "Constructors in Java" }, { "code": null, "e": 27608, "s": 27589, "text": "Exceptions in Java" }, { "code": null, "e": 27638, "s": 27608, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27655, "s": 27638, "text": "Generics in Java" }, { "code": null, "e": 27701, "s": 27655, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27737, "s": 27701, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 27758, "s": 27737, "text": "Introduction to Java" }, { "code": null, "e": 27801, "s": 27758, "text": "Comparator Interface in Java with Examples" } ]
case command in Linux with examples - GeeksforGeeks
15 May, 2019 case command in Linux is the best alternative when we had to use multiple if/elif on a single variable. It is used to execute the commands based on the pattern matching. Syntax: case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac Example: Options: help case : It displays help information. Linux-basic-commands linux-command Picked Technical Scripter 2018 Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples Docker - COPY Instruction mv command in Linux with examples SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25677, "s": 25649, "text": "\n15 May, 2019" }, { "code": null, "e": 25847, "s": 25677, "text": "case command in Linux is the best alternative when we had to use multiple if/elif on a single variable. It is used to execute the commands based on the pattern matching." }, { "code": null, "e": 25855, "s": 25847, "text": "Syntax:" }, { "code": null, "e": 25914, "s": 25855, "text": "case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac" }, { "code": null, "e": 25923, "s": 25914, "text": "Example:" }, { "code": null, "e": 25932, "s": 25923, "text": "Options:" }, { "code": null, "e": 25974, "s": 25932, "text": "help case : It displays help information." }, { "code": null, "e": 25995, "s": 25974, "text": "Linux-basic-commands" }, { "code": null, "e": 26009, "s": 25995, "text": "linux-command" }, { "code": null, "e": 26016, "s": 26009, "text": "Picked" }, { "code": null, "e": 26040, "s": 26016, "text": "Technical Scripter 2018" }, { "code": null, "e": 26051, "s": 26040, "text": "Linux-Unix" }, { "code": null, "e": 26070, "s": 26051, "text": "Technical Scripter" }, { "code": null, "e": 26168, "s": 26070, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26203, "s": 26168, "text": "scp command in Linux with Examples" }, { "code": null, "e": 26229, "s": 26203, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26263, "s": 26229, "text": "mv command in Linux with examples" }, { "code": null, "e": 26292, "s": 26263, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 26329, "s": 26292, "text": "chown command in Linux with Examples" }, { "code": null, "e": 26366, "s": 26329, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 26408, "s": 26366, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 26434, "s": 26408, "text": "Thread functions in C/C++" }, { "code": null, "e": 26470, "s": 26434, "text": "uniq Command in LINUX with examples" } ]
How to install specified directory using npm ? - GeeksforGeeks
10 Feb, 2021 Node. js is a platform built on Chrome’s JavaScript v8 engine, which is used for easily building fast and scalable network applications, javascript uses an event-driven, non-blocking I/O model that makes it lightweight and efficient which is perfect for data-intensive real-time applications that run across distributed devices and to make use of the tools (or packages) in Node. js, we need to be able to install in our machine and manage them in a useful way. This is where npm, the Node package manager, comes in to play and it contains default packages and also allows us to install external packages in our project. We want to use and provides a user interface to work with them. Installing npm to a specific directory using the following simple steps : First, check if Node is installed on your pc or laptop. In order to check if Node is pre-installed or not open up a terminal in mac or command prompt in windows and type the following command :node -vNow, if the Node version is displayed something like “v12.18.3′′ then you may conclude that Node is pre-installed on the pc or laptop, if not then please refer this article and install node according to your PC requirement and version.Open up a javascript project in an editor and decide on which directory you want to install the npm package, we can also create a sub-directory and install our npm packages, to create a sub-directory “cd”(change directory) into the project directory and make use of mkdir command, To create a new Folder/directory we can use mkdir <folder name > and to make a sub-directory or sub-folder inside a directory/folder use command mkdir -p <folder name>. Here, I will be creating a directory named “new” under my “TEST” project folder in which I will install my npm package.So, I will be using the command in terminal “mkdir -p new” once our directory in the terminal is set to our Project directory i.e “TEST” and we can see our project files are structured somewhat in this manner under the “TEST” main directory.Now, our final step to install to a specific directory will be to make use of the –prefix option, Here we will be making use of the following command to install our npm package into a specific directory.npm install --prefix ./(folder/sub_folder_name) <package name>Installing npm package “animation” in the current directory and using below command:npm install --prefix ./new animationConsole Output:Now, as we have installed our required npm package into our desired sub-directory i.e “new”, we can check our “new” directory by opening it and we can see that the following package is successfully installed into the directory.Updated Project structure:My Personal Notes arrow_drop_upSave First, check if Node is installed on your pc or laptop. In order to check if Node is pre-installed or not open up a terminal in mac or command prompt in windows and type the following command :node -vNow, if the Node version is displayed something like “v12.18.3′′ then you may conclude that Node is pre-installed on the pc or laptop, if not then please refer this article and install node according to your PC requirement and version. First, check if Node is installed on your pc or laptop. In order to check if Node is pre-installed or not open up a terminal in mac or command prompt in windows and type the following command : node -v Now, if the Node version is displayed something like “v12.18.3′′ then you may conclude that Node is pre-installed on the pc or laptop, if not then please refer this article and install node according to your PC requirement and version. Open up a javascript project in an editor and decide on which directory you want to install the npm package, we can also create a sub-directory and install our npm packages, to create a sub-directory “cd”(change directory) into the project directory and make use of mkdir command, To create a new Folder/directory we can use mkdir <folder name > and to make a sub-directory or sub-folder inside a directory/folder use command mkdir -p <folder name>. Here, I will be creating a directory named “new” under my “TEST” project folder in which I will install my npm package.So, I will be using the command in terminal “mkdir -p new” once our directory in the terminal is set to our Project directory i.e “TEST” and we can see our project files are structured somewhat in this manner under the “TEST” main directory. Open up a javascript project in an editor and decide on which directory you want to install the npm package, we can also create a sub-directory and install our npm packages, to create a sub-directory “cd”(change directory) into the project directory and make use of mkdir command, To create a new Folder/directory we can use mkdir <folder name > and to make a sub-directory or sub-folder inside a directory/folder use command mkdir -p <folder name>. Here, I will be creating a directory named “new” under my “TEST” project folder in which I will install my npm package.So, I will be using the command in terminal “mkdir -p new” once our directory in the terminal is set to our Project directory i.e “TEST” and we can see our project files are structured somewhat in this manner under the “TEST” main directory. Now, our final step to install to a specific directory will be to make use of the –prefix option, Here we will be making use of the following command to install our npm package into a specific directory.npm install --prefix ./(folder/sub_folder_name) <package name>Installing npm package “animation” in the current directory and using below command:npm install --prefix ./new animationConsole Output:Now, as we have installed our required npm package into our desired sub-directory i.e “new”, we can check our “new” directory by opening it and we can see that the following package is successfully installed into the directory.Updated Project structure:My Personal Notes arrow_drop_upSave Now, our final step to install to a specific directory will be to make use of the –prefix option, Here we will be making use of the following command to install our npm package into a specific directory. npm install --prefix ./(folder/sub_folder_name) <package name> Installing npm package “animation” in the current directory and using below command: npm install --prefix ./new animation Console Output: Now, as we have installed our required npm package into our desired sub-directory i.e “new”, we can check our “new” directory by opening it and we can see that the following package is successfully installed into the directory. Updated Project structure: Node-npm Picked Technical Scripter 2020 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between dependencies, devDependencies and peerDependencies How to connect Node.js with React.js ? Node.js Export Module Mongoose find() Function Mongoose Populate() Method Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26267, "s": 26239, "text": "\n10 Feb, 2021" }, { "code": null, "e": 26952, "s": 26267, "text": "Node. js is a platform built on Chrome’s JavaScript v8 engine, which is used for easily building fast and scalable network applications, javascript uses an event-driven, non-blocking I/O model that makes it lightweight and efficient which is perfect for data-intensive real-time applications that run across distributed devices and to make use of the tools (or packages) in Node. js, we need to be able to install in our machine and manage them in a useful way. This is where npm, the Node package manager, comes in to play and it contains default packages and also allows us to install external packages in our project. We want to use and provides a user interface to work with them." }, { "code": null, "e": 27026, "s": 26952, "text": "Installing npm to a specific directory using the following simple steps :" }, { "code": null, "e": 28961, "s": 27026, "text": "First, check if Node is installed on your pc or laptop. In order to check if Node is pre-installed or not open up a terminal in mac or command prompt in windows and type the following command :node -vNow, if the Node version is displayed something like “v12.18.3′′ then you may conclude that Node is pre-installed on the pc or laptop, if not then please refer this article and install node according to your PC requirement and version.Open up a javascript project in an editor and decide on which directory you want to install the npm package, we can also create a sub-directory and install our npm packages, to create a sub-directory “cd”(change directory) into the project directory and make use of mkdir command, To create a new Folder/directory we can use mkdir <folder name > and to make a sub-directory or sub-folder inside a directory/folder use command mkdir -p <folder name>. Here, I will be creating a directory named “new” under my “TEST” project folder in which I will install my npm package.So, I will be using the command in terminal “mkdir -p new” once our directory in the terminal is set to our Project directory i.e “TEST” and we can see our project files are structured somewhat in this manner under the “TEST” main directory.Now, our final step to install to a specific directory will be to make use of the –prefix option, Here we will be making use of the following command to install our npm package into a specific directory.npm install --prefix ./(folder/sub_folder_name) <package name>Installing npm package “animation” in the current directory and using below command:npm install --prefix ./new animationConsole Output:Now, as we have installed our required npm package into our desired sub-directory i.e “new”, we can check our “new” directory by opening it and we can see that the following package is successfully installed into the directory.Updated Project structure:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29397, "s": 28961, "text": "First, check if Node is installed on your pc or laptop. In order to check if Node is pre-installed or not open up a terminal in mac or command prompt in windows and type the following command :node -vNow, if the Node version is displayed something like “v12.18.3′′ then you may conclude that Node is pre-installed on the pc or laptop, if not then please refer this article and install node according to your PC requirement and version." }, { "code": null, "e": 29591, "s": 29397, "text": "First, check if Node is installed on your pc or laptop. In order to check if Node is pre-installed or not open up a terminal in mac or command prompt in windows and type the following command :" }, { "code": null, "e": 29599, "s": 29591, "text": "node -v" }, { "code": null, "e": 29835, "s": 29599, "text": "Now, if the Node version is displayed something like “v12.18.3′′ then you may conclude that Node is pre-installed on the pc or laptop, if not then please refer this article and install node according to your PC requirement and version." }, { "code": null, "e": 30647, "s": 29835, "text": "Open up a javascript project in an editor and decide on which directory you want to install the npm package, we can also create a sub-directory and install our npm packages, to create a sub-directory “cd”(change directory) into the project directory and make use of mkdir command, To create a new Folder/directory we can use mkdir <folder name > and to make a sub-directory or sub-folder inside a directory/folder use command mkdir -p <folder name>. Here, I will be creating a directory named “new” under my “TEST” project folder in which I will install my npm package.So, I will be using the command in terminal “mkdir -p new” once our directory in the terminal is set to our Project directory i.e “TEST” and we can see our project files are structured somewhat in this manner under the “TEST” main directory." }, { "code": null, "e": 31459, "s": 30647, "text": "Open up a javascript project in an editor and decide on which directory you want to install the npm package, we can also create a sub-directory and install our npm packages, to create a sub-directory “cd”(change directory) into the project directory and make use of mkdir command, To create a new Folder/directory we can use mkdir <folder name > and to make a sub-directory or sub-folder inside a directory/folder use command mkdir -p <folder name>. Here, I will be creating a directory named “new” under my “TEST” project folder in which I will install my npm package.So, I will be using the command in terminal “mkdir -p new” once our directory in the terminal is set to our Project directory i.e “TEST” and we can see our project files are structured somewhat in this manner under the “TEST” main directory." }, { "code": null, "e": 32148, "s": 31459, "text": "Now, our final step to install to a specific directory will be to make use of the –prefix option, Here we will be making use of the following command to install our npm package into a specific directory.npm install --prefix ./(folder/sub_folder_name) <package name>Installing npm package “animation” in the current directory and using below command:npm install --prefix ./new animationConsole Output:Now, as we have installed our required npm package into our desired sub-directory i.e “new”, we can check our “new” directory by opening it and we can see that the following package is successfully installed into the directory.Updated Project structure:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 32352, "s": 32148, "text": "Now, our final step to install to a specific directory will be to make use of the –prefix option, Here we will be making use of the following command to install our npm package into a specific directory." }, { "code": null, "e": 32415, "s": 32352, "text": "npm install --prefix ./(folder/sub_folder_name) <package name>" }, { "code": null, "e": 32500, "s": 32415, "text": "Installing npm package “animation” in the current directory and using below command:" }, { "code": null, "e": 32537, "s": 32500, "text": "npm install --prefix ./new animation" }, { "code": null, "e": 32553, "s": 32537, "text": "Console Output:" }, { "code": null, "e": 32781, "s": 32553, "text": "Now, as we have installed our required npm package into our desired sub-directory i.e “new”, we can check our “new” directory by opening it and we can see that the following package is successfully installed into the directory." }, { "code": null, "e": 32808, "s": 32781, "text": "Updated Project structure:" }, { "code": null, "e": 32817, "s": 32808, "text": "Node-npm" }, { "code": null, "e": 32824, "s": 32817, "text": "Picked" }, { "code": null, "e": 32848, "s": 32824, "text": "Technical Scripter 2020" }, { "code": null, "e": 32856, "s": 32848, "text": "Node.js" }, { "code": null, "e": 32875, "s": 32856, "text": "Technical Scripter" }, { "code": null, "e": 32892, "s": 32875, "text": "Web Technologies" }, { "code": null, "e": 32990, "s": 32892, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33060, "s": 32990, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 33099, "s": 33060, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 33121, "s": 33099, "text": "Node.js Export Module" }, { "code": null, "e": 33146, "s": 33121, "text": "Mongoose find() Function" }, { "code": null, "e": 33173, "s": 33146, "text": "Mongoose Populate() Method" }, { "code": null, "e": 33213, "s": 33173, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33258, "s": 33213, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33301, "s": 33258, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 33351, "s": 33301, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Be in charge of Query Execution in Spark SQL | by David Vrba | Towards Data Science
Querying data in Spark has become a luxury since Spark 2.x because of SQL and declarative DataFrame API. Using just few lines of high level code allows to express quite complex logic and carry out complicated transformations. The big benefit of the API is that users don’t need to think about the execution and can let the optimizer figure out the most efficient way to execute the query. And efficient query execution is often a requirement not only because the resources may become costly, but also it makes the work of the end user more comfortable by reducing the time he/she has to wait for the result of the computation. The Spark SQL optimizer is indeed quite mature, especially now with the upcoming version 3.0 which will introduce some new internal optimizations such as dynamic partition pruning and adaptive query execution. The optimizer is internally working with a query plan and is usually able to simplify it and optimize by various rules. For example it can change the order of some transformations or drop them completely if they are not necessary for the final output. Despite all the clever optimizations there are however still situations in which a human brain can do better. In this article we will take a look at one of these cases and see how, using a simple trick, we can lead Spark towards a more efficient execution. The code is tested in the current version of Spark which is 2.4.5 (written in June 2020) and it is checked against Spark 3.0.0-preview2 to see possible changes in the upcoming Spark 3.0. Let me now first introduce a simple example for which we will try to achieve efficient execution. Imagine that we have data in json format with the following structure: {"id": 1, "user_id": 100, "price": 50}{"id": 2, "user_id": 100, "price": 200}{"id": 3, "user_id": 101, "price": 120}{"id": 4, "price": 120} Each record is like a transaction so the user_id column may contain lots of duplicated values (possibly including nulls) and besides these three columns there can be many other fields describing the transaction. Now our query will be based on a union of two similar aggregations where each of these aggregations differs by some conditions. In the first aggregation we want to take users for which the sum of the price is less than 50 and in the second aggregation we take users for which the sum of the price is more than 100. Moreover in the second aggregation we want to consider only records where user_id is not null. This model example is just a simplified version of a more complex situation that can occur in practice and for the sake of simplicity we will use it throughout the article. Here is a basic way how to express such a query using DataFrame API of PySpark (very similarly we could write it also using the Scala API): df = spark.read.json(data_path)df_small = ( df .groupBy("user_id") .agg(sum("price").alias("price")) .filter(col("price") < 50))df_big = ( df .filter(col("user_id").isNotNull()) .groupBy("user_id") .agg(sum("price").alias("price")) .filter(col("price") > 100) )result = df_small.union(df_big) The key to achieve a good performance for your query is the ability to understand and interpret the query plan. The plan itself can be displayed by calling explain function on the Spark DataFrame or if the query is already running (or has finished) we can also go to the Spark UI and find the plan in the SQL tab. The SQL tab has lists of completed and running queries on the cluster so by selecting our query we will see the graphical representation of the physical plan (here i removed the metrics information to make the plot smaller): The plan has a tree structure where each node represents some operator that caries some information about the execution. We can see that in our example there are two branches with the root at the bottom and the leafs at the top where the execution starts. The leafs Scan json represent reading the data from the source, then there is a pair of HashAggregate operators which are responsible for the aggregation, and in between them there is Exchange which represents the shuffle. The Filter operators carry the information about the filtering conditions. The plan has a typical shape for union operations, there is a new branch for each DataFrame in the union, and since in our example both DataFrames are based on the same datasource, it means that the datasource will be scanned twice. Now we can see that there is a space for improvement. Having the datasource scanned only once can lead to a nice optimization, especially in situations where I/O is expensive. Conceptually, what we want to achieve here, is reusing some computation — scanning the data and computing the aggregation, because these are the operations that are the same in both DataFrames and in principle it should be sufficient to compute them only once. One typical approach how to reuse a computation in Spark is using caching. There is a function cache that can be called on a DataFrame: df.cache() It is a lazy transformation which means that the data will be put to the caching layer after we call some action. Caching is a very common technique used in Spark however it has its limitations, especially if the cached data is large and the resources on the cluster are limited. Also one needs to be aware that storing the data in the caching layer (memory or disk) will bring some additional overhead and the operation itself is not for free. Calling cache on the whole DataFrame df is not optimal also from the reason that it will try to put all the columns to memory which may be unnecessary. More careful way is to select a superset of all columns that will be used in the following queries and then call the cache function after this select. Apart from caching, there is another technique which is not that well described in the literature and this technique is based on reusing the Exchange. The Exchange operator represents shuffle which is a physical data movement on the cluster. This happens when the data must be reorganized (repartitioned) which is usually required for aggregations, joins and some other transformations. The important thing about shuffle is that when the data is repartitioned, Spark will always save it on the disk as the shuffle write (this is an internal behavior and it is not under control of the end user). And because it is saved on the disk, it can be reused later on if it is required. Spark will indeed reuse the data if it finds an opportunity for that. This happens each time Spark detects that the same branch from the leaf node up to an Exchange is repeating somewhere in the plan. If there is such a situation it means that these repeated branches represent identical computation and thus it is sufficient to compute it only once and then reuse it. We can recognize from the plan whether Spark found such a case, because those branches would be merged together like this: In our example, Spark didn’t reuse the Exchange, but with a simple trick, we can push him to do so. The reason why the Exchange is not reused in our query is the Filter in the right branch that corresponds to the filtering condition user_id is not null. The filter is indeed the only difference in our two DataFrames that are in the union, so if we can eliminate this difference and make the two branches the same, Spark will take care of the rest and will reuse the Exchange. How can we make the branches the same? Well, if the only difference is the filter, we can certainly switch the order of transformations and call the filter after the aggregation because that will make no impact on the correctness of the result that will be produced. However there is a catch! If we move the filter like this: df_big = ( df.groupBy("user_id") .agg(sum("price").alias("price")) .filter(col("price") > 100) .filter(col("price").isNotNull())) and check the final query plan, we will see that the plan has not changed at all! The explanation is simple — the filter was moved back by the optimizer. Conceptually it is good to understand that there are two major types of the query plan — logical plan and physical plan. And the logical plan undergoes an optimization phase before it is turned into the physical plan which is the final plan that will be executed. When we change some transformations, it is reflected in the logical plan, but then we loose control over the next steps. The optimizer will apply a set of optimization rules which are mostly based on some heuristics. The rule related to our example is called PushDownPredicate and this rule makes sure that the filters are applied as soon as possible and are pushed closer to the source. It is based on the idea that it is more efficient to first filter the data and then do the computation on the reduced dataset. This rule is indeed very useful in most of the situations, however in this very case it is fighting against us. To achieve custom position of the Filter in the plan, we have to limit the optimizer. This is possible since Spark 2.4 because there is a configuration setting which allows us to list all the optimization rules that we want to exclude from the optimizer: spark.conf.set("spark.sql.optimizer.excludedRules", "org.apache.spark.sql.catalyst.optimizer.PushDownPredicate") After setting this configuration and running the query again, we will see that now the filter stays positioned as we need. The two branches become really the same and Spark will now reuse the Exchange! The dataset will now be scanned only once and the same goes for computing the aggregation. In Spark 3.0 the situation is changed a little bit, the optimization rule now has a different name — PushDownPredicates and there is an additional rule that is also responsible for pushing a filter PushPredicateThroughNonJoin, so we actually need to exclude both of them to achieve the desired goal. We can see that through this technique Spark developers gave us the power to control the optimizer. But with power comes also responsibility. Let’s list a couple of points that is good to keep in mind when using this technique: When we stop the PushDownPredicate, we will take the responsibility for all the filters in the query, not just the one that we want to reposition. There might be other filters which are important to take place as soon as possible, for example partition filters, so we need to make sure they are positioned correctly. Limiting the optimizer and taking care of the filters is some extra work on the side of the user, so it better be worth it. In our model example the potential for speeding up the query will be in cases where I/O is expensive because we will achieve that the data will be scanned only once. This might be the case for instance with file formats which are not columnar, like json or csv, if the dataset has lots of columns. Also if the dataset is small, it might not be worth to go the extra mile to control the optimizer because simple caching will do the job. However when the dataset is large, the overhead with storing the data in the caching layer will become apparent. On the other hand the reused Exchange would bring no additional overhead because the computed shuffle will be stored on disk anyway. This technique is based on Spark’s internal behavior which has no official documentation and if something changes in this functionality it might be more difficult to find it out. In our example we could see that there is actually a change in Spark 3.0 where one rule is renamed and another rule is added. We have seen that being able to achieve the optimal performance may require understanding the query plan. Spark optimizer does a very good job by optimizing our query using a set of heuristic rules. There are, however, situations in which these rules miss the most optimal configuration. Sometimes rewriting the query is good enough, but sometimes it is not, because by rewriting the query we will achieve a different logical plan but we do not have a direct control over the physical plan that will be executed. Since Spark 2.4 we can use a configuration setting excludedRules that allows us to limit the optimizer and thus navigate Spark to a more custom physical plan. In many cases relying on the optimizer will lead to a solid plan with a quite efficient execution, however, there are cases mostly in performance critical workloads, where it might be worth to check the final plan and see whether we can improve it by taking the control over the optimizer.
[ { "code": null, "e": 798, "s": 171, "text": "Querying data in Spark has become a luxury since Spark 2.x because of SQL and declarative DataFrame API. Using just few lines of high level code allows to express quite complex logic and carry out complicated transformations. The big benefit of the API is that users don’t need to think about the execution and can let the optimizer figure out the most efficient way to execute the query. And efficient query execution is often a requirement not only because the resources may become costly, but also it makes the work of the end user more comfortable by reducing the time he/she has to wait for the result of the computation." }, { "code": null, "e": 1517, "s": 798, "text": "The Spark SQL optimizer is indeed quite mature, especially now with the upcoming version 3.0 which will introduce some new internal optimizations such as dynamic partition pruning and adaptive query execution. The optimizer is internally working with a query plan and is usually able to simplify it and optimize by various rules. For example it can change the order of some transformations or drop them completely if they are not necessary for the final output. Despite all the clever optimizations there are however still situations in which a human brain can do better. In this article we will take a look at one of these cases and see how, using a simple trick, we can lead Spark towards a more efficient execution." }, { "code": null, "e": 1704, "s": 1517, "text": "The code is tested in the current version of Spark which is 2.4.5 (written in June 2020) and it is checked against Spark 3.0.0-preview2 to see possible changes in the upcoming Spark 3.0." }, { "code": null, "e": 1873, "s": 1704, "text": "Let me now first introduce a simple example for which we will try to achieve efficient execution. Imagine that we have data in json format with the following structure:" }, { "code": null, "e": 2013, "s": 1873, "text": "{\"id\": 1, \"user_id\": 100, \"price\": 50}{\"id\": 2, \"user_id\": 100, \"price\": 200}{\"id\": 3, \"user_id\": 101, \"price\": 120}{\"id\": 4, \"price\": 120}" }, { "code": null, "e": 2948, "s": 2013, "text": "Each record is like a transaction so the user_id column may contain lots of duplicated values (possibly including nulls) and besides these three columns there can be many other fields describing the transaction. Now our query will be based on a union of two similar aggregations where each of these aggregations differs by some conditions. In the first aggregation we want to take users for which the sum of the price is less than 50 and in the second aggregation we take users for which the sum of the price is more than 100. Moreover in the second aggregation we want to consider only records where user_id is not null. This model example is just a simplified version of a more complex situation that can occur in practice and for the sake of simplicity we will use it throughout the article. Here is a basic way how to express such a query using DataFrame API of PySpark (very similarly we could write it also using the Scala API):" }, { "code": null, "e": 3251, "s": 2948, "text": "df = spark.read.json(data_path)df_small = ( df .groupBy(\"user_id\") .agg(sum(\"price\").alias(\"price\")) .filter(col(\"price\") < 50))df_big = ( df .filter(col(\"user_id\").isNotNull()) .groupBy(\"user_id\") .agg(sum(\"price\").alias(\"price\")) .filter(col(\"price\") > 100) )result = df_small.union(df_big)" }, { "code": null, "e": 3565, "s": 3251, "text": "The key to achieve a good performance for your query is the ability to understand and interpret the query plan. The plan itself can be displayed by calling explain function on the Spark DataFrame or if the query is already running (or has finished) we can also go to the Spark UI and find the plan in the SQL tab." }, { "code": null, "e": 3790, "s": 3565, "text": "The SQL tab has lists of completed and running queries on the cluster so by selecting our query we will see the graphical representation of the physical plan (here i removed the metrics information to make the plot smaller):" }, { "code": null, "e": 4344, "s": 3790, "text": "The plan has a tree structure where each node represents some operator that caries some information about the execution. We can see that in our example there are two branches with the root at the bottom and the leafs at the top where the execution starts. The leafs Scan json represent reading the data from the source, then there is a pair of HashAggregate operators which are responsible for the aggregation, and in between them there is Exchange which represents the shuffle. The Filter operators carry the information about the filtering conditions." }, { "code": null, "e": 4753, "s": 4344, "text": "The plan has a typical shape for union operations, there is a new branch for each DataFrame in the union, and since in our example both DataFrames are based on the same datasource, it means that the datasource will be scanned twice. Now we can see that there is a space for improvement. Having the datasource scanned only once can lead to a nice optimization, especially in situations where I/O is expensive." }, { "code": null, "e": 5014, "s": 4753, "text": "Conceptually, what we want to achieve here, is reusing some computation — scanning the data and computing the aggregation, because these are the operations that are the same in both DataFrames and in principle it should be sufficient to compute them only once." }, { "code": null, "e": 5150, "s": 5014, "text": "One typical approach how to reuse a computation in Spark is using caching. There is a function cache that can be called on a DataFrame:" }, { "code": null, "e": 5161, "s": 5150, "text": "df.cache()" }, { "code": null, "e": 5909, "s": 5161, "text": "It is a lazy transformation which means that the data will be put to the caching layer after we call some action. Caching is a very common technique used in Spark however it has its limitations, especially if the cached data is large and the resources on the cluster are limited. Also one needs to be aware that storing the data in the caching layer (memory or disk) will bring some additional overhead and the operation itself is not for free. Calling cache on the whole DataFrame df is not optimal also from the reason that it will try to put all the columns to memory which may be unnecessary. More careful way is to select a superset of all columns that will be used in the following queries and then call the cache function after this select." }, { "code": null, "e": 7079, "s": 5909, "text": "Apart from caching, there is another technique which is not that well described in the literature and this technique is based on reusing the Exchange. The Exchange operator represents shuffle which is a physical data movement on the cluster. This happens when the data must be reorganized (repartitioned) which is usually required for aggregations, joins and some other transformations. The important thing about shuffle is that when the data is repartitioned, Spark will always save it on the disk as the shuffle write (this is an internal behavior and it is not under control of the end user). And because it is saved on the disk, it can be reused later on if it is required. Spark will indeed reuse the data if it finds an opportunity for that. This happens each time Spark detects that the same branch from the leaf node up to an Exchange is repeating somewhere in the plan. If there is such a situation it means that these repeated branches represent identical computation and thus it is sufficient to compute it only once and then reuse it. We can recognize from the plan whether Spark found such a case, because those branches would be merged together like this:" }, { "code": null, "e": 7556, "s": 7079, "text": "In our example, Spark didn’t reuse the Exchange, but with a simple trick, we can push him to do so. The reason why the Exchange is not reused in our query is the Filter in the right branch that corresponds to the filtering condition user_id is not null. The filter is indeed the only difference in our two DataFrames that are in the union, so if we can eliminate this difference and make the two branches the same, Spark will take care of the rest and will reuse the Exchange." }, { "code": null, "e": 7882, "s": 7556, "text": "How can we make the branches the same? Well, if the only difference is the filter, we can certainly switch the order of transformations and call the filter after the aggregation because that will make no impact on the correctness of the result that will be produced. However there is a catch! If we move the filter like this:" }, { "code": null, "e": 8016, "s": 7882, "text": "df_big = ( df.groupBy(\"user_id\") .agg(sum(\"price\").alias(\"price\")) .filter(col(\"price\") > 100) .filter(col(\"price\").isNotNull()))" }, { "code": null, "e": 8170, "s": 8016, "text": "and check the final query plan, we will see that the plan has not changed at all! The explanation is simple — the filter was moved back by the optimizer." }, { "code": null, "e": 9061, "s": 8170, "text": "Conceptually it is good to understand that there are two major types of the query plan — logical plan and physical plan. And the logical plan undergoes an optimization phase before it is turned into the physical plan which is the final plan that will be executed. When we change some transformations, it is reflected in the logical plan, but then we loose control over the next steps. The optimizer will apply a set of optimization rules which are mostly based on some heuristics. The rule related to our example is called PushDownPredicate and this rule makes sure that the filters are applied as soon as possible and are pushed closer to the source. It is based on the idea that it is more efficient to first filter the data and then do the computation on the reduced dataset. This rule is indeed very useful in most of the situations, however in this very case it is fighting against us." }, { "code": null, "e": 9316, "s": 9061, "text": "To achieve custom position of the Filter in the plan, we have to limit the optimizer. This is possible since Spark 2.4 because there is a configuration setting which allows us to list all the optimization rules that we want to exclude from the optimizer:" }, { "code": null, "e": 9433, "s": 9316, "text": "spark.conf.set(\"spark.sql.optimizer.excludedRules\", \"org.apache.spark.sql.catalyst.optimizer.PushDownPredicate\")" }, { "code": null, "e": 9726, "s": 9433, "text": "After setting this configuration and running the query again, we will see that now the filter stays positioned as we need. The two branches become really the same and Spark will now reuse the Exchange! The dataset will now be scanned only once and the same goes for computing the aggregation." }, { "code": null, "e": 10026, "s": 9726, "text": "In Spark 3.0 the situation is changed a little bit, the optimization rule now has a different name — PushDownPredicates and there is an additional rule that is also responsible for pushing a filter PushPredicateThroughNonJoin, so we actually need to exclude both of them to achieve the desired goal." }, { "code": null, "e": 10254, "s": 10026, "text": "We can see that through this technique Spark developers gave us the power to control the optimizer. But with power comes also responsibility. Let’s list a couple of points that is good to keep in mind when using this technique:" }, { "code": null, "e": 10571, "s": 10254, "text": "When we stop the PushDownPredicate, we will take the responsibility for all the filters in the query, not just the one that we want to reposition. There might be other filters which are important to take place as soon as possible, for example partition filters, so we need to make sure they are positioned correctly." }, { "code": null, "e": 10993, "s": 10571, "text": "Limiting the optimizer and taking care of the filters is some extra work on the side of the user, so it better be worth it. In our model example the potential for speeding up the query will be in cases where I/O is expensive because we will achieve that the data will be scanned only once. This might be the case for instance with file formats which are not columnar, like json or csv, if the dataset has lots of columns." }, { "code": null, "e": 11377, "s": 10993, "text": "Also if the dataset is small, it might not be worth to go the extra mile to control the optimizer because simple caching will do the job. However when the dataset is large, the overhead with storing the data in the caching layer will become apparent. On the other hand the reused Exchange would bring no additional overhead because the computed shuffle will be stored on disk anyway." }, { "code": null, "e": 11682, "s": 11377, "text": "This technique is based on Spark’s internal behavior which has no official documentation and if something changes in this functionality it might be more difficult to find it out. In our example we could see that there is actually a change in Spark 3.0 where one rule is renamed and another rule is added." }, { "code": null, "e": 12354, "s": 11682, "text": "We have seen that being able to achieve the optimal performance may require understanding the query plan. Spark optimizer does a very good job by optimizing our query using a set of heuristic rules. There are, however, situations in which these rules miss the most optimal configuration. Sometimes rewriting the query is good enough, but sometimes it is not, because by rewriting the query we will achieve a different logical plan but we do not have a direct control over the physical plan that will be executed. Since Spark 2.4 we can use a configuration setting excludedRules that allows us to limit the optimizer and thus navigate Spark to a more custom physical plan." } ]
Break and Continue statement in Java - GeeksforGeeks
26 Feb, 2021 The break and continue statements are the jump statements that are used to skip some statements inside the loop or terminate the loop immediately without checking the test expression. These statements can be used inside any loops such as for, while, do-while loop. Break: The break statement in java is used to terminate from the loop immediately. When a break statement is encountered inside a loop, the loop iteration stops there, and control returns from the loop immediately to the first statement after the loop. Basically, break statements are used in situations when we are not sure about the actual number of iteration for the loop, or we want to terminate the loop based on some condition. Syntax : break; In Java, a break statement is majorly used for: To exit a loop. Used as a “civilized” form of goto. Terminate a sequence in a switch statement. Using break to exit a loop Using break, we can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When we use break inside the nested loops, it will only break out of the innermost loop. Example: Java // Java program to demonstrate using// break to exit a loopclass GFG { public static void main(String[] args) { // Initially loop is set to run from 0-9 for (int i = 0; i < 10; i++) { // Terminate the loop when i is 5 if (i == 5) break; System.out.println("i: " + i); } System.out.println("Out of Loop"); }} i: 0 i: 1 i: 2 i: 3 i: 4 Out of Loop Using break as a Form of Goto Java does not have a goto statement because it provides a way to branch in an arbitrary and unstructured manner. Java uses a label. A Label is used to identify a block of code. Syntax: label: { statement1; statement2; statement3; . . } Now, the break statements can be used to jump out of the target block. We cannot break to any label which is not defined for an enclosing block. Syntax: break label; Example: Java // Java program to demonstrates using break with gotoclass GFG { public static void main(String args[]) { // First label first: for (int i = 0; i < 3; i++) { // Second label second: for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { // Using break statement with label break first; } System.out.println(i + " " + j); } } }} 0 0 0 1 0 2 1 0 Using break to terminate a sequence in a switch statement. The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. The break statement is used inside the switch to terminate a statement sequence. The break statement is optional. If omitted, execution will continue on into the next case. Syntax: switch (expression) { case value1: statement1; break; case value2: statement2; break; . . case valueN: statementN; break; default: statementDefault; } Example: Java // Java program to demonstrate using break to terminate a// sequence in a switch statement.class GFG { public static void main(String args[]) { int i = 2; switch (i) { case 0: System.out.println("i is zero."); break; case 1: System.out.println("i is one."); break; case 2: System.out.println("i is two."); break; default: System.out.println("Invalid number"); } }} i is two. Continue: The continue statement in Java is used to skip the current iteration of a loop. We can use continue statement inside any types of loops such as for, while, and do-while loop. Basically continue statements are used in the situations when we want to continue the loop but do not want the remaining statement after the continue statement. Syntax: continue; Using continue to continue a loop Using continue, we can skip the current iteration of a loop and jumps to the next iteration of the loop immediately. Example: Java // Java program to demonstrates the continue// statement to continue a loopclass GFG { public static void main(String args[]) { for (int i = 0; i < 10; i++) { // If the number is 2 // skip and continue if (i == 2) continue; System.out.print(i + " "); } }} 0 1 3 4 5 6 7 8 9 Using continue as a labelled continue statement The unlabeled continue statement is used to continue the innermost loop. However, since JDK 1.5 java introduces another feature known as labelled continue statement. We can use a labelled continue statement to continue the outermost loop. Example: Java // Java program to demonstrates labeled continue statementclass GFG { public static void main(String args[]) { // First label first: for (int i = 0; i < 3; i++) { // Second label second: for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { // Using continue statement with label continue first; } System.out.println(i + " " + j); } } }} 0 0 0 1 0 2 1 0 2 0 2 1 2 2 Difference between break and continue: Break Continue The break statement is used to terminate the loop immediately. The continue statement is used to skip the current iteration of the loop. break keyword is used to indicate break statements in java programming. continue keyword is used to indicate continue statement in java programming. We can use a break with the switch statement. We can not use a continue with the switch statement. The break statement terminates the whole loop early. The continue statement brings the next iteration early. It stops the execution of the loop. It does not stop the execution of the loop. dipenkadecha java-basics Java-Control-Flow Java Java-Control-Flow Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 24002, "s": 23974, "text": "\n26 Feb, 2021" }, { "code": null, "e": 24267, "s": 24002, "text": "The break and continue statements are the jump statements that are used to skip some statements inside the loop or terminate the loop immediately without checking the test expression. These statements can be used inside any loops such as for, while, do-while loop." }, { "code": null, "e": 24701, "s": 24267, "text": "Break: The break statement in java is used to terminate from the loop immediately. When a break statement is encountered inside a loop, the loop iteration stops there, and control returns from the loop immediately to the first statement after the loop. Basically, break statements are used in situations when we are not sure about the actual number of iteration for the loop, or we want to terminate the loop based on some condition." }, { "code": null, "e": 24710, "s": 24701, "text": "Syntax :" }, { "code": null, "e": 24717, "s": 24710, "text": "break;" }, { "code": null, "e": 24765, "s": 24717, "text": "In Java, a break statement is majorly used for:" }, { "code": null, "e": 24781, "s": 24765, "text": "To exit a loop." }, { "code": null, "e": 24817, "s": 24781, "text": "Used as a “civilized” form of goto." }, { "code": null, "e": 24861, "s": 24817, "text": "Terminate a sequence in a switch statement." }, { "code": null, "e": 24888, "s": 24861, "text": "Using break to exit a loop" }, { "code": null, "e": 25121, "s": 24888, "text": "Using break, we can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When we use break inside the nested loops, it will only break out of the innermost loop." }, { "code": null, "e": 25130, "s": 25121, "text": "Example:" }, { "code": null, "e": 25135, "s": 25130, "text": "Java" }, { "code": "// Java program to demonstrate using// break to exit a loopclass GFG { public static void main(String[] args) { // Initially loop is set to run from 0-9 for (int i = 0; i < 10; i++) { // Terminate the loop when i is 5 if (i == 5) break; System.out.println(\"i: \" + i); } System.out.println(\"Out of Loop\"); }}", "e": 25528, "s": 25135, "text": null }, { "code": null, "e": 25565, "s": 25528, "text": "i: 0\ni: 1\ni: 2\ni: 3\ni: 4\nOut of Loop" }, { "code": null, "e": 25595, "s": 25565, "text": "Using break as a Form of Goto" }, { "code": null, "e": 25772, "s": 25595, "text": "Java does not have a goto statement because it provides a way to branch in an arbitrary and unstructured manner. Java uses a label. A Label is used to identify a block of code." }, { "code": null, "e": 25781, "s": 25772, "text": "Syntax: " }, { "code": null, "e": 25842, "s": 25781, "text": "label:\n{\n statement1;\n statement2;\n statement3;\n .\n .\n}" }, { "code": null, "e": 25987, "s": 25842, "text": "Now, the break statements can be used to jump out of the target block. We cannot break to any label which is not defined for an enclosing block." }, { "code": null, "e": 25996, "s": 25987, "text": "Syntax: " }, { "code": null, "e": 26009, "s": 25996, "text": "break label;" }, { "code": null, "e": 26019, "s": 26009, "text": "Example: " }, { "code": null, "e": 26024, "s": 26019, "text": "Java" }, { "code": "// Java program to demonstrates using break with gotoclass GFG { public static void main(String args[]) { // First label first: for (int i = 0; i < 3; i++) { // Second label second: for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { // Using break statement with label break first; } System.out.println(i + \" \" + j); } } }}", "e": 26500, "s": 26024, "text": null }, { "code": null, "e": 26516, "s": 26500, "text": "0 0\n0 1\n0 2\n1 0" }, { "code": null, "e": 26575, "s": 26516, "text": "Using break to terminate a sequence in a switch statement." }, { "code": null, "e": 26913, "s": 26575, "text": "The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. The break statement is used inside the switch to terminate a statement sequence. The break statement is optional. If omitted, execution will continue on into the next case." }, { "code": null, "e": 26922, "s": 26913, "text": "Syntax: " }, { "code": null, "e": 27113, "s": 26922, "text": "switch (expression)\n{\n case value1:\n statement1;\n break;\n case value2:\n statement2;\n break;\n .\n .\n case valueN:\n statementN;\n break;\n default:\n statementDefault;\n}" }, { "code": null, "e": 27122, "s": 27113, "text": "Example:" }, { "code": null, "e": 27127, "s": 27122, "text": "Java" }, { "code": "// Java program to demonstrate using break to terminate a// sequence in a switch statement.class GFG { public static void main(String args[]) { int i = 2; switch (i) { case 0: System.out.println(\"i is zero.\"); break; case 1: System.out.println(\"i is one.\"); break; case 2: System.out.println(\"i is two.\"); break; default: System.out.println(\"Invalid number\"); } }}", "e": 27627, "s": 27127, "text": null }, { "code": null, "e": 27637, "s": 27627, "text": "i is two." }, { "code": null, "e": 27647, "s": 27637, "text": "Continue:" }, { "code": null, "e": 27983, "s": 27647, "text": "The continue statement in Java is used to skip the current iteration of a loop. We can use continue statement inside any types of loops such as for, while, and do-while loop. Basically continue statements are used in the situations when we want to continue the loop but do not want the remaining statement after the continue statement." }, { "code": null, "e": 27992, "s": 27983, "text": "Syntax: " }, { "code": null, "e": 28002, "s": 27992, "text": "continue;" }, { "code": null, "e": 28036, "s": 28002, "text": "Using continue to continue a loop" }, { "code": null, "e": 28153, "s": 28036, "text": "Using continue, we can skip the current iteration of a loop and jumps to the next iteration of the loop immediately." }, { "code": null, "e": 28163, "s": 28153, "text": "Example: " }, { "code": null, "e": 28168, "s": 28163, "text": "Java" }, { "code": "// Java program to demonstrates the continue// statement to continue a loopclass GFG { public static void main(String args[]) { for (int i = 0; i < 10; i++) { // If the number is 2 // skip and continue if (i == 2) continue; System.out.print(i + \" \"); } }}", "e": 28507, "s": 28168, "text": null }, { "code": null, "e": 28525, "s": 28507, "text": "0 1 3 4 5 6 7 8 9" }, { "code": null, "e": 28573, "s": 28525, "text": "Using continue as a labelled continue statement" }, { "code": null, "e": 28812, "s": 28573, "text": "The unlabeled continue statement is used to continue the innermost loop. However, since JDK 1.5 java introduces another feature known as labelled continue statement. We can use a labelled continue statement to continue the outermost loop." }, { "code": null, "e": 28822, "s": 28812, "text": "Example: " }, { "code": null, "e": 28827, "s": 28822, "text": "Java" }, { "code": "// Java program to demonstrates labeled continue statementclass GFG { public static void main(String args[]) { // First label first: for (int i = 0; i < 3; i++) { // Second label second: for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { // Using continue statement with label continue first; } System.out.println(i + \" \" + j); } } }}", "e": 29314, "s": 28827, "text": null }, { "code": null, "e": 29342, "s": 29314, "text": "0 0\n0 1\n0 2\n1 0\n2 0\n2 1\n2 2" }, { "code": null, "e": 29381, "s": 29342, "text": "Difference between break and continue:" }, { "code": null, "e": 29387, "s": 29381, "text": "Break" }, { "code": null, "e": 29396, "s": 29387, "text": "Continue" }, { "code": null, "e": 29459, "s": 29396, "text": "The break statement is used to terminate the loop immediately." }, { "code": null, "e": 29533, "s": 29459, "text": "The continue statement is used to skip the current iteration of the loop." }, { "code": null, "e": 29605, "s": 29533, "text": "break keyword is used to indicate break statements in java programming." }, { "code": null, "e": 29682, "s": 29605, "text": "continue keyword is used to indicate continue statement in java programming." }, { "code": null, "e": 29728, "s": 29682, "text": "We can use a break with the switch statement." }, { "code": null, "e": 29781, "s": 29728, "text": "We can not use a continue with the switch statement." }, { "code": null, "e": 29834, "s": 29781, "text": "The break statement terminates the whole loop early." }, { "code": null, "e": 29890, "s": 29834, "text": "The continue statement brings the next iteration early." }, { "code": null, "e": 29926, "s": 29890, "text": "It stops the execution of the loop." }, { "code": null, "e": 29970, "s": 29926, "text": "It does not stop the execution of the loop." }, { "code": null, "e": 29983, "s": 29970, "text": "dipenkadecha" }, { "code": null, "e": 29995, "s": 29983, "text": "java-basics" }, { "code": null, "e": 30013, "s": 29995, "text": "Java-Control-Flow" }, { "code": null, "e": 30018, "s": 30013, "text": "Java" }, { "code": null, "e": 30036, "s": 30018, "text": "Java-Control-Flow" }, { "code": null, "e": 30041, "s": 30036, "text": "Java" }, { "code": null, "e": 30139, "s": 30041, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30148, "s": 30139, "text": "Comments" }, { "code": null, "e": 30161, "s": 30148, "text": "Old Comments" }, { "code": null, "e": 30212, "s": 30161, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30242, "s": 30212, "text": "HashMap in Java with Examples" }, { "code": null, "e": 30273, "s": 30242, "text": "How to iterate any Map in Java" }, { "code": null, "e": 30305, "s": 30273, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 30324, "s": 30305, "text": "Interfaces in Java" }, { "code": null, "e": 30342, "s": 30324, "text": "ArrayList in Java" }, { "code": null, "e": 30374, "s": 30342, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 30394, "s": 30374, "text": "Stack Class in Java" }, { "code": null, "e": 30418, "s": 30394, "text": "Singleton Class in Java" } ]
How to prevent column break within an element? - GeeksforGeeks
18 Apr, 2019 We can prevent column break within an element by using a CSS break-inside Property. The break-inside property in CSS is used to specify how the column breaks inside the element. Sometimes content of an element is stuck between the column. To prevent column break we should use the break-inside Property set to avoid. Syntax: column-break-inside:avoid; Example: This Example uses to prevent the column break within an element. <html> <head> <style> .x { -moz-column-count: 3; column-count: 3; width: 30em; } .x li { -webkit-column-break-inside: avoid; } </style></head> <body> <h1>Geeks For Geeks</h1> <div class='x'> <ul> <li>GeeksForGeeks</li> <li>Sudo Placement</li> <li>DataBase management System</li> <li>Operating System</li> <li>A computer science portal for geeks.</li> <li>Java Programming</li> </ul> </div></body> </html> Output: shubham_singh Picked CSS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24985, "s": 24957, "text": "\n18 Apr, 2019" }, { "code": null, "e": 25302, "s": 24985, "text": "We can prevent column break within an element by using a CSS break-inside Property. The break-inside property in CSS is used to specify how the column breaks inside the element. Sometimes content of an element is stuck between the column. To prevent column break we should use the break-inside Property set to avoid." }, { "code": null, "e": 25310, "s": 25302, "text": "Syntax:" }, { "code": null, "e": 25337, "s": 25310, "text": "column-break-inside:avoid;" }, { "code": null, "e": 25411, "s": 25337, "text": "Example: This Example uses to prevent the column break within an element." }, { "code": "<html> <head> <style> .x { -moz-column-count: 3; column-count: 3; width: 30em; } .x li { -webkit-column-break-inside: avoid; } </style></head> <body> <h1>Geeks For Geeks</h1> <div class='x'> <ul> <li>GeeksForGeeks</li> <li>Sudo Placement</li> <li>DataBase management System</li> <li>Operating System</li> <li>A computer science portal for geeks.</li> <li>Java Programming</li> </ul> </div></body> </html>", "e": 26004, "s": 25411, "text": null }, { "code": null, "e": 26012, "s": 26004, "text": "Output:" }, { "code": null, "e": 26026, "s": 26012, "text": "shubham_singh" }, { "code": null, "e": 26033, "s": 26026, "text": "Picked" }, { "code": null, "e": 26037, "s": 26033, "text": "CSS" }, { "code": null, "e": 26054, "s": 26037, "text": "Web Technologies" }, { "code": null, "e": 26081, "s": 26054, "text": "Web technologies Questions" }, { "code": null, "e": 26179, "s": 26081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26188, "s": 26179, "text": "Comments" }, { "code": null, "e": 26201, "s": 26188, "text": "Old Comments" }, { "code": null, "e": 26238, "s": 26201, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26267, "s": 26238, "text": "Form validation using jQuery" }, { "code": null, "e": 26306, "s": 26267, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 26348, "s": 26306, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 26383, "s": 26348, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 26439, "s": 26383, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26472, "s": 26439, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26515, "s": 26472, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26576, "s": 26515, "text": "Difference between var, let and const keywords in JavaScript" } ]
How to create a 3D time-series map using Python and Kepler.gl | by Erik Yan | Towards Data Science
In the wake of protests rippling throughout the U.S., I wanted to better understand just how often interactions between police and victims lead to death. This presented a great opportunity to test out Uber’s Kepler.gl toolbox and create an interactive 3D map of police interactions that have resulted in death. In this post I’ll talk about the map, what it does, and how we can interact with the data. I’ll also talk about the creation process and how you can easily make interactive geospatial visualizations (for those that are interested in the technical aspects of this project). When you open the map you’ll notice a time series slider with a play/pause button. You can click the play button to animate the data and see how the number of deaths change over time (ranging from January 2013 to December of 2019). If you click on the > button (in the top left corner of the page), you can interact with the data to change what you see on the map. For example you can: hide layers, add new ones, filter the data by variables (such as race, gender, etc). I added a hidden layer that visualizes aggregated data based on geospatial radius. When the layer is visible, you’ll see calculated clusters: I won’t talk in-depth about everything you can do within the map interface. Feel free to check out a live version of the map here and play around with the map’s features / explore the data. Let’s walk through the process of creating this map. To do this we leverage open-access datasets and Kepler.gl, Uber’s open-source geospatial analysis tool. Uber recently released a great article talking about Kepler.gl. It was built using React & Redux, Deck.gl, and WebGL. If you’ve worked with Deck.gl, using Kepler.gl is even easier. Deck.gl already makes it easy to create WebGL-based visualization of large datasets. Kepler.gl further simplifies the process by providing an on-screen interface where you can quickly configure your data visualization. Map configurations can be saved for archiving or edited directly (if you want to make changes to your configuration script manually). Your dataset will need to include three variables: a ‘datetime’ variable (to enable time series functionality)a latitude variable (from the polygon centroid for each county)a longitude variable (from the polygon centroid for each county) a ‘datetime’ variable (to enable time series functionality) a latitude variable (from the polygon centroid for each county) a longitude variable (from the polygon centroid for each county) If you have a date variable already, you’ll want to modify the variable to include at least hours and minutes (i.e. convert the date to a date time format). Currently, Kepler.gl can only process date time stamps and not dates only (see Kepler.gl Github Issue #78). A quick way to do this (if your date column is formatted as mm/dd/yy): kepler_mvp_df[‘datetime’] = kepler_mvp_df[‘datetime’].astype(str) + ‘ 0:00’ We’ll want to include longitude and latitude information for Kepler time series maps because rather than assigning a geojson shape to each time stamp, we’ll use the centroid of each polygon as the central longitude and latitude of each distinct area/region. The police interaction dataset I used (see dataset source/validity section) includes the street address, city, state, zip code, and county information. We’ll map the data by state counties because we can use the National Weather Service’s GIS shape files to extract each county’s central longitude and latitude using the centroid of each county’s respective geospatial shape. I recommend using geopandas to extract the shapefile data: shapefile_data = gpd.read_file("c_03mr20.shp")print(shapefile_data)shapfile_raw = pd.DataFrame()shapfile_raw = shapfile_raw.append(shapefile_data)shapfile_raw Once you’ve extracted the longitude and latitudes, we simply merge the coordinate dictionary with the dataset using state and county variables (which should be present in both datasets). In this case, we’ll merge the data using State abbreviations and County names: kepler_mvp_df = pd.merge(MVP_raw,merged_dict_df, on=[‘STATE’,’County’]) Now we’re ready to load our data into Kepler.gl and begin creating our visualization! There are many ways to use Kepler.gl. For this map, I used the Kepler.gl Jupyter widget. This method is useful because Kepler.gl loads within a cell in Jupyter Notebook, allowing you to manipulate your data and load it directly into Kepler without having to toggle between environments or transfer your dataset. If you don’t have Jupyter Notebook, I highly recommend this tutorial. The easiest way to install Kepler is using pip: pip install keplergl I recommend pushing your data to a DataFrame using pandas. In this case our dataset was prepared within Jupyter Notebook, so we just directly import the dataset into the Kepler Jupyter widget: from keplergl import KeplerGlkepler_map = KeplerGl(height = 800, data={‘data_name_here’: dataset_df})kepler_map In the above snippet, we’re importing the Kepler widget, specifying a window height, and defining/importing our dataset into the widget. Once the data is loaded you can configure the map visuals to your liking using the Kepler.gl built-in interface. For this map, a heat map was overlaid along the x- and z-axis, where the heat density ranges from dark red to yellow as the density of deaths increase. 3D rendering of the map allows us to take advantage of the y-axis, using yellow lines to show the intensity of the heatmap density color (seeing a yellow dot in the center of a heat spot doesn’t tell you about its intensity relative to other yellow-colored hot spots, so the hexbin lines help us better visualize hotspot density by utilizing the y-axis). Your configuration script will looking something like this: new_config = {'version': 'v1', 'config': {'visState': {'filters': [{'dataId': ['police action that resulted in death'], 'id': 'o7g4tr5v', 'name': ['datetime'], 'type': 'timeRange', 'value': [1357006005000, 1374938411000], 'enlarged': True, 'plotType': 'histogram', 'yAxis': None}, {'dataId': ['police action that resulted in death'], 'id': 'p34jx073r', 'name': ["Victim's race"], 'type': 'multiSelect', 'value': [], 'enlarged': False, 'plotType': 'histogram', 'yAxis': None}], 'layers': [{'id': 'e136xu9', 'type': 'heatmap', 'config': {'dataId': 'police action that resulted in death', 'label': 'Heat', 'color': [231, 159, 213], 'columns': {'lat': 'LAT', 'lng': 'LON'}, 'isVisible': True, 'visConfig': {'opacity': 0.5, 'colorRange': {'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']}, 'radius': 40}, 'hidden': False, 'textLabel': [{'field': None, 'color': [255, 255, 255], 'size': 18, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center'}]}, 'visualChannels': {'weightField': None, 'weightScale': 'linear'}}, {'id': 'm9ia9z', 'type': 'hexagon', 'config': {'dataId': 'police action that resulted in death', 'label': 'Hex', 'color': [221, 178, 124], 'columns': {'lat': 'LAT', 'lng': 'LON'}, 'isVisible': True, 'visConfig': {'opacity': 0.4, 'worldUnitSize': 8, 'resolution': 8, 'colorRange': {'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']}, 'coverage': 1, 'sizeRange': [0, 500], 'percentile': [0, 100], 'elevationPercentile': [0, 100], 'elevationScale': 40, 'colorAggregation': 'count', 'sizeAggregation': 'count', 'enable3d': True}, 'hidden': False, 'textLabel': [{'field': None, 'color': [255, 255, 255], 'size': 18, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center'}]}, 'visualChannels': {'colorField': None, 'colorScale': 'quantile', 'sizeField': None, 'sizeScale': 'linear'}}, {'id': 'l2vlgiq', 'type': 'cluster', 'config': {'dataId': 'police action that resulted in death', 'label': 'Cluster', 'color': [23, 184, 190], 'columns': {'lat': 'LAT', 'lng': 'LON'}, 'isVisible': True, 'visConfig': {'opacity': 0.05, 'clusterRadius': 110, 'colorRange': {'name': 'Uber Viz Diverging 1.5', 'type': 'diverging', 'category': 'Uber', 'colors': ['#00939C', '#5DBABF', '#BAE1E2', '#F8C0AA', '#DD7755', '#C22E00']}, 'radiusRange': [1, 40], 'colorAggregation': 'count'}, 'hidden': False, 'textLabel': [{'field': None, 'color': [255, 255, 255], 'size': 18, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center'}]}, 'visualChannels': {'colorField': None, 'colorScale': 'quantize'}}, {'id': 'ci0b6l', 'type': 'point', 'config': {'dataId': 'police action that resulted in death', 'label': "Victim's Name", 'color': [28, 27, 27], 'columns': {'lat': 'LAT', 'lng': 'LON', 'altitude': None}, 'isVisible': False, 'visConfig': {'radius': 0, 'fixedRadius': False, 'opacity': 0.8, 'outline': False, 'thickness': 0.5, 'strokeColor': None, 'colorRange': {'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']}, 'strokeColorRange': {'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']}, 'radiusRange': [0, 50], 'filled': False}, 'hidden': False, 'textLabel': [{'field': {'name': "Victim's name", 'type': 'string'}, 'color': [255, 255, 255], 'size': 3, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center'}]}, 'visualChannels': {'colorField': None, 'colorScale': 'quantile', 'strokeColorField': None, 'strokeColorScale': 'quantile', 'sizeField': None, 'sizeScale': 'linear'}}], 'interactionConfig': {'tooltip': {'fieldsToShow': {'police action that resulted in death': ["Victim's name", "Victim's age", "Victim's gender", "Victim's race", 'URL of image of victim']}, 'enabled': True}, 'brush': {'size': 0.5, 'enabled': False}, 'geocoder': {'enabled': False}, 'coordinate': {'enabled': False}}, 'layerBlending': 'additive', 'splitMaps': [], 'animationConfig': {'currentTime': None, 'speed': 0.5}}, 'mapState': {'bearing': 12.35033335232777, 'dragRotate': True, 'latitude': 33.612636906131925, 'longitude': -98.63889376921583, 'pitch': 55.12552722162369, 'zoom': 3.5734484899775754, 'isSplit': False}, 'mapStyle': {'styleType': 'dark', 'topLayerGroups': {}, 'visibleLayerGroups': {'label': True, 'road': True, 'border': True, 'building': False, 'water': True, 'land': True, '3d building': False}, 'threeDBuildingColor': [9.665468314072013, 17.18305478057247, 31.1442867897876], 'mapStyles': {}}}} Be sure to save your configuration script for future reference (or if you want to make changes manually to your config script): current_config = kepler_map.configcurrent_config You can also export the map as an interactive html map: kepler_map.save_to_html(file_name=”kepler_map.html”) Always be sure to keep a copy of the final configuration files. You can use the config files to re-load map visuals in the Kepler Jupyter widget: kepler_map = KeplerGl(height=800, data={‘data_name_here’: dataset_df}, config=current_config)kepler_map OR you can also use saved config files to re-create interactive html maps quickly: kepler_map.save_to_html(data={‘data_name_here’: dataset_df}, config=config, file_name=”kepler_map.html”) And that’s it! Creating an interactive 3D map doesn’t get much easier than that. The dataset I used came from mappingpoliceviolence.org, which was created by Samuel Sinyangwe and DeRay McKesson. I can’t attest to the accuracy nor validity of the dataset, but the dataset does contain deep detail about each individual data point listed in the set (such as demographic information, geographic information, and relevant links).
[ { "code": null, "e": 482, "s": 171, "text": "In the wake of protests rippling throughout the U.S., I wanted to better understand just how often interactions between police and victims lead to death. This presented a great opportunity to test out Uber’s Kepler.gl toolbox and create an interactive 3D map of police interactions that have resulted in death." }, { "code": null, "e": 755, "s": 482, "text": "In this post I’ll talk about the map, what it does, and how we can interact with the data. I’ll also talk about the creation process and how you can easily make interactive geospatial visualizations (for those that are interested in the technical aspects of this project)." }, { "code": null, "e": 987, "s": 755, "text": "When you open the map you’ll notice a time series slider with a play/pause button. You can click the play button to animate the data and see how the number of deaths change over time (ranging from January 2013 to December of 2019)." }, { "code": null, "e": 1368, "s": 987, "text": "If you click on the > button (in the top left corner of the page), you can interact with the data to change what you see on the map. For example you can: hide layers, add new ones, filter the data by variables (such as race, gender, etc). I added a hidden layer that visualizes aggregated data based on geospatial radius. When the layer is visible, you’ll see calculated clusters:" }, { "code": null, "e": 1558, "s": 1368, "text": "I won’t talk in-depth about everything you can do within the map interface. Feel free to check out a live version of the map here and play around with the map’s features / explore the data." }, { "code": null, "e": 1833, "s": 1558, "text": "Let’s walk through the process of creating this map. To do this we leverage open-access datasets and Kepler.gl, Uber’s open-source geospatial analysis tool. Uber recently released a great article talking about Kepler.gl. It was built using React & Redux, Deck.gl, and WebGL." }, { "code": null, "e": 2249, "s": 1833, "text": "If you’ve worked with Deck.gl, using Kepler.gl is even easier. Deck.gl already makes it easy to create WebGL-based visualization of large datasets. Kepler.gl further simplifies the process by providing an on-screen interface where you can quickly configure your data visualization. Map configurations can be saved for archiving or edited directly (if you want to make changes to your configuration script manually)." }, { "code": null, "e": 2300, "s": 2249, "text": "Your dataset will need to include three variables:" }, { "code": null, "e": 2487, "s": 2300, "text": "a ‘datetime’ variable (to enable time series functionality)a latitude variable (from the polygon centroid for each county)a longitude variable (from the polygon centroid for each county)" }, { "code": null, "e": 2547, "s": 2487, "text": "a ‘datetime’ variable (to enable time series functionality)" }, { "code": null, "e": 2611, "s": 2547, "text": "a latitude variable (from the polygon centroid for each county)" }, { "code": null, "e": 2676, "s": 2611, "text": "a longitude variable (from the polygon centroid for each county)" }, { "code": null, "e": 2941, "s": 2676, "text": "If you have a date variable already, you’ll want to modify the variable to include at least hours and minutes (i.e. convert the date to a date time format). Currently, Kepler.gl can only process date time stamps and not dates only (see Kepler.gl Github Issue #78)." }, { "code": null, "e": 3012, "s": 2941, "text": "A quick way to do this (if your date column is formatted as mm/dd/yy):" }, { "code": null, "e": 3088, "s": 3012, "text": "kepler_mvp_df[‘datetime’] = kepler_mvp_df[‘datetime’].astype(str) + ‘ 0:00’" }, { "code": null, "e": 3346, "s": 3088, "text": "We’ll want to include longitude and latitude information for Kepler time series maps because rather than assigning a geojson shape to each time stamp, we’ll use the centroid of each polygon as the central longitude and latitude of each distinct area/region." }, { "code": null, "e": 3722, "s": 3346, "text": "The police interaction dataset I used (see dataset source/validity section) includes the street address, city, state, zip code, and county information. We’ll map the data by state counties because we can use the National Weather Service’s GIS shape files to extract each county’s central longitude and latitude using the centroid of each county’s respective geospatial shape." }, { "code": null, "e": 3781, "s": 3722, "text": "I recommend using geopandas to extract the shapefile data:" }, { "code": null, "e": 3940, "s": 3781, "text": "shapefile_data = gpd.read_file(\"c_03mr20.shp\")print(shapefile_data)shapfile_raw = pd.DataFrame()shapfile_raw = shapfile_raw.append(shapefile_data)shapfile_raw" }, { "code": null, "e": 4206, "s": 3940, "text": "Once you’ve extracted the longitude and latitudes, we simply merge the coordinate dictionary with the dataset using state and county variables (which should be present in both datasets). In this case, we’ll merge the data using State abbreviations and County names:" }, { "code": null, "e": 4278, "s": 4206, "text": "kepler_mvp_df = pd.merge(MVP_raw,merged_dict_df, on=[‘STATE’,’County’])" }, { "code": null, "e": 4364, "s": 4278, "text": "Now we’re ready to load our data into Kepler.gl and begin creating our visualization!" }, { "code": null, "e": 4676, "s": 4364, "text": "There are many ways to use Kepler.gl. For this map, I used the Kepler.gl Jupyter widget. This method is useful because Kepler.gl loads within a cell in Jupyter Notebook, allowing you to manipulate your data and load it directly into Kepler without having to toggle between environments or transfer your dataset." }, { "code": null, "e": 4794, "s": 4676, "text": "If you don’t have Jupyter Notebook, I highly recommend this tutorial. The easiest way to install Kepler is using pip:" }, { "code": null, "e": 4815, "s": 4794, "text": "pip install keplergl" }, { "code": null, "e": 5008, "s": 4815, "text": "I recommend pushing your data to a DataFrame using pandas. In this case our dataset was prepared within Jupyter Notebook, so we just directly import the dataset into the Kepler Jupyter widget:" }, { "code": null, "e": 5120, "s": 5008, "text": "from keplergl import KeplerGlkepler_map = KeplerGl(height = 800, data={‘data_name_here’: dataset_df})kepler_map" }, { "code": null, "e": 5257, "s": 5120, "text": "In the above snippet, we’re importing the Kepler widget, specifying a window height, and defining/importing our dataset into the widget." }, { "code": null, "e": 5370, "s": 5257, "text": "Once the data is loaded you can configure the map visuals to your liking using the Kepler.gl built-in interface." }, { "code": null, "e": 5877, "s": 5370, "text": "For this map, a heat map was overlaid along the x- and z-axis, where the heat density ranges from dark red to yellow as the density of deaths increase. 3D rendering of the map allows us to take advantage of the y-axis, using yellow lines to show the intensity of the heatmap density color (seeing a yellow dot in the center of a heat spot doesn’t tell you about its intensity relative to other yellow-colored hot spots, so the hexbin lines help us better visualize hotspot density by utilizing the y-axis)." }, { "code": null, "e": 5937, "s": 5877, "text": "Your configuration script will looking something like this:" }, { "code": null, "e": 11598, "s": 5937, "text": "new_config = {'version': 'v1', 'config': {'visState': {'filters': [{'dataId': ['police action that resulted in death'], 'id': 'o7g4tr5v', 'name': ['datetime'], 'type': 'timeRange', 'value': [1357006005000, 1374938411000], 'enlarged': True, 'plotType': 'histogram', 'yAxis': None}, {'dataId': ['police action that resulted in death'], 'id': 'p34jx073r', 'name': [\"Victim's race\"], 'type': 'multiSelect', 'value': [], 'enlarged': False, 'plotType': 'histogram', 'yAxis': None}], 'layers': [{'id': 'e136xu9', 'type': 'heatmap', 'config': {'dataId': 'police action that resulted in death', 'label': 'Heat', 'color': [231, 159, 213], 'columns': {'lat': 'LAT', 'lng': 'LON'}, 'isVisible': True, 'visConfig': {'opacity': 0.5, 'colorRange': {'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']}, 'radius': 40}, 'hidden': False, 'textLabel': [{'field': None, 'color': [255, 255, 255], 'size': 18, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center'}]}, 'visualChannels': {'weightField': None, 'weightScale': 'linear'}}, {'id': 'm9ia9z', 'type': 'hexagon', 'config': {'dataId': 'police action that resulted in death', 'label': 'Hex', 'color': [221, 178, 124], 'columns': {'lat': 'LAT', 'lng': 'LON'}, 'isVisible': True, 'visConfig': {'opacity': 0.4, 'worldUnitSize': 8, 'resolution': 8, 'colorRange': {'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']}, 'coverage': 1, 'sizeRange': [0, 500], 'percentile': [0, 100], 'elevationPercentile': [0, 100], 'elevationScale': 40, 'colorAggregation': 'count', 'sizeAggregation': 'count', 'enable3d': True}, 'hidden': False, 'textLabel': [{'field': None, 'color': [255, 255, 255], 'size': 18, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center'}]}, 'visualChannels': {'colorField': None, 'colorScale': 'quantile', 'sizeField': None, 'sizeScale': 'linear'}}, {'id': 'l2vlgiq', 'type': 'cluster', 'config': {'dataId': 'police action that resulted in death', 'label': 'Cluster', 'color': [23, 184, 190], 'columns': {'lat': 'LAT', 'lng': 'LON'}, 'isVisible': True, 'visConfig': {'opacity': 0.05, 'clusterRadius': 110, 'colorRange': {'name': 'Uber Viz Diverging 1.5', 'type': 'diverging', 'category': 'Uber', 'colors': ['#00939C', '#5DBABF', '#BAE1E2', '#F8C0AA', '#DD7755', '#C22E00']}, 'radiusRange': [1, 40], 'colorAggregation': 'count'}, 'hidden': False, 'textLabel': [{'field': None, 'color': [255, 255, 255], 'size': 18, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center'}]}, 'visualChannels': {'colorField': None, 'colorScale': 'quantize'}}, {'id': 'ci0b6l', 'type': 'point', 'config': {'dataId': 'police action that resulted in death', 'label': \"Victim's Name\", 'color': [28, 27, 27], 'columns': {'lat': 'LAT', 'lng': 'LON', 'altitude': None}, 'isVisible': False, 'visConfig': {'radius': 0, 'fixedRadius': False, 'opacity': 0.8, 'outline': False, 'thickness': 0.5, 'strokeColor': None, 'colorRange': {'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']}, 'strokeColorRange': {'name': 'Global Warming', 'type': 'sequential', 'category': 'Uber', 'colors': ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']}, 'radiusRange': [0, 50], 'filled': False}, 'hidden': False, 'textLabel': [{'field': {'name': \"Victim's name\", 'type': 'string'}, 'color': [255, 255, 255], 'size': 3, 'offset': [0, 0], 'anchor': 'start', 'alignment': 'center'}]}, 'visualChannels': {'colorField': None, 'colorScale': 'quantile', 'strokeColorField': None, 'strokeColorScale': 'quantile', 'sizeField': None, 'sizeScale': 'linear'}}], 'interactionConfig': {'tooltip': {'fieldsToShow': {'police action that resulted in death': [\"Victim's name\", \"Victim's age\", \"Victim's gender\", \"Victim's race\", 'URL of image of victim']}, 'enabled': True}, 'brush': {'size': 0.5, 'enabled': False}, 'geocoder': {'enabled': False}, 'coordinate': {'enabled': False}}, 'layerBlending': 'additive', 'splitMaps': [], 'animationConfig': {'currentTime': None, 'speed': 0.5}}, 'mapState': {'bearing': 12.35033335232777, 'dragRotate': True, 'latitude': 33.612636906131925, 'longitude': -98.63889376921583, 'pitch': 55.12552722162369, 'zoom': 3.5734484899775754, 'isSplit': False}, 'mapStyle': {'styleType': 'dark', 'topLayerGroups': {}, 'visibleLayerGroups': {'label': True, 'road': True, 'border': True, 'building': False, 'water': True, 'land': True, '3d building': False}, 'threeDBuildingColor': [9.665468314072013, 17.18305478057247, 31.1442867897876], 'mapStyles': {}}}}" }, { "code": null, "e": 11726, "s": 11598, "text": "Be sure to save your configuration script for future reference (or if you want to make changes manually to your config script):" }, { "code": null, "e": 11775, "s": 11726, "text": "current_config = kepler_map.configcurrent_config" }, { "code": null, "e": 11831, "s": 11775, "text": "You can also export the map as an interactive html map:" }, { "code": null, "e": 11884, "s": 11831, "text": "kepler_map.save_to_html(file_name=”kepler_map.html”)" }, { "code": null, "e": 12030, "s": 11884, "text": "Always be sure to keep a copy of the final configuration files. You can use the config files to re-load map visuals in the Kepler Jupyter widget:" }, { "code": null, "e": 12134, "s": 12030, "text": "kepler_map = KeplerGl(height=800, data={‘data_name_here’: dataset_df}, config=current_config)kepler_map" }, { "code": null, "e": 12217, "s": 12134, "text": "OR you can also use saved config files to re-create interactive html maps quickly:" }, { "code": null, "e": 12322, "s": 12217, "text": "kepler_map.save_to_html(data={‘data_name_here’: dataset_df}, config=config, file_name=”kepler_map.html”)" }, { "code": null, "e": 12403, "s": 12322, "text": "And that’s it! Creating an interactive 3D map doesn’t get much easier than that." } ]
7 Easter Eggs in Python. Countless Ways to Entertain Yourself at... | by Eden Au | Towards Data Science
Most of us are working from home amid the coronavirus outbreak. Many of you might already be so bored staying at home all day. And I feel you. Python might only be a tool for you to build projects, simulation, and automation, and it could be really fun. Thanks to the amazing Python community, we can find many hidden features and easter eggs in this open-source language. Here are 7 of them. The first thing to do when learning a programming language is to print out ‘Hello World’ on the screen. How can you do Hello World in Python? print('Hello World!')? Turns out Python developers hid a module that could do Hello World simply by importing this module! Try this: >>> import __hello__Hello World! That line of code consists of 16 characters only, including the spacebar! This is arguably one of the ‘easiest’ Hello World programs. Note that you can’t reimport a module in a Python program, so you could print the message once in a single run. But I guess that might mean something deep... This was proposed in PEP 20. PEP stands for Python enhancement proposals. Is Python your favourite language? What do you like about Python? Is it the design? The guiding principles for Python’s design can be described by 20 aphorisms, and you can find 19 of them by: >>> import this What about the missing one? I guess you can’t know everything in the world. Here are the first 3 aphorisms: Beautiful is better than ugly.Explicit is better than implicit.Simple is better than complex. You have got to appreciate the effort the developers have invested in making such an elegant and human-readable programming language. This is also by far the only ‘official’ easter egg that is stated as an ‘easter egg’ in Python Developer’s Guide. Remember the first 3 lines in the Zen of Python? When you dig deeper and find the module file this.py, it is the most beautiful, explicit, and simple code I have ever seen. Check out the file here. Well done. You can actually experience antigravity using one line of code in Python! import antigravity Really! Try it out! Bear in mind that you might be stuck in outer space and spend hours browsing xkcd webcomic. Unlike many other programming languages, Python doesn’t really utilise curly braces {} when constructing statements, functions, and loops. But they might change in the future. The __future__ module includes incompatible changes that will be mandatorily enforced in the foreseeable future. For instance, importing print_function from __future__ in Python 2.6 or 2.7 allows you to make ‘print’ a function that takes arguments print(), just like in Python 3. Let’s see how braces would work from __future__: >>> from __future__ import bracesSyntaxError: not a chance Well played. The hash of infinity and NaN. >>> hash(float('inf'))314159>>> hash(float('nan'))0 And I somehow found this easter egg on Reddit. I was expecting the answer to life, the universe and everything to be honest. The debate of operator choice has gone on four two long. Let’s settle this. This was proposed in PEP 401. You might sense what is coming up. A well-known Python developer Barry Warsaw (aka Uncle Barry) was ‘chosen’ to become the Friendly Language Uncle For Life, which is FLUFL in short. Great acronym. He enacted a few ‘modifications’, which enabled the replacement inequality operator != by diamond operator<>. If you agree with Uncle Barry’s vision, you could import this interesting library, and the <> syntax would become valid, whereas the != one would result in a syntax error. >>> from __future__ import barry_as_FLUFL>>> 0 != 1SyntaxError: with Barry as BDFL, use '<>' instead of '!='>>> 0 <> 1True>>> 1 <> 1False April Fool! Poor Barry... I assure you there is no typo in the example above. The list goes on and on, but I will stop here and let you explore them yourself. Thanks for reading! If you want to receive updates on my new articles, you can subscribe to my newsletter using the slider below: And if you are still reading this, you are probably interested in Python. The following articles might be useful:
[ { "code": null, "e": 315, "s": 172, "text": "Most of us are working from home amid the coronavirus outbreak. Many of you might already be so bored staying at home all day. And I feel you." }, { "code": null, "e": 426, "s": 315, "text": "Python might only be a tool for you to build projects, simulation, and automation, and it could be really fun." }, { "code": null, "e": 565, "s": 426, "text": "Thanks to the amazing Python community, we can find many hidden features and easter eggs in this open-source language. Here are 7 of them." }, { "code": null, "e": 730, "s": 565, "text": "The first thing to do when learning a programming language is to print out ‘Hello World’ on the screen. How can you do Hello World in Python? print('Hello World!')?" }, { "code": null, "e": 840, "s": 730, "text": "Turns out Python developers hid a module that could do Hello World simply by importing this module! Try this:" }, { "code": null, "e": 873, "s": 840, "text": ">>> import __hello__Hello World!" }, { "code": null, "e": 1007, "s": 873, "text": "That line of code consists of 16 characters only, including the spacebar! This is arguably one of the ‘easiest’ Hello World programs." }, { "code": null, "e": 1165, "s": 1007, "text": "Note that you can’t reimport a module in a Python program, so you could print the message once in a single run. But I guess that might mean something deep..." }, { "code": null, "e": 1239, "s": 1165, "text": "This was proposed in PEP 20. PEP stands for Python enhancement proposals." }, { "code": null, "e": 1432, "s": 1239, "text": "Is Python your favourite language? What do you like about Python? Is it the design? The guiding principles for Python’s design can be described by 20 aphorisms, and you can find 19 of them by:" }, { "code": null, "e": 1448, "s": 1432, "text": ">>> import this" }, { "code": null, "e": 1556, "s": 1448, "text": "What about the missing one? I guess you can’t know everything in the world. Here are the first 3 aphorisms:" }, { "code": null, "e": 1650, "s": 1556, "text": "Beautiful is better than ugly.Explicit is better than implicit.Simple is better than complex." }, { "code": null, "e": 1784, "s": 1650, "text": "You have got to appreciate the effort the developers have invested in making such an elegant and human-readable programming language." }, { "code": null, "e": 1898, "s": 1784, "text": "This is also by far the only ‘official’ easter egg that is stated as an ‘easter egg’ in Python Developer’s Guide." }, { "code": null, "e": 1947, "s": 1898, "text": "Remember the first 3 lines in the Zen of Python?" }, { "code": null, "e": 2071, "s": 1947, "text": "When you dig deeper and find the module file this.py, it is the most beautiful, explicit, and simple code I have ever seen." }, { "code": null, "e": 2107, "s": 2071, "text": "Check out the file here. Well done." }, { "code": null, "e": 2181, "s": 2107, "text": "You can actually experience antigravity using one line of code in Python!" }, { "code": null, "e": 2200, "s": 2181, "text": "import antigravity" }, { "code": null, "e": 2312, "s": 2200, "text": "Really! Try it out! Bear in mind that you might be stuck in outer space and spend hours browsing xkcd webcomic." }, { "code": null, "e": 2488, "s": 2312, "text": "Unlike many other programming languages, Python doesn’t really utilise curly braces {} when constructing statements, functions, and loops. But they might change in the future." }, { "code": null, "e": 2768, "s": 2488, "text": "The __future__ module includes incompatible changes that will be mandatorily enforced in the foreseeable future. For instance, importing print_function from __future__ in Python 2.6 or 2.7 allows you to make ‘print’ a function that takes arguments print(), just like in Python 3." }, { "code": null, "e": 2817, "s": 2768, "text": "Let’s see how braces would work from __future__:" }, { "code": null, "e": 2876, "s": 2817, "text": ">>> from __future__ import bracesSyntaxError: not a chance" }, { "code": null, "e": 2889, "s": 2876, "text": "Well played." }, { "code": null, "e": 2919, "s": 2889, "text": "The hash of infinity and NaN." }, { "code": null, "e": 2971, "s": 2919, "text": ">>> hash(float('inf'))314159>>> hash(float('nan'))0" }, { "code": null, "e": 3018, "s": 2971, "text": "And I somehow found this easter egg on Reddit." }, { "code": null, "e": 3096, "s": 3018, "text": "I was expecting the answer to life, the universe and everything to be honest." }, { "code": null, "e": 3172, "s": 3096, "text": "The debate of operator choice has gone on four two long. Let’s settle this." }, { "code": null, "e": 3237, "s": 3172, "text": "This was proposed in PEP 401. You might sense what is coming up." }, { "code": null, "e": 3399, "s": 3237, "text": "A well-known Python developer Barry Warsaw (aka Uncle Barry) was ‘chosen’ to become the Friendly Language Uncle For Life, which is FLUFL in short. Great acronym." }, { "code": null, "e": 3509, "s": 3399, "text": "He enacted a few ‘modifications’, which enabled the replacement inequality operator != by diamond operator<>." }, { "code": null, "e": 3681, "s": 3509, "text": "If you agree with Uncle Barry’s vision, you could import this interesting library, and the <> syntax would become valid, whereas the != one would result in a syntax error." }, { "code": null, "e": 3819, "s": 3681, "text": ">>> from __future__ import barry_as_FLUFL>>> 0 != 1SyntaxError: with Barry as BDFL, use '<>' instead of '!='>>> 0 <> 1True>>> 1 <> 1False" }, { "code": null, "e": 3897, "s": 3819, "text": "April Fool! Poor Barry... I assure you there is no typo in the example above." }, { "code": null, "e": 3978, "s": 3897, "text": "The list goes on and on, but I will stop here and let you explore them yourself." }, { "code": null, "e": 4108, "s": 3978, "text": "Thanks for reading! If you want to receive updates on my new articles, you can subscribe to my newsletter using the slider below:" } ]
How to Configure Nagios Server for Monitoring Apache Server
In this article, we will be covering about the installation of Nagios 4, a very popular and open source monitoring tool on Centos 6.7. We shall cover some basic configuration steps which might be useful to monitor a host of resources via the web interface. Here, we shall also utilize the Nagios Remote Plugin Executor (NRPE) that is installed as an agent on remote hosts to monitor the local resources of Servers/clients. Nagios is useful for keeping an inventory of your servers, and making sure your critical services are up and running. Using a monitoring system, Nagios is an essential tool for any production server environment. To configure Nagios, we must have a root user privilege on the Linux server that will run Nagios Ideally. Creating Nagios User and Group: We must create a user and group that will run the Nagios process. Create a “Nagios” user and “nagcmd” group, then add the user to the group with these commands # useradd nagios # groupadd nagcmd # usermod -a -G nagcmd nagios As we are building Nagios Core from source, we must install a few development libraries that will allow us to complete the build. While we’re at it, we will also install apache2-utils, which will be used to set up the Nagios web interface. # yum update # yum install -y httpd php gcc glibc glibc-common gd gd-devel make net-snmp perl-rrd xinetd openssl-devel package perl-GD* ntp perl-rrd* # wget http://prdownloads.sourceforge.net/sourceforge/nagios/nagios-4.1.1.tar.gz # wget https://www.nagios-plugins.org/download/nagios-plugins-2.1.1.tar.gz We need to extract downloaded package with tar command as follows. # tar –xvf nagios-4.1.1.tar.gz # cd nagios-* Before building Nagios, we must configure it. If you want to configure it to use postfix (which you can install with apt-get), add –with-mail=/usr/sbin/sendmail to the following command: # ./configure --with-nagios-group=nagios --with-command-group=nagcmd Output: General Options: ------------------------- Nagios executable: nagios Nagios user/group: nagios,nagios Command user/group: nagios,nagcmd Event Broker: yes Install ${prefix}: /usr/local/nagios Install ${includedir}: /usr/local/nagios/include/nagios Lock file: ${prefix}/var/nagios.lock Check result directory: ${prefix}/var/spool/checkresults Init directory: /etc/init.d Apache conf.d directory: /etc/httpd/conf.d Mail program: /usr/bin/mail Host OS: nagios.test.com Web Interface Options: ------------------------ HTML URL: http://localhost/nagios/ CGI URL: http://localhost/nagios/cgi-bin/ Traceroute (used by WAP): /usr/sbin/traceroute Review the options above for accuracy. If they look okay, type 'make all' to compile the main program and CGIs *** Main program, CGIs and HTML files installed *** Now compile Nagios with this command: Output: You can continue with installing Nagios as follows (type 'make'without any arguments for a list of all possible options): # make install-init – This installs the init script in /etc/rc.d/init.d # make install-commandmode – This installs and configures permissions on the directory for holding the external command file # make install-init To make nagios work from the command line we need to install command-mode. # make install-commandmode Next, install sample nagios files, please run following command. # make install-config Output: /usr/bin/install -c -m 775 -o nagios -g nagios -d /usr/local/nagios/etc /usr/bin/install -c -m 775 -o nagios -g nagios -d /usr/local/nagios/etc/objects /usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/nagios.cfg /usr/local/nagios/etc/nagios.cfg /usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/cgi.cfg /usr/local/nagios/etc/cgi.cfg /usr/bin/install -c -b -m 660 -o nagios -g nagios sample-config/resource.cfg /usr/local/nagios/etc/resource.cfg /usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/templates.cfg /usr/local/nagios/etc/objects/templates.cfg/usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/commands.cfg /usr/local/nagios/etc/objects/commands.cfg /usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/contacts.cfg /usr/local/nagios/etc/objects/contacts.cfg /usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/timeperiods.cfg /usr/local/nagios/etc/objects/timeperiods.cfg /usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/localhost.cfg /usr/local/nagios/etc/objects/localhost.cfg /usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/windows.cfg /usr/local/nagios/etc/objects/windows.cfg /usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/printer.cfg /usr/local/nagios/etc/objects/printer.cfg /usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/switch.cfg /usr/local/nagios/etc/objects/switch.cfg *** Config files installed *** Find the latest release of Nagios Plugins here: Nagios Plugins Download. Copy the link address for the latest version, and copy the link address so you can download it to your Nagios server. At the time of this writing, the latest version is Nagios Plugins 2.1.1. # cd /root/nagios # cd tar –xvf nagios-plugins-2.1.1.tar.gz # ./configure --with-nagios-user=nagios --with-nagios-group=nagios --with-openssl=/usr/bin/openssl --enable-perl-modules --enable-libtap # make # make install Find the source code for the latest stable release of NRPE at the NRPE downloads page. Download the latest version to your Nagios server. At the time of this writing, the latest release is 2.15. # mkdir -p /usr/local/src/nrpe # cd /usr/local/src/nrpe # wget http://kent.dl.sourceforge.net/project/nagios/nrpe-2.x/nrpe-2.15/nrpe-2.15.tar.gz # tar -xf nrpe-2.15.tar.gz # cd nrpe-2.15 Because of an issue with the OpenSSL library folder, we need to use another path than /usr/lib: #./configure --with-ssl=/usr/bin/openssl --with-ssl-lib=/usr/lib/x86_64-linux-gnu Now make and make install # make all Next, install the NRPE plugin daemon, and sample daemon config file. # make install-plugin # make install-daemon # make install-daemon-config Install the NRPE daemon under xinetd as a service. # make install-xinetd Next, open /etc/services file, add the following entry for the NRPE daemon at the bottom of the file. # vi /etc/services nrpe 5666/tcp NRPE Restart the xinetd service. # service xinetd restart Verify NRPE Daemon Locally Run the following command to verify the NRPE daemon working correctly under xinetd. # netstat -at | grep nrpe tcp 0 0 *:nrpe *:* LISTEN Verify the NRPE daemon is functioning properly. # /usr/local/nagios/libexec/check_nrpe -H localhost Output: NRPE v2.15 Now that Nagios 4.1.1 is installed, we need to configure it. Now let’s perform the initial Nagios configuration. You only need to perform this section once, on your Nagios server. Open the main Nagios configuration file in your favorite text editor. We’ll use vi to edit the file: # vi /usr/local/nagios/etc/nagios.cfg Now find an uncomment this line by deleting the # # cfg_dir=/usr/local/nagios/etc/servers Now create the directory that will store the configuration file for each server that you will monitor: # mkdir /usr/local/nagios/etc/servers Open the Nagios contacts configuration in your favorite text editor. We’ll use vi to edit the file # vi /usr/local/nagios/etc/objects/contacts.cfg Find the email directive, and replace its value (the highlighted part) with your own email address email nagios@localhost ; <<***** CHANGE THIS TO YOUR EMAIL ADDRESS ****** Let’s add a new command to our Nagios configuration # vi /usr/local/nagios/etc/objects/commands.cfg Add the following to the end of the file define command{ command_name check_nrpe command_line $USER1$/check_nrpe -H $HOSTADDRESS$ -c $ARG1$ } We are done with all configurations in the back end, now we will configure Web Interface For Nagios with following command. The below command will Configure Web interface for Nagios and a web admin user will be created “nagiosadmin”. # make install-webconf In this step, we will be creating a password for “nagiosadmin”. After executing this command, please provide a password twice and keep it remember because this password will be used when you login in the Nagios Web interface. # htpasswd -s -c /usr/local/nagios/etc/htpasswd.users nagiosadmin New password:************ Re-type new password:************ Adding password for user nagiosadmin Restart Apache to make the new settings take effect. # service httpd start Nagios is now running, so let’s try and log in. Open your favorite web browser, and go to your Nagios server http://nagios_server_public_IP or private IP address/nagios. Because we configured Apache to use htpasswd, you must enter the login credentials that you created earlier. We used “nagiosadmin” as the username: After authenticating, you will be seeing the default Nagios home page. Click on the Hosts link, in the left navigation bar, to see which hosts Nagios is monitoring As you can see, Nagios is monitoring only “localhost”, or itself. In this section, we’ll show you how to add a new host to Nagios, so it will be monitored. Repeat this section for each server you wish to monitor. On a server that you want to monitor, update apt-get: # yum update Now install Nagios Plugins and NRPE: # yum install nagios-plugins nagios-nrpe-server Now, let’s update the NRPE configuration file. Open it in your favorite editor (we’re using vi) # vi /etc/nagios/nrpe.cfg Find the allowed_hosts directive, and add the private IP address of your Nagios server to the comma-delimited list (substitute it in place of the highlighted example) allowed_hosts=127.0.0.1,10.132.224.168 Save and exit. This configures NRPE to accept requests from your Nagios server, via its private IP or public IP address. To add the host: # cd /usr/local/nagios/etc # vi /usr/local/nagios/etc/hosts.cfg define host{ name linux-box ; Name of this template use generic-host ; Inherit default values check_period 24x7 check_interval 5 retry_interval 1 max_check_attempts 10 check_command check-host-alive notification_period 24x7 notification_interval 30 notification_options d,r contact_groups admins register 0 } define host{ use linux-box ; Inherit default values from a template host_name Testbox ; The name we're giving to this server alias CentOS 6.7 ; A longer name for the server address 192.168.1.84 ; IP address of Remote Linux host } To add the services we needed to edit the services.cfg file we are adding CPU Load, Total Process, Current Users, Root Partition, Home Partition, Ping status # vi /usr/local/nagios/etc/services.cfg define service{ use generic-service host_name TestBox service_description CPU Load check_command check_nrpe!check_load } define service{ use generic-service host_name Testbox service_description Total Processes check_command check_nrpe!check_total_procs } define service{ use generic-service host_name Testbox service_description Current Users check_command check_nrpe!check_users } define service{ use generic-service host_name Testbox service_description Root Partition check_command check_nrpe!check_disk } define service{ use generic-service host_name Testbox service_description Home Partition check_command check_nrpe!check_disk_home } define service{ use generic-service host_name Testbox service_description Ping Status check_command check_ping!10.0,80%!50.0,90% } We needed to add this configuration file in nagios.cfg # vi /usr/local/nagios/nagios.cfg cfg_file=/usr/local/nagios/etc/hosts.cfg cfg_file=/usr/local/nagios/etc/services.cfg Now NRPE commands should definition needs to be created in commands.cfg file. # vi /usr/local/nagios/etc/objects/commands.cfg define command{ command_name check_nrpe command_line $USER1$/check_nrpe -H $HOSTADDRESS$ -c $ARG1$ } Finally, verify Nagios Configuration files for any errors. Now we are all done with Nagios configuration and its time to verify it and to do so please run below command. If everything goes smoothly it will show up similar to below output. # /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg Output: Nagios Core 4.1.1 Copyright (c) 2009-present Nagios Core Development Team and Community Contributors Copyright (c) 1999-2009 Ethan Galstad Last Modified: 08-19-2015 License: GPL Website: https://www.nagios.org Reading configuration data... Read main config file okay... Read object config files okay... Running pre-flight check on configuration data... Checking objects... Checked 7 services. Checked 1 hosts. Checked 1 host groups. Checked 0 service groups. Checked 1 contacts. Checked 1 contact groups. Checked 7 commands. Checked 5 time periods. Checked 0 host escalations. Checked 0 service escalations. Checking for circular paths... Checked 1 hosts Checked 0 service dependencies Checked 0 host dependencies Checked 1 timeperiods Checking global event handlers... Checking obsessive compulsive processor commands... Checking misc settings... Total Warnings: 0 Total Errors: 0 Things look okay - No serious problems were detected during the pre-flight check # service nagios reload Running configuration check... Stopping nagios: done. Starting nagios: done. Nagios can be used to monitor Apache web server as well. Monitor whether the apache server is available. This task is really easy as Nagios has a built-in command for this we needed to edit below file. # vi /etc/nagios3/conf.d/services.cfg define service{ use generic-service host_name Webserver service_description Check Apache Web Server check_command check_http } Once we are done, please check the Nagios configuration and restart the services when we open web interfaces and click on services, we can see Apache services are monitoring. Now that you know about Nagios and its features like monitoring your hosts and some of the services, you might want to spend some time to figure out which services are critical to you so you can start monitoring these servers. You may also want to set up notifications so, for example, you receive an email when your disk utilization reaches a warning or critical threshold or your main website is down, so you can resolve the situation promptly or before a problem even occurs.
[ { "code": null, "e": 1485, "s": 1062, "text": "In this article, we will be covering about the installation of Nagios 4, a very popular and open source monitoring tool on Centos 6.7. We shall cover some basic configuration steps which might be useful to monitor a host of resources via the web interface. Here, we shall also utilize the Nagios Remote Plugin Executor (NRPE) that is installed as an agent on remote hosts to monitor the local resources of Servers/clients." }, { "code": null, "e": 1697, "s": 1485, "text": "Nagios is useful for keeping an inventory of your servers, and making sure your critical services are up and running. Using a monitoring system, Nagios is an essential tool for any production server environment." }, { "code": null, "e": 1803, "s": 1697, "text": "To configure Nagios, we must have a root user privilege on the Linux server that will run Nagios Ideally." }, { "code": null, "e": 1995, "s": 1803, "text": "Creating Nagios User and Group: We must create a user and group that will run the Nagios process. Create a “Nagios” user and “nagcmd” group, then add the user to the group with these commands" }, { "code": null, "e": 2060, "s": 1995, "text": "# useradd nagios\n# groupadd nagcmd\n# usermod -a -G nagcmd nagios" }, { "code": null, "e": 2300, "s": 2060, "text": "As we are building Nagios Core from source, we must install a few development libraries that will allow us to complete the build. While we’re at it, we will also install apache2-utils, which will be used to set up the Nagios web interface." }, { "code": null, "e": 2313, "s": 2300, "text": "# yum update" }, { "code": null, "e": 2450, "s": 2313, "text": "# yum install -y httpd php gcc glibc glibc-common gd gd-devel make net-snmp perl-rrd xinetd openssl-devel package perl-GD* ntp perl-rrd*" }, { "code": null, "e": 2606, "s": 2450, "text": "# wget http://prdownloads.sourceforge.net/sourceforge/nagios/nagios-4.1.1.tar.gz\n# wget https://www.nagios-plugins.org/download/nagios-plugins-2.1.1.tar.gz" }, { "code": null, "e": 2673, "s": 2606, "text": "We need to extract downloaded package with tar command as follows." }, { "code": null, "e": 2718, "s": 2673, "text": "# tar –xvf nagios-4.1.1.tar.gz\n# cd nagios-*" }, { "code": null, "e": 2905, "s": 2718, "text": "Before building Nagios, we must configure it. If you want to configure it to use postfix (which you can install with apt-get), add –with-mail=/usr/sbin/sendmail to the following command:" }, { "code": null, "e": 3953, "s": 2905, "text": "# ./configure --with-nagios-group=nagios --with-command-group=nagcmd\n\nOutput:\n\nGeneral Options:\n-------------------------\nNagios executable: nagios\nNagios user/group: nagios,nagios\nCommand user/group: nagios,nagcmd\nEvent Broker: yes\nInstall ${prefix}: /usr/local/nagios\nInstall ${includedir}: /usr/local/nagios/include/nagios\nLock file: ${prefix}/var/nagios.lock\nCheck result directory: ${prefix}/var/spool/checkresults\nInit directory: /etc/init.d\nApache conf.d directory: /etc/httpd/conf.d\nMail program: /usr/bin/mail\nHost OS: nagios.test.com\nWeb Interface Options:\n------------------------\nHTML URL: http://localhost/nagios/\nCGI URL: http://localhost/nagios/cgi-bin/\nTraceroute (used by WAP): /usr/sbin/traceroute\nReview the options above for accuracy. If they look okay,\ntype 'make all' to compile the main program and CGIs\n*** Main program, CGIs and HTML files installed ***\nNow compile Nagios with this command:\n\nOutput:\nYou can continue with installing Nagios as follows (type 'make'without any arguments for a list of all possible options):" }, { "code": null, "e": 3973, "s": 3953, "text": "# make install-init" }, { "code": null, "e": 4025, "s": 3973, "text": "– This installs the init script in /etc/rc.d/init.d" }, { "code": null, "e": 4052, "s": 4025, "text": "# make install-commandmode" }, { "code": null, "e": 4150, "s": 4052, "text": "– This installs and configures permissions on the directory for holding the external command file" }, { "code": null, "e": 4170, "s": 4150, "text": "# make install-init" }, { "code": null, "e": 4245, "s": 4170, "text": "To make nagios work from the command line we need to install command-mode." }, { "code": null, "e": 4272, "s": 4245, "text": "# make install-commandmode" }, { "code": null, "e": 4337, "s": 4272, "text": "Next, install sample nagios files, please run following command." }, { "code": null, "e": 5962, "s": 4337, "text": "# make install-config\n\nOutput:\n/usr/bin/install -c -m 775 -o nagios -g nagios -d /usr/local/nagios/etc\n/usr/bin/install -c -m 775 -o nagios -g nagios -d /usr/local/nagios/etc/objects\n/usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/nagios.cfg /usr/local/nagios/etc/nagios.cfg\n/usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/cgi.cfg /usr/local/nagios/etc/cgi.cfg\n/usr/bin/install -c -b -m 660 -o nagios -g nagios sample-config/resource.cfg /usr/local/nagios/etc/resource.cfg\n/usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/templates.cfg\n/usr/local/nagios/etc/objects/templates.cfg/usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/commands.cfg\n/usr/local/nagios/etc/objects/commands.cfg\n/usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/contacts.cfg /usr/local/nagios/etc/objects/contacts.cfg\n/usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/timeperiods.cfg /usr/local/nagios/etc/objects/timeperiods.cfg\n/usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/localhost.cfg /usr/local/nagios/etc/objects/localhost.cfg\n/usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/windows.cfg /usr/local/nagios/etc/objects/windows.cfg\n/usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/printer.cfg /usr/local/nagios/etc/objects/printer.cfg\n/usr/bin/install -c -b -m 664 -o nagios -g nagios sample-config/template-object/switch.cfg /usr/local/nagios/etc/objects/switch.cfg\n*** Config files installed ***" }, { "code": null, "e": 6153, "s": 5962, "text": "Find the latest release of Nagios Plugins here: Nagios Plugins Download. Copy the link address for the latest version, and copy the link address so you can download it to your Nagios server." }, { "code": null, "e": 6226, "s": 6153, "text": "At the time of this writing, the latest version is Nagios Plugins 2.1.1." }, { "code": null, "e": 6445, "s": 6226, "text": "# cd /root/nagios\n# cd tar –xvf nagios-plugins-2.1.1.tar.gz\n# ./configure --with-nagios-user=nagios --with-nagios-group=nagios --with-openssl=/usr/bin/openssl --enable-perl-modules --enable-libtap\n# make\n# make install" }, { "code": null, "e": 6583, "s": 6445, "text": "Find the source code for the latest stable release of NRPE at the NRPE downloads page. Download the latest version to your Nagios server." }, { "code": null, "e": 6640, "s": 6583, "text": "At the time of this writing, the latest release is 2.15." }, { "code": null, "e": 6696, "s": 6640, "text": "# mkdir -p /usr/local/src/nrpe\n# cd /usr/local/src/nrpe" }, { "code": null, "e": 6827, "s": 6696, "text": "# wget http://kent.dl.sourceforge.net/project/nagios/nrpe-2.x/nrpe-2.15/nrpe-2.15.tar.gz\n# tar -xf nrpe-2.15.tar.gz\n# cd nrpe-2.15" }, { "code": null, "e": 6923, "s": 6827, "text": "Because of an issue with the OpenSSL library folder, we need to use another path than /usr/lib:" }, { "code": null, "e": 7005, "s": 6923, "text": "#./configure --with-ssl=/usr/bin/openssl --with-ssl-lib=/usr/lib/x86_64-linux-gnu" }, { "code": null, "e": 7031, "s": 7005, "text": "Now make and make install" }, { "code": null, "e": 7042, "s": 7031, "text": "# make all" }, { "code": null, "e": 7111, "s": 7042, "text": "Next, install the NRPE plugin daemon, and sample daemon config file." }, { "code": null, "e": 7184, "s": 7111, "text": "# make install-plugin\n# make install-daemon\n# make install-daemon-config" }, { "code": null, "e": 7235, "s": 7184, "text": "Install the NRPE daemon under xinetd as a service." }, { "code": null, "e": 7257, "s": 7235, "text": "# make install-xinetd" }, { "code": null, "e": 7359, "s": 7257, "text": "Next, open /etc/services file, add the following entry for the NRPE daemon at the bottom of the file." }, { "code": null, "e": 7415, "s": 7359, "text": "# vi /etc/services\nnrpe 5666/tcp NRPE" }, { "code": null, "e": 7443, "s": 7415, "text": "Restart the xinetd service." }, { "code": null, "e": 7468, "s": 7443, "text": "# service xinetd restart" }, { "code": null, "e": 7495, "s": 7468, "text": "Verify NRPE Daemon Locally" }, { "code": null, "e": 7579, "s": 7495, "text": "Run the following command to verify the NRPE daemon working correctly under xinetd." }, { "code": null, "e": 7664, "s": 7579, "text": "# netstat -at | grep nrpe\ntcp 0 0 *:nrpe *:* LISTEN" }, { "code": null, "e": 7712, "s": 7664, "text": "Verify the NRPE daemon is functioning properly." }, { "code": null, "e": 7783, "s": 7712, "text": "# /usr/local/nagios/libexec/check_nrpe -H localhost\nOutput:\nNRPE v2.15" }, { "code": null, "e": 7844, "s": 7783, "text": "Now that Nagios 4.1.1 is installed, we need to configure it." }, { "code": null, "e": 7963, "s": 7844, "text": "Now let’s perform the initial Nagios configuration. You only need to perform this section once, on your Nagios server." }, { "code": null, "e": 8064, "s": 7963, "text": "Open the main Nagios configuration file in your favorite text editor. We’ll use vi to edit the file:" }, { "code": null, "e": 8102, "s": 8064, "text": "# vi /usr/local/nagios/etc/nagios.cfg" }, { "code": null, "e": 8152, "s": 8102, "text": "Now find an uncomment this line by deleting the #" }, { "code": null, "e": 8192, "s": 8152, "text": "# cfg_dir=/usr/local/nagios/etc/servers" }, { "code": null, "e": 8295, "s": 8192, "text": "Now create the directory that will store the configuration file for each server that you will monitor:" }, { "code": null, "e": 8333, "s": 8295, "text": "# mkdir /usr/local/nagios/etc/servers" }, { "code": null, "e": 8432, "s": 8333, "text": "Open the Nagios contacts configuration in your favorite text editor. We’ll use vi to edit the file" }, { "code": null, "e": 8480, "s": 8432, "text": "# vi /usr/local/nagios/etc/objects/contacts.cfg" }, { "code": null, "e": 8579, "s": 8480, "text": "Find the email directive, and replace its value (the highlighted part) with your own email address" }, { "code": null, "e": 8683, "s": 8579, "text": "email nagios@localhost ; <<***** CHANGE THIS TO YOUR EMAIL ADDRESS ******" }, { "code": null, "e": 8735, "s": 8683, "text": "Let’s add a new command to our Nagios configuration" }, { "code": null, "e": 8783, "s": 8735, "text": "# vi /usr/local/nagios/etc/objects/commands.cfg" }, { "code": null, "e": 8824, "s": 8783, "text": "Add the following to the end of the file" }, { "code": null, "e": 8949, "s": 8824, "text": "define command{\ncommand_name check_nrpe\ncommand_line $USER1$/check_nrpe -H $HOSTADDRESS$ -c $ARG1$\n}" }, { "code": null, "e": 9183, "s": 8949, "text": "We are done with all configurations in the back end, now we will configure Web Interface For Nagios with following command. The below command will Configure Web interface for Nagios and a web admin user will be created “nagiosadmin”." }, { "code": null, "e": 9206, "s": 9183, "text": "# make install-webconf" }, { "code": null, "e": 9432, "s": 9206, "text": "In this step, we will be creating a password for “nagiosadmin”. After executing this command, please provide a password twice and keep it remember because this password will be used when you login in the Nagios Web interface." }, { "code": null, "e": 9558, "s": 9432, "text": "# htpasswd -s -c /usr/local/nagios/etc/htpasswd.users nagiosadmin\nNew password:************\nRe-type new password:************" }, { "code": null, "e": 9595, "s": 9558, "text": "Adding password for user nagiosadmin" }, { "code": null, "e": 9648, "s": 9595, "text": "Restart Apache to make the new settings take effect." }, { "code": null, "e": 9670, "s": 9648, "text": "# service httpd start" }, { "code": null, "e": 9718, "s": 9670, "text": "Nagios is now running, so let’s try and log in." }, { "code": null, "e": 9840, "s": 9718, "text": "Open your favorite web browser, and go to your Nagios server http://nagios_server_public_IP or private IP address/nagios." }, { "code": null, "e": 9988, "s": 9840, "text": "Because we configured Apache to use htpasswd, you must enter the login credentials that you created earlier. We used “nagiosadmin” as the username:" }, { "code": null, "e": 10152, "s": 9988, "text": "After authenticating, you will be seeing the default Nagios home page. Click on the Hosts link, in the left navigation bar, to see which hosts Nagios is monitoring" }, { "code": null, "e": 10218, "s": 10152, "text": "As you can see, Nagios is monitoring only “localhost”, or itself." }, { "code": null, "e": 10365, "s": 10218, "text": "In this section, we’ll show you how to add a new host to Nagios, so it will be monitored. Repeat this section for each server you wish to monitor." }, { "code": null, "e": 10419, "s": 10365, "text": "On a server that you want to monitor, update apt-get:" }, { "code": null, "e": 10432, "s": 10419, "text": "# yum update" }, { "code": null, "e": 10469, "s": 10432, "text": "Now install Nagios Plugins and NRPE:" }, { "code": null, "e": 10517, "s": 10469, "text": "# yum install nagios-plugins nagios-nrpe-server" }, { "code": null, "e": 10613, "s": 10517, "text": "Now, let’s update the NRPE configuration file. Open it in your favorite editor (we’re using vi)" }, { "code": null, "e": 10639, "s": 10613, "text": "# vi /etc/nagios/nrpe.cfg" }, { "code": null, "e": 10806, "s": 10639, "text": "Find the allowed_hosts directive, and add the private IP address of your Nagios server to the comma-delimited list (substitute it in place of the highlighted example)" }, { "code": null, "e": 10845, "s": 10806, "text": "allowed_hosts=127.0.0.1,10.132.224.168" }, { "code": null, "e": 10966, "s": 10845, "text": "Save and exit. This configures NRPE to accept requests from your Nagios server, via its private IP or public IP address." }, { "code": null, "e": 10983, "s": 10966, "text": "To add the host:" }, { "code": null, "e": 11047, "s": 10983, "text": "# cd /usr/local/nagios/etc\n# vi /usr/local/nagios/etc/hosts.cfg" }, { "code": null, "e": 11586, "s": 11047, "text": "define host{ name linux-box ; Name of this template use generic-host ; Inherit default values check_period 24x7 check_interval 5 retry_interval 1 max_check_attempts 10 check_command check-host-alive notification_period 24x7 notification_interval 30 notification_options d,r contact_groups admins register 0 } define host{ use linux-box ; Inherit default values from a template host_name Testbox ; The name we're giving to this server alias CentOS 6.7 ; A longer name for the server address 192.168.1.84 ; IP address of Remote Linux host }" }, { "code": null, "e": 11744, "s": 11586, "text": "To add the services we needed to edit the services.cfg file we are adding CPU Load, Total Process, Current Users, Root Partition, Home Partition, Ping status" }, { "code": null, "e": 12961, "s": 11744, "text": "# vi /usr/local/nagios/etc/services.cfg\ndefine service{\n use generic-service\n host_name TestBox\n service_description CPU Load\n check_command check_nrpe!check_load\n}\ndefine service{\n use generic-service\n host_name Testbox\n service_description Total Processes\n check_command check_nrpe!check_total_procs\n}\ndefine service{\n use generic-service\n host_name Testbox\n service_description Current Users\n check_command check_nrpe!check_users\n}\ndefine service{\n use generic-service\n host_name Testbox\n service_description Root Partition\n check_command check_nrpe!check_disk\n}\ndefine service{\n use generic-service\n host_name Testbox\n service_description Home Partition\n check_command check_nrpe!check_disk_home\n}\ndefine service{\n use generic-service\n host_name Testbox\n service_description Ping Status\n check_command check_ping!10.0,80%!50.0,90%\n}" }, { "code": null, "e": 13016, "s": 12961, "text": "We needed to add this configuration file in nagios.cfg" }, { "code": null, "e": 13136, "s": 13016, "text": "# vi /usr/local/nagios/nagios.cfg\n\ncfg_file=/usr/local/nagios/etc/hosts.cfg\ncfg_file=/usr/local/nagios/etc/services.cfg" }, { "code": null, "e": 13214, "s": 13136, "text": "Now NRPE commands should definition needs to be created in commands.cfg file." }, { "code": null, "e": 13369, "s": 13214, "text": "# vi /usr/local/nagios/etc/objects/commands.cfg\ndefine command{\n command_name check_nrpe\n command_line $USER1$/check_nrpe -H $HOSTADDRESS$ -c $ARG1$\n}" }, { "code": null, "e": 13428, "s": 13369, "text": "Finally, verify Nagios Configuration files for any errors." }, { "code": null, "e": 13608, "s": 13428, "text": "Now we are all done with Nagios configuration and its time to verify it and to do so please run below command. If everything goes smoothly it will show up similar to below output." }, { "code": null, "e": 14646, "s": 13608, "text": "# /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg\nOutput:\nNagios Core 4.1.1\nCopyright (c) 2009-present Nagios Core Development Team and Community Contributors\nCopyright (c) 1999-2009 Ethan Galstad\nLast Modified: 08-19-2015\nLicense: GPL\nWebsite: https://www.nagios.org\nReading configuration data...\nRead main config file okay...\nRead object config files okay...\nRunning pre-flight check on configuration data...\nChecking objects...\nChecked 7 services.\nChecked 1 hosts.\nChecked 1 host groups.\nChecked 0 service groups.\nChecked 1 contacts.\nChecked 1 contact groups.\nChecked 7 commands.\nChecked 5 time periods.\nChecked 0 host escalations.\nChecked 0 service escalations.\nChecking for circular paths...\nChecked 1 hosts\nChecked 0 service dependencies\nChecked 0 host dependencies\nChecked 1 timeperiods\nChecking global event handlers...\nChecking obsessive compulsive processor commands...\nChecking misc settings...\nTotal Warnings: 0\nTotal Errors: 0\nThings look okay - No serious problems were detected during the pre-flight check" }, { "code": null, "e": 14747, "s": 14646, "text": "# service nagios reload\nRunning configuration check...\nStopping nagios: done.\nStarting nagios: done." }, { "code": null, "e": 14804, "s": 14747, "text": "Nagios can be used to monitor Apache web server as well." }, { "code": null, "e": 14949, "s": 14804, "text": "Monitor whether the apache server is available. This task is really easy as Nagios has a built-in command for this we needed to edit below file." }, { "code": null, "e": 15168, "s": 14949, "text": "# vi /etc/nagios3/conf.d/services.cfg\ndefine service{\n use generic-service\n host_name Webserver\n service_description Check Apache Web Server\n check_command check_http\n}" }, { "code": null, "e": 15343, "s": 15168, "text": "Once we are done, please check the Nagios configuration and restart the services when we open web interfaces and click on services, we can see Apache services are monitoring." }, { "code": null, "e": 15822, "s": 15343, "text": "Now that you know about Nagios and its features like monitoring your hosts and some of the services, you might want to spend some time to figure out which services are critical to you so you can start monitoring these servers. You may also want to set up notifications so, for example, you receive an email when your disk utilization reaches a warning or critical threshold or your main website is down, so you can resolve the situation promptly or before a problem even occurs." } ]
C# | LongLength property of an Array - GeeksforGeeks
23 Jan, 2019 Array.LongLength Property is used to get a 64-bit integer that represents the total number of elements in all the dimensions of the Array. Syntax: public long LongLength { get; } Property Value: This property returns a 64-bit integer that represents the total number of elements in all the dimensions of the Array. Example: // C# program to illustrate the// Array.LongLength Propertyusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // Two-dimensional array int[, ] intarray = new int[, ] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; // The same array with dimensions // specified 4 row and 2 column. int[, ] intarray_d = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; Console.Write("Total Number of Elements in intarray: "); // using LongLength property Console.Write(intarray.LongLength); // getting the type of returned value Console.WriteLine("\nType of returned Length: " + (intarray.LongLength).GetType()); // showing difference between Length // and LongLength property by getting // the type of the both property's // returned value Console.Write("\nTotal Number of Elements in intarray_d: "); // using Length property Console.Write(intarray_d.Length); // getting the type of returned value Console.WriteLine("\nType of returned Length: " + (intarray_d.Length).GetType()); Console.Write("\nTotal Number of Elements in intarray_d: "); // using LongLengthLength property Console.Write(intarray_d.LongLength); // getting the type of returned value Console.WriteLine("\nType of returned Length: " + (intarray_d.LongLength).GetType()); }}} Total Number of Elements in intarray: 8 Type of returned Length: System.Int64 Total Number of Elements in intarray_d: 8 Type of returned Length: System.Int32 Total Number of Elements in intarray_d: 8 Type of returned Length: System.Int64 Note: In the above program you can see that Array.Length property always returns the length of the type System.Int32 but Array.LongLength property always returns the length of the type System.Int64. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.longlength?view=netframework-4.7.2 CSharp-Arrays C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Constructors C# | Class and Object Introduction to .NET Framework Difference between Ref and Out keywords in C# Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 C# | Delegates C# | Data Types C# | Abstract Classes C# | Replace() Method
[ { "code": null, "e": 24092, "s": 24064, "text": "\n23 Jan, 2019" }, { "code": null, "e": 24231, "s": 24092, "text": "Array.LongLength Property is used to get a 64-bit integer that represents the total number of elements in all the dimensions of the Array." }, { "code": null, "e": 24239, "s": 24231, "text": "Syntax:" }, { "code": null, "e": 24271, "s": 24239, "text": "public long LongLength { get; }" }, { "code": null, "e": 24407, "s": 24271, "text": "Property Value: This property returns a 64-bit integer that represents the total number of elements in all the dimensions of the Array." }, { "code": null, "e": 24416, "s": 24407, "text": "Example:" }, { "code": "// C# program to illustrate the// Array.LongLength Propertyusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // Two-dimensional array int[, ] intarray = new int[, ] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; // The same array with dimensions // specified 4 row and 2 column. int[, ] intarray_d = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; Console.Write(\"Total Number of Elements in intarray: \"); // using LongLength property Console.Write(intarray.LongLength); // getting the type of returned value Console.WriteLine(\"\\nType of returned Length: \" + (intarray.LongLength).GetType()); // showing difference between Length // and LongLength property by getting // the type of the both property's // returned value Console.Write(\"\\nTotal Number of Elements in intarray_d: \"); // using Length property Console.Write(intarray_d.Length); // getting the type of returned value Console.WriteLine(\"\\nType of returned Length: \" + (intarray_d.Length).GetType()); Console.Write(\"\\nTotal Number of Elements in intarray_d: \"); // using LongLengthLength property Console.Write(intarray_d.LongLength); // getting the type of returned value Console.WriteLine(\"\\nType of returned Length: \" + (intarray_d.LongLength).GetType()); }}}", "e": 26208, "s": 24416, "text": null }, { "code": null, "e": 26449, "s": 26208, "text": "Total Number of Elements in intarray: 8\nType of returned Length: System.Int64\n\nTotal Number of Elements in intarray_d: 8\nType of returned Length: System.Int32\n\nTotal Number of Elements in intarray_d: 8\nType of returned Length: System.Int64\n" }, { "code": null, "e": 26648, "s": 26449, "text": "Note: In the above program you can see that Array.Length property always returns the length of the type System.Int32 but Array.LongLength property always returns the length of the type System.Int64." }, { "code": null, "e": 26659, "s": 26648, "text": "Reference:" }, { "code": null, "e": 26751, "s": 26659, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.array.longlength?view=netframework-4.7.2" }, { "code": null, "e": 26765, "s": 26751, "text": "CSharp-Arrays" }, { "code": null, "e": 26768, "s": 26765, "text": "C#" }, { "code": null, "e": 26866, "s": 26768, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26875, "s": 26866, "text": "Comments" }, { "code": null, "e": 26888, "s": 26875, "text": "Old Comments" }, { "code": null, "e": 26906, "s": 26888, "text": "C# | Constructors" }, { "code": null, "e": 26928, "s": 26906, "text": "C# | Class and Object" }, { "code": null, "e": 26959, "s": 26928, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27005, "s": 26959, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27028, "s": 27005, "text": "Extension Method in C#" }, { "code": null, "e": 27068, "s": 27028, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27083, "s": 27068, "text": "C# | Delegates" }, { "code": null, "e": 27099, "s": 27083, "text": "C# | Data Types" }, { "code": null, "e": 27121, "s": 27099, "text": "C# | Abstract Classes" } ]
Apply function to each element of a list - Python - GeeksforGeeks
26 Nov, 2020 In this article, we will learn how to apply a function to each element of a Python list. Let’s see what exactly is Applying a function to each element of a list means: Suppose we have a list of integers and a function that doubles each integer in this list. On applying the function to the list, the function should double all the integers in the list. We achieve this functionality in the following ways: map() method.Using list comprehensions.lambda function map() method. Using list comprehensions. lambda function map() methods take two arguments: iterables and functions and returns a map object. We use list() to convert the map object to a list. Program: Python3 def double(integer): return integer*2 # driver codeinteger_list = [1, 2, 3] # Map method returns a map object# so we cast it into list using list()output_list = list(map(double, integer_list)) print(output_list) Output: [2, 4, 6] Time Complexity: O(n)*(O complexity of function applied on list) We use a list comprehension to call a function on each element of the list and then double it for this case. Program: Python3 def double(integer): return integer*2 # driver codeinteger_list = [1, 2, 3] # Calling double method on each integer# in list using list comprehension.output_list = [double(i) for i in integer_list] print(output_list) Output: [2, 4, 6] Time Complexity: O(n)*(O complexity of function applied on list) A lambda function can also be employed to produce the above functionality. Lambda is capable of creating an anonymous function that can be made enough to fit the given requirement. Program: Python3 lst = [1, 2, 3] ans = [] for x in lst: def res(x): return x*2 ans.append(res(x)) print(ans) Output: [2, 4, 6] python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Pandas dataframe.groupby() Create a directory in Python Defaultdict in Python Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n26 Nov, 2020" }, { "code": null, "e": 25815, "s": 25647, "text": "In this article, we will learn how to apply a function to each element of a Python list. Let’s see what exactly is Applying a function to each element of a list means:" }, { "code": null, "e": 26053, "s": 25815, "text": "Suppose we have a list of integers and a function that doubles each integer in this list. On applying the function to the list, the function should double all the integers in the list. We achieve this functionality in the following ways:" }, { "code": null, "e": 26108, "s": 26053, "text": "map() method.Using list comprehensions.lambda function" }, { "code": null, "e": 26122, "s": 26108, "text": "map() method." }, { "code": null, "e": 26149, "s": 26122, "text": "Using list comprehensions." }, { "code": null, "e": 26165, "s": 26149, "text": "lambda function" }, { "code": null, "e": 26300, "s": 26165, "text": "map() methods take two arguments: iterables and functions and returns a map object. We use list() to convert the map object to a list." }, { "code": null, "e": 26309, "s": 26300, "text": "Program:" }, { "code": null, "e": 26317, "s": 26309, "text": "Python3" }, { "code": "def double(integer): return integer*2 # driver codeinteger_list = [1, 2, 3] # Map method returns a map object# so we cast it into list using list()output_list = list(map(double, integer_list)) print(output_list)", "e": 26537, "s": 26317, "text": null }, { "code": null, "e": 26545, "s": 26537, "text": "Output:" }, { "code": null, "e": 26555, "s": 26545, "text": "[2, 4, 6]" }, { "code": null, "e": 26620, "s": 26555, "text": "Time Complexity: O(n)*(O complexity of function applied on list)" }, { "code": null, "e": 26729, "s": 26620, "text": "We use a list comprehension to call a function on each element of the list and then double it for this case." }, { "code": null, "e": 26738, "s": 26729, "text": "Program:" }, { "code": null, "e": 26746, "s": 26738, "text": "Python3" }, { "code": "def double(integer): return integer*2 # driver codeinteger_list = [1, 2, 3] # Calling double method on each integer# in list using list comprehension.output_list = [double(i) for i in integer_list] print(output_list)", "e": 26971, "s": 26746, "text": null }, { "code": null, "e": 26979, "s": 26971, "text": "Output:" }, { "code": null, "e": 26989, "s": 26979, "text": "[2, 4, 6]" }, { "code": null, "e": 27054, "s": 26989, "text": "Time Complexity: O(n)*(O complexity of function applied on list)" }, { "code": null, "e": 27235, "s": 27054, "text": "A lambda function can also be employed to produce the above functionality. Lambda is capable of creating an anonymous function that can be made enough to fit the given requirement." }, { "code": null, "e": 27244, "s": 27235, "text": "Program:" }, { "code": null, "e": 27252, "s": 27244, "text": "Python3" }, { "code": "lst = [1, 2, 3] ans = [] for x in lst: def res(x): return x*2 ans.append(res(x)) print(ans)", "e": 27353, "s": 27252, "text": null }, { "code": null, "e": 27361, "s": 27353, "text": "Output:" }, { "code": null, "e": 27371, "s": 27361, "text": "[2, 4, 6]" }, { "code": null, "e": 27383, "s": 27371, "text": "python-list" }, { "code": null, "e": 27390, "s": 27383, "text": "Python" }, { "code": null, "e": 27402, "s": 27390, "text": "python-list" }, { "code": null, "e": 27500, "s": 27402, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27532, "s": 27500, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27574, "s": 27532, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27616, "s": 27574, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27672, "s": 27616, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27699, "s": 27672, "text": "Python Classes and Objects" }, { "code": null, "e": 27730, "s": 27699, "text": "Python | os.path.join() method" }, { "code": null, "e": 27766, "s": 27730, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27795, "s": 27766, "text": "Create a directory in Python" }, { "code": null, "e": 27817, "s": 27795, "text": "Defaultdict in Python" } ]
Difference between 2-address instruction and 1-address instructions - GeeksforGeeks
19 Jun, 2020 Prerequisite – Instruction Formats1. Two-Address Instructions :Two-address instruction is a format of machine instruction. It has one opcode and two address fields. One address field is common and can be used for either destination or source and other address field for source. Example: X = (A + B) x (C + D) Solution: MOV R1, A R1 <- M[A] ADD R1, B R1 <- R1 + M[B] MOV R2, C R2 <- M[C] ADD R2, D R2 <- R2 + D MUL R1, R2 R1 <- R1 x R2 MOV X, R1 M[X] <- R1 2. One-Address Instructions :One-Address instruction is also a format of machine instruction. It has only two fields. One for opcode and other for operand. Example: X = (A + B) x (C + D) Solution: LOAD A AC <- M[A] ADD B AC <- AC + M[B] STORE T M[T] <- AC LOAD C AC <- M[C] ADD D AC <- AC + M[D] MUL T AC <- AC x M[T] STORE X M[X] <- AC Difference between Two-Address Instruction and One-Address Instruction : Computer Organization & Architecture Difference Between GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Architecture of 8085 microprocessor Pin diagram of 8086 microprocessor Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) Direct Access Media (DMA) Controller in Computer Architecture General purpose registers in 8086 microprocessor Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between Process and Thread Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24700, "s": 24672, "text": "\n19 Jun, 2020" }, { "code": null, "e": 24978, "s": 24700, "text": "Prerequisite – Instruction Formats1. Two-Address Instructions :Two-address instruction is a format of machine instruction. It has one opcode and two address fields. One address field is common and can be used for either destination or source and other address field for source." }, { "code": null, "e": 24987, "s": 24978, "text": "Example:" }, { "code": null, "e": 25010, "s": 24987, "text": "X = (A + B) x (C + D) " }, { "code": null, "e": 25020, "s": 25010, "text": "Solution:" }, { "code": null, "e": 25187, "s": 25020, "text": "MOV R1, A R1 <- M[A]\nADD R1, B R1 <- R1 + M[B]\nMOV R2, C R2 <- M[C]\nADD R2, D R2 <- R2 + D\nMUL R1, R2 R1 <- R1 x R2\nMOV X, R1 M[X] <- R1 " }, { "code": null, "e": 25343, "s": 25187, "text": "2. One-Address Instructions :One-Address instruction is also a format of machine instruction. It has only two fields. One for opcode and other for operand." }, { "code": null, "e": 25352, "s": 25343, "text": "Example:" }, { "code": null, "e": 25375, "s": 25352, "text": "X = (A + B) x (C + D) " }, { "code": null, "e": 25385, "s": 25375, "text": "Solution:" }, { "code": null, "e": 25563, "s": 25385, "text": "LOAD A AC <- M[A]\nADD B AC <- AC + M[B]\nSTORE T M[T] <- AC\nLOAD C AC <- M[C]\nADD D AC <- AC + M[D]\nMUL T AC <- AC x M[T]\nSTORE X M[X] <- AC " }, { "code": null, "e": 25636, "s": 25563, "text": "Difference between Two-Address Instruction and One-Address Instruction :" }, { "code": null, "e": 25673, "s": 25636, "text": "Computer Organization & Architecture" }, { "code": null, "e": 25692, "s": 25673, "text": "Difference Between" }, { "code": null, "e": 25700, "s": 25692, "text": "GATE CS" }, { "code": null, "e": 25798, "s": 25700, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25807, "s": 25798, "text": "Comments" }, { "code": null, "e": 25820, "s": 25807, "text": "Old Comments" }, { "code": null, "e": 25856, "s": 25820, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 25891, "s": 25856, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 25982, "s": 25891, "text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)" }, { "code": null, "e": 26044, "s": 25982, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 26093, "s": 26044, "text": "General purpose registers in 8086 microprocessor" }, { "code": null, "e": 26124, "s": 26093, "text": "Difference between BFS and DFS" }, { "code": null, "e": 26164, "s": 26124, "text": "Class method vs Static method in Python" }, { "code": null, "e": 26196, "s": 26164, "text": "Differences between TCP and UDP" }, { "code": null, "e": 26234, "s": 26196, "text": "Difference between Process and Thread" } ]
DateFormat format(Date obj) method in Java - GeeksforGeeks
28 Feb, 2019 The format() method of DateFormat class in Java is used to format a given Date object into a string representing Date/Time. Syntax: String format(Date date) Parameters: This method accepts a single parameter date which is a Date object. Return Value: This method returns a String which is the formatted date-time value of the Date object passed as a parameter to the method. Below programs illustrate the above method: Program 1: // Java program to illustrate the// format() method import java.text.DateFormat;import java.util.Date; public class GFG { public static void main(String[] args) { // Create a Date instance Date currentDate = new Date(); // Create a DateFormat instance and format // current Date String dateToStr = DateFormat.getInstance() .format(currentDate); System.out.println("Formatted Date String: " + dateToStr); }} Formatted Date String: 2/27/19 3:31 PM Program 2: // Java program to illustrate the// format() method import java.text.DateFormat;import java.util.*; public class GFG { public static void main(String[] args) { // Create a Date instance Date date = new Date(2323223232L); // Create a DateFormat instance and format // the specified Date String dateToStr = DateFormat.getInstance() .format(date); System.out.println("Formatted Date String: " + dateToStr); }} Formatted Date String: 1/27/70 9:20 PM Reference: https://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#format(java.util.Date)\ Java-Date-Time 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 Stream In Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 25863, "s": 25835, "text": "\n28 Feb, 2019" }, { "code": null, "e": 25987, "s": 25863, "text": "The format() method of DateFormat class in Java is used to format a given Date object into a string representing Date/Time." }, { "code": null, "e": 25995, "s": 25987, "text": "Syntax:" }, { "code": null, "e": 26021, "s": 25995, "text": "String format(Date date)\n" }, { "code": null, "e": 26101, "s": 26021, "text": "Parameters: This method accepts a single parameter date which is a Date object." }, { "code": null, "e": 26239, "s": 26101, "text": "Return Value: This method returns a String which is the formatted date-time value of the Date object passed as a parameter to the method." }, { "code": null, "e": 26283, "s": 26239, "text": "Below programs illustrate the above method:" }, { "code": null, "e": 26294, "s": 26283, "text": "Program 1:" }, { "code": "// Java program to illustrate the// format() method import java.text.DateFormat;import java.util.Date; public class GFG { public static void main(String[] args) { // Create a Date instance Date currentDate = new Date(); // Create a DateFormat instance and format // current Date String dateToStr = DateFormat.getInstance() .format(currentDate); System.out.println(\"Formatted Date String: \" + dateToStr); }}", "e": 26814, "s": 26294, "text": null }, { "code": null, "e": 26854, "s": 26814, "text": "Formatted Date String: 2/27/19 3:31 PM\n" }, { "code": null, "e": 26865, "s": 26854, "text": "Program 2:" }, { "code": "// Java program to illustrate the// format() method import java.text.DateFormat;import java.util.*; public class GFG { public static void main(String[] args) { // Create a Date instance Date date = new Date(2323223232L); // Create a DateFormat instance and format // the specified Date String dateToStr = DateFormat.getInstance() .format(date); System.out.println(\"Formatted Date String: \" + dateToStr); }}", "e": 27385, "s": 26865, "text": null }, { "code": null, "e": 27425, "s": 27385, "text": "Formatted Date String: 1/27/70 9:20 PM\n" }, { "code": null, "e": 27528, "s": 27425, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#format(java.util.Date)\\" }, { "code": null, "e": 27543, "s": 27528, "text": "Java-Date-Time" }, { "code": null, "e": 27558, "s": 27543, "text": "Java-Functions" }, { "code": null, "e": 27576, "s": 27558, "text": "Java-text package" }, { "code": null, "e": 27581, "s": 27576, "text": "Java" }, { "code": null, "e": 27586, "s": 27581, "text": "Java" }, { "code": null, "e": 27684, "s": 27586, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27735, "s": 27684, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27750, "s": 27735, "text": "Stream In Java" }, { "code": null, "e": 27780, "s": 27750, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27799, "s": 27780, "text": "Interfaces in Java" }, { "code": null, "e": 27830, "s": 27799, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27862, "s": 27830, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27880, "s": 27862, "text": "ArrayList in Java" }, { "code": null, "e": 27900, "s": 27880, "text": "Stack Class in Java" }, { "code": null, "e": 27924, "s": 27900, "text": "Singleton Class in Java" } ]
HTML | Clearing the input field - GeeksforGeeks
29 Jul, 2021 To clear the entire input field without having to delete the whole thing manually Or what if there is already a pre-suggested input present in the input field, that the user doesn’t want. There could be many scenarios. Therefore, in this article, we are going to learn about how to clear the input field. There are two ways to do this and both are super easy and short. Let us check out both of them. Method 1: Clearing Input on Focus. Syntax: <input onfocus=this.value=''> Approach: Create an input field. Set the onfocus attribute to NULL using this.value Example: <!DOCTYPE html><html> <body> <body style="text-align:center"> <h2 style="color:green">GeeksForGeeks</h2> <h2 style="color:purple">Clearing Input Field</h2> <p>The below input field will be cleared, as soon as it gets the focus</p> <input type="text" onfocus="this.value=''" value="Click here to clear"> </body> </html> Output:Before: After: Method 2: Clearing Input with the help of button. Syntax: <button onclick="document.getElementById('InputID').value = ''> Approach: Create a button. Get the id of input field. Set the value NULL of input field using document.getElementById(‘myInput’).value = ” <!DOCTYPE html><html> <body style="text-align:center"> <h2 style="color:green"> GeeksForGeeks </h2> <h2 style="color:purple"> Clearing Input Field </h2> <p>The below input field will be cleared, as soon as the button gets clicked </p> <button onclick= "document.getElementById( 'myInput').value = ''"> Click here to clear </button> <input type="text" value="GeeksForGeeks" id="myInput"></body> </html> Output:Before: After: HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. shubham_singh HTML-Misc HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML How to Insert Form Data into Database using PHP ? How to position a div at the bottom of its container using CSS? Form validation using HTML and 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 ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26812, "s": 26784, "text": "\n29 Jul, 2021" }, { "code": null, "e": 27117, "s": 26812, "text": "To clear the entire input field without having to delete the whole thing manually Or what if there is already a pre-suggested input present in the input field, that the user doesn’t want. There could be many scenarios. Therefore, in this article, we are going to learn about how to clear the input field." }, { "code": null, "e": 27213, "s": 27117, "text": "There are two ways to do this and both are super easy and short. Let us check out both of them." }, { "code": null, "e": 27248, "s": 27213, "text": "Method 1: Clearing Input on Focus." }, { "code": null, "e": 27256, "s": 27248, "text": "Syntax:" }, { "code": null, "e": 27286, "s": 27256, "text": "<input onfocus=this.value=''>" }, { "code": null, "e": 27296, "s": 27286, "text": "Approach:" }, { "code": null, "e": 27319, "s": 27296, "text": "Create an input field." }, { "code": null, "e": 27370, "s": 27319, "text": "Set the onfocus attribute to NULL using this.value" }, { "code": null, "e": 27379, "s": 27370, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <body> <body style=\"text-align:center\"> <h2 style=\"color:green\">GeeksForGeeks</h2> <h2 style=\"color:purple\">Clearing Input Field</h2> <p>The below input field will be cleared, as soon as it gets the focus</p> <input type=\"text\" onfocus=\"this.value=''\" value=\"Click here to clear\"> </body> </html>", "e": 27736, "s": 27379, "text": null }, { "code": null, "e": 27751, "s": 27736, "text": "Output:Before:" }, { "code": null, "e": 27758, "s": 27751, "text": "After:" }, { "code": null, "e": 27808, "s": 27758, "text": "Method 2: Clearing Input with the help of button." }, { "code": null, "e": 27816, "s": 27808, "text": "Syntax:" }, { "code": null, "e": 27880, "s": 27816, "text": "<button onclick=\"document.getElementById('InputID').value = ''>" }, { "code": null, "e": 27890, "s": 27880, "text": "Approach:" }, { "code": null, "e": 27907, "s": 27890, "text": "Create a button." }, { "code": null, "e": 27934, "s": 27907, "text": "Get the id of input field." }, { "code": null, "e": 28019, "s": 27934, "text": "Set the value NULL of input field using document.getElementById(‘myInput’).value = ”" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align:center\"> <h2 style=\"color:green\"> GeeksForGeeks </h2> <h2 style=\"color:purple\"> Clearing Input Field </h2> <p>The below input field will be cleared, as soon as the button gets clicked </p> <button onclick= \"document.getElementById( 'myInput').value = ''\"> Click here to clear </button> <input type=\"text\" value=\"GeeksForGeeks\" id=\"myInput\"></body> </html>", "e": 28520, "s": 28019, "text": null }, { "code": null, "e": 28535, "s": 28520, "text": "Output:Before:" }, { "code": null, "e": 28542, "s": 28535, "text": "After:" }, { "code": null, "e": 28736, "s": 28542, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 28873, "s": 28736, "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": 28887, "s": 28873, "text": "shubham_singh" }, { "code": null, "e": 28897, "s": 28887, "text": "HTML-Misc" }, { "code": null, "e": 28902, "s": 28897, "text": "HTML" }, { "code": null, "e": 28919, "s": 28902, "text": "Web Technologies" }, { "code": null, "e": 28924, "s": 28919, "text": "HTML" }, { "code": null, "e": 29022, "s": 28924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29046, "s": 29022, "text": "REST API (Introduction)" }, { "code": null, "e": 29087, "s": 29046, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 29137, "s": 29087, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 29201, "s": 29137, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 29243, "s": 29201, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 29283, "s": 29243, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29316, "s": 29283, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29361, "s": 29316, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29404, "s": 29361, "text": "How to fetch data from an API in ReactJS ?" } ]
MATLAB - Graphics
This chapter will continue exploring the plotting and graphics capabilities of MATLAB. We will discuss − Drawing bar charts Drawing contours Three dimensional plots The bar command draws a two dimensional bar chart. Let us take up an example to demonstrate the idea. Let us have an imaginary classroom with 10 students. We know the percent of marks obtained by these students are 75, 58, 90, 87, 50, 85, 92, 75, 60 and 95. We will draw the bar chart for this data. Create a script file and type the following code − x = [1:10]; y = [75, 58, 90, 87, 50, 85, 92, 75, 60, 95]; bar(x,y), xlabel('Student'),ylabel('Score'), title('First Sem:') print -deps graph.eps When you run the file, MATLAB displays the following bar chart − A contour line of a function of two variables is a curve along which the function has a constant value. Contour lines are used for creating contour maps by joining points of equal elevation above a given level, such as mean sea level. MATLAB provides a contour function for drawing contour maps. Let us generate a contour map that shows the contour lines for a given function g = f(x, y). This function has two variables. So, we will have to generate two independent variables, i.e., two data sets x and y. This is done by calling the meshgrid command. The meshgrid command is used for generating a matrix of elements that give the range over x and y along with the specification of increment in each case. Let us plot our function g = f(x, y), where −5 ≤ x ≤ 5, −3 ≤ y ≤ 3. Let us take an increment of 0.1 for both the values. The variables are set as − [x,y] = meshgrid(–5:0.1:5, –3:0.1:3); Lastly, we need to assign the function. Let our function be: x2 + y2 Create a script file and type the following code − [x,y] = meshgrid(-5:0.1:5,-3:0.1:3); %independent variables g = x.^2 + y.^2; % our function contour(x,y,g) % call the contour function print -deps graph.eps When you run the file, MATLAB displays the following contour map − Let us modify the code a little to spruce up the map [x,y] = meshgrid(-5:0.1:5,-3:0.1:3); %independent variables g = x.^2 + y.^2; % our function [C, h] = contour(x,y,g); % call the contour function set(h,'ShowText','on','TextStep',get(h,'LevelStep')*2) print -deps graph.eps When you run the file, MATLAB displays the following contour map − Three-dimensional plots basically display a surface defined by a function in two variables, g = f (x,y). As before, to define g, we first create a set of (x,y) points over the domain of the function using the meshgrid command. Next, we assign the function itself. Finally, we use the surf command to create a surface plot. The following example demonstrates the concept − Let us create a 3D surface map for the function g = xe-(x2 + y2) Create a script file and type the following code − [x,y] = meshgrid(-2:.2:2); g = x .* exp(-x.^2 - y.^2); surf(x, y, g) print -deps graph.eps When you run the file, MATLAB displays the following 3-D map − You can also use the mesh command to generate a three-dimensional surface. However, the surf command displays both the connecting lines and the faces of the surface in color, whereas, the mesh command creates a wireframe surface with colored lines connecting the defining points. 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2246, "s": 2141, "text": "This chapter will continue exploring the plotting and graphics capabilities of MATLAB. We will discuss −" }, { "code": null, "e": 2265, "s": 2246, "text": "Drawing bar charts" }, { "code": null, "e": 2282, "s": 2265, "text": "Drawing contours" }, { "code": null, "e": 2306, "s": 2282, "text": "Three dimensional plots" }, { "code": null, "e": 2408, "s": 2306, "text": "The bar command draws a two dimensional bar chart. Let us take up an example to demonstrate the idea." }, { "code": null, "e": 2606, "s": 2408, "text": "Let us have an imaginary classroom with 10 students. We know the percent of marks obtained by these students are 75, 58, 90, 87, 50, 85, 92, 75, 60 and 95. We will draw the bar chart for this data." }, { "code": null, "e": 2657, "s": 2606, "text": "Create a script file and type the following code −" }, { "code": null, "e": 2802, "s": 2657, "text": "x = [1:10];\ny = [75, 58, 90, 87, 50, 85, 92, 75, 60, 95];\nbar(x,y), xlabel('Student'),ylabel('Score'),\ntitle('First Sem:')\nprint -deps graph.eps" }, { "code": null, "e": 2867, "s": 2802, "text": "When you run the file, MATLAB displays the following bar chart −" }, { "code": null, "e": 3102, "s": 2867, "text": "A contour line of a function of two variables is a curve along which the function has a constant value. Contour lines are used for creating contour maps by joining points of equal elevation above a given level, such as mean sea level." }, { "code": null, "e": 3163, "s": 3102, "text": "MATLAB provides a contour function for drawing contour maps." }, { "code": null, "e": 3420, "s": 3163, "text": "Let us generate a contour map that shows the contour lines for a given function g = f(x, y). This function has two variables. So, we will have to generate two independent variables, i.e., two data sets x and y. This is done by calling the meshgrid command." }, { "code": null, "e": 3574, "s": 3420, "text": "The meshgrid command is used for generating a matrix of elements that give the range over x and y along with the specification of increment in each case." }, { "code": null, "e": 3722, "s": 3574, "text": "Let us plot our function g = f(x, y), where −5 ≤ x ≤ 5, −3 ≤ y ≤ 3. Let us take an increment of 0.1 for both the values. The variables are set as −" }, { "code": null, "e": 3760, "s": 3722, "text": "[x,y] = meshgrid(–5:0.1:5, –3:0.1:3);" }, { "code": null, "e": 3829, "s": 3760, "text": "Lastly, we need to assign the function. Let our function be: x2 + y2" }, { "code": null, "e": 3880, "s": 3829, "text": "Create a script file and type the following code −" }, { "code": null, "e": 4085, "s": 3880, "text": "[x,y] = meshgrid(-5:0.1:5,-3:0.1:3); %independent variables\ng = x.^2 + y.^2; % our function\ncontour(x,y,g) % call the contour function\nprint -deps graph.eps" }, { "code": null, "e": 4152, "s": 4085, "text": "When you run the file, MATLAB displays the following contour map −" }, { "code": null, "e": 4205, "s": 4152, "text": "Let us modify the code a little to spruce up the map" }, { "code": null, "e": 4465, "s": 4205, "text": "[x,y] = meshgrid(-5:0.1:5,-3:0.1:3); %independent variables\ng = x.^2 + y.^2; % our function\n[C, h] = contour(x,y,g); % call the contour function\nset(h,'ShowText','on','TextStep',get(h,'LevelStep')*2)\nprint -deps graph.eps" }, { "code": null, "e": 4532, "s": 4465, "text": "When you run the file, MATLAB displays the following contour map −" }, { "code": null, "e": 4637, "s": 4532, "text": "Three-dimensional plots basically display a surface defined by a function in two variables, g = f (x,y)." }, { "code": null, "e": 4855, "s": 4637, "text": "As before, to define g, we first create a set of (x,y) points over the domain of the function using the meshgrid command. Next, we assign the function itself. Finally, we use the surf command to create a surface plot." }, { "code": null, "e": 4904, "s": 4855, "text": "The following example demonstrates the concept −" }, { "code": null, "e": 4969, "s": 4904, "text": "Let us create a 3D surface map for the function g = xe-(x2 + y2)" }, { "code": null, "e": 5020, "s": 4969, "text": "Create a script file and type the following code −" }, { "code": null, "e": 5111, "s": 5020, "text": "[x,y] = meshgrid(-2:.2:2);\ng = x .* exp(-x.^2 - y.^2);\nsurf(x, y, g)\nprint -deps graph.eps" }, { "code": null, "e": 5174, "s": 5111, "text": "When you run the file, MATLAB displays the following 3-D map −" }, { "code": null, "e": 5454, "s": 5174, "text": "You can also use the mesh command to generate a three-dimensional surface. However, the surf command displays both the connecting lines and the faces of the surface in color, whereas, the mesh command creates a wireframe surface with colored lines connecting the defining points." }, { "code": null, "e": 5487, "s": 5454, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 5500, "s": 5487, "text": " Nouman Azam" }, { "code": null, "e": 5535, "s": 5500, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 5548, "s": 5535, "text": " Nouman Azam" }, { "code": null, "e": 5581, "s": 5548, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 5590, "s": 5581, "text": " Sanjeev" }, { "code": null, "e": 5623, "s": 5590, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 5639, "s": 5623, "text": " TELCOMA Global" }, { "code": null, "e": 5672, "s": 5639, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 5688, "s": 5672, "text": " TELCOMA Global" }, { "code": null, "e": 5721, "s": 5688, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 5738, "s": 5721, "text": " Phinite Academy" }, { "code": null, "e": 5745, "s": 5738, "text": " Print" }, { "code": null, "e": 5756, "s": 5745, "text": " Add Notes" } ]
How to create a CLI in golang with cobra | by Shubham Chadokar | Towards Data Science
Have you ever wonder why in the world of GUI, CLI still exist? You’ll better understand it when you build one of your own. Published on schadokar.dev When you learn golang then it is very often that you’ll come across that ‘golang is great to build cli tools’. This fascinated me too. So, I tried to get my hands dirty and found a few tutorials of creating a cli but most of all are not basic. In this tutorial, I’ll try to smooth the learning curve. This is the basic cli application where we are going to cover basic cli operations. I am planning to write another article with advance cli operations but that’s for later. We are creating a simple mathematical cli which will be capable of doing the following 2 jobs: addition of numbers addition of only even or odd numbers I know these jobs don’t meet your expectations but trust me, after this, you will feel comfortable with building a cli. CLI works on the basic principle of software engineering, takes the input, process it and gives the output. In the cli tool instead of a flashing frontend, it takes the input from the black window. Remember, Matrix Trilogy. If you are using Windows just type cmd or powershell in the startand enter, the black window or blue window is a cli. In Mac or Linux it is known by the name terminal . A command-line interface (CLI) is a means of interacting with a computer program where the user (or client) issues commands to the program in the form of successive lines of text (command lines). The program which handles the interface is called a command-line interpreter or command-line processor. — wikipedia There are many CLIs’ you might work on like npm, node, go, python, docker, Kubernetes etc. All are an ideal interface to interact with the software. It is lightweight and fast. Minimal or no dependencies. Best for system administration and task-based automation etc. Enough of theory, let’s start with the requirements: golang installed (I am using go1.11.5 windows/amd64) Cobra library (go get -u github.com/spf13/cobra/cobra) Any code editor of your choice. (I am using VS Code) I recommend to use VS code and install the go extension by Microsoft. This will update the import statement according to the code. If you use a new package, it will import that package on save. If a package is imported and not used, it will remove that package from the import. A little introduction to the Cobra library. We will use cobra cli to use the cobra library. We will use a cli to build a cli 😃 Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files. Many of the most widely used Go projects are built using Cobra, such as: Kubernetes, Hugo, Docker (distribution) etc. — Github Cobra is built on a structure of commands, arguments & flags. Commands represent actions Args are things Flags are modifiers for those actions The basic structure will be like a simple sentence APPNAME Command Args --Flags or APPNAME Command --Flags Args For Ex. git clone URL -bare go get -u URL npm install package --save docker run image -d Create a new project directory outside the GOPATH. I have created my-calc project directory for this tutorial. You can name any of your choices. Creating projects outside the GOPATH ease the importing local files. Initialize modules in the project. This module will keep all the libraries and dependency require and used in this project. It is similar to the package.json in the nodejs. To read more about the modules, please read this great article. A module is a collection of related Go packages that are versioned together as a single unit. Modules record precise dependency requirements and create reproducible builds. — wiki Open the project directory in the command line of your choices. I am using bash . Once you are inside the project directory, run the below command to initialize the modules. go mod init my-calc You can notice that it creates a go.mod file in the project. Note: Creating modules inside the $GOPATHis disabled by default. You will get this error if you run above command — go: modules disabled inside GOPATH/src by GO111MODULE=auto; see ‘go help modules’ . If you still want to create the go modules inside the $GOPATH then first set GO111MODULE environment variable to on . export GO111MODULE=on Now whenever you use any third-party packages in the project, it’ll save it as a dependency with their version. In this way, even if a breaking change introduces in the new version of the library, your project will work as expected. If you still haven’t installed the cobra library, you can install it using below command. go get -u github.com/spf13/cobra/cobra Initialize the cli scaffolding for the project using cobra initcommand. cobra init --pkg-name my-calc Edit: thank you Brandon Caton, for the update of init command. It will initialize the my-calc project with cobra library. You can observe that it created a few files in the project. ▾ my-calc/ ▾ cmd/ root.go main.go The main.go is the entry point of the cli . Inside the main.go it is calling the Execute function of the cmd/root.go . // main.gopackage mainimport "my-calc/cmd"func main() { cmd.Execute()} Let’s examine the root.go . Root command is the base command of any cli. For Ex. go get URL — go is the root command here and get is the child command of the go . In the root.go it is initiating the rootCmd struct variable with the cobra command. All the other commands in the cli will be a child of the rootCmd . Open the root.go in the editor and inside the rootCmd uncomment the Run: func(cmd *cobra.Command, args []string) {}, And paste the fmt.Println("Hello CLI") inside the curly braces. Run: func(cmd *cobra.Command, args []string) {fmt.Println("Hello CLI"}, ⚠️ Don’t remove the comma after the closing curly braces. It will throw syntax error. Open the terminal inside the my-calc project and run go install my-calc This command will generate the binary or executable file of the project in the $GOPATH/bin folder. Now run my-calc in the terminal. As it is saved in the bin folder you don’t have to set the environment variable for this. The name of cli is the rootCmd. my-calc is the rootCmd. You will see the output similar to this. This is the first function which gets called whenever a package initialize in the golang. The cobra.OnInitialize(funcDeclarations) append the user-defined functions in the command’s initialization. Whenever the command run or called it will first execute all the functions in the command’s initialization and then it will run the execute method. This initialization can be used in loading the configuration file or can be used as constructor. It all depends on your use case and your creativity. I believe I lost you here. Let’s understand this with an example. In the root.go , the command is the rootCmd. The cobra.OnInitialize(initConfig) append the initConfigfunction declaration in the rootCmd’s initialization. So, whenever the rootCmd ‘s execute method (RUN: func) run, the rootCmd will first run the initConfigfunction. Once the execution of all the initialize functions over, it will run the RUN: func execution method of rootCmd. To visualize it, add a print message in the initConfig function. func initConfig() { fmt.Println("inside initConfig")... Save the changes. Open the terminal inside the my-calc project. Rebuild the binary go install my-calc. go install my-calc Run my-calc. Whenever you’ll make any changes in the cli you have to rebuild the binary. Run go install my-calc to reflect it in the cli commands. You can see that initConfig run first and later Hello CLI . To understand the complete flow of cli, add a message inside the init function and a message inside the main func in the main.go. // root.gofunc init() { fmt.Println("inside init") cobra.OnInitialize(initConfig)...// main.gofunc main() { fmt.Println("inside main") cmd.Execute()} Save the changes. Rebuild the binary go install my-calc and run my-calc . Now, you know the cli command flow. The last thing in the init function is flags . Flags are like modifiers to the command. You can think of them as conditional actions. We will learn more about it later in the tutorial. There are 2 types of flags Persistent Flags and Local Flags . Persistent Flags: This flag will be available to the command it is assigned as well as all the child or subcommands of the command. Local Flags: This flag is only available to the command which it is assigned to. This function is setting the configuration path in the home directory and config filename is .my-calc . It will use the configuration file if it exists. The viper library is famous for configuration solution for go application. It reads from JSON, TOML, YAML, HCL, envfile and Java properties config files. It does much more than reading configuration. To learn more about it, follow this link. With this function, we completed the root.go examination. It is a bit lengthier, but it is good to understand what we are using. Note: Now if you want, you can remove all the print statements from the root.go and main.go . I have removed all the print statements to keep the code clean. It’s time to add some commands in our cli. We already created one command which is my-calc asrootCmd which returns Hello CLI. Open the terminal inside the project directory and create a command named add . The cobra command to add a new command is cobra add <commandName> cobra add add// outputadd created at C:\Work\golang\my-calc Check the cmd folder, an add.go file is added in it. Open the add.go . It is similar to the root.go . First, an addCmd struct variable is declared of type *cobra.Command . The *cobra.Command have RUN which is a func and takes pointer of *cobra.Command and a slice of string []string. Then it is initialized in init function. In the init, it is added to the rootCmd . We can understand it as addCmdis the sub-command or child command of the rootCmd. func init() { rootCmd.AddCommand(addCmd) In the terminal, rebuild the binary using go install my-calc command and run my-calc add . The add command is working fine. It’s time to modify it to add a series of numbers. The commands only take a slice of string as an argument. To add the numbers, we first have to convert the string into int then return the result. We will use strconv library to convert the string to int. Import the strconv package. import ( "fmt" "strconv" "github.com/spf13/cobra") Inside the add.go, create a new addInt function. // add.gofunc addInt(args []string) { var sum int // iterate over the arguments // the first return value is index of args, we can omit it using _ for _, ival := range args { // strconv is the library used for type conversion. for string // to int conversion Atio method is used. itemp, err := strconv.Atoi(ival) if err != nil { fmt.Println(err) } sum = sum + itemp } fmt.Printf("Addition of numbers %s is %d", args, sum)} Save the changes. In the addCmd variable, update the RUN func. Remove the print message and call the addInt function with args. // addCmdRun: func(cmd *cobra.Command, args []string) { addInt(args)}, Rebuild the binary using go install my-calc . Run my-calc add 2 3 . ⚠️Don’t forget the space between the arguments. You can pass as many arguments as you want. If you remember the args is a slice of string. But there is a limitation in this function. It can only add integers not decimal number. In the addInt function we are converting the string into int not in float32/64 . It is time to introduce a flag in the addCmd . This flag will help the cli to decide if it is an int operation or float. In the add.go , inside the init func, create a local flag of the bool type, Flags().BoolP. Its name will be float , shortened name f , default value false and description. The default value is very important. It means even if flag is not called in the command, the flag value will be false . For bool type, if a flag is called it will toggle the default. // add.gofunc init() { rootCmd.AddCommand(addCmd) addCmd.Flags().BoolP("float", "f", false, "Add Floating Numbers")} Create a new addFloat function in the add.go // add.gofunc addFloat(args []string) { var sum float64 for _, fval := range args { // convert string to float64 ftemp, err := strconv.ParseFloat(fval, 64) if err != nil { fmt.Println(err) } sum = sum + ftemp } fmt.Printf("Sum of floating numbers %s is %f", args, sum)} This function is the same as addInt except, it is converting string to float64. In the addCmd RUN function, it will call the addInt or addFloat according to the flag. If flag --float or -f is passed then it will call addFloat . // add.go // addCmdRun: func(cmd *cobra.Command, args []string) { // get the flag value, its default value is false fstatus, _ := cmd.Flags().GetBool("float") if fstatus { // if status is true, call addFloat addFloat(args) } else { addInt(args) }}, Save all the changes. Rebuild the binary using go install my-calc . Run my-calc add 1.2 2.5 -f or my-calc add 1.2 2.5 --float You can do lots of things with flags. You can even pass values to flags like a slice of int, float, string etc. The basic addition of operation implementation is completed. Let’s expand it by adding sub-commands to the addCmd . Open the terminal in the project directory and create a new even command. cobra add even The even command as even.go added in the cmd folder. Open the even.go in the editor. Change rootCmd to addCmd in the init . // even.gofunc init() { addCmd.AddCommand(evenCmd)...} The addCmd.AddCommand(evenCmd) will add evenCmd as child or subcommand of the addCmd . Update the evenCmd struct variable’s RUN method. // even.goRun: func(cmd *cobra.Command, args []string) { var evenSum int for _, ival := range args { itemp, _ := strconv.Atoi(ival) if itemp%2 == 0 { evenSum = evenSum + itemp } } fmt.Printf("The even addition of %s is %d", args, evenSum)}, It will first convert the string into int using strconv package, then adding only even numbers. Save all the changes. Rebuild the binary using go install my-calc . Run my-calc add even 1 2 3 4 5 6 The my-calc is the root command, add it the command of the rootCmd and even is the command (subcommand) of the addCmd . This is same as evenCmd . Instead of adding even numbers, it will add odd numbers. Open the terminal in the project directory and create a new odd command. cobra add odd The odd command as odd.go added in the cmd folder. Open the odd.go in the editor. Change rootCmd to addCmd in the init . // odd.gofunc init() { addCmd.AddCommand(oddCmd)...} The addCmd.AddCommand(oddCmd) will add oddCmd as child or subcommand of the addCmd . Update the oddCmd struct variable’s RUN method. // odd.goRun: func(cmd *cobra.Command, args []string) { var oddSum int for _, ival := range args { itemp, _ := strconv.Atoi(ival) if itemp%2 != 0 { oddSum = oddSum + itemp } } fmt.Printf("The odd addition of %s is %d", args, oddSum)}, It will first convert the string into int using strconv package, then adding only even numbers. Save all the changes. Rebuild the binary using go install my-calc . Run my-calc add odd 1 2 3 4 5 6 The my-calc is the root command, add it the command of the rootCmd and odd is the command (subcommand) of the addCmd . Congratulations! You created your own cli in golang with cobra. The complete code is saved on Github. The my-calc cli project is complete. The main aim of this tutorial to understand the basics of the cobra library. The tutorial covered most of the basic operations required to create a cli. I will keep updating it with more basic operations if it requires. I hope I smoothened the learning curve of creating cli. Thanks for your time to read the tutorial. I hope you learned something and it is worth your time. Please give your valuable feedback on this tutorial. I’ll make changes accordingly. If you love this tutorial, You can read my latest tutorials on my blog. 📑
[ { "code": null, "e": 295, "s": 172, "text": "Have you ever wonder why in the world of GUI, CLI still exist? You’ll better understand it when you build one of your own." }, { "code": null, "e": 322, "s": 295, "text": "Published on schadokar.dev" }, { "code": null, "e": 623, "s": 322, "text": "When you learn golang then it is very often that you’ll come across that ‘golang is great to build cli tools’. This fascinated me too. So, I tried to get my hands dirty and found a few tutorials of creating a cli but most of all are not basic. In this tutorial, I’ll try to smooth the learning curve." }, { "code": null, "e": 796, "s": 623, "text": "This is the basic cli application where we are going to cover basic cli operations. I am planning to write another article with advance cli operations but that’s for later." }, { "code": null, "e": 891, "s": 796, "text": "We are creating a simple mathematical cli which will be capable of doing the following 2 jobs:" }, { "code": null, "e": 911, "s": 891, "text": "addition of numbers" }, { "code": null, "e": 948, "s": 911, "text": "addition of only even or odd numbers" }, { "code": null, "e": 1068, "s": 948, "text": "I know these jobs don’t meet your expectations but trust me, after this, you will feel comfortable with building a cli." }, { "code": null, "e": 1292, "s": 1068, "text": "CLI works on the basic principle of software engineering, takes the input, process it and gives the output. In the cli tool instead of a flashing frontend, it takes the input from the black window. Remember, Matrix Trilogy." }, { "code": null, "e": 1410, "s": 1292, "text": "If you are using Windows just type cmd or powershell in the startand enter, the black window or blue window is a cli." }, { "code": null, "e": 1461, "s": 1410, "text": "In Mac or Linux it is known by the name terminal ." }, { "code": null, "e": 1773, "s": 1461, "text": "A command-line interface (CLI) is a means of interacting with a computer program where the user (or client) issues commands to the program in the form of successive lines of text (command lines). The program which handles the interface is called a command-line interpreter or command-line processor. — wikipedia" }, { "code": null, "e": 1922, "s": 1773, "text": "There are many CLIs’ you might work on like npm, node, go, python, docker, Kubernetes etc. All are an ideal interface to interact with the software." }, { "code": null, "e": 1950, "s": 1922, "text": "It is lightweight and fast." }, { "code": null, "e": 1978, "s": 1950, "text": "Minimal or no dependencies." }, { "code": null, "e": 2040, "s": 1978, "text": "Best for system administration and task-based automation etc." }, { "code": null, "e": 2093, "s": 2040, "text": "Enough of theory, let’s start with the requirements:" }, { "code": null, "e": 2146, "s": 2093, "text": "golang installed (I am using go1.11.5 windows/amd64)" }, { "code": null, "e": 2201, "s": 2146, "text": "Cobra library (go get -u github.com/spf13/cobra/cobra)" }, { "code": null, "e": 2254, "s": 2201, "text": "Any code editor of your choice. (I am using VS Code)" }, { "code": null, "e": 2532, "s": 2254, "text": "I recommend to use VS code and install the go extension by Microsoft. This will update the import statement according to the code. If you use a new package, it will import that package on save. If a package is imported and not used, it will remove that package from the import." }, { "code": null, "e": 2659, "s": 2532, "text": "A little introduction to the Cobra library. We will use cobra cli to use the cobra library. We will use a cli to build a cli 😃" }, { "code": null, "e": 2794, "s": 2659, "text": "Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files." }, { "code": null, "e": 2921, "s": 2794, "text": "Many of the most widely used Go projects are built using Cobra, such as: Kubernetes, Hugo, Docker (distribution) etc. — Github" }, { "code": null, "e": 2983, "s": 2921, "text": "Cobra is built on a structure of commands, arguments & flags." }, { "code": null, "e": 3010, "s": 2983, "text": "Commands represent actions" }, { "code": null, "e": 3026, "s": 3010, "text": "Args are things" }, { "code": null, "e": 3064, "s": 3026, "text": "Flags are modifiers for those actions" }, { "code": null, "e": 3115, "s": 3064, "text": "The basic structure will be like a simple sentence" }, { "code": null, "e": 3176, "s": 3115, "text": "APPNAME Command Args --Flags or APPNAME Command --Flags Args" }, { "code": null, "e": 3184, "s": 3176, "text": "For Ex." }, { "code": null, "e": 3204, "s": 3184, "text": "git clone URL -bare" }, { "code": null, "e": 3218, "s": 3204, "text": "go get -u URL" }, { "code": null, "e": 3245, "s": 3218, "text": "npm install package --save" }, { "code": null, "e": 3265, "s": 3245, "text": "docker run image -d" }, { "code": null, "e": 3410, "s": 3265, "text": "Create a new project directory outside the GOPATH. I have created my-calc project directory for this tutorial. You can name any of your choices." }, { "code": null, "e": 3716, "s": 3410, "text": "Creating projects outside the GOPATH ease the importing local files. Initialize modules in the project. This module will keep all the libraries and dependency require and used in this project. It is similar to the package.json in the nodejs. To read more about the modules, please read this great article." }, { "code": null, "e": 3810, "s": 3716, "text": "A module is a collection of related Go packages that are versioned together as a single unit." }, { "code": null, "e": 3896, "s": 3810, "text": "Modules record precise dependency requirements and create reproducible builds. — wiki" }, { "code": null, "e": 4070, "s": 3896, "text": "Open the project directory in the command line of your choices. I am using bash . Once you are inside the project directory, run the below command to initialize the modules." }, { "code": null, "e": 4090, "s": 4070, "text": "go mod init my-calc" }, { "code": null, "e": 4151, "s": 4090, "text": "You can notice that it creates a go.mod file in the project." }, { "code": null, "e": 4491, "s": 4151, "text": "Note: Creating modules inside the $GOPATHis disabled by default. You will get this error if you run above command — go: modules disabled inside GOPATH/src by GO111MODULE=auto; see ‘go help modules’ . If you still want to create the go modules inside the $GOPATH then first set GO111MODULE environment variable to on . export GO111MODULE=on" }, { "code": null, "e": 4724, "s": 4491, "text": "Now whenever you use any third-party packages in the project, it’ll save it as a dependency with their version. In this way, even if a breaking change introduces in the new version of the library, your project will work as expected." }, { "code": null, "e": 4814, "s": 4724, "text": "If you still haven’t installed the cobra library, you can install it using below command." }, { "code": null, "e": 4853, "s": 4814, "text": "go get -u github.com/spf13/cobra/cobra" }, { "code": null, "e": 4925, "s": 4853, "text": "Initialize the cli scaffolding for the project using cobra initcommand." }, { "code": null, "e": 4955, "s": 4925, "text": "cobra init --pkg-name my-calc" }, { "code": null, "e": 5018, "s": 4955, "text": "Edit: thank you Brandon Caton, for the update of init command." }, { "code": null, "e": 5137, "s": 5018, "text": "It will initialize the my-calc project with cobra library. You can observe that it created a few files in the project." }, { "code": null, "e": 5178, "s": 5137, "text": "▾ my-calc/ ▾ cmd/ root.go main.go" }, { "code": null, "e": 5297, "s": 5178, "text": "The main.go is the entry point of the cli . Inside the main.go it is calling the Execute function of the cmd/root.go ." }, { "code": null, "e": 5370, "s": 5297, "text": "// main.gopackage mainimport \"my-calc/cmd\"func main() { cmd.Execute()}" }, { "code": null, "e": 5398, "s": 5370, "text": "Let’s examine the root.go ." }, { "code": null, "e": 5684, "s": 5398, "text": "Root command is the base command of any cli. For Ex. go get URL — go is the root command here and get is the child command of the go . In the root.go it is initiating the rootCmd struct variable with the cobra command. All the other commands in the cli will be a child of the rootCmd ." }, { "code": null, "e": 5752, "s": 5684, "text": "Open the root.go in the editor and inside the rootCmd uncomment the" }, { "code": null, "e": 5801, "s": 5752, "text": "Run: func(cmd *cobra.Command, args []string) {}," }, { "code": null, "e": 5865, "s": 5801, "text": "And paste the fmt.Println(\"Hello CLI\") inside the curly braces." }, { "code": null, "e": 5937, "s": 5865, "text": "Run: func(cmd *cobra.Command, args []string) {fmt.Println(\"Hello CLI\"}," }, { "code": null, "e": 6023, "s": 5937, "text": "⚠️ Don’t remove the comma after the closing curly braces. It will throw syntax error." }, { "code": null, "e": 6076, "s": 6023, "text": "Open the terminal inside the my-calc project and run" }, { "code": null, "e": 6095, "s": 6076, "text": "go install my-calc" }, { "code": null, "e": 6194, "s": 6095, "text": "This command will generate the binary or executable file of the project in the $GOPATH/bin folder." }, { "code": null, "e": 6317, "s": 6194, "text": "Now run my-calc in the terminal. As it is saved in the bin folder you don’t have to set the environment variable for this." }, { "code": null, "e": 6373, "s": 6317, "text": "The name of cli is the rootCmd. my-calc is the rootCmd." }, { "code": null, "e": 6414, "s": 6373, "text": "You will see the output similar to this." }, { "code": null, "e": 6910, "s": 6414, "text": "This is the first function which gets called whenever a package initialize in the golang. The cobra.OnInitialize(funcDeclarations) append the user-defined functions in the command’s initialization. Whenever the command run or called it will first execute all the functions in the command’s initialization and then it will run the execute method. This initialization can be used in loading the configuration file or can be used as constructor. It all depends on your use case and your creativity." }, { "code": null, "e": 6976, "s": 6910, "text": "I believe I lost you here. Let’s understand this with an example." }, { "code": null, "e": 7021, "s": 6976, "text": "In the root.go , the command is the rootCmd." }, { "code": null, "e": 7354, "s": 7021, "text": "The cobra.OnInitialize(initConfig) append the initConfigfunction declaration in the rootCmd’s initialization. So, whenever the rootCmd ‘s execute method (RUN: func) run, the rootCmd will first run the initConfigfunction. Once the execution of all the initialize functions over, it will run the RUN: func execution method of rootCmd." }, { "code": null, "e": 7419, "s": 7354, "text": "To visualize it, add a print message in the initConfig function." }, { "code": null, "e": 7477, "s": 7419, "text": "func initConfig() { fmt.Println(\"inside initConfig\")..." }, { "code": null, "e": 7541, "s": 7477, "text": "Save the changes. Open the terminal inside the my-calc project." }, { "code": null, "e": 7580, "s": 7541, "text": "Rebuild the binary go install my-calc." }, { "code": null, "e": 7599, "s": 7580, "text": "go install my-calc" }, { "code": null, "e": 7746, "s": 7599, "text": "Run my-calc. Whenever you’ll make any changes in the cli you have to rebuild the binary. Run go install my-calc to reflect it in the cli commands." }, { "code": null, "e": 7806, "s": 7746, "text": "You can see that initConfig run first and later Hello CLI ." }, { "code": null, "e": 7936, "s": 7806, "text": "To understand the complete flow of cli, add a message inside the init function and a message inside the main func in the main.go." }, { "code": null, "e": 8102, "s": 7936, "text": "// root.gofunc init() { fmt.Println(\"inside init\") cobra.OnInitialize(initConfig)...// main.gofunc main() { fmt.Println(\"inside main\") cmd.Execute()}" }, { "code": null, "e": 8176, "s": 8102, "text": "Save the changes. Rebuild the binary go install my-calc and run my-calc ." }, { "code": null, "e": 8212, "s": 8176, "text": "Now, you know the cli command flow." }, { "code": null, "e": 8259, "s": 8212, "text": "The last thing in the init function is flags ." }, { "code": null, "e": 8397, "s": 8259, "text": "Flags are like modifiers to the command. You can think of them as conditional actions. We will learn more about it later in the tutorial." }, { "code": null, "e": 8459, "s": 8397, "text": "There are 2 types of flags Persistent Flags and Local Flags ." }, { "code": null, "e": 8591, "s": 8459, "text": "Persistent Flags: This flag will be available to the command it is assigned as well as all the child or subcommands of the command." }, { "code": null, "e": 8672, "s": 8591, "text": "Local Flags: This flag is only available to the command which it is assigned to." }, { "code": null, "e": 8825, "s": 8672, "text": "This function is setting the configuration path in the home directory and config filename is .my-calc . It will use the configuration file if it exists." }, { "code": null, "e": 9067, "s": 8825, "text": "The viper library is famous for configuration solution for go application. It reads from JSON, TOML, YAML, HCL, envfile and Java properties config files. It does much more than reading configuration. To learn more about it, follow this link." }, { "code": null, "e": 9196, "s": 9067, "text": "With this function, we completed the root.go examination. It is a bit lengthier, but it is good to understand what we are using." }, { "code": null, "e": 9354, "s": 9196, "text": "Note: Now if you want, you can remove all the print statements from the root.go and main.go . I have removed all the print statements to keep the code clean." }, { "code": null, "e": 9480, "s": 9354, "text": "It’s time to add some commands in our cli. We already created one command which is my-calc asrootCmd which returns Hello CLI." }, { "code": null, "e": 9602, "s": 9480, "text": "Open the terminal inside the project directory and create a command named add . The cobra command to add a new command is" }, { "code": null, "e": 9626, "s": 9602, "text": "cobra add <commandName>" }, { "code": null, "e": 9686, "s": 9626, "text": "cobra add add// outputadd created at C:\\Work\\golang\\my-calc" }, { "code": null, "e": 9739, "s": 9686, "text": "Check the cmd folder, an add.go file is added in it." }, { "code": null, "e": 9788, "s": 9739, "text": "Open the add.go . It is similar to the root.go ." }, { "code": null, "e": 9858, "s": 9788, "text": "First, an addCmd struct variable is declared of type *cobra.Command ." }, { "code": null, "e": 9970, "s": 9858, "text": "The *cobra.Command have RUN which is a func and takes pointer of *cobra.Command and a slice of string []string." }, { "code": null, "e": 10135, "s": 9970, "text": "Then it is initialized in init function. In the init, it is added to the rootCmd . We can understand it as addCmdis the sub-command or child command of the rootCmd." }, { "code": null, "e": 10178, "s": 10135, "text": "func init() { rootCmd.AddCommand(addCmd)" }, { "code": null, "e": 10269, "s": 10178, "text": "In the terminal, rebuild the binary using go install my-calc command and run my-calc add ." }, { "code": null, "e": 10353, "s": 10269, "text": "The add command is working fine. It’s time to modify it to add a series of numbers." }, { "code": null, "e": 10557, "s": 10353, "text": "The commands only take a slice of string as an argument. To add the numbers, we first have to convert the string into int then return the result. We will use strconv library to convert the string to int." }, { "code": null, "e": 10585, "s": 10557, "text": "Import the strconv package." }, { "code": null, "e": 10642, "s": 10585, "text": "import ( \"fmt\" \"strconv\" \"github.com/spf13/cobra\")" }, { "code": null, "e": 10691, "s": 10642, "text": "Inside the add.go, create a new addInt function." }, { "code": null, "e": 11168, "s": 10691, "text": "// add.gofunc addInt(args []string) { var sum int // iterate over the arguments // the first return value is index of args, we can omit it using _ for _, ival := range args { // strconv is the library used for type conversion. for string // to int conversion Atio method is used. itemp, err := strconv.Atoi(ival) if err != nil { fmt.Println(err) } sum = sum + itemp } fmt.Printf(\"Addition of numbers %s is %d\", args, sum)}" }, { "code": null, "e": 11186, "s": 11168, "text": "Save the changes." }, { "code": null, "e": 11296, "s": 11186, "text": "In the addCmd variable, update the RUN func. Remove the print message and call the addInt function with args." }, { "code": null, "e": 11368, "s": 11296, "text": "// addCmdRun: func(cmd *cobra.Command, args []string) { addInt(args)}," }, { "code": null, "e": 11414, "s": 11368, "text": "Rebuild the binary using go install my-calc ." }, { "code": null, "e": 11436, "s": 11414, "text": "Run my-calc add 2 3 ." }, { "code": null, "e": 11484, "s": 11436, "text": "⚠️Don’t forget the space between the arguments." }, { "code": null, "e": 11745, "s": 11484, "text": "You can pass as many arguments as you want. If you remember the args is a slice of string. But there is a limitation in this function. It can only add integers not decimal number. In the addInt function we are converting the string into int not in float32/64 ." }, { "code": null, "e": 11866, "s": 11745, "text": "It is time to introduce a flag in the addCmd . This flag will help the cli to decide if it is an int operation or float." }, { "code": null, "e": 12221, "s": 11866, "text": "In the add.go , inside the init func, create a local flag of the bool type, Flags().BoolP. Its name will be float , shortened name f , default value false and description. The default value is very important. It means even if flag is not called in the command, the flag value will be false . For bool type, if a flag is called it will toggle the default." }, { "code": null, "e": 12338, "s": 12221, "text": "// add.gofunc init() { rootCmd.AddCommand(addCmd) addCmd.Flags().BoolP(\"float\", \"f\", false, \"Add Floating Numbers\")}" }, { "code": null, "e": 12383, "s": 12338, "text": "Create a new addFloat function in the add.go" }, { "code": null, "e": 12702, "s": 12383, "text": "// add.gofunc addFloat(args []string) { var sum float64 for _, fval := range args { // convert string to float64 ftemp, err := strconv.ParseFloat(fval, 64) if err != nil { fmt.Println(err) } sum = sum + ftemp } fmt.Printf(\"Sum of floating numbers %s is %f\", args, sum)}" }, { "code": null, "e": 12782, "s": 12702, "text": "This function is the same as addInt except, it is converting string to float64." }, { "code": null, "e": 12930, "s": 12782, "text": "In the addCmd RUN function, it will call the addInt or addFloat according to the flag. If flag --float or -f is passed then it will call addFloat ." }, { "code": null, "e": 13187, "s": 12930, "text": "// add.go // addCmdRun: func(cmd *cobra.Command, args []string) { // get the flag value, its default value is false fstatus, _ := cmd.Flags().GetBool(\"float\") if fstatus { // if status is true, call addFloat addFloat(args) } else { addInt(args) }}," }, { "code": null, "e": 13255, "s": 13187, "text": "Save all the changes. Rebuild the binary using go install my-calc ." }, { "code": null, "e": 13313, "s": 13255, "text": "Run my-calc add 1.2 2.5 -f or my-calc add 1.2 2.5 --float" }, { "code": null, "e": 13425, "s": 13313, "text": "You can do lots of things with flags. You can even pass values to flags like a slice of int, float, string etc." }, { "code": null, "e": 13486, "s": 13425, "text": "The basic addition of operation implementation is completed." }, { "code": null, "e": 13541, "s": 13486, "text": "Let’s expand it by adding sub-commands to the addCmd ." }, { "code": null, "e": 13615, "s": 13541, "text": "Open the terminal in the project directory and create a new even command." }, { "code": null, "e": 13630, "s": 13615, "text": "cobra add even" }, { "code": null, "e": 13683, "s": 13630, "text": "The even command as even.go added in the cmd folder." }, { "code": null, "e": 13754, "s": 13683, "text": "Open the even.go in the editor. Change rootCmd to addCmd in the init ." }, { "code": null, "e": 13812, "s": 13754, "text": "// even.gofunc init() { addCmd.AddCommand(evenCmd)...}" }, { "code": null, "e": 13899, "s": 13812, "text": "The addCmd.AddCommand(evenCmd) will add evenCmd as child or subcommand of the addCmd ." }, { "code": null, "e": 13948, "s": 13899, "text": "Update the evenCmd struct variable’s RUN method." }, { "code": null, "e": 14220, "s": 13948, "text": "// even.goRun: func(cmd *cobra.Command, args []string) { var evenSum int for _, ival := range args { itemp, _ := strconv.Atoi(ival) if itemp%2 == 0 { evenSum = evenSum + itemp } } fmt.Printf(\"The even addition of %s is %d\", args, evenSum)}," }, { "code": null, "e": 14316, "s": 14220, "text": "It will first convert the string into int using strconv package, then adding only even numbers." }, { "code": null, "e": 14384, "s": 14316, "text": "Save all the changes. Rebuild the binary using go install my-calc ." }, { "code": null, "e": 14417, "s": 14384, "text": "Run my-calc add even 1 2 3 4 5 6" }, { "code": null, "e": 14537, "s": 14417, "text": "The my-calc is the root command, add it the command of the rootCmd and even is the command (subcommand) of the addCmd ." }, { "code": null, "e": 14620, "s": 14537, "text": "This is same as evenCmd . Instead of adding even numbers, it will add odd numbers." }, { "code": null, "e": 14693, "s": 14620, "text": "Open the terminal in the project directory and create a new odd command." }, { "code": null, "e": 14707, "s": 14693, "text": "cobra add odd" }, { "code": null, "e": 14758, "s": 14707, "text": "The odd command as odd.go added in the cmd folder." }, { "code": null, "e": 14828, "s": 14758, "text": "Open the odd.go in the editor. Change rootCmd to addCmd in the init ." }, { "code": null, "e": 14884, "s": 14828, "text": "// odd.gofunc init() { addCmd.AddCommand(oddCmd)...}" }, { "code": null, "e": 14969, "s": 14884, "text": "The addCmd.AddCommand(oddCmd) will add oddCmd as child or subcommand of the addCmd ." }, { "code": null, "e": 15017, "s": 14969, "text": "Update the oddCmd struct variable’s RUN method." }, { "code": null, "e": 15287, "s": 15017, "text": "// odd.goRun: func(cmd *cobra.Command, args []string) { var oddSum int for _, ival := range args { itemp, _ := strconv.Atoi(ival) if itemp%2 != 0 { oddSum = oddSum + itemp } } fmt.Printf(\"The odd addition of %s is %d\", args, oddSum)}," }, { "code": null, "e": 15383, "s": 15287, "text": "It will first convert the string into int using strconv package, then adding only even numbers." }, { "code": null, "e": 15451, "s": 15383, "text": "Save all the changes. Rebuild the binary using go install my-calc ." }, { "code": null, "e": 15483, "s": 15451, "text": "Run my-calc add odd 1 2 3 4 5 6" }, { "code": null, "e": 15602, "s": 15483, "text": "The my-calc is the root command, add it the command of the rootCmd and odd is the command (subcommand) of the addCmd ." }, { "code": null, "e": 15666, "s": 15602, "text": "Congratulations! You created your own cli in golang with cobra." }, { "code": null, "e": 15704, "s": 15666, "text": "The complete code is saved on Github." }, { "code": null, "e": 16116, "s": 15704, "text": "The my-calc cli project is complete. The main aim of this tutorial to understand the basics of the cobra library. The tutorial covered most of the basic operations required to create a cli. I will keep updating it with more basic operations if it requires. I hope I smoothened the learning curve of creating cli. Thanks for your time to read the tutorial. I hope you learned something and it is worth your time." }, { "code": null, "e": 16200, "s": 16116, "text": "Please give your valuable feedback on this tutorial. I’ll make changes accordingly." } ]
User-defined Exceptions in Python with Examples
Python throws errors and exceptions whenever code behaves abnormally & its execution stop abruptly. Python provides us tools to handle such scenarios by the help of exception handling method using try-except statements. Some standard exceptions which are found are include ArithmeticError, AssertionError, AttributeError, ImportError, etc. Here we created a new exception class i.e. User_Error. Exceptions need to be derived from the built-in Exception class, either directly or indirectly. Let’s look at the given example which contains a constructor and display method within the given class. Live Demo # class MyError is extended from super class Exception class User_Error(Exception): # Constructor method def __init__(self, value): self.value = value # __str__ display function def __str__(self): return(repr(self.value)) try: raise(User_Error("User defined error")) # Value of Exception is stored in error except User_Error as error: print('A New Exception occured:',error.value) A New Exception occured: User defined error Derived class Exceptions are created when a single module handles multiple several distinct errors. Here we created a base class for exceptions defined by that module. This base class is inherited by various user-defined class to handle different types of errors. Live Demo # define Python user-defined exceptions class Error(Exception): """Base class for other exceptions""" pass class Dividebyzero(Error): """Raised when the input value is zero""" pass try: i_num = int(input("Enter a number: ")) if i_num ==0: raise Dividebyzero except Dividebyzero: print("Input value is zero, try again!") print() Enter a number: Input value is zero, try again! Runtime error is a built-in class which is raised whenever a generated error does not fall into mentioned categories. The program below explains how to use runtime error as base class and user-defined error as derived class. Live Demo # User defined error class Usererror(RuntimeError): def __init__(self, arg): self.args = arg try: raise Usererror("userError") except Usererror as e: print (e.args) ('u', 's', 'e', 'r', 'E', 'r', 'r', 'o', 'r') In this article, we learnt how we declare and implement user-defined exceptions in Python 3.x. Or earlier.
[ { "code": null, "e": 1527, "s": 1187, "text": "Python throws errors and exceptions whenever code behaves abnormally & its execution stop abruptly. Python provides us tools to handle such scenarios by the help of exception handling method using try-except statements. Some standard exceptions which are found are include ArithmeticError, AssertionError, AttributeError, ImportError, etc." }, { "code": null, "e": 1782, "s": 1527, "text": "Here we created a new exception class i.e. User_Error. Exceptions need to be derived from the built-in Exception class, either directly or indirectly. Let’s look at the given example which contains a constructor and display method within the given class." }, { "code": null, "e": 1793, "s": 1782, "text": " Live Demo" }, { "code": null, "e": 2207, "s": 1793, "text": "# class MyError is extended from super class Exception\nclass User_Error(Exception):\n # Constructor method\n def __init__(self, value):\n self.value = value\n # __str__ display function\n def __str__(self):\n return(repr(self.value))\ntry:\n raise(User_Error(\"User defined error\"))\n # Value of Exception is stored in error\nexcept User_Error as error:\n print('A New Exception occured:',error.value)" }, { "code": null, "e": 2251, "s": 2207, "text": "A New Exception occured: User defined error" }, { "code": null, "e": 2515, "s": 2251, "text": "Derived class Exceptions are created when a single module handles multiple several distinct errors. Here we created a base class for exceptions defined by that module. This base class is inherited by various user-defined class to handle different types of errors." }, { "code": null, "e": 2526, "s": 2515, "text": " Live Demo" }, { "code": null, "e": 2884, "s": 2526, "text": "# define Python user-defined exceptions\nclass Error(Exception):\n \"\"\"Base class for other exceptions\"\"\"\n pass\nclass Dividebyzero(Error):\n \"\"\"Raised when the input value is zero\"\"\"\n pass\ntry:\n i_num = int(input(\"Enter a number: \"))\n if i_num ==0:\n raise Dividebyzero\nexcept Dividebyzero:\n print(\"Input value is zero, try again!\")\n print()" }, { "code": null, "e": 2932, "s": 2884, "text": "Enter a number: Input value is zero, try again!" }, { "code": null, "e": 3157, "s": 2932, "text": "Runtime error is a built-in class which is raised whenever a generated error does not fall into mentioned categories. The program below explains how to use runtime error as base class and user-defined error as derived class." }, { "code": null, "e": 3168, "s": 3157, "text": " Live Demo" }, { "code": null, "e": 3348, "s": 3168, "text": "# User defined error\nclass Usererror(RuntimeError):\n def __init__(self, arg):\n self.args = arg\ntry:\n raise Usererror(\"userError\")\nexcept Usererror as e:\n print (e.args)" }, { "code": null, "e": 3394, "s": 3348, "text": "('u', 's', 'e', 'r', 'E', 'r', 'r', 'o', 'r')" }, { "code": null, "e": 3501, "s": 3394, "text": "In this article, we learnt how we declare and implement user-defined exceptions in Python 3.x. Or earlier." } ]